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
f4c3935d5c53f5dc38eedd44dcb2dfa28372811e
5,245
ts
TypeScript
workspaces/sengi-express/src/errors/requestErrors.ts
karlhulme/sen
316070efe463a507afaa6d7f81dc9cfbe10a7167
[ "MIT" ]
null
null
null
workspaces/sengi-express/src/errors/requestErrors.ts
karlhulme/sen
316070efe463a507afaa6d7f81dc9cfbe10a7167
[ "MIT" ]
5
2021-06-27T08:43:59.000Z
2021-06-27T08:52:33.000Z
workspaces/sengi-express/src/errors/requestErrors.ts
karlhulme/sengi
316070efe463a507afaa6d7f81dc9cfbe10a7167
[ "MIT" ]
null
null
null
export class SengiExpressError extends Error { constructor (message: string) { super(message) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressRequestError extends SengiExpressError { constructor (message: string) { super(message) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressDocIdNotFoundError extends SengiExpressRequestError { constructor (readonly id: string) { super(`Document with id (${id}) not found.`) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name this.id = id } } export class SengiExpressInvalidRequestIdError extends SengiExpressRequestError { constructor (readonly requestId: string) { super(`The value of X-REQUEST-ID (${requestId}) is not valid.`) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name this.requestId = requestId } } export class SengiExpressInvalidReqVersionError extends SengiExpressRequestError { constructor () { super('The value of the IF-MATCH header is not valid. It should be a string or left undefined.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMalformedFilterNameError extends SengiExpressRequestError { constructor () { super('The filterName value in the query string cannot be parsed into a string.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMalformedFilterParamsError extends SengiExpressRequestError { constructor () { super('The filterParams value in the query string cannot be parsed into a JSON object.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMalformedQueryNameError extends SengiExpressRequestError { constructor () { super('The queryName value in the query string cannot be parsed into a string.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMalformedQueryParamsError extends SengiExpressRequestError { constructor () { super('The queryParams value in the query string cannot be parsed into a JSON object.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMalformedUserError extends SengiExpressRequestError { constructor () { super('The X-USER header could not be parsed as a JSON object.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMissingApiKeyError extends SengiExpressRequestError { constructor () { super('The request did not specify an X-API-KEY header.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMissingUserError extends SengiExpressRequestError { constructor () { super('The request did not specify an X-USER header.') Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name } } export class SengiExpressMismatchedIdsError extends SengiExpressRequestError { constructor (readonly idFromRequestBody?: string, readonly idFromRequestUrlParams?: string) { super(`The id from the request body '${idFromRequestBody}' does not match the id from the url parameters '${idFromRequestUrlParams}'.`) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name this.idFromRequestBody = idFromRequestBody this.idFromRequestUrlParams = idFromRequestUrlParams } } export class SengiExpressUnrecognisedDocTypeNameError extends SengiExpressRequestError { constructor (readonly docTypePluralName: string) { super(`The value '${docTypePluralName}' was not recognised as either a singular or plural name of a known doc type.`) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name this.docTypePluralName = docTypePluralName } } export class SengiExpressUnsupportedRequestContentTypeError extends SengiExpressRequestError { constructor (readonly reqContentType: string, readonly supportedContentType: string) { super(`Cannot read payloads in the '${reqContentType}' format as declared in the sent Content-Type header. Try '${supportedContentType}'.`) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name this.reqContentType = reqContentType this.supportedContentType = supportedContentType } } export class SengiExpressUnsupportedResponseContentTypeError extends SengiExpressRequestError { constructor (readonly reqContentType: string, readonly supportedContentType: string) { super(`Cannot provide responses in the '${reqContentType}' format as requested in the sent Accept header. Try '${supportedContentType}'.`) Object.setPrototypeOf(this, new.target.prototype) this.name = this.constructor.name this.reqContentType = reqContentType this.supportedContentType = supportedContentType } }
38.284672
143
0.768351
38f5aa463225ecc42e32c48139ad85a98140e9ee
705
ps1
PowerShell
build/scripts/setmanifestpaths.ps1
skynode/roslyn
a3fc4fe5d1222f9554ca3bdaaed87c6439cfa3de
[ "Apache-2.0" ]
null
null
null
build/scripts/setmanifestpaths.ps1
skynode/roslyn
a3fc4fe5d1222f9554ca3bdaaed87c6439cfa3de
[ "Apache-2.0" ]
null
null
null
build/scripts/setmanifestpaths.ps1
skynode/roslyn
a3fc4fe5d1222f9554ca3bdaaed87c6439cfa3de
[ "Apache-2.0" ]
1
2018-12-06T04:17:27.000Z
2018-12-06T04:17:27.000Z
# Take care to return nothing if we don't yet have any vsman files # as will occur at the start of the build. # This will allow us to set it after the build when called again. $vsmanpath = "Binaries/VSSetup/$Env:BuildConfiguration/Insertion" if (Test-Path $vsmanpath) { $SetupManifests = [string]::Join(',', (Get-ChildItem "Binaries/VSSetup/$Env:BuildConfiguration/Insertion/*.vsman")) Write-Host "Using the following manifests '$SetupManifests'" Write-Host "SetupManifests=$SetupManifests" Write-Host "##vso[task.setvariable variable=SetupManifests;]$SetupManifests" Set-Item -Path "env:SetupManifests" -Value $SetupManifests } else { Write-Host "Unable to find manifest files" }
47
119
0.744681
0ce350327410bd52386dc4f52ad7e13532c7b32f
1,626
swift
Swift
happyshop/Classes/Common/ShopStorage.swift
pushm0v/HappyShopiOS
1752d6c33fc519eb79febab07f5eec97a28288b8
[ "MIT" ]
null
null
null
happyshop/Classes/Common/ShopStorage.swift
pushm0v/HappyShopiOS
1752d6c33fc519eb79febab07f5eec97a28288b8
[ "MIT" ]
null
null
null
happyshop/Classes/Common/ShopStorage.swift
pushm0v/HappyShopiOS
1752d6c33fc519eb79febab07f5eec97a28288b8
[ "MIT" ]
null
null
null
// // ShopStorage.swift // happyshop // // Created by Bherly Novrandy on 3/3/17. // Copyright © 2017 Bherly Novrandy. All rights reserved. // import Foundation import FirebaseStorage import UIKit protocol IShopStorage: class { var firebaseStorageRef: FIRStorageReference { get } var delegate: IShopStorageDelegate? { get set } func uploadImage(image: Any) } protocol IShopStorageDelegate: class { func shopStorage(shopStorage: IShopStorage, didSuccessUploadImage: Bool, metaData: FIRStorageMetadata?) func shopStorage(shopStorage: IShopStorage, didFailureUploadImage: Bool, error: Error?) func shopStorage(shopStorage: IShopStorage, progressUploadImage: Progress) } class ShopStorage: IShopStorage { var firebaseStorageRef: FIRStorageReference var delegate: IShopStorageDelegate? let filePath: String = "images/" init() { firebaseStorageRef = FIRStorage.storage().reference() } func uploadImage(image: Any) { guard let image = image as? UIImage, let data: Data = UIImageJPEGRepresentation(image, 0.8) else { return } let metaData = FIRStorageMetadata() metaData.contentType = "image/jpg" firebaseStorageRef.child(filePath).put(data, metadata: metaData){(metaData,error) in if let error = error { self.delegate?.shopStorage(shopStorage: self, didFailureUploadImage: true, error: error) return }else{ self.delegate?.shopStorage(shopStorage: self, didSuccessUploadImage: true, metaData: metaData) } } } }
32.52
115
0.682042
795b893e82ef67bccecdccd9ddd3cde130418e5c
2,295
php
PHP
PokemonMarketplace/app/views/includes/navbar.php
KrikorAstour/eCommerce22
ffaa9945c3c1f9c01f41ae4827b5df4c65cc3aa4
[ "MIT" ]
1
2022-02-13T20:13:35.000Z
2022-02-13T20:13:35.000Z
PokemonMarketplace/app/views/includes/navbar.php
KrikorAstour/eCommerce22
ffaa9945c3c1f9c01f41ae4827b5df4c65cc3aa4
[ "MIT" ]
null
null
null
PokemonMarketplace/app/views/includes/navbar.php
KrikorAstour/eCommerce22
ffaa9945c3c1f9c01f41ae4827b5df4c65cc3aa4
[ "MIT" ]
null
null
null
<nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-5"> <div class="container"> <a class="navbar-brand" href="<?= URLROOT ?>">PokeMarket</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse ms-auto" id="navbarSupportedContent"> <ul class="navbar-nav mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="<?= URLROOT ?>/profile/my_profile">Profile</a> </li> <li class="nav-item"> <a class="nav-link active" href="<?= URLROOT ?>/saves">Saves</a> </li> <li class="nav-item"> <a class="nav-link active" href="<?= URLROOT ?>/transactions">Transactions</a> </li> <li class="nav-item"> <a class="nav-link active" href="<?= URLROOT ?>/deposit">Deposit</a> </li> <li class="nav-item"> <a class="nav-link active" href="<?= URLROOT ?>/login/logout">Logout</a> </li> </ul> <form class="d-flex mb-0 ms-auto" action="/eCommerce22/PokemonMarketplace/Search/getResult/" mthode="POST"> <input class="form-control me-2" name="search_text" type="search" placeholder="Search" aria-label="Search"> <select name="search_type"> <option value="newFirst" selected>newest to oldest</option> <option value="oldFirst">oldest to newest</option> <option value="highFirst">higher price first</option> <option value="lowFirst">lower price first</option> </select> <select name="rarity" style="margin-left: 10px"> <option value="all" selected>All</option> <option value="oldFirst">Common</option> <option value="rare">Rare</option> <option value="epic">Epic</option> <option value="legendary">Legendary</option> </select> <button class="btn btn-outline-success" type="submit" name="search" style="margin-left: 10px">Search</button> </form> </div> </div> </nav>
49.891304
208
0.59695
8ea1c16ade22bae4e418199a2ed19b19adfc60bd
112
js
JavaScript
testrandom/aoo.js
Qasem-moh/LSInJS
7ec17285efef291eb0b843cfa394b74ed0e4e15f
[ "MIT" ]
null
null
null
testrandom/aoo.js
Qasem-moh/LSInJS
7ec17285efef291eb0b843cfa394b74ed0e4e15f
[ "MIT" ]
null
null
null
testrandom/aoo.js
Qasem-moh/LSInJS
7ec17285efef291eb0b843cfa394b74ed0e4e15f
[ "MIT" ]
null
null
null
'use strict' async function matRan(num) { return console.log(Math.floor(Math.random() * num)); } matRan(100);
18.666667
54
0.696429
22bdf1f157195a0af6c1fa2e12a54f4b6529e236
1,497
lua
Lua
travel/travel.lua
dennisjenkins75/pandorabox_custom
98bddc836483ab6fa42e397859aa1e2771366a39
[ "MIT" ]
null
null
null
travel/travel.lua
dennisjenkins75/pandorabox_custom
98bddc836483ab6fa42e397859aa1e2771366a39
[ "MIT" ]
null
null
null
travel/travel.lua
dennisjenkins75/pandorabox_custom
98bddc836483ab6fa42e397859aa1e2771366a39
[ "MIT" ]
null
null
null
-- current world height limit local max_height = 18000 -- generic travel check -- returns (success, error_message) pandorabox.can_travel = function(player, pos) -- world height limit if pos.y > max_height then return false, "The area above " .. max_height .. " is reserved for future use, sorry..." end -- moon if pos.y > 5000 and pos.y < 6000 and not minetest.check_player_privs(player, "moon_access") then return false, "You need the 'moon_access' priv to go to the moon!" end -- asteroids if pos.y > 6000 and pos.y < 10000 and not minetest.check_player_privs(player, "asteroids_access") then return false, "You need the 'asteroids_access' priv to go to the asteroids!" end -- mars if pos.y > 10000 and pos.y < 17000 and not minetest.check_player_privs(player, "mars_access") then return false, "You need the 'mars_access' priv to go to the mars!" end -- warzone if pos.y > 17000 and pos.y < 18000 and not minetest.check_player_privs(player, "warzone_access") then return false, "You need the 'warzone_access' priv to go to the warzone!" end -- non-restricted area return true end -- teleport only check (for "walk-only" areas) -- returns (success, error_message) pandorabox.can_teleport = function(player, pos) -- check if the player can travel there "by foot" local can_travel, err_msg = pandorabox.can_travel(player, pos) if not can_travel then return false, err_msg end -- walk-only areas here -- TODO: maybe add warzone here return true end
28.245283
103
0.728123
d9e08927a5ef81eedc0f1a19d4d9d62b0814df6a
1,714
sql
SQL
postgres/postgresql-8.3.9/contrib/hstore/uninstall_hstore.sql
KMU-embedded/mosbench-ext
721d789576cd7fdd8a90b3833a67d4cf3de46036
[ "MIT" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
postgres/postgresql-8.3.9/contrib/hstore/uninstall_hstore.sql
KMU-embedded/mosbench-ext
721d789576cd7fdd8a90b3833a67d4cf3de46036
[ "MIT" ]
null
null
null
postgres/postgresql-8.3.9/contrib/hstore/uninstall_hstore.sql
KMU-embedded/mosbench-ext
721d789576cd7fdd8a90b3833a67d4cf3de46036
[ "MIT" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
/* $PostgreSQL: pgsql/contrib/hstore/uninstall_hstore.sql,v 1.6 2007/11/13 04:24:28 momjian Exp $ */ -- Adjust this setting to control where the objects get dropped. SET search_path = public; DROP OPERATOR CLASS gist_hstore_ops USING gist CASCADE; DROP OPERATOR CLASS gin_hstore_ops USING gin CASCADE; DROP OPERATOR ? ( hstore, text ); DROP OPERATOR ->( hstore, text ); DROP OPERATOR ||( hstore, hstore ); DROP OPERATOR @>( hstore, hstore ); DROP OPERATOR <@( hstore, hstore ); DROP OPERATOR @( hstore, hstore ); DROP OPERATOR ~( hstore, hstore ); DROP OPERATOR =>( text, text ); DROP FUNCTION fetchval(hstore,text); DROP FUNCTION isexists(hstore,text); DROP FUNCTION exist(hstore,text); DROP FUNCTION isdefined(hstore,text); DROP FUNCTION defined(hstore,text); DROP FUNCTION delete(hstore,text); DROP FUNCTION hs_concat(hstore,hstore); DROP FUNCTION hs_contains(hstore,hstore); DROP FUNCTION hs_contained(hstore,hstore); DROP FUNCTION tconvert(text,text); DROP FUNCTION akeys(hstore); DROP FUNCTION avals(hstore); DROP FUNCTION skeys(hstore); DROP FUNCTION svals(hstore); DROP FUNCTION each(hstore); DROP FUNCTION ghstore_compress(internal); DROP FUNCTION ghstore_decompress(internal); DROP FUNCTION ghstore_penalty(internal,internal,internal); DROP FUNCTION ghstore_picksplit(internal, internal); DROP FUNCTION ghstore_union(internal, internal); DROP FUNCTION ghstore_same(internal, internal, internal); DROP FUNCTION ghstore_consistent(internal,internal,int4); DROP FUNCTION gin_consistent_hstore(internal, smallint, internal); DROP FUNCTION gin_extract_hstore(internal, internal); DROP FUNCTION gin_extract_hstore_query(internal, internal, smallint); DROP TYPE hstore CASCADE; DROP TYPE ghstore CASCADE;
36.468085
100
0.792882
c3cc24e2f3f6d3853e41e29943b8f68b8a2e763f
292
cs
C#
MinecraftRegion.Business/Models/ChunkSector.cs
mhollebecq/MinecraftRegion.net
5aedfdf2f2c78237a1970176e73f5c58d1204804
[ "MIT" ]
1
2019-01-16T08:42:00.000Z
2019-01-16T08:42:00.000Z
MinecraftRegion.Business/Models/ChunkSector.cs
mhollebecq/MinecraftRegion.net
5aedfdf2f2c78237a1970176e73f5c58d1204804
[ "MIT" ]
null
null
null
MinecraftRegion.Business/Models/ChunkSector.cs
mhollebecq/MinecraftRegion.net
5aedfdf2f2c78237a1970176e73f5c58d1204804
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MinecraftRegion.Business.Models { public class ChunkSector { public int DataVersion { get; set; } public Level Level { get; set; } } }
18.25
44
0.695205
587c4695d3319f7ca0838e2ab3bc53f9cce3e965
626
css
CSS
assets/css/style.css
manukutty74/TriviaGame
2f3ea30b3f47eff264542cac9e00237fbd6f6dc9
[ "MIT" ]
null
null
null
assets/css/style.css
manukutty74/TriviaGame
2f3ea30b3f47eff264542cac9e00237fbd6f6dc9
[ "MIT" ]
null
null
null
assets/css/style.css
manukutty74/TriviaGame
2f3ea30b3f47eff264542cac9e00237fbd6f6dc9
[ "MIT" ]
1
2019-07-19T19:27:51.000Z
2019-07-19T19:27:51.000Z
body{ background: url('../images/cloudBG.jpeg'); background-repeat:no-repeat; font-family: 'Raleway', sans-serif; font-size: 25px; } header{ margin-bottom: 20px; } .btn-primary,.reset{ background-color: #313477; color: white; font-family: 'Sigmar One', sans-serif; font-size: 30px; padding: 20px; margin-top: 100px; } .btn-primary:hover, .reset:hover{ background-color: #202364; } .container{ margin-top: 50px; text-align: center; height: 100%; width: 700px; } h2, #message, #finalMessage{ font-family: Sigmar One; } .thisChoice:hover{ background-color: #202364; color: white; padding: 10px; }
14.227273
43
0.683706
21910c92f82ad76f929fe86a3f89b0579b54a279
3,259
js
JavaScript
src/components/Footer.js
mattyc246/datocms-Cerulean-Diamond
f0edaa943f7723d2439f02f7dc53fe3b8bf75a6f
[ "MIT" ]
null
null
null
src/components/Footer.js
mattyc246/datocms-Cerulean-Diamond
f0edaa943f7723d2439f02f7dc53fe3b8bf75a6f
[ "MIT" ]
null
null
null
src/components/Footer.js
mattyc246/datocms-Cerulean-Diamond
f0edaa943f7723d2439f02f7dc53fe3b8bf75a6f
[ "MIT" ]
null
null
null
import React from 'react' import styled from 'styled-components' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faCaretSquareUp } from '@fortawesome/free-regular-svg-icons' import { faFacebook, faInstagram } from '@fortawesome/free-brands-svg-icons' import { useStaticQuery, graphql, Link } from 'gatsby' import { MEDIA, COLORS } from '../constants/variables' const Footer = styled.footer` position: relative; background-color: ${COLORS.darkBrown}; color: white; box-sizing: border-box; padding-top: 10px; padding-bottom: 30px; .container .row [class^=col-] { padding-left: 2.5em; padding-right: 2.5em; } .footer-section { margin: 20px auto; .nav-links { padding-left: .3em; a { text-decoration: none; color: white; display: block; margin-bottom: 3px; &:hover { color: ${COLORS.textDark}; } } } .socials { margin-top: 1em; a { color: white; &:hover { color: ${COLORS.textDark}; } } } .title { margin: 0.8em 0 0.3em auto; font-weight: 700; color: ${COLORS.lightBrown}; } } ` const StyledIcon = styled(props => <FontAwesomeIcon {...props} />)` color: #e6be8a; font-size: 48px; position: absolute; right: 10px; bottom: 10px; ` const FooterBar = ({ jumpToTop }) => { const { footer } = useStaticQuery(graphql` query Footer { footer: datoCmsFooter { phone email facebookLink instagramLink } } `) const { phone, email, facebookLink, instagramLink } = footer return ( <Footer> <div className="container"> <div className="row"> <div className="col-sm-6"> <div className="footer-section"> <div className="title">Cerulean Diamonds</div> <div className="nav-links"> <Link to="/about">About</Link> <Link to="/educate">Educate</Link> <Link to="/contact">Contact</Link> </div> </div> <div className="footer-section"> <div className="title">Find Us On:</div> <div className="socials"> <a href={facebookLink}> <FontAwesomeIcon className="mr-3" size="2x" icon={faFacebook} /> </a> <a href={instagramLink}> <FontAwesomeIcon className="mr-3" size="2x" icon={faInstagram} /> </a> </div> </div> </div> <div className="col-sm-6"> <div className="footer-section"> <div className="title">Phone</div> <div>{phone}</div> </div> <div className="footer-section"> <div className="title">Email</div> <div>{email}</div> </div> </div> </div> </div> <StyledIcon onClick={() => jumpToTop()} icon={faCaretSquareUp} /> </Footer> ) } export default FooterBar
24.689394
76
0.506597
d3cce82284af90e799e82751a431a89b68a82b00
553
swift
Swift
Sources/TensorBoxifyUI/AppDelegate.swift
dhushon/TensorBoxify
fdacc1e254c80f79f41920da92586ce0757918e7
[ "Apache-2.0" ]
null
null
null
Sources/TensorBoxifyUI/AppDelegate.swift
dhushon/TensorBoxify
fdacc1e254c80f79f41920da92586ce0757918e7
[ "Apache-2.0" ]
null
null
null
Sources/TensorBoxifyUI/AppDelegate.swift
dhushon/TensorBoxify
fdacc1e254c80f79f41920da92586ce0757918e7
[ "Apache-2.0" ]
null
null
null
// // AppDelegate.swift // MetaMerge // // Created by Dan Hushon on 9/6/17. // Copyright © 2017 Dan Hushon. All rights reserved. // #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
19.75
71
0.701627
f73e69d4c893458845403faf4eb7169ce8645e06
1,403
rb
Ruby
spec/support/matchers/delayed_job_matchers.rb
s030827/peoplefinder
3bd2516a069044e121e34fd9d48d40a41c5e020b
[ "MIT" ]
null
null
null
spec/support/matchers/delayed_job_matchers.rb
s030827/peoplefinder
3bd2516a069044e121e34fd9d48d40a41c5e020b
[ "MIT" ]
1
2021-09-28T05:46:12.000Z
2021-09-28T05:46:12.000Z
spec/support/matchers/delayed_job_matchers.rb
s030827/peoplefinder
3bd2516a069044e121e34fd9d48d40a41c5e020b
[ "MIT" ]
null
null
null
# frozen_string_literal: true require 'rspec/expectations' module DelayedJobHelper RSpec::Matchers.define :delay_method do |expected| def supports_block_expectations? true end match do |proc| Delayed::Worker.new.work_off proc.call job = Delayed::Job.last @actual = job.payload_object.method_name.to_sym (@actual == expected) || (@actual == "#{expected}_without_delay".to_sym) end failure_message do |proc| "expected #{proc} to have delayed the method '#{expected}' but got '#{@actual}'" end failure_message_when_negated do |proc| "expected #{proc} not to have delayed the method '#{expected}'" end end RSpec::Matchers.define :have_delayed_job do |count| def supports_block_expectations? true end match do |proc| Delayed::Worker.new.work_off @expected_count = count || 1 before_count = Delayed::Job.count proc.call after_count = Delayed::Job.count @actual_count = (after_count - before_count) @actual_count == @expected_count end failure_message do |proc| "expected #{proc} to have enqueued #{@expected_count} delayed job(s) but enqueued #{@actual_count}" end failure_message_when_negated do |proc| "expected #{proc} not to have enqueued #{@expected_count} delayed job(s) but enqueued #{@actual_count}" end end end
26.980769
109
0.669993
e243cfd94e6e6534fb7283752c0cffc484097d90
339
js
JavaScript
src/components/AboutCard.js
Alvarg27/grupo-farma
1253ba451ec72984aa5bdd44c24fb27d720e027e
[ "RSA-MD" ]
null
null
null
src/components/AboutCard.js
Alvarg27/grupo-farma
1253ba451ec72984aa5bdd44c24fb27d720e027e
[ "RSA-MD" ]
null
null
null
src/components/AboutCard.js
Alvarg27/grupo-farma
1253ba451ec72984aa5bdd44c24fb27d720e027e
[ "RSA-MD" ]
null
null
null
import React from "react"; import "../style.css"; export default function AboutCard(props) { return ( <div className="card-container"> <div className="about-card"> <img src={props.img} loading="lazy" alt="about-image" /> <h3>{props.title}</h3> <p>{props.description}</p> </div> </div> ); }
22.6
64
0.581121
34a9269115f3aa314c513ca3b5bb2e9376b50200
17,726
rs
Rust
plumber_core/src/vmf/types.rs
lasa01/plumber_core
056b42a7f0b29793407153cf8b52c6a0ca2e6076
[ "Apache-2.0", "MIT" ]
4
2022-02-06T22:01:00.000Z
2022-02-12T14:03:47.000Z
plumber_core/src/vmf/types.rs
lasa01/plumber_core
056b42a7f0b29793407153cf8b52c6a0ca2e6076
[ "Apache-2.0", "MIT" ]
null
null
null
plumber_core/src/vmf/types.rs
lasa01/plumber_core
056b42a7f0b29793407153cf8b52c6a0ca2e6076
[ "Apache-2.0", "MIT" ]
null
null
null
#![allow(clippy::wildcard_imports)] use crate::parsers::{bracketed, parenthesed, space_separated}; use std::fmt::{self, Display}; use glam::{Vec2, Vec3}; use nom::sequence::tuple; use rgb::RGB8; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; pub mod color { use super::*; #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(color: &RGB8, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { Color::serialize(&Color(*color), serializer) } pub fn deserialize<'de, D>(deserializer: D) -> Result<RGB8, D::Error> where D: Deserializer<'de>, { Color::deserialize(deserializer).map(|color| color.0) } } pub struct Color(pub RGB8); impl<'de> Deserialize<'de> for Color { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct RgbVisitor; impl<'de> Visitor<'de> for RgbVisitor { type Value = Color; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an rgb string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match tuple((space_separated, space_separated, space_separated))(v) { Ok((_, (r, g, b))) => { let r = r.parse().map_err(|_| { de::Error::invalid_value( de::Unexpected::Str(r), &"an int between 0 and 255", ) })?; let g = g.parse().map_err(|_| { de::Error::invalid_value( de::Unexpected::Str(g), &"an int between 0 and 255", ) })?; let b = b.parse().map_err(|_| { de::Error::invalid_value( de::Unexpected::Str(b), &"an int between 0 and 255", ) })?; Ok(Color(RGB8 { r, g, b })) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(RgbVisitor) } } impl Serialize for Color { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for Color { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {} {}", self.0.r, self.0.g, self.0.b) } } pub struct Vector2(pub Vec2); impl<'de> Deserialize<'de> for Vector2 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Vec2Visitor; impl<'de> Visitor<'de> for Vec2Visitor { type Value = Vector2; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("vector2") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match tuple((space_separated, space_separated))(v) { Ok((_, (x, y))) => { let x = x.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x), &"float") })?; let y = y.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y), &"float") })?; Ok(Vector2(Vec2::new(x, y))) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(Vec2Visitor) } } impl Serialize for Vector2 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for Vector2 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.0.x, self.0.y) } } pub struct Vector3(pub Vec3); impl<'de> Deserialize<'de> for Vector3 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Vec3Visitor; impl<'de> Visitor<'de> for Vec3Visitor { type Value = Vector3; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("vector3") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match tuple((space_separated, space_separated, space_separated))(v) { Ok((_, (x, y, z))) => { let x = x.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x), &"float") })?; let y = y.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y), &"float") })?; let z = z.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(z), &"float") })?; Ok(Vector3(Vec3::new(x, y, z))) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(Vec3Visitor) } } impl Serialize for Vector3 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for Vector3 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {} {}", self.0.x, self.0.y, self.0.z) } } pub mod bracketed_vector2 { use super::*; pub mod option { use super::*; pub fn serialize<S>( vector: &Option<Vec2>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { Option::<BracketedVector2>::serialize(&vector.map(BracketedVector2), serializer) } pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<Vec2>, D::Error> where D: Deserializer<'de>, { Option::<BracketedVector2>::deserialize(deserializer) .map(|option| option.map(|vector| vector.0)) } } } pub struct BracketedVector2(pub Vec2); impl<'de> Deserialize<'de> for BracketedVector2 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct SquareBracketedVec2Visitor; impl<'de> Visitor<'de> for SquareBracketedVec2Visitor { type Value = BracketedVector2; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("square bracketed vector2") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match bracketed(tuple((space_separated, space_separated)))(v) { Ok((_, (x, y))) => { let x = x.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x), &"float") })?; let y = y.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y), &"float") })?; Ok(BracketedVector2(Vec2::new(x, y))) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(SquareBracketedVec2Visitor) } } impl Serialize for BracketedVector2 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for BracketedVector2 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[{} {}]", self.0.x, self.0.y) } } pub mod bracketed_vector3 { use super::*; pub fn serialize<S>(vector: &Vec3, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { BracketedVector3::serialize(&BracketedVector3(*vector), serializer) } } pub struct BracketedVector3(pub Vec3); impl<'de> Deserialize<'de> for BracketedVector3 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct SquareBracketedVec3Visitor; impl<'de> Visitor<'de> for SquareBracketedVec3Visitor { type Value = BracketedVector3; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("square bracketed vector3") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match bracketed(tuple((space_separated, space_separated, space_separated)))(v) { Ok((_, (x, y, z))) => { let x = x.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x), &"float") })?; let y = y.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y), &"float") })?; let z = z.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(z), &"float") })?; Ok(BracketedVector3(Vec3::new(x, y, z))) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(SquareBracketedVec3Visitor) } } impl Serialize for BracketedVector3 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for BracketedVector3 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[{} {} {}]", self.0.x, self.0.y, self.0.z) } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct Plane( pub Vec3, pub Vec3, pub Vec3, ); impl Default for Plane { fn default() -> Self { Self( Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0), ) } } impl<'de> Deserialize<'de> for Plane { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct PlaneVisitor; impl<'de> Visitor<'de> for PlaneVisitor { type Value = Plane; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a plane string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match tuple(( parenthesed(tuple((space_separated, space_separated, space_separated))), parenthesed(tuple((space_separated, space_separated, space_separated))), parenthesed(tuple((space_separated, space_separated, space_separated))), ))(v) { Ok((_, ((x0, y0, z0), (x1, y1, z1), (x2, y2, z2)))) => { let x0 = x0.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x0), &"a float") })?; let y0 = y0.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y0), &"a float") })?; let z0 = z0.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(z0), &"a float") })?; let x1 = x1.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x1), &"a float") })?; let y1 = y1.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y1), &"a float") })?; let z1 = z1.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(z1), &"a float") })?; let x2 = x2.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x2), &"a float") })?; let y2 = y2.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y2), &"a float") })?; let z2 = z2.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(z2), &"a float") })?; Ok(Plane( Vec3::new(x0, y0, z0), Vec3::new(x1, y1, z1), Vec3::new(x2, y2, z2), )) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(PlaneVisitor) } } impl Serialize for Plane { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for Plane { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "({} {} {}) ({} {} {}) ({} {} {})", self.0.x, self.0.y, self.0.z, self.1.x, self.1.y, self.1.z, self.2.x, self.2.y, self.2.z, ) } } #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct UvAxis { pub axis: Vec3, pub translation: f64, pub scale: f64, } impl<'de> Deserialize<'de> for UvAxis { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct UvAxisVisitor; impl<'de> Visitor<'de> for UvAxisVisitor { type Value = UvAxis; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an uv axis string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match tuple(( bracketed(tuple(( space_separated, space_separated, space_separated, space_separated, ))), space_separated, ))(v) { Ok((_, ((x, y, z, translation), scale))) => { let x = x.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(x), &"a float") })?; let y = y.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(y), &"a float") })?; let z = z.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(z), &"a float") })?; let translation = translation.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(translation), &"a float") })?; let scale = scale.parse().map_err(|_| { de::Error::invalid_value(de::Unexpected::Str(scale), &"a float") })?; Ok(UvAxis { axis: Vec3::new(x, y, z), translation, scale, }) } Err(..) => Err(de::Error::invalid_value(de::Unexpected::Str(v), &Self)), } } } deserializer.deserialize_str(UvAxisVisitor) } } impl Serialize for UvAxis { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl Display for UvAxis { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "[{} {} {} {}] {}", self.axis.x, self.axis.y, self.axis.z, self.translation, self.scale, ) } }
31.881295
98
0.447873
cfad8b0bc435329691b00b8519b6744026b6936d
1,058
swift
Swift
beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/RarityOfItems.swift
alirsamar/BiOS
d7980f6570cfb61b7711af3a4331d8b55bb0d9f5
[ "MIT" ]
null
null
null
beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/RarityOfItems.swift
alirsamar/BiOS
d7980f6570cfb61b7711af3a4331d8b55bb0d9f5
[ "MIT" ]
null
null
null
beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/RarityOfItems.swift
alirsamar/BiOS
d7980f6570cfb61b7711af3a4331d8b55bb0d9f5
[ "MIT" ]
null
null
null
// // RarityOfItems.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func rarityOfItems(inventory: [UDItem]) -> [UDItemRarity:Int] { var rarityCount = [UDItemRarity.Common: 0, .Uncommon: 0, .Rare: 0, .Legendary: 0] for item in inventory { switch item.rarity { case .Common: rarityCount[.Common] = rarityCount[.Common]! + 1 case.Uncommon: rarityCount[.Uncommon] = rarityCount[.Uncommon]! + 1 case .Rare: rarityCount[.Rare] = rarityCount[.Rare]! + 1 case .Legendary: rarityCount[.Legendary] = rarityCount[.Legendary]! + 1 } } return rarityCount } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 4"
36.482759
235
0.60397
79a44951fc4e573dbcd79c6568c756f5f34c6398
394
php
PHP
application/admin/validate/User.php
rauwang/m_blog
78b440ba61677a207a4ae93645523527c384043e
[ "Apache-2.0" ]
null
null
null
application/admin/validate/User.php
rauwang/m_blog
78b440ba61677a207a4ae93645523527c384043e
[ "Apache-2.0" ]
null
null
null
application/admin/validate/User.php
rauwang/m_blog
78b440ba61677a207a4ae93645523527c384043e
[ "Apache-2.0" ]
null
null
null
<?php namespace app\admin\validate; use think\Validate; class User extends Validate { /** * 定义验证规则 * 格式:'字段名' => ['规则1','规则2'...] * * @var array */ protected $rule = [ 'username|用户名' => 'require|min:5', 'password|密码' => 'require|min:5', ]; public function sceneLogin() { return $this->only(['username', 'password']); } }
15.76
53
0.515228
4b54cf8b15adccd3e061e56992b047716e6b0ae3
1,153
swift
Swift
ShortcutsSwift.playgroundbook/Contents/Sources/InterpolatedText.swift
mohsinalimat/shortcuts-swift
af8413edeb270943a85a3ea3690fab8880d440f9
[ "MIT" ]
1
2018-12-26T06:19:22.000Z
2018-12-26T06:19:22.000Z
ShortcutsSwift.playgroundbook/Contents/Sources/InterpolatedText.swift
mohsinalimat/shortcuts-swift
af8413edeb270943a85a3ea3690fab8880d440f9
[ "MIT" ]
null
null
null
ShortcutsSwift.playgroundbook/Contents/Sources/InterpolatedText.swift
mohsinalimat/shortcuts-swift
af8413edeb270943a85a3ea3690fab8880d440f9
[ "MIT" ]
null
null
null
import Foundation func withInterpolatedText(_ string: String) -> Any { var result = string var attachments = [String: Any]() let objectReplacementCharacter = "\u{fffc}" let replacementCharacter = "\u{fffd}" var rangeStart = result.startIndex while let orcRange = result.range(of: objectReplacementCharacter, range: rangeStart ..< result.endIndex) { if let rcRange = result.range(of: replacementCharacter, range: orcRange.upperBound ..< result.endIndex) { let data = Data(result[orcRange.upperBound ..< rcRange.lowerBound].utf8) let jsonObject = try! JSONSerialization.jsonObject(with: data) attachments[NSStringFromRange(NSRange(orcRange, in: result))] = jsonObject result.removeSubrange(orcRange.upperBound ..< rcRange.upperBound) } rangeStart = orcRange.upperBound } guard !attachments.isEmpty else { return string } return [ "WFSerializationType": "WFTextTokenString", "Value": [ "attachmentsByRange": attachments, "string": result, ] as PropertyList, ] as PropertyList }
33.911765
113
0.656548
1a92756df2d0ad4c90fc6eb076cff6a6788db682
1,288
py
Python
src/python/backends/py/runtime/currylib/prelude/math.py
andyjost/Sprite
7ecd6fc7d48d7f62da644e48c12c7b882e1a2929
[ "MIT" ]
1
2022-03-16T16:37:11.000Z
2022-03-16T16:37:11.000Z
src/python/backends/py/runtime/currylib/prelude/math.py
andyjost/Sprite
7ecd6fc7d48d7f62da644e48c12c7b882e1a2929
[ "MIT" ]
null
null
null
src/python/backends/py/runtime/currylib/prelude/math.py
andyjost/Sprite
7ecd6fc7d48d7f62da644e48c12c7b882e1a2929
[ "MIT" ]
null
null
null
from ...... import inspect from six.moves import range import operator as op __all__ = [ 'apply_unboxed', 'modInt', 'prim_divFloat', 'prim_minusFloat' , 'prim_roundFloat', 'quotInt', 'remInt' ] def apply_unboxed(rts, unboxedfunc, _0): '''Apply an unboxed function to the successors of _0 and box the result.''' result_value = unboxedfunc(*_unbox(rts, _0)) box = BOXER[type(result_value)] return rts.Node(*box(rts, result_value), target=_0) def modInt(x, y): return x - y * op.floordiv(x,y) def prim_divFloat(x, y): return op.truediv(y, x) def prim_minusFloat(x, y): return y - x def prim_roundFloat(x): return int(round(x)) def quotInt(x, y): return int(op.truediv(x, y)) def remInt(x, y): return x - y * quotInt(x, y) def _unbox(rts, _0): args = [ rts.variable(_0, i).hnf_or_free() for i in range(len(_0.successors)) ] freevars = [arg for arg in args if inspect.isa_freevar(arg.target)] if freevars: rts.suspend(freevars) else: return (arg.unboxed_value for arg in args) BOXER = { bool: lambda rts, rv: [getattr(rts.prelude, 'True' if rv else 'False')] , float: lambda rts, rv: [rts.prelude.Float, rv] , int: lambda rts, rv: [rts.prelude.Int, rv] , str: lambda rts, rv: [rts.prelude.Char, rv] }
24.769231
77
0.656832
b8b4cebde3a050876733ce2c8f13ef6377fe3e47
5,112
c
C
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/WLAN-Identifiers-r12.c
davidraditya/OAI-Powder
a082c3e8af06cd7583c003a69ec517eb73d175b3
[ "Apache-2.0" ]
null
null
null
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/WLAN-Identifiers-r12.c
davidraditya/OAI-Powder
a082c3e8af06cd7583c003a69ec517eb73d175b3
[ "Apache-2.0" ]
null
null
null
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/WLAN-Identifiers-r12.c
davidraditya/OAI-Powder
a082c3e8af06cd7583c003a69ec517eb73d175b3
[ "Apache-2.0" ]
null
null
null
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "fixed_grammar.asn" * `asn1c -gen-PER` */ #include "WLAN-Identifiers-r12.h" static int memb_ssid_r12_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr; size_t size; if(!sptr) { _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } size = st->size; if((size >= 1 && size <= 32)) { /* Constraint check succeeded */ return 0; } else { _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static int memb_bssid_r12_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr; size_t size; if(!sptr) { _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } size = st->size; if((size == 6)) { /* Constraint check succeeded */ return 0; } else { _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static int memb_hessid_r12_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr; size_t size; if(!sptr) { _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } size = st->size; if((size == 6)) { /* Constraint check succeeded */ return 0; } else { _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static asn_per_constraints_t asn_PER_memb_ssid_r12_constr_2 GCC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 5, 5, 1, 32 } /* (SIZE(1..32)) */, 0, 0 /* No PER value map */ }; static asn_per_constraints_t asn_PER_memb_bssid_r12_constr_3 GCC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 6, 6 } /* (SIZE(6..6)) */, 0, 0 /* No PER value map */ }; static asn_per_constraints_t asn_PER_memb_hessid_r12_constr_4 GCC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 6, 6 } /* (SIZE(6..6)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_WLAN_Identifiers_r12_1[] = { { ATF_POINTER, 3, offsetof(struct WLAN_Identifiers_r12, ssid_r12), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_OCTET_STRING, memb_ssid_r12_constraint_1, &asn_PER_memb_ssid_r12_constr_2, 0, "ssid-r12" }, { ATF_POINTER, 2, offsetof(struct WLAN_Identifiers_r12, bssid_r12), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_OCTET_STRING, memb_bssid_r12_constraint_1, &asn_PER_memb_bssid_r12_constr_3, 0, "bssid-r12" }, { ATF_POINTER, 1, offsetof(struct WLAN_Identifiers_r12, hessid_r12), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_OCTET_STRING, memb_hessid_r12_constraint_1, &asn_PER_memb_hessid_r12_constr_4, 0, "hessid-r12" }, }; static int asn_MAP_WLAN_Identifiers_r12_oms_1[] = { 0, 1, 2 }; static ber_tlv_tag_t asn_DEF_WLAN_Identifiers_r12_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_TYPE_tag2member_t asn_MAP_WLAN_Identifiers_r12_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* ssid-r12 at 3400 */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* bssid-r12 at 3401 */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 } /* hessid-r12 at 3402 */ }; static asn_SEQUENCE_specifics_t asn_SPC_WLAN_Identifiers_r12_specs_1 = { sizeof(struct WLAN_Identifiers_r12), offsetof(struct WLAN_Identifiers_r12, _asn_ctx), asn_MAP_WLAN_Identifiers_r12_tag2el_1, 3, /* Count of tags in the map */ asn_MAP_WLAN_Identifiers_r12_oms_1, /* Optional members */ 3, 0, /* Root/Additions */ 2, /* Start extensions */ 4 /* Stop extensions */ }; asn_TYPE_descriptor_t asn_DEF_WLAN_Identifiers_r12 = { "WLAN-Identifiers-r12", "WLAN-Identifiers-r12", SEQUENCE_free, SEQUENCE_print, SEQUENCE_constraint, SEQUENCE_decode_ber, SEQUENCE_encode_der, SEQUENCE_decode_xer, SEQUENCE_encode_xer, SEQUENCE_decode_uper, SEQUENCE_encode_uper, SEQUENCE_decode_aper, SEQUENCE_encode_aper, SEQUENCE_compare, 0, /* Use generic outmost tag fetcher */ asn_DEF_WLAN_Identifiers_r12_tags_1, sizeof(asn_DEF_WLAN_Identifiers_r12_tags_1) /sizeof(asn_DEF_WLAN_Identifiers_r12_tags_1[0]), /* 1 */ asn_DEF_WLAN_Identifiers_r12_tags_1, /* Same as above */ sizeof(asn_DEF_WLAN_Identifiers_r12_tags_1) /sizeof(asn_DEF_WLAN_Identifiers_r12_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ asn_MBR_WLAN_Identifiers_r12_1, 3, /* Elements count */ &asn_SPC_WLAN_Identifiers_r12_specs_1 /* Additional specs */ };
28.558659
77
0.698357
570d26383fdf6084bce61e293387ccf7ae9d6431
899
js
JavaScript
server.js
tr8b5/Club-Social
c7aa50ee0326e79252adc930e6e80a4fee09862e
[ "Unlicense" ]
null
null
null
server.js
tr8b5/Club-Social
c7aa50ee0326e79252adc930e6e80a4fee09862e
[ "Unlicense" ]
null
null
null
server.js
tr8b5/Club-Social
c7aa50ee0326e79252adc930e6e80a4fee09862e
[ "Unlicense" ]
3
2021-02-03T16:46:14.000Z
2021-02-04T13:46:44.000Z
//Require express const express = require("express"); const handlebars = require("handlebars"); const { allowInsecurePrototypeAccess, } = require("@handlebars/allow-prototype-access"); //Create an instance of express const app = express(); //Create a PORT const PORT = process.env.PORT || 8080; //Require models const db = require("./models"); //Add middleware app.use(express.urlencoded({ extended: true })); app.use(express.json()); // Set Handlebars. var exphbs = require("express-handlebars"); app.engine("handlebars", exphbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); //Import routes and give the server access to them const routes = require("./controllers/postController"); app.use(routes); //Listen on the PORT db.sequelize.sync({ force: false }).then(() => { app.listen(PORT, () => console.log(`Listening on PORT http://localhost:${PORT}`) ); });
23.051282
61
0.696329
25a590dd055a5e96ef109161e3f7626515dcce39
3,661
js
JavaScript
package_scraper/package_scraper.js
Mercotui/qt-installer-package-lister
40f2ed837b679e6c846aaf06de949a88b48b8403
[ "MIT" ]
null
null
null
package_scraper/package_scraper.js
Mercotui/qt-installer-package-lister
40f2ed837b679e6c846aaf06de949a88b48b8403
[ "MIT" ]
3
2019-12-06T16:46:55.000Z
2019-12-06T22:46:29.000Z
package_scraper/package_scraper.js
Mercotui/qt-installer-package-lister
40f2ed837b679e6c846aaf06de949a88b48b8403
[ "MIT" ]
null
null
null
const util = require('util'); const fs = require('fs'); const child_process = require('child_process'); const axios = require('axios'); const readline = require('readline'); const DATAKEY = 'MercotuisComponentList' const installer_base_url = 'http://download.qt.io/official_releases/online_installers/'; const installer_executables = { 'win32': 'qt-unified-windows-x86-online.exe', 'linux': 'qt-unified-linux-x64-online.run', 'darwin': 'qt-unified-mac-x64-online.dmg' }; main(); async function main() { try { const runner_os = process.platform; const installer_path = installer_executables[runner_os]; const response = await downloadInstaller(installer_path); await saveInstaller(response.data, installer_path); await prepareInstaller(process.platform, installer_path); const output = await runInstaller(process.platform, installer_path); const package_list = parseOutput(output); await savePackageList(package_list); console.log('Listing Complete!'); } catch (error) { console.log(`Listing failed: ${error}`); } } function downloadInstaller(installer_path) { const installer_url = installer_base_url + installer_path; console.log('Downloading Installer ' + installer_url); return axios.get(installer_url, { responseType: 'stream' }); } function saveInstaller(data, installer_path) { console.log('Saving installer to ' + installer_path); return new Promise((resolve, reject) => { const file = fs.createWriteStream(installer_path); data.pipe(file); file.on("finish", resolve); file.on("error", reject); }); } function prepareInstaller(os, installer_path) { switch (os) { case 'linux': console.log('Setting installer permissions to 775'); const chmod = util.promisify(fs.chmod); return chmod('./' + installer_path, 0o775); break; case 'darwin': console.log('Mounting ' + installer_path); // fs.chmod('./' + installer_path, 0o775); break; case 'win32': break; default: throw ("Unsuported OS: " + os); } } function runInstaller(os, installer_path) { return new Promise((resolve, reject) => { console.log('Running installer'); var child; switch (os) { case 'linux': child = child_process.spawn('xvfb-run', ['./' + installer_path, '--verbose', '--script', __dirname+'/installer_control_script.qs']); break; case 'darwin': child = child_process.spawn('./' + installer_path, ['--verbose', '--script', __dirname+'/installer_control_script.qs']); break; case 'win32': child = child_process.spawn('./' + installer_path, ['--verbose', '--script', __dirname+'\\installer_control_script.qs']); break; default: throw ("Unsuported OS: " + os); } const rl = readline.createInterface(child.stdout); var data_line; rl.on('line', (line)=>{ console.log(line); if (line.includes(DATAKEY)){ data_line = line; } }); child.on('close', ()=>{ resolve(data_line); }); child.on('error', reject); }); } function parseOutput(output){ console.log('Parsing Output'); package_list_string = output.split(DATAKEY+'=')[1]; return JSON.parse(package_list_string); } function savePackageList(package_array) { const writeFile = util.promisify(fs.writeFile); console.log('Save Package List to qt_package_list.json'); const date_string = new Date().toJSON(); const package_list = {date: date_string, packages:package_array}; const package_list_json = JSON.stringify(package_list, null, 2); return writeFile('qt_package_list.json', package_list_json); }
31.025424
140
0.671128
932fab6ea5facd219bc320e7a7961f769fff0f4c
2,446
rs
Rust
xpc-sys/src/objects/xpc_shmem.rs
mach-kernel/launchk
ef9b8708696c1affd9510fe333e1a4fa597947e8
[ "MIT" ]
40
2021-03-01T14:40:55.000Z
2022-03-26T16:36:42.000Z
xpc-sys/src/objects/xpc_shmem.rs
mach-kernel/launchk
ef9b8708696c1affd9510fe333e1a4fa597947e8
[ "MIT" ]
7
2021-03-01T15:06:58.000Z
2021-10-06T03:18:32.000Z
xpc-sys/src/objects/xpc_shmem.rs
mach-kernel/launchk
ef9b8708696c1affd9510fe333e1a4fa597947e8
[ "MIT" ]
1
2021-03-08T11:52:40.000Z
2021-03-08T11:52:40.000Z
use crate::objects::xpc_error::XPCError; use crate::objects::xpc_object::XPCObject; use crate::{ mach_port_t, mach_task_self_, rs_strerror, vm_address_t, vm_allocate, vm_deallocate, vm_size_t, xpc_shmem_create, }; use std::ffi::c_void; use std::os::raw::c_int; use std::ptr::null_mut; use std::sync::Arc; /// Wrapper around vm_allocate() vm_deallocate() with an XPCObject /// member of XPC type _xpc_type_shmem #[derive(Debug, Clone)] pub struct XPCShmem { pub task: mach_port_t, pub size: vm_size_t, pub region: *mut c_void, pub xpc_object: Arc<XPCObject>, } unsafe impl Send for XPCShmem {} impl XPCShmem { /// Allocate a region of memory of vm_size_t & flags, then wrap in a XPC Object #[must_use] pub fn new(task: mach_port_t, size: vm_size_t, flags: c_int) -> Result<XPCShmem, XPCError> { let mut region: *mut c_void = null_mut(); let err = unsafe { vm_allocate( task, &mut region as *const _ as *mut vm_address_t, size, flags, ) }; if err > 0 { Err(XPCError::IOError(rs_strerror(err))) } else { let xpc_object: XPCObject = unsafe { xpc_shmem_create(region as *mut c_void, size as u64).into() }; log::info!( "XPCShmem new (region: {:p}, xpc_object_t {:p})", region, xpc_object.as_ptr() ); Ok(XPCShmem { task, size, region, xpc_object: xpc_object.into(), }) } } /// new() with _mach_task_self /// https://web.mit.edu/darwin/src/modules/xnu/osfmk/man/mach_task_self.html #[must_use] pub fn new_task_self(size: vm_size_t, flags: c_int) -> Result<XPCShmem, XPCError> { unsafe { Self::new(mach_task_self_, size, flags) } } } impl Drop for XPCShmem { fn drop(&mut self) { let XPCShmem { size, task, region, xpc_object, } = self; log::info!( "XPCShmem drop (region: {:p}, xpc_object_t {:p})", region, xpc_object.as_ptr() ); let ok = unsafe { vm_deallocate(*task, *region as vm_address_t, *size) }; if ok != 0 { panic!("shmem won't drop (vm_deallocate errno {})", ok); } } }
27.795455
99
0.546198
347b9542f048246b0032f44a98b22859a9873b80
2,714
swift
Swift
SwiftToolkitTests/Extensions/CALayerTests.swift
avery-pierce/SwiftToolkit
038f9b17bf2006ab4d0c797e13a9debc0a6fb82f
[ "MIT" ]
null
null
null
SwiftToolkitTests/Extensions/CALayerTests.swift
avery-pierce/SwiftToolkit
038f9b17bf2006ab4d0c797e13a9debc0a6fb82f
[ "MIT" ]
null
null
null
SwiftToolkitTests/Extensions/CALayerTests.swift
avery-pierce/SwiftToolkit
038f9b17bf2006ab4d0c797e13a9debc0a6fb82f
[ "MIT" ]
null
null
null
// // CALayerTests.swift // SwiftToolkitTests // // Created by Avery Pierce on 12/18/18. // Copyright © 2018 Avery Pierce. All rights reserved. // import XCTest @testable import SwiftToolkit class CALayerTests: XCTestCase { var layer: CALayer! override func setUp() { let view = UIView() layer = view.layer } override func tearDown() { layer = nil } func testShadowGetter() { layer.shadowOpacity = 0.5 layer.shadowColor = UIColor.blue.cgColor layer.shadowOffset = CGSize(width: 5.0, height: 2.0) layer.shadowRadius = 10.0 layer.shadowPath = nil let shadow = layer.shadow XCTAssertEqual(shadow.opacity, 0.5) XCTAssertEqual(shadow.color, UIColor.blue.cgColor) XCTAssertEqual(shadow.uiColor, UIColor.blue) XCTAssertEqual(shadow.offset, CGSize(width: 5.0, height: 2.0)) XCTAssertEqual(shadow.radius, 10.0) XCTAssertNil(shadow.path) } func testShadowSetter() { var shadow = ShadowDescriptor.none shadow.opacity = 0.5 shadow.uiColor = .blue shadow.offset = CGSize(width: 5.0, height: 2.0) shadow.radius = 10.0 shadow.path = nil layer.shadow = shadow XCTAssertEqual(layer.shadowOpacity, 0.5) XCTAssertEqual(layer.shadowColor, UIColor.blue.cgColor) XCTAssertEqual(layer.shadowOffset, CGSize(width: 5.0, height: 2.0)) XCTAssertEqual(layer.shadowRadius, 10.0) XCTAssertNil(layer.shadowPath) } func testBorderGetter() { layer.borderWidth = 2.0 layer.borderColor = UIColor.blue.cgColor let border = layer.border XCTAssertEqual(border.width, 2.0) XCTAssertEqual(border.color, UIColor.blue.cgColor) } func testBorderSetter() { var border = BorderDescriptor() border.width = 2.0 border.color = UIColor.blue.cgColor layer.border = border XCTAssertEqual(layer.borderWidth, 2.0) XCTAssertEqual(layer.borderColor, UIColor.blue.cgColor) } func testConfigureWithLayerDescriptor() { var layerDescriptor = ViewLayerDescriptor() layerDescriptor.border = .hairline layerDescriptor.shadow = .dropSubtle layerDescriptor.cornerRadius = 10.0 layerDescriptor.masksToBounds = true layer.configure(with: layerDescriptor) XCTAssertEqual(layer.border, .hairline) XCTAssertEqual(layer.shadow, .dropSubtle) XCTAssertEqual(layer.cornerRadius, 10.0) XCTAssertEqual(layer.masksToBounds, true) } }
28.568421
75
0.626013
c3c3994fc86fdddf557bf0f46b24313c17c3cb8f
915
cs
C#
Models/Models.Dynamic/ReversibleConstant.cs
NMFCode/NMF
91de1ee87c1def37e7d013b1d2e62f6dcb6aa83d
[ "BSD-3-Clause" ]
35
2015-10-16T12:10:01.000Z
2022-03-07T12:25:27.000Z
Models/Models.Dynamic/ReversibleConstant.cs
NMFCode/NMF
91de1ee87c1def37e7d013b1d2e62f6dcb6aa83d
[ "BSD-3-Clause" ]
45
2016-02-03T17:13:32.000Z
2022-01-27T17:52:31.000Z
Models/Models.Dynamic/ReversibleConstant.cs
NMFCode/NMF
91de1ee87c1def37e7d013b1d2e62f6dcb6aa83d
[ "BSD-3-Clause" ]
20
2016-02-03T16:02:27.000Z
2021-12-12T21:21:05.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NMF.Expressions; namespace NMF.Models.Dynamic { internal class ReversibleConstant<T> : NotifyExpression<T>, INotifyReversableExpression<T> { public ReversibleConstant(T value) : base(value) { } public override bool IsParameterFree => true; public override IEnumerable<INotifiable> Dependencies => Enumerable.Empty<INotifiable>(); public bool IsReversable => false; T INotifyReversableValue<T>.Value { get => Value; set => throw new NotSupportedException(); } protected override INotifyExpression<T> ApplyParametersCore(IDictionary<string, object> parameters, IDictionary<INotifiable, INotifiable> trace) { return this; } protected override T GetValue() { return Value; } } }
26.911765
152
0.665574
be164a1e3a8592327b3815f1addadadfdfce5981
761
ts
TypeScript
src/app/chat/conversation/input-bar/input-bar.component.ts
kullo/chat-web
7039c317292d6beabd33f09fba2a84bad78e60d2
[ "BSD-3-Clause" ]
null
null
null
src/app/chat/conversation/input-bar/input-bar.component.ts
kullo/chat-web
7039c317292d6beabd33f09fba2a84bad78e60d2
[ "BSD-3-Clause" ]
null
null
null
src/app/chat/conversation/input-bar/input-bar.component.ts
kullo/chat-web
7039c317292d6beabd33f09fba2a84bad78e60d2
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017–2018 Kullo GmbH * * This source code is licensed under the 3-clause BSD license. See LICENSE.txt * in the root directory of this source tree for details. */ import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-input-bar', templateUrl: './input-bar.component.html', styleUrls: ['./input-bar.component.less'] }) export class InputBarComponent implements OnInit { @Output() textSubmitted: EventEmitter<string> = new EventEmitter<string>() constructor() { } ngOnInit() { } onSubmit(textInput: any) { let trimmedText:string = textInput.value.trim() if (trimmedText.length != 0) { this.textSubmitted.emit(trimmedText) textInput.value = '' } } }
23.78125
79
0.684625
dd5f3620ab42ccc1507f810684d728127fff4165
14,792
java
Java
aws-java-sdk-eks/src/main/java/com/amazonaws/services/eks/AbstractAmazonEKSAsync.java
rbalamohan/aws-sdk-java
82799b422d209879e56ca861efb0380a7961d532
[ "Apache-2.0" ]
1
2021-02-12T03:35:28.000Z
2021-02-12T03:35:28.000Z
aws-java-sdk-eks/src/main/java/com/amazonaws/services/eks/AbstractAmazonEKSAsync.java
rbalamohan/aws-sdk-java
82799b422d209879e56ca861efb0380a7961d532
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-eks/src/main/java/com/amazonaws/services/eks/AbstractAmazonEKSAsync.java
rbalamohan/aws-sdk-java
82799b422d209879e56ca861efb0380a7961d532
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.eks; import javax.annotation.Generated; import com.amazonaws.services.eks.model.*; /** * Abstract implementation of {@code AmazonEKSAsync}. Convenient method forms pass through to the corresponding overload * that takes a request object and an {@code AsyncHandler}, which throws an {@code UnsupportedOperationException}. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AbstractAmazonEKSAsync extends AbstractAmazonEKS implements AmazonEKSAsync { protected AbstractAmazonEKSAsync() { } @Override public java.util.concurrent.Future<CreateAddonResult> createAddonAsync(CreateAddonRequest request) { return createAddonAsync(request, null); } @Override public java.util.concurrent.Future<CreateAddonResult> createAddonAsync(CreateAddonRequest request, com.amazonaws.handlers.AsyncHandler<CreateAddonRequest, CreateAddonResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateClusterResult> createClusterAsync(CreateClusterRequest request) { return createClusterAsync(request, null); } @Override public java.util.concurrent.Future<CreateClusterResult> createClusterAsync(CreateClusterRequest request, com.amazonaws.handlers.AsyncHandler<CreateClusterRequest, CreateClusterResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateFargateProfileResult> createFargateProfileAsync(CreateFargateProfileRequest request) { return createFargateProfileAsync(request, null); } @Override public java.util.concurrent.Future<CreateFargateProfileResult> createFargateProfileAsync(CreateFargateProfileRequest request, com.amazonaws.handlers.AsyncHandler<CreateFargateProfileRequest, CreateFargateProfileResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateNodegroupResult> createNodegroupAsync(CreateNodegroupRequest request) { return createNodegroupAsync(request, null); } @Override public java.util.concurrent.Future<CreateNodegroupResult> createNodegroupAsync(CreateNodegroupRequest request, com.amazonaws.handlers.AsyncHandler<CreateNodegroupRequest, CreateNodegroupResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteAddonResult> deleteAddonAsync(DeleteAddonRequest request) { return deleteAddonAsync(request, null); } @Override public java.util.concurrent.Future<DeleteAddonResult> deleteAddonAsync(DeleteAddonRequest request, com.amazonaws.handlers.AsyncHandler<DeleteAddonRequest, DeleteAddonResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteClusterResult> deleteClusterAsync(DeleteClusterRequest request) { return deleteClusterAsync(request, null); } @Override public java.util.concurrent.Future<DeleteClusterResult> deleteClusterAsync(DeleteClusterRequest request, com.amazonaws.handlers.AsyncHandler<DeleteClusterRequest, DeleteClusterResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteFargateProfileResult> deleteFargateProfileAsync(DeleteFargateProfileRequest request) { return deleteFargateProfileAsync(request, null); } @Override public java.util.concurrent.Future<DeleteFargateProfileResult> deleteFargateProfileAsync(DeleteFargateProfileRequest request, com.amazonaws.handlers.AsyncHandler<DeleteFargateProfileRequest, DeleteFargateProfileResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteNodegroupResult> deleteNodegroupAsync(DeleteNodegroupRequest request) { return deleteNodegroupAsync(request, null); } @Override public java.util.concurrent.Future<DeleteNodegroupResult> deleteNodegroupAsync(DeleteNodegroupRequest request, com.amazonaws.handlers.AsyncHandler<DeleteNodegroupRequest, DeleteNodegroupResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeAddonResult> describeAddonAsync(DescribeAddonRequest request) { return describeAddonAsync(request, null); } @Override public java.util.concurrent.Future<DescribeAddonResult> describeAddonAsync(DescribeAddonRequest request, com.amazonaws.handlers.AsyncHandler<DescribeAddonRequest, DescribeAddonResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeAddonVersionsResult> describeAddonVersionsAsync(DescribeAddonVersionsRequest request) { return describeAddonVersionsAsync(request, null); } @Override public java.util.concurrent.Future<DescribeAddonVersionsResult> describeAddonVersionsAsync(DescribeAddonVersionsRequest request, com.amazonaws.handlers.AsyncHandler<DescribeAddonVersionsRequest, DescribeAddonVersionsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeClusterResult> describeClusterAsync(DescribeClusterRequest request) { return describeClusterAsync(request, null); } @Override public java.util.concurrent.Future<DescribeClusterResult> describeClusterAsync(DescribeClusterRequest request, com.amazonaws.handlers.AsyncHandler<DescribeClusterRequest, DescribeClusterResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeFargateProfileResult> describeFargateProfileAsync(DescribeFargateProfileRequest request) { return describeFargateProfileAsync(request, null); } @Override public java.util.concurrent.Future<DescribeFargateProfileResult> describeFargateProfileAsync(DescribeFargateProfileRequest request, com.amazonaws.handlers.AsyncHandler<DescribeFargateProfileRequest, DescribeFargateProfileResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeNodegroupResult> describeNodegroupAsync(DescribeNodegroupRequest request) { return describeNodegroupAsync(request, null); } @Override public java.util.concurrent.Future<DescribeNodegroupResult> describeNodegroupAsync(DescribeNodegroupRequest request, com.amazonaws.handlers.AsyncHandler<DescribeNodegroupRequest, DescribeNodegroupResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeUpdateResult> describeUpdateAsync(DescribeUpdateRequest request) { return describeUpdateAsync(request, null); } @Override public java.util.concurrent.Future<DescribeUpdateResult> describeUpdateAsync(DescribeUpdateRequest request, com.amazonaws.handlers.AsyncHandler<DescribeUpdateRequest, DescribeUpdateResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListAddonsResult> listAddonsAsync(ListAddonsRequest request) { return listAddonsAsync(request, null); } @Override public java.util.concurrent.Future<ListAddonsResult> listAddonsAsync(ListAddonsRequest request, com.amazonaws.handlers.AsyncHandler<ListAddonsRequest, ListAddonsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListClustersResult> listClustersAsync(ListClustersRequest request) { return listClustersAsync(request, null); } @Override public java.util.concurrent.Future<ListClustersResult> listClustersAsync(ListClustersRequest request, com.amazonaws.handlers.AsyncHandler<ListClustersRequest, ListClustersResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListFargateProfilesResult> listFargateProfilesAsync(ListFargateProfilesRequest request) { return listFargateProfilesAsync(request, null); } @Override public java.util.concurrent.Future<ListFargateProfilesResult> listFargateProfilesAsync(ListFargateProfilesRequest request, com.amazonaws.handlers.AsyncHandler<ListFargateProfilesRequest, ListFargateProfilesResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListNodegroupsResult> listNodegroupsAsync(ListNodegroupsRequest request) { return listNodegroupsAsync(request, null); } @Override public java.util.concurrent.Future<ListNodegroupsResult> listNodegroupsAsync(ListNodegroupsRequest request, com.amazonaws.handlers.AsyncHandler<ListNodegroupsRequest, ListNodegroupsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) { return listTagsForResourceAsync(request, null); } @Override public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request, com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListUpdatesResult> listUpdatesAsync(ListUpdatesRequest request) { return listUpdatesAsync(request, null); } @Override public java.util.concurrent.Future<ListUpdatesResult> listUpdatesAsync(ListUpdatesRequest request, com.amazonaws.handlers.AsyncHandler<ListUpdatesRequest, ListUpdatesResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) { return tagResourceAsync(request, null); } @Override public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request, com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) { return untagResourceAsync(request, null); } @Override public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request, com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateAddonResult> updateAddonAsync(UpdateAddonRequest request) { return updateAddonAsync(request, null); } @Override public java.util.concurrent.Future<UpdateAddonResult> updateAddonAsync(UpdateAddonRequest request, com.amazonaws.handlers.AsyncHandler<UpdateAddonRequest, UpdateAddonResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateClusterConfigResult> updateClusterConfigAsync(UpdateClusterConfigRequest request) { return updateClusterConfigAsync(request, null); } @Override public java.util.concurrent.Future<UpdateClusterConfigResult> updateClusterConfigAsync(UpdateClusterConfigRequest request, com.amazonaws.handlers.AsyncHandler<UpdateClusterConfigRequest, UpdateClusterConfigResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateClusterVersionResult> updateClusterVersionAsync(UpdateClusterVersionRequest request) { return updateClusterVersionAsync(request, null); } @Override public java.util.concurrent.Future<UpdateClusterVersionResult> updateClusterVersionAsync(UpdateClusterVersionRequest request, com.amazonaws.handlers.AsyncHandler<UpdateClusterVersionRequest, UpdateClusterVersionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateNodegroupConfigResult> updateNodegroupConfigAsync(UpdateNodegroupConfigRequest request) { return updateNodegroupConfigAsync(request, null); } @Override public java.util.concurrent.Future<UpdateNodegroupConfigResult> updateNodegroupConfigAsync(UpdateNodegroupConfigRequest request, com.amazonaws.handlers.AsyncHandler<UpdateNodegroupConfigRequest, UpdateNodegroupConfigResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateNodegroupVersionResult> updateNodegroupVersionAsync(UpdateNodegroupVersionRequest request) { return updateNodegroupVersionAsync(request, null); } @Override public java.util.concurrent.Future<UpdateNodegroupVersionResult> updateNodegroupVersionAsync(UpdateNodegroupVersionRequest request, com.amazonaws.handlers.AsyncHandler<UpdateNodegroupVersionRequest, UpdateNodegroupVersionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } }
38.824147
137
0.771836
0dade68f5cba80851f22f02a3555f8ed12da1ba2
868
cs
C#
.NETCore/ASP.NETCore/v5.0/AutoLot50/AutoLot.Web/TagHelpers/ItemDetailsTagHelper.cs
djoshi001Personal/presentations
da2198aaef595e5fa44bf71263fc418d833a4a12
[ "BSD-3-Clause", "MIT" ]
349
2017-01-17T19:58:13.000Z
2022-03-28T15:28:45.000Z
.NETCore/ASP.NETCore/v5.0/AutoLot50/AutoLot.Web/TagHelpers/ItemDetailsTagHelper.cs
MalikWaseemJaved/presentations
49c5229e9cd8b117d226fac6b2ddb8d4e3711eef
[ "BSD-3-Clause", "MIT" ]
6
2017-04-13T09:02:16.000Z
2020-05-01T12:53:27.000Z
.NETCore/ASP.NETCore/v5.0/AutoLot50/AutoLot.Web/TagHelpers/ItemDetailsTagHelper.cs
MalikWaseemJaved/presentations
49c5229e9cd8b117d226fac6b2ddb8d4e3711eef
[ "BSD-3-Clause", "MIT" ]
278
2017-03-27T22:43:55.000Z
2022-03-21T21:36:54.000Z
// Copyright Information // ================================== // AutoLot - AutoLot.Web - ItemDetailsTagHelper.cs // All samples copyright Philip Japikse // http://www.skimedic.com 2020/12/13 // ================================== using AutoLot.Web.TagHelpers.Base; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Razor.TagHelpers; namespace AutoLot.Web.TagHelpers { public class ItemDetailsTagHelper : ItemLinkTagHelperBase { public ItemDetailsTagHelper(IActionContextAccessor contextAccessor, IUrlHelperFactory urlHelperFactory) : base(contextAccessor, urlHelperFactory) { } public override void Process(TagHelperContext context, TagHelperOutput output) { BuildContent(output,"Details","text-info","Details","info-circle"); } } }
34.72
112
0.680876
01d725fb31097836b98bd8e97d0c517bc2ab9532
504
c
C
C/signal/sigtest.c
jiaoqiyuan/Tests
a3595b0e4b430d910f90e428d6b6b4465f67a059
[ "Apache-2.0" ]
null
null
null
C/signal/sigtest.c
jiaoqiyuan/Tests
a3595b0e4b430d910f90e428d6b6b4465f67a059
[ "Apache-2.0" ]
null
null
null
C/signal/sigtest.c
jiaoqiyuan/Tests
a3595b0e4b430d910f90e428d6b6b4465f67a059
[ "Apache-2.0" ]
null
null
null
#include "apue.h" static void sig_usr(int); int main(void) { if (signal(SIGUSR1, sig_usr) == SIG_ERR) printf("can't catch SIGUSR1"); if (signal(SIGUSR2, sig_usr) == SIG_ERR) printf("can't catch SIGUSR2"); for ( ; ;) pause(); return 0; } static void sig_usr(int signo) { if (signo == SIGUSR1) printf("received SIGUSR1\n"); else if (signo == SIGUSR2) printf("received SIGUSR2\n"); else printf("received signal %d\n", signo); }
22.909091
46
0.579365
319423c0d3e8c3f82381e9487fe3e6f07ae6f88d
5,429
swift
Swift
ESCore/Core/Views/Loader View/ESLoaderView.swift
EslamHanafy/ESCore
92728b9e73ca36e64cbfb54696884a09b10adf45
[ "MIT" ]
null
null
null
ESCore/Core/Views/Loader View/ESLoaderView.swift
EslamHanafy/ESCore
92728b9e73ca36e64cbfb54696884a09b10adf45
[ "MIT" ]
null
null
null
ESCore/Core/Views/Loader View/ESLoaderView.swift
EslamHanafy/ESCore
92728b9e73ca36e64cbfb54696884a09b10adf45
[ "MIT" ]
null
null
null
// // ESLoaderView.swift // EslamCore // // Created by Eslam on 11/14/16. // Copyright © 2016 Eslam. All rights reserved. // import UIKit import NVActivityIndicatorView import Alamofire import SDWebImage typealias LoaderView = ESLoaderView open class ESLoaderView: UIView { public static let shared: ESLoaderView = ESLoaderView.getInstance() @IBOutlet open var loader: NVActivityIndicatorView! @IBOutlet open var titleLabel: UILabel! @IBOutlet open var progressView: UIProgressView! open var request: Request? { didSet { if self.isHidden { request = nil } } } open var imageOperation: SDWebImageCombinedOperation? { didSet { if self.isHidden { imageOperation = nil } } } public static var request: Request? { get { return shared.request } set { shared.request = newValue } } public static var onCancel: (()->())? open override func awakeFromNib() { super.awakeFromNib() let color = UIApplication.shared.keyWindow?.tintColor ?? .white loader.color = color titleLabel.textColor = color progressView.progressTintColor = color } /// get new instance from ESLoaderView and add it to the main window /// /// - Returns: new ESLoaderView fileprivate static func getInstance() -> ESLoaderView { let window = (UIApplication.shared.delegate!.window!)! let view = currentBundle.loadNibNamed("ESLoaderView", owner: window, options: nil)?.first as! ESLoaderView view.frame = window.frame view.isHidden = true view.progressView.isHidden = true window.addSubview(view) return view } //MARK: - IBAction @IBAction func cancelAction() { displayConfirmationAlert() } } //MARK: - ESLoaderType extension ESLoaderView: ESLoaderType { public func show() { show(withTitle: nil) } public func show(withTitle title: String?) { mainQueue { [weak self] in guard let self = self else { return } if let title = title { self.titleLabel.text = title self.titleLabel.isHidden = false }else { self.titleLabel.isHidden = true } if self.isHidden { UIApplication.shared.keyWindow?.bringSubviewToFront(self) self.isHidden = false self.loader.startAnimating() } } } public func show(with request: Request? = nil, andTitle title: String? = nil) { self.request = request show(withTitle: title) } public func hide() { guard !self.isHidden else { return } mainQueue { [weak self] in guard let self = self else { return } self.cancelRequests() UIApplication.shared.keyWindow?.sendSubviewToBack(self) self.progressView.isHidden = true self.titleLabel.isHidden = true self.titleLabel.text = "" self.isHidden = true self.loader.stopAnimating() } } public func comeToWindowIfNeeded() { mainQueue { [weak self] in guard let self = self else { return } if !self.isHidden { UIApplication.shared.keyWindow?.bringSubviewToFront(self) } } } public func update(progress: Float) { mainQueue { [weak self] in guard let self = self else { return } if self.progressView.isHidden == true { self.progressView.isHidden = false } self.progressView.progress = progress } } public func cancelRequests() { self.request?.cancel() request = nil imageOperation = nil ESLoaderView.onCancel = nil } } //MARK: - Show/Hide Options public extension ESLoaderView { static func show(with request: Request?, andTitle title: String? = nil) { shared.show(with: request, andTitle: title) } static func show(withTitle title: String? = nil) { shared.show(withTitle: title) } /// hide the loader view static func hide() { shared.hide() } } //MARK: - Helpers public extension ESLoaderView { static func comeToWindowIfNeeded() { shared.comeToWindowIfNeeded() } static func update(progress: Float) { shared.update(progress: progress) } /// display cancel request confirmation alert fileprivate func displayConfirmationAlert() { let alert = UIAlertController(title: "cancel".selfLocalized, message: "cancelRequest".selfLocalized, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "yes".selfLocalized, style: .destructive, handler: { (_) in ESLoaderView.onCancel?() ESLoaderView.hide() })) alert.addAction(UIAlertAction(title: "no".selfLocalized, style: .cancel, handler: { (_) in UIApplication.shared.keyWindow?.bringSubviewToFront(self) })) UIApplication.shared.keyWindow?.sendSubviewToBack(self) currentController?.present(alert, animated: true, completion: nil) } }
28.129534
132
0.588506
e24d9f946b79be582b94d3191f42364fa4bdf6da
479
py
Python
003BranchSums/branchSums.py
GitProfAn/100DaysOfAlgo
966b2b45e46ddcace4d7e374eb0ab9a03f1787c0
[ "MIT" ]
null
null
null
003BranchSums/branchSums.py
GitProfAn/100DaysOfAlgo
966b2b45e46ddcace4d7e374eb0ab9a03f1787c0
[ "MIT" ]
null
null
null
003BranchSums/branchSums.py
GitProfAn/100DaysOfAlgo
966b2b45e46ddcace4d7e374eb0ab9a03f1787c0
[ "MIT" ]
1
2021-05-15T19:42:15.000Z
2021-05-15T19:42:15.000Z
# Solution 1 # O(n) time / O(n) space def branchSums(root): sums = [] calculateBranchSums(root, 0, sums) return sums def calculateBranchSums(node, runningSum, sums): if node is None: return sums newRunningSum = runningSum + node.value if node.left is None and node.right is None: sums.append(newRunningSum) return calculateBranchSums(node.left, newRunningSum, sums) calculateBranchSums(node.right, newRunningSum, sums)
23.95
56
0.682672
351609689f7ca71d6760d89b1de68d1896066c3d
1,855
kt
Kotlin
app/src/main/java/com/sumera/sample/ui/waituntil/WaitUntilCoreactor.kt
SumeraMartin/coreactor
ce065d6a0a6573d63ca3262ef4dee11fb3c565af
[ "MIT" ]
4
2019-10-07T06:21:21.000Z
2019-11-11T07:56:00.000Z
app/src/main/java/com/sumera/sample/ui/waituntil/WaitUntilCoreactor.kt
SumeraMartin/Coreactor
ce065d6a0a6573d63ca3262ef4dee11fb3c565af
[ "MIT" ]
null
null
null
app/src/main/java/com/sumera/sample/ui/waituntil/WaitUntilCoreactor.kt
SumeraMartin/Coreactor
ce065d6a0a6573d63ca3262ef4dee11fb3c565af
[ "MIT" ]
null
null
null
package com.sumera.sample.ui.waituntil import com.sumera.coreactor.Coreactor import com.sumera.coreactor.contract.action.Action import com.sumera.sample.ui.waituntil.contract.ConfirmAction import com.sumera.sample.ui.waituntil.contract.EnableConfirmButtonsReducer import com.sumera.sample.ui.waituntil.contract.EnableSecondButtonReducer import com.sumera.sample.ui.waituntil.contract.EnableThirdButtonReducer import com.sumera.sample.ui.waituntil.contract.FirstButtonClicked import com.sumera.sample.ui.waituntil.contract.SecondButtonClicked import com.sumera.sample.ui.waituntil.contract.SetCompletedStateReducer import com.sumera.sample.ui.waituntil.contract.SetInitialStateReducer import com.sumera.sample.ui.waituntil.contract.ThirdButtonClicked import com.sumera.sample.ui.waituntil.contract.WaitUntilState import kotlinx.coroutines.launch class WaitUntilCoreactor : Coreactor<WaitUntilState>() { override fun createInitialState() = WaitUntilState( isFirstButtonEnabled = true, isSecondButtonEnabled = false, isThirdButtonEnabled = false, isConfirmEnabled = false, isCompleted = false ) override fun onAction(action: Action<WaitUntilState>) { when (action) { FirstButtonClicked -> launch { emit { EnableSecondButtonReducer } waitUntilAction { it is SecondButtonClicked } emit { EnableThirdButtonReducer } waitUntilAction { it is ThirdButtonClicked } emit { EnableConfirmButtonsReducer } val confirmAction = waitUntilActionType<ConfirmAction>() if (confirmAction.confirmed) { emit { SetCompletedStateReducer } } else { emit { SetInitialStateReducer } } } } } }
36.372549
74
0.709434
8518dcff46a1c9e5316e62c85054db31cd52591f
1,555
cs
C#
Assets/Scripts/Contador.cs
PalaciosIgn/Unity-CS-0.1
90ea68ae4430a89d6300ef9943bbaf16c58650b6
[ "MIT" ]
null
null
null
Assets/Scripts/Contador.cs
PalaciosIgn/Unity-CS-0.1
90ea68ae4430a89d6300ef9943bbaf16c58650b6
[ "MIT" ]
null
null
null
Assets/Scripts/Contador.cs
PalaciosIgn/Unity-CS-0.1
90ea68ae4430a89d6300ef9943bbaf16c58650b6
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Contador : MonoBehaviour { [Tooltip("Tiempo iniciar en Segundos")] public int tiempoinicial; [Tooltip("Escala del Tiempo del Reloj")] [Range(-10.0f, 10.0f)] public float escalaDeTiempo = 1; public Text myText; private float TiempoFrameConTiempoScale = 0f; private float tiempoMostrarEnSegundos = 0F; private float escalaDeTiempoPausar, escalaDeTiempoInicial; void Start() { //Escala de Tiempo Original escalaDeTiempoInicial = escalaDeTiempo; myText = GetComponent<Text>(); tiempoMostrarEnSegundos = tiempoinicial; ActualizarReloj(tiempoinicial); } // Update is called once per frame void Update() { TiempoFrameConTiempoScale = Time.deltaTime * escalaDeTiempo; tiempoMostrarEnSegundos -= TiempoFrameConTiempoScale; ActualizarReloj(tiempoMostrarEnSegundos); } public void ActualizarReloj(float tiempoEnSegundos) { int minutos = 0; int segundos = 0; // int milisegundos = 0; string textoDelReloj; if (tiempoEnSegundos <= 0) tiempoEnSegundos = 0; minutos = (int)tiempoEnSegundos / 60; segundos = (int)tiempoEnSegundos % 60; //milisegundos = (int)tiempoEnSegundos / 1000; textoDelReloj = minutos.ToString("00") + ":" + segundos.ToString("00"); //+ ":" + milisegundos.ToString("00"); myText.text = textoDelReloj; } }
28.796296
118
0.664952
1a8e27474bc3a28cfed5db70340810bed09007a6
1,795
py
Python
script.py
clock21am/download_quotesandshare
c7614c2a28a32ece08bbf353bedf60d89bdd07ac
[ "Apache-2.0" ]
null
null
null
script.py
clock21am/download_quotesandshare
c7614c2a28a32ece08bbf353bedf60d89bdd07ac
[ "Apache-2.0" ]
null
null
null
script.py
clock21am/download_quotesandshare
c7614c2a28a32ece08bbf353bedf60d89bdd07ac
[ "Apache-2.0" ]
null
null
null
#!usr/bin/python import tweepy from bs4 import BeautifulSoup from urllib2 import urlopen import urllib import os import cv2 import signal #key delecrations consumer_key = '' consumer_secret_key = '' access_key = '' access_key_secret = '' url = 'http://www.wookmark.com' path = '/home/bugeater/Documents/Jugnoo/download_quotesandshare' auth = tweepy.OAuthHandler(consumer_key,consumer_secret_key); auth.set_access_token(access_key,access_key_secret); try: redirect_url = auth.get_authorization_url() except: print "failed" api = tweepy.API(auth) def make_soup(url): html = urlopen(url).read() return BeautifulSoup(html) def downloading(): soup = make_soup(url) images = [img for img in soup.findAll('img')] print(str(len(images)) + "images found.") print 'Downloading images to current working directory.' image_links = [each.get('src') for each in images] count = 0 for each in image_links: if count == 10: break else: count = count + 1 filename=each.split('/')[-1] print filename urllib.urlretrieve(each, filename) def uploadinganddelteting(): images = os.listdir(path) count = 0 for f in images[:]: if f.endswith(".jpg") or f.endswith(".png") or f.endswith(".gif"): print f; count = count + 1 break if count == 0: downloading() images = os.listdir(path) for f in images[:]: if f.endswith(".jpg") or f.endswith(".png") or f.endswith(".gif"): api.update_with_media(f); os.remove(path+'/'+f) print "done" break else: for f in images[:]: if f.endswith(".jpg") or f.endswith(".png") or f.endswith(".gif"): api.update_with_media(f); os.remove(path+'/'+f) print "done" break uploadinganddelteting()
21.369048
70
0.652368
5833bbfec467d5c2f42a5293ec0cf0f2d0f336b9
834
css
CSS
static/css/space-mono.css
bgrnwd/cartographer
162a4d675a36b2fa9b8b7870034dae20289e868d
[ "MIT" ]
null
null
null
static/css/space-mono.css
bgrnwd/cartographer
162a4d675a36b2fa9b8b7870034dae20289e868d
[ "MIT" ]
null
null
null
static/css/space-mono.css
bgrnwd/cartographer
162a4d675a36b2fa9b8b7870034dae20289e868d
[ "MIT" ]
null
null
null
@font-face { font-family: 'Space Mono'; font-style: italic; font-weight: 400; src: local('Space Mono Italic'), local('SpaceMono-Italic'), url(/font/SpaceMono-Italic) format('truetype'); } @font-face { font-family: 'Space Mono'; font-style: italic; font-weight: 700; src: local('Space Mono Bold Italic'), local('SpaceMono-BoldItalic'), url(/fonts/SpaceMono-BoldItalic) format('truetype'); } @font-face { font-family: 'Space Mono'; font-style: normal; font-weight: 400; src: local('Space Mono'), local('SpaceMono-Regular'), url(/fonts/SpaceMono-Regular) format('truetype'); } @font-face { font-family: 'Space Mono'; font-style: normal; font-weight: 700; src: local('Space Mono Bold'), local('SpaceMono-Bold'), url(/fonts/SpaceMono-Bold) format('truetype'); }
34.75
125
0.648681
1bc8cabbc8f88342c6982a3039efb4b3eb28ac7f
1,430
php
PHP
resources/views/dashboard/provider/list.blade.php
jostyftm/pos_system_api
2fc3038f70a9fdc6fd3ff1f0bf05d541c418a1db
[ "MIT" ]
null
null
null
resources/views/dashboard/provider/list.blade.php
jostyftm/pos_system_api
2fc3038f70a9fdc6fd3ff1f0bf05d541c418a1db
[ "MIT" ]
null
null
null
resources/views/dashboard/provider/list.blade.php
jostyftm/pos_system_api
2fc3038f70a9fdc6fd3ff1f0bf05d541c418a1db
[ "MIT" ]
null
null
null
@extends('layouts.dashboard') @section('title', 'Prooveedores') @section('main') <div> <div class="d-flex my-3 justify-content-between"> <div></div> <a href="{{route('providers.create')}}" class="btn btn-primary btn-sm">Nuevo proovedor</a> </div> @include('messages') <div> <table class="table"> <thead> <thead> <tr> <th>Nombre</th> <th>Nit</th> <th>Teléfono</th> <th>Email</th> <th>Acción</th> </tr> </thead> </thead> <tbody> @foreach($providers as $provider) <tr> <td>{{ $provider->name }}</td> <td>{{ $provider->nit }}</td> <td>{{ $provider->phone }}</td> <td>{{ $provider->email }}</td> <td> <a class="btn btn-sm btn-primary" href="{{route('providers.edit', $provider->id)}}" > Editar </a> </td> </tr> @endforeach </tbody> </table> {{ $providers->links() }} </div> </div> @endsection
30.425532
98
0.344056
1a300feeb1489d80c5e1aa38555ac20a50c24d8e
34
py
Python
cdot/hgvs/dataproviders/__init__.py
SACGF/seedot
1f525b163b3e2f15fc8437c4f71acc15b804cccb
[ "MIT" ]
6
2022-02-03T06:38:11.000Z
2022-02-22T08:46:56.000Z
cdot/hgvs/dataproviders/__init__.py
SACGF/seedot
1f525b163b3e2f15fc8437c4f71acc15b804cccb
[ "MIT" ]
8
2022-01-19T23:06:47.000Z
2022-02-02T06:43:09.000Z
cdot/hgvs/dataproviders/__init__.py
SACGF/cdot
1f525b163b3e2f15fc8437c4f71acc15b804cccb
[ "MIT" ]
null
null
null
from .json_data_provider import *
17
33
0.823529
2defb711e5cc59d2181a33c5448c40a804240138
55,580
cpp
C++
src/graphx_dx9.cpp
juce/taksi
154ce405d5c51429d66c5e160891afa60dd23044
[ "BSD-3-Clause" ]
2
2020-10-23T02:42:18.000Z
2021-12-08T14:01:46.000Z
src/graphx_dx9.cpp
juce/taksi
154ce405d5c51429d66c5e160891afa60dd23044
[ "BSD-3-Clause" ]
null
null
null
src/graphx_dx9.cpp
juce/taksi
154ce405d5c51429d66c5e160891afa60dd23044
[ "BSD-3-Clause" ]
null
null
null
#include <windows.h> #include "d3d9types.h" #include "d3d9.h" #define _COMPILING_MYDLL #include "mydll.h" #include "config.h" #include "log.h" #include "dinp.h" #include "shared.h" #include "util.h" #include "heap.h" #include "graphx_dx9.h" extern HINSTANCE hInst; HMODULE hD3D9 = NULL; extern HMODULE hDI; #define RESET_REL_POS 10 #define PRESENT_REL_POS 11 #define RELEASE_REL_POS -4 #define ADDREF_POS 1 #define RELEASE_POS 2 #define RESET_POS 16 #define PRESENT_POS 17 // external SHARED SEGEMENT variables extern HWND sg_hServerWnd; extern HHOOK sg_hGetMsgHook; extern BOOL sg_bHookInstalled; extern BOOL sg_bExiting; extern BOOL sg_bIgnoreOverhead; extern BOOL sg_bUnhookDevice; extern DWORD sg_reconfCounter; // global flag inidicating whether logging // and config params were initialized. extern BOOL g_initDone; // window handle of the process extern HWND hProcWnd; // Thread-specific keyboard hook extern HHOOK g_hKeyboardHook; // information about process extern MYINFO g_myinfo; // information about current state extern MYSTATE g_mystate; extern DWORD g_reconfCounter; extern TAXI_CONFIG g_config; extern DXPOINTERS g_dxInfo; BOOL g_needToUnloadLibrary = FALSE; // frame rate calculators extern float g_frameRate; extern DWORD g_skipped; extern DWORD g_lastOverhead; extern DWORD g_freq; extern DWORD g_customFrameRate; extern float g_customFrameWeight; // custom config (if any exists for current process) static TAXI_CUSTOM_CONFIG* customConfig = NULL; struct CUSTOMVERTEX { FLOAT x,y,z,w; DWORD color; }; static HANDLE procHeap = NULL; // name of the process-specific log static char logName[BUFLEN]; static IDirect3DSurface9* g_backBuffer; static D3DFORMAT g_bbFormat; static BOOL g_bGotFormat = false; static int bpp = 0; extern HANDLE videoFile; // back-buffer dimensions extern UINT g_bbWidth; extern UINT g_bbHeight; // buffer to keep current frame static BYTE* g_rgbBuf = NULL; static INT g_rgbSize = 0; static INT g_Pitch = 0; // hook-helping code holders BYTE g_codeFragment_p9[5] = {0, 0, 0, 0, 0}; BYTE g_codeFragment_r9[5] = {0, 0, 0, 0, 0}; BYTE g_jmp_p9[5] = {0, 0, 0, 0, 0}; BYTE g_jmp_r9[5] = {0, 0, 0, 0, 0}; DWORD g_savedProtection_p9 = 0; DWORD g_savedProtection_r9 = 0; // video capture parameters extern ALGORITHM_TYPE g_algorithm; typedef DWORD (STDMETHODCALLTYPE *GETPROCESSHEAPS)(DWORD, PHANDLE); static ULONG g_refCount = 1; static ULONG g_myCount = 0; static IDirect3DDevice9* g_dev = NULL; static IDirect3DVertexBuffer9* g_pVBidle = NULL; static IDirect3DVertexBuffer9* g_pVBswHook = NULL; static IDirect3DVertexBuffer9* g_pVBrec = NULL; static IDirect3DVertexBuffer9* g_pVBborder = NULL; static IDirect3DStateBlock9* g_pSavedStateBlock = 0L; static IDirect3DStateBlock9* g_pDrawTextStateBlock = 0L; /* IDirect3DDevice9 method-types */ typedef ULONG (STDMETHODCALLTYPE *ADDREF9)(IUnknown* self); typedef ULONG (STDMETHODCALLTYPE *RELEASE9)(IUnknown* self); typedef HRESULT (STDMETHODCALLTYPE *RESET9)(IDirect3DDevice9* self, LPVOID); typedef HRESULT (STDMETHODCALLTYPE *PRESENT9)(IDirect3DDevice9* self, CONST RECT*, CONST RECT*, HWND, LPVOID); /* function pointers */ static ADDREF9 g_D3D9_AddRef = NULL; static RELEASE9 g_D3D9_Release = NULL; static RESET9 g_D3D9_Reset = NULL; static PRESENT9 g_D3D9_Present = NULL; static DWORD* pAddRefPtr = NULL; static DWORD* pReleasePtr = NULL; #define IWIDTH 16.0f #define IHEIGHT 16.0f #define INDX 8.0f #define INDY 8.0f static CUSTOMVERTEX g_VertIdle[] = { {INDX, INDY, 0.0f, 1.0f, 0xff88ff00 }, // x, y, z, rhw, color {INDX, INDY+IHEIGHT, 0.0f, 1.0f, 0xff88ff00 }, // x, y, z, rhw, color {INDX+IWIDTH, INDY, 0.0f, 1.0f, 0xff88ff00 }, // x, y, z, rhw, color {INDX+IWIDTH, INDY+IHEIGHT, 0.0f, 1.0f, 0xff88ff00 }, // x, y, z, rhw, color }; static CUSTOMVERTEX g_VertSWHook[] = { {INDX, INDY, 0.0f, 1.0f, 0xff4488ff }, // x, y, z, rhw, color {INDX, INDY+IHEIGHT, 0.0f, 1.0f, 0xff4488ff }, // x, y, z, rhw, color {INDX+IWIDTH, INDY, 0.0f, 1.0f, 0xff4488ff }, // x, y, z, rhw, color {INDX+IWIDTH, INDY+IHEIGHT, 0.0f, 1.0f, 0xff4488ff }, // x, y, z, rhw, color }; static CUSTOMVERTEX g_VertRec[] = { {INDX, INDY, 0.0f, 1.0f, 0xffff4400 }, // x, y, z, rhw, color {INDX, INDY+IHEIGHT, 0.0f, 1.0f, 0xffff4400 }, // x, y, z, rhw, color {INDX+IWIDTH, INDY, 0.0f, 1.0f, 0xffff4400 }, // x, y, z, rhw, color {INDX+IWIDTH, INDY+IHEIGHT, 0.0f, 1.0f, 0xffff4400 }, // x, y, z, rhw, color }; static CUSTOMVERTEX g_VertBorder[] = { {INDX, INDY, 0.0f, 1.0f, 0xff000000 }, // x, y, z, rhw, color {INDX, INDY+IHEIGHT, 0.0f, 1.0f, 0xff000000 }, // x, y, z, rhw, color {INDX+IWIDTH, INDY+IHEIGHT, 0.0f, 1.0f, 0xff000000 }, // x, y, z, rhw, color {INDX+IWIDTH, INDY, 0.0f, 1.0f, 0xff000000 }, // x, y, z, rhw, color {INDX, INDY, 0.0f, 1.0f, 0xff000000 }, // x, y, z, rhw, color }; #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE) static HRESULT LoadSurfaceFromFile(IDirect3DSurface9* surf, char* filename); static HRESULT SaveSurfaceToFile(IDirect3DSurface9* surf, char* filename, RECT* rect); static HRESULT InvalidateDeviceObjects(IDirect3DDevice9* dev, BOOL detaching); static HRESULT DeleteDeviceObjects(IDirect3DDevice9* dev); static void DrawIndicator(LPVOID); static HRESULT JuceGetRGB(IDirect3DDevice9* d3dDevice, IDirect3DSurface9* srcSurf, RECT* rect, D3DFORMAT format, BYTE* destBuf, INT destPitch); static HRESULT JuceGetHalfSizeRGB(IDirect3DDevice9* d3dDevice, IDirect3DSurface9* srcSurf, RECT* rect, D3DFORMAT format, BYTE* destBuf, INT destPitch); EXTERN_C ULONG _declspec(dllexport) STDMETHODCALLTYPE JuceAddRef9( IUnknown* self); EXTERN_C ULONG _declspec(dllexport) STDMETHODCALLTYPE JuceRelease9( IUnknown* self); EXTERN_C HRESULT _declspec(dllexport) STDMETHODCALLTYPE JuceReset9( IDirect3DDevice9* self, LPVOID params); EXTERN_C HRESULT _declspec(dllexport) STDMETHODCALLTYPE JucePresent9( IDirect3DDevice9* self, CONST RECT* src, CONST RECT* dest, HWND hWnd, LPVOID unused); static void VerifyHooks(IDirect3DDevice9* dev); void InitHooksD9(); static void HookDeviceMethods9(HMODULE hMod); static HWND GetProcWnd(IDirect3DDevice9* d3dDevice); static void GetBackBufferInfo(IDirect3DDevice9* d3dDevice); static void MakeScreenShot(IDirect3DDevice9* d3dDevice, BYTE* rgbBuf, SIZE_T size, INT pitch); static void MakeSmallScreenShot(IDirect3DDevice9* d3dDevice, BYTE* rgbBuf, SIZE_T size, INT pitch); static void GetFrame(IDirect3DDevice9* d3dDevice, BYTE* rgbBuf, SIZE_T size, INT pitch); static HRESULT InitVB(IDirect3DDevice9* dev); static HRESULT RestoreDeviceObjects(IDirect3DDevice9* dev); // function pointer for grabbing RGB-data typedef HRESULT (*PFNGETPIXELSPROC)(IDirect3DDevice9*, IDirect3DSurface9*, RECT*, D3DFORMAT, BYTE*, INT); static PFNGETPIXELSPROC GetPixels; /////////////////////////////////////// // FUNCTIONS /////////////////////////////////////// /* This function hooks two IDirect3DDevice9 methods, using code overwriting technique. */ void HookDeviceMethods9(HMODULE hMod) { // hook IDirect3DDevice9::Present(), using code modifications at run-time. // ALGORITHM: we overwrite the beginning of real IDirect3DDevice9::Present // with a JMP instruction to our routine (JucePresent9). // When our routine gets called, first thing that it does - it restores // the original bytes of IDirect3DDevice9::Present, then performs its pre-call tasks, // then calls IDirect3DDevice9::Present, then does post-call tasks, then writes // the JMP instruction back into the beginning of IDirect3DDevice9::Present, and // returns. if (!hMod) { Log("HookDeviceMethods9: d3d9 is not loaded at this moment. No hooking performed."); return; } if (!g_dxInfo.present9 || !g_dxInfo.reset9) { Log("HookDeviceMethods9: No info on Present and/or Reset."); Log("HookDeviceMethods9: Possible reason: DirectX 9 is not installed."); return; } g_D3D9_Present = (PRESENT9)((DWORD)hMod + g_dxInfo.present9); g_D3D9_Reset = (RESET9)((DWORD)hMod + g_dxInfo.reset9); TRACE("HookDeviceMethods9: checking JMP-implants..."); if (memcmp(g_D3D9_Present, g_jmp_p9, 5)==0) { TRACE("HookDeviceMethods9: Present already has JMP-implant."); } else { TRACE2("HookDeviceMethods9: g_D3D9_Present = %08x", (DWORD)g_D3D9_Present); TRACE2("HookDeviceMethods9: JucePresent9 = %08x", (DWORD)JucePresent9); // unconditional JMP to relative address is 5 bytes. g_jmp_p9[0] = 0xe9; DWORD addr = (DWORD)JucePresent9 - (DWORD)g_D3D9_Present - 5; TRACE2("JMP %08x", addr); memcpy(g_jmp_p9 + 1, &addr, sizeof(DWORD)); memcpy(g_codeFragment_p9, g_D3D9_Present, 5); DWORD newProtection = PAGE_EXECUTE_READWRITE; if (VirtualProtect(g_D3D9_Present, 8, newProtection, &g_savedProtection_p9)) { memcpy(g_D3D9_Present, g_jmp_p9, 5); TRACE("HookDeviceMethods9: JMP-hook for Present planted."); } } if (memcmp(g_D3D9_Reset, g_jmp_r9, 5)==0) { TRACE("HookDeviceMethods9: Reset alreadry has JMP-implant."); } else { TRACE2("HookDeviceMethods9: g_D3D9_Reset = %08x", (DWORD)g_D3D9_Reset); TRACE2("HookDeviceMethods9: JuceReset9 = %08x", (DWORD)JuceReset9); // unconditional JMP to relative address is 5 bytes. g_jmp_r9[0] = 0xe9; DWORD addr = (DWORD)JuceReset9 - (DWORD)g_D3D9_Reset - 5; TRACE2("JMP %08x", addr); memcpy(g_jmp_r9 + 1, &addr, sizeof(DWORD)); memcpy(g_codeFragment_r9, g_D3D9_Reset, 5); DWORD newProtection = PAGE_EXECUTE_READWRITE; if (VirtualProtect(g_D3D9_Reset, 8, newProtection, &g_savedProtection_r9)) { memcpy(g_D3D9_Reset, g_jmp_r9, 5); TRACE("HookDeviceMethods9: JMP-hook for Reset planted."); } } } /* Restore original Reset() and Present() */ EXTERN_C _declspec(dllexport) void RestoreDeviceMethods9() { if (pAddRefPtr != NULL && g_D3D9_AddRef != NULL) *pAddRefPtr = (DWORD)g_D3D9_AddRef; if (pReleasePtr != NULL && g_D3D9_Release != NULL) *pReleasePtr = (DWORD)g_D3D9_Release; Log("RestoreDeviceMethods9: done."); } /* determine window handle */ HWND GetProcWnd(IDirect3DDevice9* d3dDevice) { TRACE("GetProcWnd: called."); D3DDEVICE_CREATION_PARAMETERS params; if (SUCCEEDED(d3dDevice->GetCreationParameters(&params))) { return params.hFocusWindow; } return NULL; } /** * Determine format of back buffer and its dimensions. */ void GetBackBufferInfo(IDirect3DDevice9* d3dDevice) { TRACE("GetBackBufferInfo: called."); // get the 0th backbuffer. if (SUCCEEDED(d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &g_backBuffer))) { D3DSURFACE_DESC desc; g_backBuffer->GetDesc(&desc); g_bbFormat = desc.Format; g_bbWidth = desc.Width; g_bbHeight = desc.Height; // check dest.surface format bpp = 0; if (g_bbFormat == D3DFMT_R8G8B8) bpp = 3; else if (g_bbFormat == D3DFMT_R5G6B5 || g_bbFormat == D3DFMT_X1R5G5B5) bpp = 2; else if (g_bbFormat == D3DFMT_A8R8G8B8 || g_bbFormat == D3DFMT_X8R8G8B8) bpp = 4; // release backbuffer g_backBuffer->Release(); Log("GetBackBufferInfo: got new back buffer format and info."); g_bGotFormat = true; } } /** * Loads the bitmap and puts on the surface. */ HRESULT LoadSurfaceFromFile(IDirect3DSurface9* surf, char* filename) { BYTE* rgbBuf = NULL; BITMAPINFOHEADER* infoheader = NULL; if (FAILED(LoadFromBMP(filename, procHeap, &rgbBuf, &infoheader))) { Log("LoadSurfaceFromFile: LoadFromBMP failed."); return E_FAIL; } D3DSURFACE_DESC desc; if (FAILED(surf->GetDesc(&desc))) { Log("LoadSurfaceFromFile: GetDesc failed for dest.surface."); return E_FAIL; } if (infoheader->biBitCount < 24) { Log("LoadSurfaceFromFile: can only work with 24-bit bitmaps."); return E_FAIL; } INT bytes = infoheader->biWidth * infoheader->biBitCount / 8; INT rem = bytes % sizeof(ULONG); INT srcPitch = (rem == 0) ? bytes : bytes + sizeof(ULONG) - rem; INT width = infoheader->biWidth; INT height = infoheader->biHeight; LogWithNumber("LoadSurfaceFromFile: width = %d", width); LogWithNumber("LoadSurfaceFromFile: height = %d", height); D3DLOCKED_RECT destLockedRect; RECT rect = {0, 0, width, height}; // lock rect if (FAILED(surf->LockRect(&destLockedRect, &rect, 0))) { Log("LoadSurfaceFromFile: failed to lock rect."); return E_FAIL; } BYTE* destPtr = (BYTE*)destLockedRect.pBits; INT destPitch = destLockedRect.Pitch; // write data int i,j,k; BYTE b0, b1, b2; switch (desc.Format) { case D3DFMT_X1R5G5B5: Log("LoadSurfaceFromFile: desc.Format = D3DFMT_X1R5G5B5"); // 16-bit target surface: we need to do some conversion for (i=0, k=height-1; i<height, k>=0; i++, k--) { for (j=0; j<width; j++) { b0 = rgbBuf[k*srcPitch + j*3]; // blue b1 = rgbBuf[k*srcPitch + j*3 + 1]; // green b2 = rgbBuf[k*srcPitch + j*3 + 2]; // red // memory layout 24 bit: // -------------------------------------------------- // Lo Hi Lo Hi Lo Hi // b0b1b2b3b4b5b6b7 g0g1g2g3g4g5g6g7 r0r1r2r3r4r5r6r7 // -------------------------------------------------- // blue green red // // turns into:-> // // memory layout 16 bit: // --------------------------------- // Lo Hi Lo Hi // b3b4b5b6b7g3g4g5 g6g7r3r4r5r6r700 // --------------------------------- // blue green red destPtr[i*destPitch + j*2] = ((b0 >> 3) & 0x1f) | ((b1 << 2) & 0xe0); destPtr[i*destPitch + j*2 + 1] = ((b1 >> 6) & 0x03) | ((b2 >> 1) & 0x7c); } } break; case D3DFMT_R5G6B5: Log("LoadSurfaceFromFile: desc.Format = D3DFMT_R5G6B5"); // 16-bit target surface: we need to do some conversion for (i=0, k=height-1; i<height, k>=0; i++, k--) { for (j=0; j<width; j++) { b0 = rgbBuf[k*srcPitch + j*3]; // blue b1 = rgbBuf[k*srcPitch + j*3 + 1]; // green b2 = rgbBuf[k*srcPitch + j*3 + 2]; // red // memory layout 24 bit: // -------------------------------------------------- // Lo Hi Lo Hi Lo Hi // b0b1b2b3b4b5b6b7 g0g1g2g3g4g5g6g7 r0r1r2r3r4r5r6r7 // -------------------------------------------------- // blue green red // // turns into:-> // // memory layout 16 bit: // --------------------------------- // Lo Hi Lo Hi // b3b4b5b6b7g2g3g4 g5g6g7r3r4r5r6r7 // --------------------------------- // blue green red destPtr[i*destPitch + j*2] = ((b0 >> 3) & 0x1f) | ((b1 << 3) & 0xe0); destPtr[i*destPitch + j*2 + 1] = ((b1 >> 5) & 0x07) | (b2 & 0xf8); } } break; case D3DFMT_R8G8B8: Log("LoadSurfaceFromFile: desc.Format = D3DFMT_R8G8B8"); // 24-bit target surface: straight copy for (i=0, k=height-1; i<height, k>=0; i++, k--) { memcpy(destPtr + i*destPitch, rgbBuf + k*srcPitch, bytes); } break; case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: Log("LoadSurfaceFromFile: desc.Format = D3DFMT_A8R8G8B8 or D3DFMT_X8R8G8B8"); // 32-bit target surface: we need to do some conversion for (i=0, k=height-1; i<height, k>=0; i++, k--) { for (j=0; j<width; j++) { destPtr[i*destPitch + j*4] = rgbBuf[k*srcPitch + j*3]; destPtr[i*destPitch + j*4 + 1] = rgbBuf[k*srcPitch + j*3 + 1]; destPtr[i*destPitch + j*4 + 2] = rgbBuf[k*srcPitch + j*3 + 2]; destPtr[i*destPitch + j*4 + 3] = 0xff; } } break; default: Log("LoadSurfaceFromFile: surface format not supported."); return E_FAIL; } // unlock rect if (FAILED(surf->UnlockRect())) { Log("LoadSurfaceFromFile: failed to unlock rect."); return E_FAIL; } // release memory if (rgbBuf != NULL) HeapFree(procHeap, 0, rgbBuf); if (infoheader != NULL) HeapFree(procHeap, 0, infoheader); return S_OK; } /** * Saves the surface into bitmap file. */ HRESULT SaveSurfaceToFile(IDirect3DSurface9* surf, char* filename, RECT* rect) { D3DSURFACE_DESC desc; if (FAILED(surf->GetDesc(&desc))) { Log("SaveSurfaceToFile: GetDesc failed for surface."); return E_FAIL; } // allocate buffer for pixel data INT width = rect->right - rect->left; INT height = rect->bottom - rect->top; INT bytes = width * 3; INT rem = bytes % sizeof(ULONG); INT pitch = (rem == 0) ? bytes : bytes + sizeof(ULONG) - rem; SIZE_T size = pitch * height; //LogWithNumber("SaveSurfaceToFile: bytes = %d", bytes); //LogWithNumber("SaveSurfaceToFile: pitch = %d", pitch); //LogWithNumber("SaveSurfaceToFile: size = %d", size); BYTE* rgbBuf = (BYTE*)HeapAlloc(procHeap, HEAP_ZERO_MEMORY, size); //LogWithNumber("SaveSurfaceToFile: rgbBuf = %d", (DWORD)rgbBuf); // get RGB data INT bpp; IDirect3DDevice9* d3dDevice; if (FAILED(surf->GetDevice(&d3dDevice))) { Log("SaveSurfaceToFile: GetDevice failed for surface."); return E_FAIL; } if (FAILED(JuceGetRGB(d3dDevice, surf, rect, desc.Format, rgbBuf, pitch))) { Log("SaveSurfaceToFile: JuceGetRGB failed for surface."); return E_FAIL; } // save the bitmap if (FAILED(SaveAsBMP(NULL, rgbBuf, size, width, height, 3))) { Log("SaveSurfaceToFile: SaveAsBMP failed."); return E_FAIL; } if (rgbBuf) HeapFree(procHeap, 0, rgbBuf); return S_OK; } /* Makes a screen shot from back buffer. Doesn't use D3DX functions.*/ void MakeScreenShot(IDirect3DDevice9* d3dDevice, BYTE* rgbBuf, SIZE_T size, INT pitch) { IDirect3DSurface9* buffer; if (FAILED(d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &buffer))) { Log("MakeScreenShot: failed to get back-buffer"); return; } // get pixels from the backbuffer into the new buffer RECT rect = {0, 0, g_bbWidth, g_bbHeight}; if (FAILED(JuceGetRGB(d3dDevice, buffer, &rect, g_bbFormat, rgbBuf, pitch))) { Log("MakeScreenShot: unable to get RGB-data"); return; } // save as bitmap LONG width = rect.right - rect.left; LONG height = rect.bottom - rect.top; if (FAILED(SaveAsBMP(NULL, rgbBuf, size, width, height, 3))) { Log("MakeScreenShot: SaveAsBMP failed."); return; } // release back-buffer buffer->Release(); } /* Makes a small screen shot (1/2 original size) from back buffer. Doesn't use D3DX functions.*/ void MakeSmallScreenShot(IDirect3DDevice9* d3dDevice, BYTE* rgbBuf, SIZE_T size, INT pitch) { IDirect3DSurface9* buffer; if (FAILED(d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &buffer))) { Log("MakeSmallScreenShot: failed to get back-buffer"); return; } // get pixels from the backbuffer into the new buffer int bpp = 0; RECT rect = {0, 0, g_bbWidth, g_bbHeight}; if (FAILED(JuceGetHalfSizeRGB(d3dDevice, buffer, &rect, g_bbFormat, rgbBuf, pitch))) { Log("MakeSmallScreenShot: unable to get RGB-data"); return; } // save as bitmap LONG width = rect.right - rect.left; LONG height = rect.bottom - rect.top; if (FAILED(SaveAsBMP(NULL, rgbBuf, size, width/2, height/2, 3))) { Log("MakeSmallScreenShot: SaveAsBMP failed."); return; } // release back-buffer buffer->Release(); } /* Makes a small screen shot (1/2 original size) from back buffer. Doesn't use D3DX functions.*/ void GetFrame(IDirect3DDevice9* d3dDevice, BYTE* rgbBuf, SIZE_T size, INT pitch) { IDirect3DSurface9* buffer; if (FAILED(d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &buffer))) { Log("GetFrame: failed to get back-buffer"); return; } // get pixels from the backbuffer into the new buffer int bpp = 0; RECT rect = {0, 0, g_bbWidth, g_bbHeight}; if (FAILED(GetPixels(d3dDevice, buffer, &rect, g_bbFormat, rgbBuf, pitch))) { Log("GetFrame: unable to get RGB-data"); return; } // release back-buffer buffer->Release(); } /* New Reset function */ EXTERN_C HRESULT _declspec(dllexport) STDMETHODCALLTYPE JuceReset9( IDirect3DDevice9* self, LPVOID params) { TRACE("#################################"); TRACE("JuceReset9: called."); Log("JuceReset9: cleaning-up."); BYTE* codeDest = (BYTE*)g_D3D9_Reset; // put back saved code fragment codeDest[0] = g_codeFragment_r9[0]; *((DWORD*)(codeDest + 1)) = *((DWORD*)(g_codeFragment_r9 + 1)); // drop HWND hProcWnd = NULL; // if in recording mode, close the AVI file, // and set the flag so that the next Present() will continue. if (g_mystate.bNowRecording) { CloseAVIFile(videoFile); g_mystate.bNowRecording = false; Log("Recording stopped. (Reset is called)."); g_mystate.bStartRecording = true; } // clean-up if (g_rgbBuf != NULL) { HeapFree(procHeap, 0, g_rgbBuf); g_rgbBuf = NULL; } InvalidateDeviceObjects(self, false); DeleteDeviceObjects(self); g_bGotFormat = false; /* call real Present() */ HRESULT res = g_D3D9_Reset(self, params); VerifyHooks(self); TRACE("JuceReset9: Reset() is done. About to return."); // put JMP instruction again codeDest[0] = g_jmp_r9[0]; *((DWORD*)(codeDest + 1)) = *((DWORD*)(g_jmp_r9 + 1)); return res; } /* New AddRef function */ EXTERN_C ULONG _declspec(dllexport) STDMETHODCALLTYPE JuceAddRef9(IUnknown* self) { g_refCount = g_D3D9_AddRef(self); TRACE2("JuceAddRef9: called (g_refCount = %d).", g_refCount); return g_refCount; } /* New Release function */ EXTERN_C ULONG _declspec(dllexport) STDMETHODCALLTYPE JuceRelease9(IUnknown* self) { // a "fall-through" case if ((g_refCount > g_myCount + 1) && g_D3D9_Release) { g_refCount = g_D3D9_Release(self); TRACE2("JuceRelease9: called (g_refCount = %d).", g_refCount); return g_refCount; } TRACE("+++++++++++++++++++++++++++++++++++++"); TRACE("JuceRelease9: called."); TRACE2("JuceRelease9: self = %08x", (DWORD)self); TRACE2("JuceRelease9: VTABLE[0] = %08x", ((DWORD*)(*((DWORD*)self)))[0]); TRACE2("JuceRelease9: VTABLE[1] = %08x", ((DWORD*)(*((DWORD*)self)))[1]); TRACE2("JuceRelease9: VTABLE[2] = %08x", ((DWORD*)(*((DWORD*)self)))[2]); // if in recording mode, close the AVI file, // and set the flag so that the next Present() will continue. if (g_mystate.bNowRecording) { CloseAVIFile(videoFile); g_mystate.bNowRecording = false; Log("Recording stopped. (Reset is called)."); g_mystate.bStartRecording = true; } // unhook device methods RestoreDeviceMethods9(); // clean up IDirect3DDevice9* dev = (IDirect3DDevice9*)self; InvalidateDeviceObjects(dev, false); DeleteDeviceObjects(dev); // reset the pointers pAddRefPtr = NULL; pReleasePtr = NULL; // call the real Release() TRACE("JuceRelease9: about to call real Release."); g_refCount = g_D3D9_Release(self); TRACE("JuceRelease9: real Release done."); TRACE2("JuceRelease9: g_refCount = %d", g_refCount); TRACE("JuceRelease9() done."); return g_refCount; } /* New Present function */ EXTERN_C HRESULT _declspec(dllexport) STDMETHODCALLTYPE JucePresent9( IDirect3DDevice9* self, CONST RECT* src, CONST RECT* dest, HWND hWnd, LPVOID unused) { TRACE("--------------------------------"); TRACE("JucePresent9: called."); /* log the usage */ //Log("JucePresent9: Present() is about to be called."); BYTE* codeDest = (BYTE*)g_D3D9_Present; // put back saved code fragment codeDest[0] = g_codeFragment_p9[0]; *((DWORD*)(codeDest + 1)) = *((DWORD*)(g_codeFragment_p9 + 1)); // rememeber IDirect3DDevice9::Release pointer so that we can clean-up properly. if (pAddRefPtr == NULL || pReleasePtr == NULL) { DWORD* vtable = (DWORD*)(*((DWORD*)self)); pAddRefPtr = vtable + 1; pReleasePtr = vtable + 2; TRACE2("*pAddRefPtr = %08x", *pAddRefPtr); TRACE2("*pReleasePtr = %08x", *pReleasePtr); // hook AddRef method g_D3D9_AddRef = (RELEASE9)(*pAddRefPtr); *pAddRefPtr = (DWORD)JuceAddRef9; // hook Release method g_D3D9_Release = (RELEASE9)(*pReleasePtr); *pReleasePtr = (DWORD)JuceRelease9; } // determine whether this frame needs to be grabbed when recording. DWORD frameDups = GetFrameDups(); // determine backbuffer's format and dimensions, if not done yet. if (!g_bGotFormat) GetBackBufferInfo(self); TRACE("JucePresent9: new frame."); // determine how we are going to handle keyboard hot-keys: // Use DirectInput, if configured so, // Otherwise use thread-specific keyboard hook. if (!g_mystate.bKeyboardInitDone) { if (g_config.useDirectInput) { hDI = (HINSTANCE)GetModuleHandle("dinput8.dll"); if (!hDI) hDI = (HINSTANCE)LoadLibrary("dinput8.dll"); if (hDI) { TRACE("JucePresent9: KEYBOARD INIT: using DirectInput."); GetDirectInputCreator(); // install dummy keyboard hook so that we don't get unmapped, // when going to exclusive mode (i.e. unhooking GetMsgProc) if (hProcWnd == NULL) hProcWnd = GetProcWnd(self); DWORD tid = GetWindowThreadProcessId(hProcWnd, NULL); InstallDummyKeyboardHook(tid); g_mystate.bKeyboardInitDone = TRUE; } else { TRACE("JucePresent9: KEYBOARD INIT: Unable to load dinput8.dll."); } } // if we're not done at this point, use keyboard hook if (!g_mystate.bKeyboardInitDone) { TRACE("JucePresent9: KEYBOARD INIT: using keyboard hook."); // install keyboard hook if (hProcWnd == NULL) hProcWnd = GetProcWnd(self); DWORD tid = GetWindowThreadProcessId(hProcWnd, NULL); InstallKeyboardHook(tid); } // Goto "exclusive" mode (i.e. unhook GetMsgProc) // if specified so in the g_mystate if (g_mystate.bUnhookGetMsgProc) { Log("JucePresent9: Signaling to unhook GetMsgProc."); if (UninstallTheHook()) { Log("JucePresent9: GetMsgProc unhooked."); // change indicator to "green" } g_mystate.bUnhookGetMsgProc = FALSE; } // keyboard configuration done g_mystate.bKeyboardInitDone = TRUE; } // Process DirectInput input if (g_config.useDirectInput) ProcessDirectInput(&g_config); // Open AVI file, if asked so. if (g_mystate.bStartRecording) { TRACE("JucePresent9: calling OpenAVIFile."); videoFile = OpenAVIFile(); g_mystate.bStartRecording = false; Log("Recording started."); g_mystate.bNowRecording = true; } // Close AVI file, if asked so. else if (g_mystate.bStopRecording) { TRACE("JucePresent9: calling CloseAVIFile."); CloseAVIFile(videoFile); g_mystate.bStopRecording = false; Log("Recording stopped."); g_mystate.bNowRecording = false; } /* make custom screen shot, if requested so. */ else if (g_mystate.bMakeScreenShot) { //DWORD start, stop; //start = GetTickCount(); // allocate buffer for pixel data INT bytes = g_bbWidth * 3; INT rem = bytes % sizeof(ULONG); INT pitch = (rem == 0) ? bytes : bytes + sizeof(ULONG) - rem; SIZE_T size = pitch * g_bbHeight; BYTE* rgbBuf = (BYTE*)HeapAlloc(procHeap, HEAP_ZERO_MEMORY, size); // shoot MakeScreenShot(self, rgbBuf, size, pitch); // free the buffer HeapFree(procHeap, 0, rgbBuf); g_mystate.bMakeScreenShot = false; //stop = GetTickCount(); //LogWithNumber("MakeScreenShot: %d ticks", (stop-start)); } /* make small screen shot, if requested so. */ else if (g_mystate.bMakeSmallScreenShot) { //DWORD start, stop; //start = GetTickCount(); // allocate buffer for pixel data INT bytes = g_bbWidth / 2 * 3; INT rem = bytes % sizeof(ULONG); INT pitch = (rem == 0) ? bytes : bytes + sizeof(ULONG) - rem; SIZE_T size = pitch * g_bbHeight / 2; BYTE* rgbBuf = (BYTE*)HeapAlloc(procHeap, HEAP_ZERO_MEMORY, size); // shoot MakeSmallScreenShot(self, rgbBuf, size, pitch); // free the buffer HeapFree(procHeap, 0, rgbBuf); g_mystate.bMakeSmallScreenShot = false; //stop = GetTickCount(); //LogWithNumber("MakeSmallScreenShot: %d ticks", (stop-start)); } TRACE2("g_mystate.bNowRecording = %d", g_mystate.bNowRecording); /* write AVI-file, if in recording mode. */ if (g_mystate.bNowRecording) { if (frameDups > 0) { DWORD start = QPC(); if (g_rgbBuf == NULL) { INT divider = (g_config.fullSizeVideo) ? 1 : 2; // allocate buffer for pixel data INT bytes = g_bbWidth / divider * 3; INT rem = bytes % sizeof(ULONG); g_Pitch = (rem == 0) ? bytes : bytes + sizeof(ULONG) - rem; g_rgbSize = g_Pitch * g_bbHeight / divider; g_rgbBuf = (BYTE*)HeapAlloc(procHeap, HEAP_ZERO_MEMORY, g_rgbSize); } // shoot a frame TRACE("Getting FRAME"); GetFrame(self, g_rgbBuf, g_rgbSize, g_Pitch); TRACE("Got FRAME"); WriteAVIFrame(videoFile, g_rgbBuf, g_rgbSize, frameDups); // keep track of recording overhead DWORD stop = QPC(); g_lastOverhead = stop - start; g_skipped = 1; g_frameRate = 0.0; } else { g_skipped++; } } /* draw the indicator */ if (g_mystate.bIndicate || g_mystate.bNowRecording) DrawIndicator(self); /* call real Present() */ HRESULT res = g_D3D9_Present(self, src, dest, hWnd, unused); /* check unhook flag */ //TRACE2("JucePresent9: sg_bUnhookDevice = %d.", GetUnhookFlag()); if (GetUnhookFlag()) { // we're ordered to unhook IDirect3DDevice9 methods. RestoreDeviceMethods9(); // uninstall keyboard hook UninstallKeyboardHook(); } /* check if we need to reconfigure */ if (sg_reconfCounter != g_reconfCounter && !g_mystate.bNowRecording) { Log("JucePresent9: Reconfiguring custom settings..."); g_algorithm = SearchCustomConfig(g_myinfo.processfile, g_myinfo.dir, &customConfig) ? CUSTOM : ADAPTIVE; if (customConfig) { g_customFrameRate = customConfig->frameRate; g_customFrameWeight = customConfig->frameWeight; } g_reconfCounter = sg_reconfCounter; } VerifyHooks(self); TRACE("JucePresent9: Present() is done. About to return."); // put JMP instruction again codeDest[0] = g_jmp_p9[0]; *((DWORD*)(codeDest + 1)) = *((DWORD*)(g_jmp_p9 + 1)); return res; } HRESULT InitVB(IDirect3DDevice9* dev) { VOID* pVertices; // create vertex buffer for green light if (FAILED(dev->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVBidle, NULL))) { Log("CreateVertexBuffer() failed."); return E_FAIL; } Log("CreateVertexBuffer() done."); g_myCount++; if (FAILED(g_pVBidle->Lock(0, sizeof(g_VertIdle), &pVertices, 0))) { Log("g_pVBidle->Lock() failed."); return E_FAIL; } memcpy(pVertices, g_VertIdle, sizeof(g_VertIdle)); g_pVBidle->Unlock(); // create vertex buffer for blue light if (FAILED(dev->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVBswHook, NULL))) { Log("CreateVertexBuffer() failed."); return E_FAIL; } Log("CreateVertexBuffer() done."); g_myCount++; if (FAILED(g_pVBswHook->Lock(0, sizeof(g_VertSWHook), &pVertices, 0))) { Log("g_pVBswHook->Lock() failed."); return E_FAIL; } memcpy(pVertices, g_VertSWHook, sizeof(g_VertSWHook)); g_pVBswHook->Unlock(); // create vertex buffer for red light if (FAILED(dev->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVBrec, NULL))) { Log("CreateVertexBuffer() failed."); return E_FAIL; } Log("CreateVertexBuffer() done."); g_myCount++; if (FAILED(g_pVBrec->Lock(0, sizeof(g_VertRec), &pVertices, 0))) { Log("g_pVrec->Lock() failed."); return E_FAIL; } memcpy(pVertices, g_VertRec, sizeof(g_VertRec)); g_pVBrec->Unlock(); // create vertex buffer for black border if (FAILED(dev->CreateVertexBuffer(5*sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVBborder, NULL))) { Log("CreateVertexBuffer() failed."); return E_FAIL; } Log("CreateVertexBuffer() done."); g_myCount++; if (FAILED(g_pVBborder->Lock(0, sizeof(g_VertBorder), &pVertices, 0))) { Log("g_pVBborder->Lock() failed."); return E_FAIL; } memcpy(pVertices, g_VertBorder, sizeof(g_VertBorder)); g_pVBborder->Unlock(); return S_OK; } //----------------------------------------------------------------------------- // Name: RestoreDeviceObjects() // Desc: //----------------------------------------------------------------------------- HRESULT RestoreDeviceObjects(IDirect3DDevice9* dev) { g_dev = dev; HRESULT hr = InitVB(dev); if (FAILED(hr)) { Log("InitVB() failed."); return hr; } Log("InitVB() done."); D3DVIEWPORT9 vp; vp.X = 0; vp.Y = 0; vp.Width = INDX*2 + IWIDTH; vp.Height = INDY*2 + IHEIGHT; vp.MinZ = 0.0f; vp.MaxZ = 1.0f; // Create the state blocks for rendering text for( UINT which=0; which<2; which++ ) { dev->BeginStateBlock(); dev->SetViewport( &vp ); dev->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE ); dev->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); dev->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); dev->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW ); dev->SetRenderState( D3DRS_STENCILENABLE, FALSE ); dev->SetRenderState( D3DRS_CLIPPING, TRUE ); dev->SetRenderState( D3DRS_CLIPPLANEENABLE, FALSE ); dev->SetRenderState( D3DRS_FOGENABLE, FALSE ); dev->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_DISABLE ); dev->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); dev->SetVertexShader( NULL ); dev->SetFVF( D3DFVF_CUSTOMVERTEX ); dev->SetPixelShader ( NULL ); dev->SetStreamSource( 0, g_pVBidle, 0, sizeof(CUSTOMVERTEX) ); if( which==0 ) { dev->EndStateBlock( &g_pSavedStateBlock ); g_myCount++; } else { dev->EndStateBlock( &g_pDrawTextStateBlock ); g_myCount++; } } return S_OK; } //----------------------------------------------------------------------------- // Name: InvalidateDeviceObjects() // Desc: Destroys all device-dependent objects //----------------------------------------------------------------------------- HRESULT InvalidateDeviceObjects(IDirect3DDevice9* dev, BOOL detaching) { TRACE("InvalidateDeviceObjects: called."); //if (detaching) return S_OK; // Delete the state blocks //if( dev && !detaching ) { SAFE_RELEASE2( g_pSavedStateBlock, g_myCount ); SAFE_RELEASE2( g_pDrawTextStateBlock, g_myCount ); Log("InvalidateDeviceObjects: DeleteStateBlock(s) done."); } SAFE_RELEASE2( g_pVBidle, g_myCount ); SAFE_RELEASE2( g_pVBswHook, g_myCount ); SAFE_RELEASE2( g_pVBborder, g_myCount ); SAFE_RELEASE2( g_pVBrec, g_myCount ); Log("InvalidateDeviceObjects: SAFE_RELEASE(s) done."); Log("InvalidateDeviceObjects: done."); return S_OK; } //----------------------------------------------------------------------------- // Name: DeleteDeviceObjects() // Desc: Destroys all device-dependent objects //----------------------------------------------------------------------------- HRESULT DeleteDeviceObjects(IDirect3DDevice9* dev) { return S_OK; } void DrawIndicator(LPVOID self) { IDirect3DDevice9* dev = (IDirect3DDevice9*)self; if (g_pVBidle == NULL) { if (FAILED(RestoreDeviceObjects(dev))) { Log("RestoreDeviceObjects() failed."); } Log("RestoreDeviceObjects() done."); } // setup renderstate g_pSavedStateBlock->Capture(); g_pDrawTextStateBlock->Apply(); // render dev->BeginScene(); if (g_mystate.bNowRecording) dev->SetStreamSource( 0, g_pVBrec, 0, sizeof(CUSTOMVERTEX) ); else if (g_mystate.bSystemWideMode) dev->SetStreamSource( 0, g_pVBswHook, 0, sizeof(CUSTOMVERTEX) ); else dev->SetStreamSource( 0, g_pVBidle, 0, sizeof(CUSTOMVERTEX) ); dev->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 ); dev->SetStreamSource( 0, g_pVBborder, 0, sizeof(CUSTOMVERTEX) ); dev->DrawPrimitive( D3DPT_LINESTRIP, 0, 4 ); dev->EndScene(); // restore the modified renderstates g_pSavedStateBlock->Apply(); } /* Copies pixel's RGB data into dest buffer. Alpha information is discarded. */ HRESULT JuceGetRGB(IDirect3DDevice9* d3dDevice, IDirect3DSurface9* srcSurf, RECT* rect, D3DFORMAT format, BYTE* destBuf, INT destPitch) { //Log("JuceGetRGB: called."); // check dest.surface format if (!(format == D3DFMT_R8G8B8 || format == D3DFMT_A8R8G8B8 || format == D3DFMT_X8R8G8B8 || format == D3DFMT_R5G6B5 || format == D3DFMT_X1R5G5B5)) { Log("JuceGetRGB: surface format not supported."); return E_FAIL; } D3DLOCKED_RECT lockedSrcRect; int width = rect->right - rect->left; int height = rect->bottom - rect->top; // copy rect to a new surface and lock the rect there. // NOTE: apparently, this works faster than locking a rect on the back buffer itself. // LOOKS LIKE: reading from the backbuffer is faster via GetRenderTargetData, but writing // is faster if done directly. IDirect3DSurface9* surf = NULL; if (FAILED(d3dDevice->CreateOffscreenPlainSurface( width, height, format, D3DPOOL_SYSTEMMEM, &surf, NULL))) { Log("JuceGetRGB: Unable to create image surface."); return E_FAIL; } POINT points[] = {{0, 0}}; //Log("JuceGetRGB: created image surface."); //LogWithNumber("JuceGetRGB: d3dDevice = %d", (DWORD)d3dDevice); //LogWithNumber("JuceGetRGB: srcSurf = %d", (DWORD)srcSurf); //LogWithNumber("JuceGetRGB: rect = %d", (DWORD)rect); //LogWithNumber("JuceGetRGB: imgSurf = %d", (DWORD)imgSurf); //LogWithNumber("JuceGetRGB: points = %d", (DWORD)points); if (FAILED(d3dDevice->GetRenderTargetData(srcSurf, surf))) { Log("JuceGetRGB: GetRenderTargetData() failed for image surface."); return E_FAIL; } //Log("JuceGetRGB: copied rects."); //DWORD start = GetTickCount(); RECT newRect = {0, 0, width, height}; if (FAILED(surf->LockRect(&lockedSrcRect, &newRect, 0))) { Log("JuceGetRGB: Unable to lock source rect."); return E_FAIL; } //Log("JuceGetRGB: locked rect."); //DWORD stop = GetTickCount(); //LogWithNumber("JuceGetRGB: LockRect = %d ticks", (stop-start)); // copy data //start = GetTickCount(); BYTE* pSrcRow = (BYTE*)lockedSrcRect.pBits; INT srcPitch = lockedSrcRect.Pitch; //LogWithNumber("width = %d", width); //LogWithNumber("height = %d", width); //LogWithNumber("srcPitch = %d", srcPitch); //LogWithNumber("destPitch = %d", destPitch); int i, j, k; BYTE b0, b1; switch (format) { case D3DFMT_R8G8B8: Log("JuceGetRGB: source format = D3DFMT_R8G8B8"); // 24-bit: straight copy for (i=0, k=height-1; i<height, k>=0; i++, k--) { memcpy(destBuf + i*destPitch, pSrcRow + k*srcPitch, 3*width); } break; case D3DFMT_X1R5G5B5: Log("JuceGetRGB: source format = D3DFMT_X1R5G5B5"); // 16-bit: some conversion needed. for (i=0, k=height-1; i<height, k>=0; i++, k--) { for (j=0; j<width; j++) { b0 = pSrcRow[k*srcPitch + j*2]; b1 = pSrcRow[k*srcPitch + j*2 + 1]; // memory layout 16 bit: // --------------------------------- // Lo Hi Lo Hi // b3b4b5b6b7g3g4g5 g6g7r3r4r5r6r700 // --------------------------------- // blue green red // // turns into:-> // // memory layout 24 bit: // -------------------------------------------------- // Lo Hi Lo Hi Lo Hi // 000000b3b4b5b6b7 000000g3g4g5g6g7 000000r3r4r5r6r7 // -------------------------------------------------- // blue green red destBuf[i*destPitch + j*3] = (b0 << 3) & 0xf8; destBuf[i*destPitch + j*3 + 1] = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); destBuf[i*destPitch + j*3 + 2] = (b1 << 1) & 0xf8; } } break; case D3DFMT_R5G6B5: Log("JuceGetRGB: source format = D3DFMT_R5G6B5"); // 16-bit: some conversion needed. for (i=0, k=height-1; i<height, k>=0; i++, k--) { for (j=0; j<width; j++) { b0 = pSrcRow[k*srcPitch + j*2]; b1 = pSrcRow[k*srcPitch + j*2 + 1]; // memory layout 16 bit: // --------------------------------- // Lo Hi Lo Hi // b3b4b5b6b7g2g3g4 g5g6g7r3r4r5r6r7 // --------------------------------- // blue green red // // turns into:-> // // memory layout 24 bit: // -------------------------------------------------- // Lo Hi Lo Hi Lo Hi // 000000b3b4b5b6b7 000000g3g4g5g6g7 000000r3r4r5r6r7 // -------------------------------------------------- // blue green red destBuf[i*destPitch + j*3] = (b0 << 3) & 0xf8; destBuf[i*destPitch + j*3 + 1] = ((b0 >> 3) & 0x1c) | ((b1 << 5) & 0xe0); destBuf[i*destPitch + j*3 + 2] = b1 & 0xf8; } } break; case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: Log("JuceGetRGB: source format = D3DFMT_A8R8G8B8 or D3DFMT_X8R8G8B8"); // 32-bit entries: discard alpha for (i=0, k=height-1; i<height, k>=0; i++, k--) { for (j=0; j<width; j++) { destBuf[i*destPitch + j*3] = pSrcRow[k*srcPitch + j*4]; destBuf[i*destPitch + j*3 + 1] = pSrcRow[k*srcPitch + j*4 + 1]; destBuf[i*destPitch + j*3 + 2] = pSrcRow[k*srcPitch + j*4 + 2]; } } break; } //stop = GetTickCount(); //LogWithNumber("JuceGetRGB: copy data = %d ticks", (stop-start)); // unlock rect //start = GetTickCount(); surf->UnlockRect(); //stop = GetTickCount(); //LogWithNumber("JuceGetRGB: UnlockRect = %d ticks", (stop-start)); // release surface surf->Release(); return S_OK; } /* Copies pixel's RGB data into dest buffer. Alpha information is discarded. */ HRESULT JuceGetHalfSizeRGB(IDirect3DDevice9* d3dDevice, IDirect3DSurface9* srcSurf, RECT* rect, D3DFORMAT format, BYTE* destBuf, INT destPitch) { //Log("JuceGetHalfSizeRGB: called."); // check dest.surface format if (!(format == D3DFMT_R8G8B8 || format == D3DFMT_A8R8G8B8 || format == D3DFMT_X8R8G8B8 || format == D3DFMT_R5G6B5 || format == D3DFMT_X1R5G5B5)) { Log("JuceGetHalfSizeRGB: surface format not supported."); return E_FAIL; } D3DLOCKED_RECT lockedSrcRect; int width = rect->right - rect->left; int height = rect->bottom - rect->top; int dHeight = height/2; int dWidth = width/2; // copy rect to a new surface and lock the rect there. // NOTE: apparently, this works faster than locking a rect on the back buffer itself. // LOOKS LIKE: reading from the backbuffer is faster via GetRenderTargetData, but writing // is faster if done directly. IDirect3DSurface9* surf = NULL; if (FAILED(d3dDevice->CreateOffscreenPlainSurface( width, height, format, D3DPOOL_SYSTEMMEM, &surf, NULL))) { Log("JuceGetHalfSizeRGB: Unable to create image surface."); return E_FAIL; } POINT points[] = {{0, 0}}; if (FAILED(d3dDevice->GetRenderTargetData(srcSurf, surf))) { Log("JuceGetHalfSizeRGB: GetRenderTargetData() failed for image surface."); return E_FAIL; } //Log("JuceGetHalfSizeRGB: copied rects."); RECT newRect = {0, 0, width, height}; if (FAILED(surf->LockRect(&lockedSrcRect, &newRect, 0))) { Log("JuceGetHalfSizeRGB: Unable to lock source rect."); return E_FAIL; } //Log("JuceGetHalfSizeRGB: locked rect."); // copy data BYTE* pSrcRow = (BYTE*)lockedSrcRect.pBits; INT srcPitch = lockedSrcRect.Pitch; //LogWithNumber("width = %d", width); //LogWithNumber("height = %d", width); //LogWithNumber("srcPitch = %d", srcPitch); //LogWithNumber("destPitch = %d", destPitch); int sbpp = 0; int i, j, k, m; BYTE b0, b1; BYTE b00, b01, b02, b10, b11, b12, b20, b21, b22, b30, b31, b32; UINT temp; switch (format) { case D3DFMT_X1R5G5B5: //Log("JuceGetHalfSizeRGB: source format = D3DFMT_X1R5G5B5"); // 16-bit: some conversion needed. for (i=0, k=height-2; i<dHeight, k>=0; i++, k-=2) { for (j=0, m=0; j<dWidth, m<width-1; j++, m+=2) { // memory layout 16 bit: // --------------------------------- // Lo Hi Lo Hi // b3b4b5b6b7g3g4g5 g6g7r3r4r5r6r700 // --------------------------------- // blue green red // // turns into:-> // // memory layout 24 bit: // -------------------------------------------------- // Lo Hi Lo Hi Lo Hi // 000000b3b4b5b6b7 000000g3g4g5g6g7 000000r3r4r5r6r7 // -------------------------------------------------- // blue green red /* // fetch 1 pixel: nearest neigbour b0 = pSrcRow[k*srcPitch + m*2]; b1 = pSrcRow[k*srcPitch + m*2 + 1]; destBuf[i*destPitch + j*3] = (b0 << 3) & 0xf8; destBuf[i*destPitch + j*3 + 1] = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); destBuf[i*destPitch + j*3 + 2] = (b1 << 1) & 0xf8; */ // fetch 4 pixels: bilinear interpolation b0 = pSrcRow[k*srcPitch + m*2]; b1 = pSrcRow[k*srcPitch + m*2 + 1]; b00 = (b0 << 3) & 0xf8; b01 = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); b02 = (b1 << 1) & 0xf8; b0 = pSrcRow[k*srcPitch + (m+1)*2]; b1 = pSrcRow[k*srcPitch + (m+1)*2 + 1]; b10 = (b0 << 3) & 0xf8; b11 = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); b12 = (b1 << 1) & 0xf8; b0 = pSrcRow[(k+1)*srcPitch + m*2]; b1 = pSrcRow[(k+1)*srcPitch + m*2 + 1]; b20 = (b0 << 3) & 0xf8; b21 = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); b22 = (b1 << 1) & 0xf8; b0 = pSrcRow[(k+1)*srcPitch + (m+1)*2]; b1 = pSrcRow[(k+1)*srcPitch + (m+1)*2 + 1]; b30 = (b0 << 3) & 0xf8; b31 = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); b32 = (b1 << 1) & 0xf8; temp = (b00 + b10 + b20 + b30) >> 2; destBuf[i*destPitch + j*3] = (BYTE)temp; temp = (b01 + b11 + b21 + b31) >> 2; destBuf[i*destPitch + j*3 + 1] = (BYTE)temp; temp = (b02 + b12 + b22 + b32) >> 2; destBuf[i*destPitch + j*3 + 2] = (BYTE)temp; } } break; case D3DFMT_R5G6B5: //Log("JuceGetHalfSizeRGB: source format = D3DFMT_R5G6B5"); // 16-bit: some conversion needed. for (i=0, k=height-2; i<dHeight, k>=0; i++, k-=2) { for (j=0, m=0; j<dWidth, m<width-1; j++, m+=2) { // memory layout 16 bit: // --------------------------------- // Lo Hi Lo Hi // b3b4b5b6b7g2g3g4 g5g6g7r3r4r5r6r7 // --------------------------------- // blue green red // // turns into:-> // // memory layout 24 bit: // -------------------------------------------------- // Lo Hi Lo Hi Lo Hi // 000000b3b4b5b6b7 000000g3g4g5g6g7 000000r3r4r5r6r7 // -------------------------------------------------- // blue green red /* // fetch 1 pixel: nearest neigbour b0 = pSrcRow[k*srcPitch + m*2]; b1 = pSrcRow[k*srcPitch + m*2 + 1]; destBuf[i*destPitch + j*3] = (b0 << 3) & 0xf8; destBuf[i*destPitch + j*3 + 1] = ((b0 >> 2) & 0x38) | ((b1 << 6) & 0xc0); destBuf[i*destPitch + j*3 + 2] = (b1 << 1) & 0xf8; */ // fetch 4 pixels: bilinear interpolation b0 = pSrcRow[k*srcPitch + m*2]; b1 = pSrcRow[k*srcPitch + m*2 + 1]; b00 = (b0 << 3) & 0xf8; b01 = ((b0 >> 3) & 0x1c) | ((b1 << 5) & 0xe0); b02 = b1 & 0xf8; b0 = pSrcRow[k*srcPitch + (m+1)*2]; b1 = pSrcRow[k*srcPitch + (m+1)*2 + 1]; b10 = (b0 << 3) & 0xf8; b11 = ((b0 >> 3) & 0x1c) | ((b1 << 5) & 0xe0); b12 = b1 & 0xf8; b0 = pSrcRow[(k+1)*srcPitch + m*2]; b1 = pSrcRow[(k+1)*srcPitch + m*2 + 1]; b20 = (b0 << 3) & 0xf8; b21 = ((b0 >> 3) & 0x1c) | ((b1 << 5) & 0xe0); b22 = b1 & 0xf8; b0 = pSrcRow[(k+1)*srcPitch + (m+1)*2]; b1 = pSrcRow[(k+1)*srcPitch + (m+1)*2 + 1]; b30 = (b0 << 3) & 0xf8; b31 = ((b0 >> 3) & 0x1c) | ((b1 << 5) & 0xe0); b32 = b1 & 0xf8; temp = (b00 + b10 + b20 + b30) >> 2; destBuf[i*destPitch + j*3] = (BYTE)temp; temp = (b01 + b11 + b21 + b31) >> 2; destBuf[i*destPitch + j*3 + 1] = (BYTE)temp; temp = (b02 + b12 + b22 + b32) >> 2; destBuf[i*destPitch + j*3 + 2] = (BYTE)temp; } } break; case D3DFMT_R8G8B8: case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: //Log("JuceGetHalfSizeRGB: source format = D3DFMT_R8G8B or D3DFMT_A8R8G8B8 or D3DFMT_X8R8G8B8"); if (format == D3DFMT_R8G8B8) sbpp = 3; else sbpp = 4; for (i=0, k=height-2; i<dHeight, k>=0; i++, k-=2) { for (j=0, m=0; j<dWidth, m<width-1; j++, m+=2) { /* // fetch 1 pixel: nearest neigbour destBuf[i*destPitch + j*3] = pSrcRow[k*srcPitch + m*sbpp]; destBuf[i*destPitch + j*3 + 1] = pSrcRow[k*srcPitch + m*sbpp + 1]; destBuf[i*destPitch + j*3 + 2] = pSrcRow[k*srcPitch + m*sbpp + 2]; */ // fetch 4 pixels: bilinear interpolation temp = (pSrcRow[k*srcPitch + m*sbpp] + pSrcRow[k*srcPitch + (m+1)*sbpp] + pSrcRow[(k+1)*srcPitch + m*sbpp] + pSrcRow[(k+1)*srcPitch + (m+1)*sbpp]) >> 2; destBuf[i*destPitch + j*3] = (BYTE)temp; temp = (pSrcRow[k*srcPitch + m*sbpp + 1] + pSrcRow[k*srcPitch + (m+1)*sbpp + 1] + pSrcRow[(k+1)*srcPitch + m*sbpp + 1] + pSrcRow[(k+1)*srcPitch + (m+1)*sbpp + 1]) >> 2; destBuf[i*destPitch + j*3 + 1] = (BYTE)temp; temp = (pSrcRow[k*srcPitch + m*sbpp + 2] + pSrcRow[k*srcPitch + (m+1)*sbpp + 2] + pSrcRow[(k+1)*srcPitch + m*sbpp + 2] + pSrcRow[(k+1)*srcPitch + (m+1)*sbpp + 2]) >> 2; destBuf[i*destPitch + j*3 + 2] = (BYTE)temp; } } break; } // unlock rect surf->UnlockRect(); //Log("Rect unlocked."); // release surface surf->Release(); return S_OK; } void InvalidateAndDelete9() { InvalidateDeviceObjects(g_dev, true); Log("InvalidateDeviceObjects done."); DeleteDeviceObjects(g_dev); Log("DeleteDeviceObjects done."); /* release bufffer */ if (g_rgbBuf != NULL) { HeapFree(procHeap, 0, g_rgbBuf); g_rgbBuf = NULL; Log("g_rgbBuf freed."); } } void InitHooksD9() { //MasterLog(g_myinfo.logfile, g_myinfo.processfile, " uses Direct3D9"); // set function pointer to capture frame for video GetPixels = (g_config.fullSizeVideo) ? JuceGetRGB : JuceGetHalfSizeRGB; if (!g_initDone) { /* determine my directory */ ZeroMemory(g_myinfo.dir, BUFLEN); ZeroMemory(g_myinfo.file, BUFLEN); GetModuleFileName(hInst, g_myinfo.file, MAX_FILEPATH); lstrcpy(g_myinfo.dir, g_myinfo.file); char *q = g_myinfo.dir + lstrlen(g_myinfo.dir); while ((q != g_myinfo.dir) && (*q != '\\')) { *q = '\0'; q--; } /* open log file, specific for this process */ ZeroMemory(logName, BUFLEN); lstrcpy(logName, g_myinfo.dir); lstrcat(logName, g_myinfo.shortProcessfileNoExt); lstrcat(logName, ".log"); OpenLog(logName); Log("Log started."); LogWithNumber("g_config.debug = %d", g_config.debug); LogWithNumber("g_config.useDirectInput = %d", g_config.useDirectInput); LogWithNumber("g_config.startupModeSystemWide = %d", g_config.startupModeSystemWide); LogWithNumber("sg_hGetMsgHook = %d", (DWORD)sg_hGetMsgHook); LogWithNumber("sg_bHookInstalled = %d", sg_bHookInstalled); LogWithNumber("sg_bUnhookDevice = %d", sg_bUnhookDevice); LogWithNumber("sg_bExiting = %d", sg_bExiting); /* verify that capture directory is set. If not, then set to g_myinfo.dir. */ if (lstrlen(g_config.captureDir)==0) SetCaptureDir(g_myinfo.dir); LARGE_INTEGER freq = {0, 0}; if (QueryPerformanceFrequency(&freq)) Log("Performance counter exists."); LogWithNumber("Performance counter frequency (hi): %u", freq.HighPart); LogWithNumber("Performance counter frequency (lo): %u", freq.LowPart); g_freq = freq.LowPart; /* determine frame capturing algorithm */ g_algorithm = SearchCustomConfig(g_myinfo.processfile, g_myinfo.dir, &customConfig) ? CUSTOM : ADAPTIVE; if (customConfig) { g_customFrameRate = customConfig->frameRate; g_customFrameWeight = customConfig->frameWeight; } g_initDone = TRUE; } // save handle to process' heap procHeap = GetProcessHeap(); /* hook Present() and Reset() */ HookDeviceMethods9(hD3D9); } // This function is called by the main DLL thread, when // the DLL is about to detach. All the memory clean-ups should be done here. void GraphicsCleanup9() { if (customConfig) HeapFree(GetProcessHeap(), 0, customConfig); // restore IDirect3D9Device methods if (g_D3D9_Present != NULL && g_codeFragment_p9[0] != 0) { try { memcpy(g_D3D9_Present, g_codeFragment_p9, 5); VirtualProtect(g_D3D9_Present, 8, g_savedProtection_p9, &g_savedProtection_p9); } catch (...) { TRACE("GraphicsCleanup9: problem restoring Present code fragment."); } } if (g_D3D9_Reset != NULL && g_codeFragment_r9[0] != 0) { try { memcpy(g_D3D9_Reset, g_codeFragment_r9, 5); VirtualProtect(g_D3D9_Reset, 8, g_savedProtection_r9, &g_savedProtection_r9); } catch (...) { TRACE("GraphicsCleanup9: problem restoring Reset code fragment."); } } if (g_D3D9_AddRef != NULL && pAddRefPtr != NULL) { *pAddRefPtr = (DWORD)g_D3D9_AddRef; } if (g_D3D9_Release != NULL && pReleasePtr != NULL) { *pReleasePtr = (DWORD)g_D3D9_Release; } // uninstall keyboard hook (if still installed). UninstallKeyboardHook(); TRACE("GraphicsCleanup9: done."); } // It looks like at certain points, vtable entries get restored to its original values. // If that happens, we need to re-assign them to our functions again. // NOTE: we don't want blindly re-assign, because there can be other programs // hooking on the same methods. Therefore, we only re-assign if we see that // original addresses are restored by the system. void VerifyHooks(IDirect3DDevice9* dev) { DWORD* vtable = (DWORD*)(*((DWORD*)dev)); if (vtable[ADDREF_POS] == (DWORD)g_D3D9_AddRef) { vtable[ADDREF_POS] = (DWORD)JuceAddRef9; TRACE("VerifyHooks: dev->AddRef() re-hooked."); } if (vtable[RELEASE_POS] == (DWORD)g_D3D9_Release) { vtable[RELEASE_POS] = (DWORD)JuceRelease9; TRACE("VerifyHooks: dev->Release() re-hooked."); } } // verifies that JMP-implants are still in place. void VerifyD9() { HookDeviceMethods9(GetModuleHandle("d3d9.dll")); }
31.277434
111
0.617722
a3449f4c0463b3312a4c660d2cbb7e257e2db4a7
6,911
h
C
System/Library/Frameworks/ModelIO.framework/MDLCamera.h
lechium/tvOS144Headers
e22dcf52662ae03002e3a6d57273f54e74013cb0
[ "MIT" ]
2
2021-04-15T10:50:21.000Z
2021-08-19T19:00:09.000Z
System/Library/Frameworks/ModelIO.framework/MDLCamera.h
lechium/tvOS144Headers
e22dcf52662ae03002e3a6d57273f54e74013cb0
[ "MIT" ]
null
null
null
System/Library/Frameworks/ModelIO.framework/MDLCamera.h
lechium/tvOS144Headers
e22dcf52662ae03002e3a6d57273f54e74013cb0
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 14, 2021 at 2:23:12 PM Mountain Standard Time * Operating System: Version 14.4 (Build 18K802) * Image Source: /System/Library/Frameworks/ModelIO.framework/ModelIO * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <ModelIO/ModelIO-Structs.h> #import <ModelIO/MDLObject.h> @class CAAnimation; @interface MDLCamera : MDLObject { RTCamera* _camera; float _worldToMetersConversionScale; CAAnimation* _focalDistanceAnimation; CAAnimation* _fStopAnimation; CAAnimation* _focalLengthAnimation; CAAnimation* _apertureAnimation; CAAnimation* _apertureAspectAnimation; float _barrelDistortion; float _fisheyeDistortion; float _opticalVignetting; float _chromaticAberration; float _fStop; float _maximumCircleOfConfusion; unsigned long long _projection; unsigned long long _apertureBladeCount; double _shutterOpenInterval; _flash; } @property (nonatomic,copy) CAAnimation * focalLengthAnimation; //@synthesize focalLengthAnimation=_focalLengthAnimation - In the implementation block @property (nonatomic,copy) CAAnimation * focalDistanceAnimation; //@synthesize focalDistanceAnimation=_focalDistanceAnimation - In the implementation block @property (nonatomic,copy) CAAnimation * fStopAnimation; //@synthesize fStopAnimation=_fStopAnimation - In the implementation block @property (nonatomic,copy) CAAnimation * apertureAnimation; //@synthesize apertureAnimation=_apertureAnimation - In the implementation block @property (nonatomic,copy) CAAnimation * apertureAspectAnimation; //@synthesize apertureAspectAnimation=_apertureAspectAnimation - In the implementation block @property (nonatomic,readonly) SCD_Struct_MD1 projectionMatrix; @property (assign,nonatomic) unsigned long long projection; //@synthesize projection=_projection - In the implementation block @property (assign,nonatomic) float nearVisibilityDistance; @property (assign,nonatomic) float farVisibilityDistance; @property (assign,nonatomic) float worldToMetersConversionScale; //@synthesize worldToMetersConversionScale=_worldToMetersConversionScale - In the implementation block @property (assign,nonatomic) float barrelDistortion; //@synthesize barrelDistortion=_barrelDistortion - In the implementation block @property (assign,nonatomic) float fisheyeDistortion; //@synthesize fisheyeDistortion=_fisheyeDistortion - In the implementation block @property (assign,nonatomic) float opticalVignetting; //@synthesize opticalVignetting=_opticalVignetting - In the implementation block @property (assign,nonatomic) float chromaticAberration; //@synthesize chromaticAberration=_chromaticAberration - In the implementation block @property (assign,nonatomic) float focalLength; @property (assign,nonatomic) float focusDistance; @property (assign,nonatomic) float fieldOfView; @property (assign,nonatomic) float fStop; //@synthesize fStop=_fStop - In the implementation block @property (assign,nonatomic) unsigned long long apertureBladeCount; //@synthesize apertureBladeCount=_apertureBladeCount - In the implementation block @property (assign,nonatomic) float maximumCircleOfConfusion; //@synthesize maximumCircleOfConfusion=_maximumCircleOfConfusion - In the implementation block @property (assign,nonatomic) double shutterOpenInterval; //@synthesize shutterOpenInterval=_shutterOpenInterval - In the implementation block @property (assign,nonatomic) float sensorVerticalAperture; @property (assign,nonatomic) float sensorAspect; @property (assign,nonatomic) sensorEnlargement; @property (assign,nonatomic) sensorShift; @property (assign,nonatomic) flash; //@synthesize flash=_flash - In the implementation block @property (assign,nonatomic) exposureCompression; @property (assign,nonatomic) exposure; -(id)copyWithZone:(NSZone*)arg1 ; -(id)init; -(void)dealloc; -(long long)version; -(float)aspect; -(void)setAspect:(float)arg1 ; -(float)focalLength; -(void)setFocalLength:(float)arg1 ; -(void)setAperture:(float)arg1 ; -(float)aperture; -(unsigned long long)apertureBladeCount; -(RTCamera*)rtCamera; -(SCD_Struct_MD1)getViewMatrixAtTime:(double)arg1 ; -(SCD_Struct_MD1)projectionMatrix; -(SCD_Struct_MD1)getProjectionMatrixAtTime:(double)arg1 ; -(3)rayTo:forViewPort:; -(float)focusDistance; -(void)setFocusDistance:(float)arg1 ; -(float)sensorVerticalAperture; -(void)setSensorVerticalAperture:(float)arg1 ; -()sensorEnlargement; -(void)setSensorEnlargement:; -()sensorShift; -(void)setSensorShift:; -(float)fov; -(void)setFov:(float)arg1 ; -(float)fieldOfView; -(void)setFieldOfView:(float)arg1 ; -(float)sensorAspect; -(void)setSensorAspect:(float)arg1 ; -(float)circleOfConfusionForDistance:(float)arg1 ; -(float)zNear; -(void)setZNear:(float)arg1 ; -(float)zFar; -(void)setZFar:(float)arg1 ; -(float)nearVisibilityDistance; -(void)setNearVisibilityDistance:(float)arg1 ; -(float)farVisibilityDistance; -(void)setFarVisibilityDistance:(float)arg1 ; -(id)bokehKernelWithSize:; -()exposure; -(void)setExposure:; -()exposureCompression; -(void)setExposureCompression:; -(void)frameBoundingBox:({?=})arg1 setNearAndFar:(BOOL)arg2 ; -(void)lookAt:; -(void)lookAt:from:; -(float)worldToMetersConversionScale; -(void)setWorldToMetersConversionScale:(float)arg1 ; -(CAAnimation *)focalDistanceAnimation; -(void)setFocalDistanceAnimation:(CAAnimation *)arg1 ; -(CAAnimation *)fStopAnimation; -(void)setFStopAnimation:(CAAnimation *)arg1 ; -(CAAnimation *)focalLengthAnimation; -(void)setFocalLengthAnimation:(CAAnimation *)arg1 ; -(CAAnimation *)apertureAnimation; -(void)setApertureAnimation:(CAAnimation *)arg1 ; -(CAAnimation *)apertureAspectAnimation; -(void)setApertureAspectAnimation:(CAAnimation *)arg1 ; -(unsigned long long)projection; -(void)setProjection:(unsigned long long)arg1 ; -(float)barrelDistortion; -(void)setBarrelDistortion:(float)arg1 ; -(float)fisheyeDistortion; -(void)setFisheyeDistortion:(float)arg1 ; -(float)opticalVignetting; -(void)setOpticalVignetting:(float)arg1 ; -(float)chromaticAberration; -(void)setChromaticAberration:(float)arg1 ; -(float)fStop; -(void)setFStop:(float)arg1 ; -(void)setApertureBladeCount:(unsigned long long)arg1 ; -(float)maximumCircleOfConfusion; -(void)setMaximumCircleOfConfusion:(float)arg1 ; -(double)shutterOpenInterval; -(void)setShutterOpenInterval:(double)arg1 ; -()flash; -(void)setFlash:; @end
47.993056
183
0.746636
08a68ed8bc019cc95fbe565da575f741fde38fa1
744
css
CSS
demo/iniziativa/css/style.css
obujor/PalMaS
229e565072b4783bbe09b6a635219347f3be40e5
[ "MIT" ]
3
2016-11-21T21:10:42.000Z
2022-01-22T16:25:44.000Z
demo/iniziativa/css/style.css
obujor/PalMaS
229e565072b4783bbe09b6a635219347f3be40e5
[ "MIT" ]
null
null
null
demo/iniziativa/css/style.css
obujor/PalMaS
229e565072b4783bbe09b6a635219347f3be40e5
[ "MIT" ]
null
null
null
body { font-family: Verdana, Arial, Helvetica, sans-serif; } .node { cursor: pointer; } .node:hover { stroke: #000; stroke-width: 1.5px; } .node--leaf { fill: white; } .label { font: 11px "Helvetica Neue", Helvetica, Arial, sans-serif; text-anchor: middle; text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff; } .label, .node--root, .node--leaf { pointer-events: none; } #list { width: 200px; border: 1px solid black; position:absolute; left: 970px; padding: 10px; } .listName { font-weight: bold; } .listPercColor { padding-right: 5px; } .cName { padding-right: 10px; } .cName:after { content: ':'; } .iniziativaPerc { margin-bottom: 10px; } .initResults { padding-left: 20px; }
11.446154
72
0.630376
c448de0cde57393a668990a66beed745ce0007ac
3,075
cpp
C++
ad_map_access/src/point/BoundingSphereOperation.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
61
2019-12-19T20:57:24.000Z
2022-03-29T15:20:51.000Z
ad_map_access/src/point/BoundingSphereOperation.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
54
2020-04-05T05:32:47.000Z
2022-03-15T18:42:33.000Z
ad_map_access/src/point/BoundingSphereOperation.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
31
2019-12-20T07:37:39.000Z
2022-03-16T13:06:16.000Z
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2021 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #include "ad/map/point/BoundingSphereOperation.hpp" namespace ad { namespace map { namespace point { void expandBounds(point::ECEFPoint &upperBound, point::ECEFPoint &lowerBound, point::ECEFPoint const &point) { upperBound.x = std::max(upperBound.x, point.x); upperBound.y = std::max(upperBound.y, point.y); upperBound.z = std::max(upperBound.z, point.z); lowerBound.x = std::min(lowerBound.x, point.x); lowerBound.y = std::min(lowerBound.y, point.y); lowerBound.z = std::min(lowerBound.z, point.z); } point::BoundingSphere calcBoundingSphere(Geometry const &geometryLeft, Geometry const &geometryRight) { point::BoundingSphere boundingSphere; if (geometryLeft.ecefEdge.empty() && geometryRight.ecefEdge.empty()) { return boundingSphere; } point::ECEFPoint upperBound; point::ECEFPoint lowerBound; if (geometryLeft.ecefEdge.empty()) { upperBound = geometryRight.ecefEdge.front(); } else { upperBound = geometryLeft.ecefEdge.front(); } lowerBound = upperBound; for (auto const &point : geometryLeft.ecefEdge) { expandBounds(upperBound, lowerBound, point); } for (auto const &point : geometryRight.ecefEdge) { expandBounds(upperBound, lowerBound, point); } point::ECEFPoint const diagonalVector = upperBound - lowerBound; auto diagonalVectorLength = point::vectorLength(diagonalVector); boundingSphere.radius = 0.5 * diagonalVectorLength; boundingSphere.center = lowerBound + 0.5 * diagonalVector; return boundingSphere; } } // namespace point } // namespace map } // namespace ad ::ad::map::point::BoundingSphere operator+(::ad::map::point::BoundingSphere const &a, ::ad::map::point::BoundingSphere const &b) { ::ad::map::point::BoundingSphere result; ::ad::map::point::BoundingSphere const *small; ::ad::map::point::BoundingSphere const *large; if (a.radius < b.radius) { small = &a; large = &b; } else { small = &b; large = &a; } auto const fromLargeToSmallCenter = small->center - large->center; auto const sphereCenterDistance = ::ad::map::point::vectorLength(fromLargeToSmallCenter); // move the center of the larger sphere in direction of the smaller one // and increase the larger radius by the moving distance auto const displacement = 0.5 * (sphereCenterDistance - large->radius + small->radius); if (displacement <= ::ad::physics::Distance(0.)) { // small is already within large result = *large; } else if (sphereCenterDistance == ::ad::physics::Distance(0.)) { // tiny center distance result = *large; } else { result.center = large->center + ::ad::physics::Distance(displacement / sphereCenterDistance) * (fromLargeToSmallCenter); result.radius = large->radius + displacement; } return result; }
28.211009
112
0.663415
90c1b5cb1b39f3407894878cf18b044293db1e85
4,228
rs
Rust
src/system/system_logger.rs
kanishkarj/harsark.rs
83187c10ff1fbc0542390db90a29cee2af3d498d
[ "MIT" ]
10
2020-03-26T16:27:38.000Z
2022-01-04T06:45:05.000Z
src/system/system_logger.rs
GourinathBanda/HarSaRK_RS_Multicore
f9cef0d8f7d73060977dcc42c59ab9929ae0f908
[ "MIT" ]
8
2019-11-26T10:47:04.000Z
2019-11-26T10:48:31.000Z
src/system/system_logger.rs
GourinathBanda/HarSaRK_RS_Multicore
f9cef0d8f7d73060977dcc42c59ab9929ae0f908
[ "MIT" ]
6
2020-03-28T10:11:40.000Z
2021-12-11T12:25:27.000Z
use crate::system::scheduler::{BooleanVector,TaskId}; use crate::config::MAX_LOGS; use core::fmt; #[cfg(any(feature = "events_32", feature = "events_16", feature = "events_64"))] use crate::system::event::EventId; pub type Logs = [Option<LogEvent>; MAX_LOGS]; #[derive(Clone, Copy)] pub enum LogEventType { ReleaseTasks(BooleanVector), BlockTasks(BooleanVector), UnblockTasks(BooleanVector), TaskExit(BooleanVector), ResourceLock(TaskId), ResourceUnlock(TaskId), MessageBroadcast(BooleanVector), MessageRecieve(TaskId), SemaphoreSignal(BooleanVector,BooleanVector), SemaphoreReset(TaskId), DeadlineExpired(TaskId,u32), #[cfg(any(feature = "events_32", feature = "events_16", feature = "events_64"))] TimerEvent(EventId), } #[derive(Clone, Copy, Debug)] pub struct LogEvent { pub event_type: LogEventType, pub timestamp: u32 } impl LogEvent { pub fn new(event_type: LogEventType, timestamp: u32) -> Self { Self { event_type, timestamp } } } pub struct SystemLogger { logs: Logs, start: usize, end: usize, pub release_log: bool, pub block_tasks_log: bool, pub unblock_tasks_log: bool, pub task_exit_log: bool, pub resource_lock_log: bool, pub resource_unlock_log: bool, pub message_broadcast_log: bool, pub message_recieve_log: bool, pub semaphore_signal_log: bool, pub semaphore_reset_log: bool, #[cfg(any(feature = "events_32", feature = "events_16", feature = "events_64"))] pub timer_event_log: bool, } // use a circular queue instead of this crap. // ensure the handler is not None in start_kernel. impl SystemLogger { pub const fn new() -> Self { Self { logs: [None; MAX_LOGS], start: 0, end: 0, release_log : false, block_tasks_log : false, unblock_tasks_log : false, task_exit_log : false, resource_lock_log : false, resource_unlock_log : false, message_broadcast_log : false, message_recieve_log : false, semaphore_signal_log : false, semaphore_reset_log : false, #[cfg(any(feature = "events_32", feature = "events_16", feature = "events_64"))] timer_event_log : false, } } pub fn push(&mut self, event: LogEvent) { self.logs[self.end] = Some(event); self.end = (self.end+1)%MAX_LOGS; if self.start == self.end { self.start = (self.start+1)%MAX_LOGS; } } pub fn clear(&mut self) { for val in self.logs.iter_mut() { *val = None; } self.start = 0; self.end = 0; } pub fn pop(&mut self) -> Option<LogEvent> { let pos = self.start; let val = self.logs[pos]; self.logs[pos] = None; self.start = (self.start+1)%MAX_LOGS; return val; } } impl fmt::Debug for LogEventType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { LogEventType::ReleaseTasks(tasks_mask) => write!(f, "Tasks Released: {}", tasks_mask), LogEventType::BlockTasks(tasks_mask) => write!(f, "BlockTasks"), LogEventType::UnblockTasks(tasks_mask) => write!(f, "UnblockTasks"), LogEventType::TaskExit(tasks_mask) => write!(f, "TaskExit"), LogEventType::ResourceLock(ceiling) => write!(f, "ResourceLock"), LogEventType::ResourceUnlock(ceiling) => write!(f, "ResourceUnlock"), LogEventType::MessageBroadcast(recievers) => write!(f, "MessageBroadcast"), LogEventType::MessageRecieve(task_id) => write!(f, "MessageRecieve"), LogEventType::SemaphoreSignal(tasks_released,tasks_notified) => write!(f, "SemaphoreSignal"), LogEventType::SemaphoreReset(task_id) => write!(f, "SemaphoreReset"), LogEventType::DeadlineExpired(TaskId, u32) => write!(f, "DeadlineExpired"), #[cfg(any(feature = "events_32", feature = "events_16", feature = "events_64"))] LogEventType::TimerEvent(EventId) => write!(f, "TimerEvent"), } } }
33.824
105
0.611873
851e71f6f3fe33d4b87f21d61c156df0ad2393aa
1,242
cs
C#
Source/AccidentalFish.ApplicationSupport.Core/Configuration/IConfiguration.cs
JamesRandall/AccidentalFish.ApplicationSupport
a66cb1b6f863cfe0fba141325c5ce30dfacee45d
[ "MIT" ]
11
2015-04-12T16:50:19.000Z
2021-02-02T02:43:33.000Z
Source/AccidentalFish.ApplicationSupport.Core/Configuration/IConfiguration.cs
JamesRandall/AccidentalFish.ApplicationSupport
a66cb1b6f863cfe0fba141325c5ce30dfacee45d
[ "MIT" ]
2
2015-08-04T12:19:00.000Z
2015-09-07T07:21:47.000Z
Source/AccidentalFish.ApplicationSupport.Core/Configuration/IConfiguration.cs
JamesRandall/AccidentalFish.ApplicationSupport
a66cb1b6f863cfe0fba141325c5ce30dfacee45d
[ "MIT" ]
7
2015-03-12T21:47:42.000Z
2020-11-04T04:29:45.000Z
using System; using System.Threading.Tasks; namespace AccidentalFish.ApplicationSupport.Core.Configuration { /// <summary> /// Interface for supplying global configuration information /// </summary> public interface IConfiguration { /// <summary> /// Storage account connection string /// </summary> string StorageAccountConnectionString { get; } /// <summary> /// Sql connection string /// </summary> string SqlConnectionString { get; } /// <summary> /// Service bus connection string /// </summary> string ServiceBusConnectionString { get; } /// <summary> /// Application setting /// </summary> /// <param name="key">Setting name</param> /// <returns>Setting value</returns> string this[string key] { get; } /// <summary> /// Application setting /// </summary> /// <param name="key">Setting name</param> /// <returns>Setting value</returns> [Obsolete("Preferred approach is to use the IAsyncConfiguration interface. This will be deprecated in an upcoming major version.")] Task<string> GetAsync(string key); } }
31.05
139
0.591787
9592a876dd59a4ae5d09293e50e38c85b10dd809
2,717
dart
Dart
web/test_media_devices.dart
flutter-webrtc/dart-webrtc
d77e93eb097b3cd2b0f0155185fa0b4fcccd9a6c
[ "MIT" ]
17
2020-10-28T15:43:24.000Z
2022-01-10T01:01:32.000Z
web/test_media_devices.dart
flutter-webrtc/dart-webrtc
d77e93eb097b3cd2b0f0155185fa0b4fcccd9a6c
[ "MIT" ]
6
2020-11-01T15:21:19.000Z
2022-03-31T05:28:51.000Z
web/test_media_devices.dart
flutter-webrtc/dart-webrtc
d77e93eb097b3cd2b0f0155185fa0b4fcccd9a6c
[ "MIT" ]
9
2020-11-15T23:24:48.000Z
2022-03-31T15:21:55.000Z
import 'package:dart_webrtc/dart_webrtc.dart'; import 'package:dart_webrtc/src/media_devices.dart'; import 'package:test/test.dart'; MediaDevices mediaDevices; void closeMediaStream(MediaStream stream) { stream.getTracks().forEach((element) { element.stop(); }); } List<void Function()> testFunctions = <void Function()>[ () => test('MediaDevices.constructor()', () { mediaDevices = navigator.mediaDevices; expect(mediaDevices != null, true); }), () => test('MediaDevices.enumerateDevices()', () async { var list = await mediaDevices.enumerateDevices(); list.forEach((e) { print('${e.runtimeType}: ${e.label}, type => ${e.kind}'); }); expect(list != null, true); }), () => test('MediaDevices.getUserMedia()', () async { var stream = await mediaDevices.getUserMedia( constraints: MediaStreamConstraints(audio: true, video: true)); print('getUserMedia: stream.id => ${stream.id}'); expect(stream != null, true); print( 'getUserMedia: audio track.id => ${stream.getAudioTracks()[0].id}'); expect(stream.getAudioTracks().isNotEmpty, true); print( 'getUserMedia: video track.id => ${stream.getVideoTracks()[0].id}'); expect(stream.getVideoTracks().isNotEmpty, true); closeMediaStream(stream); stream = await mediaDevices.getUserMedia( constraints: MediaStreamConstraints(audio: false, video: true)); expect(stream.getAudioTracks().isEmpty, true); expect(stream.getVideoTracks().isNotEmpty, true); closeMediaStream(stream); stream = await mediaDevices.getUserMedia( constraints: MediaStreamConstraints(audio: true, video: false)); expect(stream.getAudioTracks().isNotEmpty, true); expect(stream.getVideoTracks().isEmpty, true); closeMediaStream(stream); /* expect( await mediaDevices.getUserMedia( constraints: MediaStreamConstraints(audio: false, video: false)), throwsException);*/ }), () => test('MediaDevices.getDisplayMedia()', () async { /* var stream = await mediaDevices.getDisplayMedia( constraints: MediaStreamConstraints(audio: false, video: true)); print('getDisplayMedia: stream.id => ${stream.id}'); expect(stream != null, true); expect(stream.getAudioTracks().isEmpty, true); print( 'getDisplayMedia: video track.id => ${stream.getVideoTracks()[0].id}'); expect(stream.getVideoTracks().isNotEmpty, true); closeMediaStream(stream); */ }) ];
35.285714
83
0.614649
a325ad9f1ee7d2cb3908825a7f386a52e0753812
24,371
java
Java
src/main/java/edu/mit/spacenet/gui/demand/DemandsTab.java
ptgrogan/spacenet
0a9523fb293eafa6f60b0c1a78bf4b4868b84da2
[ "Apache-2.0" ]
1
2022-03-07T19:54:14.000Z
2022-03-07T19:54:14.000Z
src/main/java/edu/mit/spacenet/gui/demand/DemandsTab.java
ptgrogan/spacenet
0a9523fb293eafa6f60b0c1a78bf4b4868b84da2
[ "Apache-2.0" ]
null
null
null
src/main/java/edu/mit/spacenet/gui/demand/DemandsTab.java
ptgrogan/spacenet
0a9523fb293eafa6f60b0c1a78bf4b4868b84da2
[ "Apache-2.0" ]
1
2018-08-21T17:07:37.000Z
2018-08-21T17:07:37.000Z
/* * Copyright 2010 MIT Strategic Engineering Research Group * * 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 edu.mit.spacenet.gui.demand; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Hashtable; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import edu.mit.spacenet.domain.resource.Demand; import edu.mit.spacenet.gui.ScenarioPanel; import edu.mit.spacenet.gui.SpaceNetFrame; import edu.mit.spacenet.gui.SpaceNetSettings; import edu.mit.spacenet.scenario.ItemDiscretization; import edu.mit.spacenet.scenario.Scenario; import edu.mit.spacenet.scenario.SupplyEdge; import edu.mit.spacenet.scenario.SupplyEdge.SupplyPoint; import edu.mit.spacenet.simulator.DemandSimulator; import edu.mit.spacenet.simulator.SimDemand; /** * Component for viewing and editing the demands associated with a scenario. * * @author Paul Grogan */ public class DemandsTab extends JSplitPane { private static final long serialVersionUID = 1065899429343403823L; private static String RAW_DEMANDS = "Raw Demands"; private static String AGGREGATED_DEMANDS = "Aggregated Demands"; private static String ID_OUTPUT = "Object IDs"; private static String NAME_OUTPUT = "Object Names"; private static String COMMA_DELIMITED = "Comma Delimited"; private static String SEMICOLON_DELIMITED = "Semicolon Delimited"; private static String TAB_DELIMITED = "Tab Delimited"; private JPanel controlPanel; private JComboBox discretizationCombo; private JSlider aggregationSlider; private JCheckBox scavengeSparesCheck, packingDemandsCheck, demandsSatisfiedCheck; private JTextField directoryPathText, fileNameText; private JCheckBox overwriteCheck; private JButton browseButton, exportButton; private JComboBox demandsCombo, referenceCombo, delimiterCombo; private JFileChooser directoryChooser; private ExportWorker exportWorker; private JTabbedPane tabbedPane; private ScenarioFeasibilityTab feasibilityTab; private SupplyNetworkTab networkTab; private ElementDemandsTab elementDemandsTab; private MissionDemandsTab missionDemandTab; private LocationDemandsTab locationDemandTab; private CommonalityTab commonalityTab; private RepairabilityTab repairabilityTab; private ScenarioPanel scenarioPanel; private DemandSimulator simulator; private SimWorker simWorker; /** * The constructor. * * @param scenarioPanel the scenario panel */ public DemandsTab(ScenarioPanel scenarioPanel) { this.scenarioPanel = scenarioPanel; controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); controlPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; c.weightx = 1; controlPanel.add(buildOptionsPanel(), c); c.gridy++; controlPanel.add(buildDisplayPanel(), c); c.gridy++; controlPanel.add(buildExportPanel(), c); c.gridy++; c.weighty = 1; controlPanel.add(new JPanel(), c); setLeftComponent(new JScrollPane(controlPanel)); tabbedPane = new JTabbedPane(); networkTab = new SupplyNetworkTab(this); tabbedPane.add(networkTab); feasibilityTab = new ScenarioFeasibilityTab(this); tabbedPane.add(feasibilityTab); elementDemandsTab = new ElementDemandsTab(this); tabbedPane.add(elementDemandsTab); missionDemandTab = new MissionDemandsTab(this); tabbedPane.add(missionDemandTab); locationDemandTab = new LocationDemandsTab(this); tabbedPane.add(locationDemandTab); commonalityTab = new CommonalityTab(this); tabbedPane.add(commonalityTab); repairabilityTab = new RepairabilityTab(this); tabbedPane.add(repairabilityTab); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { updateTab(); } }); setRightComponent(tabbedPane); setResizeWeight(.1); setDividerLocation(250); setBorder(BorderFactory.createEmptyBorder()); } /** * Initializes the demands tab. */ public void initialize() { discretizationCombo.setEnabled(getScenario()!=null); aggregationSlider.setEnabled(getScenario()!=null); scavengeSparesCheck.setEnabled(getScenario()!=null); packingDemandsCheck.setEnabled(getScenario()!=null); browseButton.setEnabled(getScenario()!=null); fileNameText.setEnabled(getScenario()!=null); demandsCombo.setEnabled(getScenario()!=null); referenceCombo.setEnabled(getScenario()!=null); delimiterCombo.setEnabled(getScenario()!=null); if(getScenario()!=null) { discretizationCombo.setSelectedItem(getScenario().getItemDiscretization()); aggregationSlider.setValue((int)(getScenario().getItemAggregation()*4)); aggregationSlider.setEnabled(getScenario().getItemDiscretization()!=ItemDiscretization.NONE); scavengeSparesCheck.setSelected(getScenario().isScavengeSpares()); fileNameText.setText("demands.txt"); //TODO: this is a hack, simulator should be initialized, not re-created simulator = new DemandSimulator(getScenario()); simulator.setDemandsSatisfied(false); packingDemandsCheck.setSelected(simulator.isPackingDemandsAdded()); demandsSatisfiedCheck.setSelected(simulator.isDemandsSatisfied()); simWorker = new SimWorker(true); simWorker.execute(); } } /** * Builds the options panel, used for accessing scenario options. * * @return the options panel */ private JPanel buildOptionsPanel() { JPanel optionsPanel = new JPanel(); optionsPanel.setBorder(BorderFactory.createTitledBorder("Demand Options")); optionsPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 0; c.weighty = 0; c.weightx = 0; optionsPanel.add(new JLabel("Item Discretization by: "), c); c.gridy++; c.anchor = GridBagConstraints.FIRST_LINE_END; optionsPanel.add(new JLabel("Item Aggregation at: "), c); c.gridy = 0; c.gridx++; c.weightx = 1; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.BOTH; discretizationCombo = new JComboBox(); discretizationCombo.setToolTipText("Discretize demands for items to integer values at the selected level"); for(ItemDiscretization t : ItemDiscretization.values()) { discretizationCombo.addItem(t); } discretizationCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(!discretizationCombo.getSelectedItem().equals(getScenario().getItemDiscretization())) { getScenario().setItemDiscretization((ItemDiscretization)discretizationCombo.getSelectedItem()); aggregationSlider.setEnabled(getScenario().getItemDiscretization()!=ItemDiscretization.NONE); updateView(); } } }); optionsPanel.add(discretizationCombo, c); c.gridy++; aggregationSlider = new JSlider(JSlider.VERTICAL, 0,4,1); aggregationSlider.setToolTipText("Aggregate discretized item demands ahead or behind demands."); Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>(); labelTable.put(new Integer(0), new JLabel("First Demand", JLabel.LEFT)); labelTable.put(new Integer(2), new JLabel("Half Demand", JLabel.LEFT)); labelTable.put(new Integer(4), new JLabel("Unit Demand", JLabel.RIGHT)); aggregationSlider.setLabelTable(labelTable); aggregationSlider.setPaintLabels(true); aggregationSlider.setMajorTickSpacing(1); aggregationSlider.setSnapToTicks(true); aggregationSlider.setPaintTicks(true); aggregationSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if(!aggregationSlider.getValueIsAdjusting() && aggregationSlider.getValue()/4d!= getScenario().getItemAggregation()) { getScenario().setItemAggregation(aggregationSlider.getValue()/4d); updateView(); } } }); aggregationSlider.setPreferredSize(new Dimension(50,100)); optionsPanel.add(aggregationSlider, c); c.gridy++; c.gridx = 0; c.gridwidth = 2; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.BOTH; scavengeSparesCheck = new JCheckBox("Scavenge Spares"); scavengeSparesCheck.setToolTipText("Scavenge spare parts from co-located decommissioned elements"); scavengeSparesCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(scavengeSparesCheck.isSelected()!=getScenario().isScavengeSpares()) { getScenario().setScavengeSpares(scavengeSparesCheck.isSelected()); updateView(); } } }); optionsPanel.add(scavengeSparesCheck, c); return optionsPanel; } /** * Builds the display panel, used for controlling the display options. * * @return the display panel */ private JPanel buildDisplayPanel() { JPanel displayPanel = new JPanel(); displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.PAGE_AXIS)); displayPanel.setBorder(BorderFactory.createTitledBorder("Display Options")); packingDemandsCheck = new JCheckBox("Estimate Logistics Container Masses"); packingDemandsCheck.setToolTipText("Estimate mass (Generic COS 5) for containers using resource packing factors."); packingDemandsCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(packingDemandsCheck.isSelected()!=simulator.isPackingDemandsAdded()) { simulator.setPackingDemandsAdded(e.getStateChange()==ItemEvent.SELECTED); updateView(); } } }); displayPanel.add(packingDemandsCheck); demandsSatisfiedCheck = new JCheckBox("Consume Existing Resources"); demandsSatisfiedCheck.setToolTipText("Consume existing resources when demanded."); demandsSatisfiedCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(demandsSatisfiedCheck.isSelected()!=simulator.isDemandsSatisfied()) { simulator.setDemandsSatisfied(e.getStateChange()==ItemEvent.SELECTED); updateView(); } } }); displayPanel.add(demandsSatisfiedCheck); return displayPanel; } private JPanel buildExportPanel() { directoryChooser = new JFileChooser(); directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); JPanel exportPanel = new JPanel(); exportPanel.setBorder(BorderFactory.createTitledBorder("Export Demands")); exportPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; exportPanel.add(new JLabel("Directory: "), c); c.gridy++; exportPanel.add(new JLabel("File Name: "), c); c.gridy+=2; exportPanel.add(new JLabel("Demands: "), c); c.gridy++; exportPanel.add(new JLabel("Output: "), c); c.gridy++; exportPanel.add(new JLabel("Delimiter: "), c); c.gridy = 0; c.gridx++; c.weightx = 1; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.HORIZONTAL; directoryPathText = new JTextField(); directoryPathText.setEnabled(false); exportPanel.add(directoryPathText, c); c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; c.gridx++; c.weightx = 0; browseButton = new JButton(new ImageIcon(getClass().getClassLoader().getResource("icons/folder_explore.png"))); browseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(directoryPathText.getText()=="") { directoryChooser.setCurrentDirectory( new File(SpaceNetSettings.getInstance().getDefaultDirectory())); } int returnVal = directoryChooser.showOpenDialog(getThis()); if(returnVal == JFileChooser.APPROVE_OPTION) { directoryPathText.setText(directoryChooser.getSelectedFile().getAbsolutePath()); } exportButton.setEnabled(directoryPathText.getText()!="" && fileNameText.getText()!=""); } }); exportPanel.add(browseButton, c); c.gridy++; c.gridx--; c.gridwidth = 2; c.weightx = 1; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.HORIZONTAL; fileNameText = new JTextField(15); fileNameText.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { exportButton.setEnabled(directoryPathText.getText()!="" && fileNameText.getText()!=""); } }); exportPanel.add(fileNameText, c); c.gridy++; overwriteCheck = new JCheckBox("Overwrite existing files", false); exportPanel.add(overwriteCheck, c); c.gridy++; demandsCombo = new JComboBox(); demandsCombo.addItem(RAW_DEMANDS); demandsCombo.addItem(AGGREGATED_DEMANDS); exportPanel.add(demandsCombo, c); c.gridy++; referenceCombo = new JComboBox(); referenceCombo.addItem(ID_OUTPUT); referenceCombo.addItem(NAME_OUTPUT); exportPanel.add(referenceCombo, c); c.gridy++; delimiterCombo = new JComboBox(); delimiterCombo.addItem(TAB_DELIMITED); delimiterCombo.addItem(COMMA_DELIMITED); delimiterCombo.addItem(SEMICOLON_DELIMITED); exportPanel.add(delimiterCombo, c); c.gridy++; c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; exportButton = new JButton("Export", new ImageIcon(getClass().getClassLoader().getResource("icons/page_white_edit.png"))); exportButton.setEnabled(false); exportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exportDemands(); } }); exportPanel.add(exportButton, c); return exportPanel; } /** * Gets the scenario panel component. * * @return the scenario panel */ public ScenarioPanel getScenarioPanel() { return scenarioPanel; } /** * Gets this. * * @return this */ private DemandsTab getThis() { return this; } /** * Gets the scenario. * * @return the scenario */ public Scenario getScenario() { return scenarioPanel.getScenario(); } /** * Gets the demand simulator. * * @return the demand simulator */ public DemandSimulator getSimulator() { return simulator; } /** * A SwingWorker subclass that manages the time-intensive simulation in a * separate thread. */ private class SimWorker extends SwingWorker<Void, Void> { private boolean isInitialization; /** * Instantiates a new sim worker. * * @param isInitialization the is initialization */ public SimWorker(boolean isInitialization) { this.isInitialization = isInitialization; } /** * Instantiates a new sim worker. */ public SimWorker() { this(false); } /* (non-Javadoc) * @see org.jdesktop.swingworker.SwingWorker#doInBackground() */ public Void doInBackground() { try { SpaceNetFrame.getInstance().getStatusBar().setStatusMessage("Simulating Demands..."); scenarioPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); simulator.simulate(); scenarioPanel.setCursor(Cursor.getDefaultCursor()); SpaceNetFrame.getInstance().getStatusBar().clearStatusMessage(); } catch(Exception ex) { ex.printStackTrace(); } return null; } /* (non-Javadoc) * @see org.jdesktop.swingworker.SwingWorker#done() */ public void done() { // update tab only after simulation has completed if(isInitialization) { feasibilityTab.initialize(); networkTab.initialize(); elementDemandsTab.initialize(); missionDemandTab.initialize(); locationDemandTab.initialize(); commonalityTab.initialize(); repairabilityTab.initialize(); } else { updateTab(); } } } /** * Export demands. */ private void exportDemands() { while(exportWorker != null && !exportWorker.isDone() && simWorker != null && !simWorker.isDone()) { // wait until previous simulation and export is complete } exportWorker = new ExportWorker(); exportWorker.execute(); } /** * Write file. */ private void writeFile() { String filePath = directoryPathText.getText() + System.getProperty("file.separator") + fileNameText.getText(); char delimiter = ','; if(delimiterCombo.getSelectedItem()==COMMA_DELIMITED) { delimiter = ','; } else if(delimiterCombo.getSelectedItem()==SEMICOLON_DELIMITED) { delimiter = ';'; } else if(delimiterCombo.getSelectedItem()==TAB_DELIMITED) { delimiter = '\t'; } try { File file = new File(filePath); if(file.exists() && !overwriteCheck.isSelected()) { int answer = JOptionPane.showOptionDialog(getThis(), "Overwrite existing file " + fileNameText.getText() + "?", "SpaceNet Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null); if (answer == JOptionPane.NO_OPTION) return; else overwriteCheck.setSelected(true); } BufferedWriter out = new BufferedWriter(new FileWriter(filePath)); if(demandsCombo.getSelectedItem()==RAW_DEMANDS) { out.write("Time" + delimiter + "Location" + delimiter + "Element" + delimiter + "Resource" + delimiter + "Amount" + System.getProperty("line.separator")); for(SimDemand simDemand : simulator.getUnsatisfiedDemands()) { for(Demand demand : simDemand.getDemands()) { if(referenceCombo.getSelectedItem()==ID_OUTPUT) { out.write("" + simDemand.getTime()); out.write(delimiter); out.write("" + simDemand.getLocation().getTid()); out.write(delimiter); if(simDemand.getElement()!=null) { out.write("" + simDemand.getElement().getUid()); } out.write(delimiter); out.write("" + demand.getResource().getTid()); out.write(delimiter); out.write("" + demand.getAmount()); } else if(referenceCombo.getSelectedItem()==NAME_OUTPUT) { out.write("" + simDemand.getTime()); out.write(delimiter); out.write(simDemand.getLocation().getName()); out.write(delimiter); if(simDemand.getElement()!=null) { out.write("" + simDemand.getElement().getName()); } out.write(delimiter); out.write(demand.getResource().getName()); out.write(delimiter); out.write("" + demand.getAmount()); } out.write(System.getProperty("line.separator")); } } } else if(demandsCombo.getSelectedItem()==AGGREGATED_DEMANDS) { out.write("Time1" + delimiter + "Time2" + delimiter + "Node1" + delimiter + "Node2" + delimiter + "Resource" + delimiter + "Amount" + System.getProperty("line.separator")); for(SupplyEdge supplyEdge : simulator.getSupplyEdges()) { for(Demand demand : simulator.getAggregatedEdgeDemands().get(supplyEdge)) { if(referenceCombo.getSelectedItem()==ID_OUTPUT) { out.write("" + supplyEdge.getStartTime()); out.write(delimiter); out.write("" + supplyEdge.getEndTime()); out.write(delimiter); out.write("" + supplyEdge.getOrigin().getTid()); out.write(delimiter); out.write("" + supplyEdge.getDestination().getTid()); out.write(delimiter); out.write("" + demand.getResource().getTid()); out.write(delimiter); out.write("" + demand.getAmount()); } else if(referenceCombo.getSelectedItem()==NAME_OUTPUT) { out.write("" + supplyEdge.getStartTime()); out.write(delimiter); out.write("" + supplyEdge.getEndTime()); out.write(delimiter); out.write(supplyEdge.getOrigin().getName()); out.write(delimiter); out.write(supplyEdge.getDestination().getName()); out.write(delimiter); out.write(demand.getResource().getName()); out.write(delimiter); out.write("" + demand.getAmount()); } out.write(System.getProperty("line.separator")); } SupplyPoint supplyPoint = supplyEdge.getPoint(); for(Demand demand : simulator.getAggregatedNodeDemands().get(supplyPoint)) { if(referenceCombo.getSelectedItem()==ID_OUTPUT) { out.write("" + supplyPoint.getNode().getTid()); out.write(delimiter); out.write(delimiter); out.write("" + supplyPoint.getTime()); out.write(delimiter); out.write(delimiter); out.write("" + demand.getResource().getTid()); out.write(delimiter); out.write("" + demand.getAmount()); } else if(referenceCombo.getSelectedItem()==NAME_OUTPUT) { out.write(supplyPoint.getNode().getName()); out.write(delimiter); out.write(delimiter); out.write("" + supplyPoint.getTime()); out.write(delimiter); out.write(delimiter); out.write(demand.getResource().getName()); out.write(delimiter); out.write("" + demand.getAmount()); } out.write(System.getProperty("line.separator")); } } } out.close(); } catch(IOException ex) { JOptionPane.showMessageDialog(this, "An error of type \"" + ex.getClass().getSimpleName() + "\" occurred while exporting the demands", "SpaceNet Error", JOptionPane.ERROR_MESSAGE); } } /** * The Class ExportWorker. */ private class ExportWorker extends SwingWorker<Void, Void> { /* (non-Javadoc) * @see org.jdesktop.swingworker.SwingWorker#doInBackground() */ protected Void doInBackground() { try { SpaceNetFrame.getInstance().getStatusBar().setStatusMessage("Exporting Demands..."); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); writeFile(); setCursor(Cursor.getDefaultCursor()); SpaceNetFrame.getInstance().getStatusBar().clearStatusMessage(); } catch(Exception ex) { ex.printStackTrace(); } return null; } } /** * Requests that the component and any nested components update themselves. */ public void updateView() { discretizationCombo.setSelectedItem(getScenario().getItemDiscretization()); aggregationSlider.setValue((int)(getScenario().getItemAggregation()*4)); aggregationSlider.setEnabled(getScenario().getItemDiscretization()!=ItemDiscretization.NONE); scavengeSparesCheck.setSelected(getScenario().isScavengeSpares()); while(simWorker != null && !simWorker.isDone()) { // lock UI while previous simulation is running } simWorker = new SimWorker(); simWorker.execute(); } /** * Updates the currently-visible tab. */ private void updateTab() { if(tabbedPane.getSelectedComponent().equals(feasibilityTab)) { feasibilityTab.updateView(); } else if(tabbedPane.getSelectedComponent().equals(networkTab)) { networkTab.updateView(); } else if(tabbedPane.getSelectedComponent().equals(elementDemandsTab)) { elementDemandsTab.updateView(); } else if(tabbedPane.getSelectedComponent().equals(missionDemandTab)) { missionDemandTab.updateView(); } else if(tabbedPane.getSelectedComponent().equals(locationDemandTab)) { locationDemandTab.updateView(); } else if(tabbedPane.getSelectedComponent().equals(repairabilityTab)) { repairabilityTab.updateView(); } else if(tabbedPane.getSelectedComponent().equals(commonalityTab)) { commonalityTab.updateView(); } } }
34.766049
124
0.722252
74cdd1c93ac6c6b23a53a36c61b4b4f5393f5298
272
css
CSS
public/stylesheets/style_list.css
AldenisFranca/sistema-cadastro
08a05e874e34c726278d17b45e1a903a22347765
[ "MIT" ]
null
null
null
public/stylesheets/style_list.css
AldenisFranca/sistema-cadastro
08a05e874e34c726278d17b45e1a903a22347765
[ "MIT" ]
null
null
null
public/stylesheets/style_list.css
AldenisFranca/sistema-cadastro
08a05e874e34c726278d17b45e1a903a22347765
[ "MIT" ]
null
null
null
html, body{ margin: 0; height: 100%; background-image: url(../images/pc.jpg); background-repeat: no-repeat; background-size: cover; background-position: center; background-attachment: fixed; } .container{ height: 100%; align-content: center; }
19.428571
44
0.665441
e6c5dd9092d7c4600c345373280b1ffaaf84d83e
130
asm
Assembly
libsrc/_DEVELOPMENT/math/float/math48/lm/c/sdcc_ix/log2_fastcall.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
libsrc/_DEVELOPMENT/math/float/math48/lm/c/sdcc_ix/log2_fastcall.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
libsrc/_DEVELOPMENT/math/float/math48/lm/c/sdcc_ix/log2_fastcall.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
SECTION code_fp_math48 PUBLIC _log2_fastcall EXTERN cm48_sdccix_log2_fastcall defc _log2_fastcall = cm48_sdccix_log2_fastcall
14.444444
47
0.884615
0fe41504c8a3b4506d4e904b6f6d3deeebd3788c
12,800
go
Go
repo/blob/s3/s3_storage_test.go
kopia/kopia
52837d12dd70169c5f831b83788e98e1b61da828
[ "Apache-2.0" ]
1,592
2016-08-18T18:24:30.000Z
2022-03-31T23:04:17.000Z
repo/blob/s3/s3_storage_test.go
kopia/kopia
52837d12dd70169c5f831b83788e98e1b61da828
[ "Apache-2.0" ]
1,315
2016-07-11T12:15:16.000Z
2022-03-31T08:21:29.000Z
repo/blob/s3/s3_storage_test.go
kopia/kopia
52837d12dd70169c5f831b83788e98e1b61da828
[ "Apache-2.0" ]
126
2016-11-30T14:29:30.000Z
2022-03-26T15:42:13.000Z
package s3 import ( "context" "encoding/json" "errors" "fmt" "net/http" "os" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sts" "github.com/google/uuid" "github.com/minio/minio-go/v7" miniocreds "github.com/minio/minio-go/v7/pkg/credentials" "github.com/stretchr/testify/require" "github.com/kopia/kopia/internal/blobtesting" "github.com/kopia/kopia/internal/clock" "github.com/kopia/kopia/internal/gather" "github.com/kopia/kopia/internal/providervalidation" "github.com/kopia/kopia/internal/testlogging" "github.com/kopia/kopia/internal/testutil" "github.com/kopia/kopia/repo/blob" ) const ( // https://github.com/minio/minio-go // fake creadentials used by minio server we're launching. minioRootAccessKeyID = "fake-key" minioRootSecretAccessKey = "fake-secret" minioRegion = "fake-region-1" minioBucketName = "my-bucket" // we use ephemeral minio for each test so this does not need to be unique // default aws S3 endpoint. awsEndpoint = "s3.amazonaws.com" // env vars need to be set to execute TestS3StorageAWS. testEndpointEnv = "KOPIA_S3_TEST_ENDPOINT" testAccessKeyIDEnv = "KOPIA_S3_TEST_ACCESS_KEY_ID" testSecretAccessKeyEnv = "KOPIA_S3_TEST_SECRET_ACCESS_KEY" testBucketEnv = "KOPIA_S3_TEST_BUCKET" testLockedBucketEnv = "KOPIA_S3_TEST_LOCKED_BUCKET" testRegionEnv = "KOPIA_S3_TEST_REGION" // additional env vars need to be set to execute TestS3StorageAWSSTS. testSTSAccessKeyIDEnv = "KOPIA_S3_TEST_STS_ACCESS_KEY_ID" testSTSSecretAccessKeyEnv = "KOPIA_S3_TEST_STS_SECRET_ACCESS_KEY" testSessionTokenEnv = "KOPIA_S3_TEST_SESSION_TOKEN" expiredBadSSL = "https://expired.badssl.com/" selfSignedBadSSL = "https://self-signed.badssl.com/" untrustedRootBadSSL = "https://untrusted-root.badssl.com/" wrongHostBadSSL = "https://wrong.host.badssl.com/" ) var providerCreds = map[string]string{ "S3": "KOPIA_S3_CREDS", "S3-Versioned": "KOPIA_S3_VERSIONED_CREDS", "Wasabi": "KOPIA_S3_WASABI_CREDS", "Wasabi-Versioned": "KOPIA_S3_WASABI_VERSIONED_CREDS", } // startDockerMinioOrSkip starts ephemeral minio instance on a random port and returns the endpoint ("localhost:xxx"). func startDockerMinioOrSkip(t *testing.T) string { t.Helper() testutil.TestSkipOnCIUnlessLinuxAMD64(t) containerID := testutil.RunContainerAndKillOnCloseOrSkip(t, "run", "--rm", "-p", "0:9000", "-e", "MINIO_ROOT_USER="+minioRootAccessKeyID, "-e", "MINIO_ROOT_PASSWORD="+minioRootSecretAccessKey, "-e", "MINIO_REGION_NAME="+minioRegion, "-d", "minio/minio", "server", "/data") endpoint := testutil.GetContainerMappedPortAddress(t, containerID, "9000") t.Logf("endpoint: %v", endpoint) return endpoint } func getEnvOrSkip(tb testing.TB, name string) string { tb.Helper() value := os.Getenv(name) if value == "" { tb.Skip(fmt.Sprintf("Environment variable '%s' not provided", name)) } return value } func getEnv(name, defValue string) string { value, ok := os.LookupEnv(name) if !ok { return defValue } return value } func getProviderOptions(tb testing.TB, envName string) *Options { tb.Helper() value := getEnvOrSkip(tb, envName) var o Options if err := json.NewDecoder(strings.NewReader(value)).Decode(&o); err != nil { tb.Skipf("invalid credentials JSON provided in '%v'", envName) } if o.Prefix != "" { tb.Fatalf("options providd in '%v' must not specify a prefix", envName) } return &o } func TestS3StorageProviders(t *testing.T) { t.Parallel() for k, env := range providerCreds { env := env t.Run(k, func(t *testing.T) { opt := getProviderOptions(t, env) testStorage(t, opt) }) } } func TestS3StorageAWS(t *testing.T) { t.Parallel() // skip the test if AWS creds are not provided options := &Options{ Endpoint: getEnv(testEndpointEnv, awsEndpoint), AccessKeyID: getEnvOrSkip(t, testAccessKeyIDEnv), SecretAccessKey: getEnvOrSkip(t, testSecretAccessKeyEnv), BucketName: getEnvOrSkip(t, testBucketEnv), Region: getEnvOrSkip(t, testRegionEnv), } createBucket(t, options) testStorage(t, options) } func TestS3StorageAWSSTS(t *testing.T) { t.Parallel() testutil.ProviderTest(t) // skip the test if AWS STS creds are not provided options := &Options{ Endpoint: getEnv(testEndpointEnv, awsEndpoint), AccessKeyID: getEnvOrSkip(t, testSTSAccessKeyIDEnv), SecretAccessKey: getEnvOrSkip(t, testSTSSecretAccessKeyEnv), SessionToken: getEnvOrSkip(t, testSessionTokenEnv), BucketName: getEnvOrSkip(t, testBucketEnv), Region: getEnvOrSkip(t, testRegionEnv), } // STS token may no have permission to create bucket // use accesskeyid and secretaccesskey to create the bucket createBucket(t, &Options{ Endpoint: getEnv(testEndpointEnv, awsEndpoint), AccessKeyID: getEnv(testAccessKeyIDEnv, ""), SecretAccessKey: getEnv(testSecretAccessKeyEnv, ""), BucketName: options.BucketName, Region: options.Region, }) testStorage(t, options) } func TestS3StorageMinio(t *testing.T) { t.Parallel() testutil.ProviderTest(t) minioEndpoint := startDockerMinioOrSkip(t) options := &Options{ Endpoint: minioEndpoint, AccessKeyID: minioRootAccessKeyID, SecretAccessKey: minioRootSecretAccessKey, BucketName: minioBucketName, Region: minioRegion, DoNotUseTLS: true, } createBucket(t, options) testStorage(t, options) } func TestInvalidCredsFailsFast(t *testing.T) { t.Parallel() testutil.ProviderTest(t) minioEndpoint := startDockerMinioOrSkip(t) ctx := testlogging.Context(t) t0 := clock.Now() _, err := New(ctx, &Options{ Endpoint: minioEndpoint, AccessKeyID: minioRootAccessKeyID, SecretAccessKey: minioRootSecretAccessKey + "bad", BucketName: minioBucketName, Region: minioRegion, DoNotUseTLS: false, DoNotVerifyTLS: false, }) require.Error(t, err) if dt := clock.Since(t0); dt > 10*time.Second { t.Fatalf("opening storage took too long, probably due to retries") } } func TestS3StorageMinioSTS(t *testing.T) { t.Parallel() testutil.ProviderTest(t) minioEndpoint := startDockerMinioOrSkip(t) time.Sleep(2 * time.Second) kopiaAccessKeyID, kopiaSecretKey, kopiaSessionToken := createMinioSessionToken(t, minioEndpoint, minioRootAccessKeyID, minioRootSecretAccessKey, minioBucketName) createBucket(t, &Options{ Endpoint: minioEndpoint, AccessKeyID: minioRootAccessKeyID, SecretAccessKey: minioRootSecretAccessKey, BucketName: minioBucketName, Region: minioRegion, DoNotUseTLS: true, }) require.NotEqual(t, kopiaAccessKeyID, minioRootAccessKeyID) require.NotEqual(t, kopiaSecretKey, minioRootSecretAccessKey) testStorage(t, &Options{ Endpoint: minioEndpoint, AccessKeyID: kopiaAccessKeyID, SecretAccessKey: kopiaSecretKey, SessionToken: kopiaSessionToken, BucketName: minioBucketName, Region: minioRegion, DoNotUseTLS: true, }) } func TestNeedMD5AWS(t *testing.T) { t.Parallel() testutil.ProviderTest(t) // skip the test if AWS creds are not provided options := &Options{ Endpoint: getEnv(testEndpointEnv, awsEndpoint), AccessKeyID: getEnvOrSkip(t, testAccessKeyIDEnv), SecretAccessKey: getEnvOrSkip(t, testSecretAccessKeyEnv), BucketName: getEnvOrSkip(t, testLockedBucketEnv), Region: getEnvOrSkip(t, testRegionEnv), } ctx := testlogging.Context(t) cli := createClient(t, options) makeBucket(t, cli, options, true) // ensure it is a bucket with object locking enabled want := "Enabled" if got, _, _, _, _ := cli.GetObjectLockConfig(ctx, options.BucketName); got != want { t.Fatalf("object locking is not enabled: got '%s', want '%s'", got, want) } // ensure a locking configuration is in place lockingMode := minio.Governance unit := uint(1) days := minio.Days err := cli.SetBucketObjectLockConfig(ctx, options.BucketName, &lockingMode, &unit, &days) require.NoError(t, err, "could not set object lock config") options.Prefix = uuid.NewString() + "/" s, err := New(ctx, options) require.NoError(t, err, "could not create storage") t.Cleanup(func() { blobtesting.CleanupOldData(context.Background(), t, s, 0) }) err = s.PutBlob(ctx, blob.ID("test-put-blob-0"), gather.FromSlice([]byte("xxyasdf243z"))) require.NoError(t, err, "could not put test blob") } // nolint:thelper func testStorage(t *testing.T, options *Options) { ctx := testlogging.Context(t) require.Equal(t, "", options.Prefix) st0, err := New(testlogging.Context(t), options) require.NoError(t, err) defer st0.Close(ctx) blobtesting.CleanupOldData(ctx, t, st0, blobtesting.MinCleanupAge) options.Prefix = uuid.NewString() st, err := New(testlogging.Context(t), options) require.NoError(t, err) defer st.Close(ctx) defer blobtesting.CleanupOldData(ctx, t, st, 0) blobtesting.VerifyStorage(ctx, t, st) blobtesting.AssertConnectionInfoRoundTrips(ctx, t, st) require.NoError(t, providervalidation.ValidateProvider(ctx, st, blobtesting.TestValidationOptions)) } func TestCustomTransportNoSSLVerify(t *testing.T) { t.Parallel() testutil.ProviderTest(t) testURL(t, expiredBadSSL) testURL(t, selfSignedBadSSL) testURL(t, untrustedRootBadSSL) testURL(t, wrongHostBadSSL) } func getURL(url string, insecureSkipVerify bool) error { client := &http.Client{Transport: getCustomTransport(insecureSkipVerify)} resp, err := client.Get(url) // nolint:noctx if err != nil { return err } defer resp.Body.Close() return nil } func testURL(t *testing.T, url string) { t.Helper() err := getURL(url, true) if err != nil { t.Fatalf("could not get url:%s, error:%v", url, err) } err = getURL(url, false) if err == nil { t.Fatalf("expected a TLS issue, but none found for url:%s", url) } } func createClient(tb testing.TB, opt *Options) *minio.Client { tb.Helper() minioClient, err := minio.New(opt.Endpoint, &minio.Options{ Creds: miniocreds.NewStaticV4(opt.AccessKeyID, opt.SecretAccessKey, ""), Secure: !opt.DoNotUseTLS, Region: opt.Region, }) if err != nil { tb.Fatalf("can't initialize minio client: %v", err) } return minioClient } func createBucket(tb testing.TB, opt *Options) { tb.Helper() minioClient := createClient(tb, opt) makeBucket(tb, minioClient, opt, false) } func makeBucket(tb testing.TB, cli *minio.Client, opt *Options, objectLocking bool) { tb.Helper() if err := cli.MakeBucket(context.Background(), opt.BucketName, minio.MakeBucketOptions{ Region: opt.Region, ObjectLocking: objectLocking, }); err != nil { var er minio.ErrorResponse if errors.As(err, &er) && er.Code == "BucketAlreadyOwnedByYou" { // ignore error return } tb.Fatalf("unable to create bucket: %v", err) } } func createMinioSessionToken(t *testing.T, minioEndpoint, kopiaUserName, kopiaUserPasswd, bucketName string) (accessID, secretKey, sessionToken string) { t.Helper() // Configure to use MinIO Server awsConfig := &aws.Config{ Credentials: credentials.NewStaticCredentials(kopiaUserName, kopiaUserPasswd, ""), Endpoint: aws.String(minioEndpoint), Region: aws.String(minioRegion), S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true), } awsSession, err := session.NewSession(awsConfig) if err != nil { t.Fatalf("failed to create aws session: %v", err) } svc := sts.New(awsSession) input := &sts.AssumeRoleInput{ // give access to only S3 bucket with name bucketName Policy: aws.String(fmt.Sprintf(`{ "Version":"2012-10-17", "Statement":[ { "Sid": "ReadBucket", "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::%v" }, { "Sid": "AllowFullAccessInBucket", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::%v/*" } ]}`, bucketName, bucketName)), // RoleArn and RoleSessionName are not meaningful for MinIO and can be set to any value RoleArn: aws.String("arn:xxx:xxx:xxx:xxxx"), RoleSessionName: aws.String("kopiaTestSession"), DurationSeconds: aws.Int64(900), // in seconds } result, err := svc.AssumeRole(input) if err != nil { t.Fatalf("failed to create session with aws assume role: %v", err) } if result.Credentials == nil { t.Fatalf("couldn't find aws creds in aws assume role response") } t.Logf("created session token with assume role: expiration: %s", result.Credentials.Expiration) return *result.Credentials.AccessKeyId, *result.Credentials.SecretAccessKey, *result.Credentials.SessionToken }
27.586207
162
0.707656
a3c5a3bab972bd7ac8dbb395d4a5582621a097cb
4,974
java
Java
mysql-binlog-reader-common/src/main/java/com/github/mysqlbinlogreader/SimpleMysqlBinlogClient.java
dwolgar/mysql-binlog-processor
75b3ff13731522c09d904bac1f333e4a87cece1e
[ "Apache-2.0" ]
2
2018-12-23T19:52:42.000Z
2018-12-23T19:55:49.000Z
mysql-binlog-reader-common/src/main/java/com/github/mysqlbinlogreader/SimpleMysqlBinlogClient.java
dwolgar2git/mysql-binlog-processor
75b3ff13731522c09d904bac1f333e4a87cece1e
[ "Apache-2.0" ]
null
null
null
mysql-binlog-reader-common/src/main/java/com/github/mysqlbinlogreader/SimpleMysqlBinlogClient.java
dwolgar2git/mysql-binlog-processor
75b3ff13731522c09d904bac1f333e4a87cece1e
[ "Apache-2.0" ]
1
2019-12-04T06:06:04.000Z
2019-12-04T06:06:04.000Z
/* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.github.mysqlbinlogreader; import com.github.mysqlbinlog.model.event.BinlogEvent; import com.github.mysqlbinlog.model.event.RotateEvent; import com.github.mysqlbinlog.model.event.TableMapEvent; import com.github.mysqlbinlogreader.common.MysqlBinlogEventListener; import com.github.mysqlbinlogreader.common.MysqlBinlogReader; import com.github.mysqlbinlogreader.common.eventposition.EventPosition; import com.github.mysqlbinlogreader.common.eventposition.EventPositionStorage; import com.github.mysqlbinlogreader.common.exception.RuntimeMysqlBinlogClientException; import com.github.mysqlbinlogreader.common.exception.RuntimeMysqlErrorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public class SimpleMysqlBinlogClient { private static final Logger LOGGER = LoggerFactory.getLogger(SimpleMysqlBinlogClient.class); private MysqlBinlogReader mysqlBinlogReader; private List<MysqlBinlogEventListener> mysqlBinlogEventListeners; private EventPositionStorage eventPositionStorage; public SimpleMysqlBinlogClient() { this.mysqlBinlogEventListeners = new ArrayList<>(); } private void updateEventPosition() { try { mysqlBinlogReader.setEventPosition(this.eventPositionStorage.getCurrent()); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to read initial binlog position.\nError[" + e.getMessage() + "]\n" + "Going to use current position from Master"); } } } public void process() { try { if (this.mysqlBinlogReader.getEventPosition() == null) { updateEventPosition(); } mysqlBinlogReader.open(); while (true) { BinlogEvent event = mysqlBinlogReader.readBinlogEvent(); if (event == null) { throw new RuntimeMysqlBinlogClientException("Null Event"); } boolean changePosition = true; for (MysqlBinlogEventListener eventListener : this.mysqlBinlogEventListeners) { if (!eventListener.onEvent(event)) { changePosition = false; } } if (event instanceof RotateEvent) { final RotateEvent e = (RotateEvent) event; if (changePosition) { EventPosition currentEventPosition = mysqlBinlogReader.getEventPosition(); currentEventPosition.setBinlogFileName(e.getBinlogFileName()); currentEventPosition.setPosition(e.getBinlogPosition()); eventPositionStorage.saveCurrent(currentEventPosition); } } else if (!(event instanceof TableMapEvent)) { long nextPosition = event.getHeader().getNextPosition(); if (nextPosition > 0 && changePosition) { EventPosition currentEventPosition = mysqlBinlogReader.getEventPosition(); currentEventPosition.setPosition(nextPosition); eventPositionStorage.saveCurrent(currentEventPosition); } } } } catch (RuntimeMysqlErrorException ex) { LOGGER.error("ERROR [" + ex.getMessage() + "][" + ex.getErrorResponsePacket() + "]", ex); } catch (Exception ex) { LOGGER.error("ERROR [" + ex.getMessage() + "]", ex); } finally { mysqlBinlogReader.close(); } } public void addMysqlBinlogEventListener(MysqlBinlogEventListener listener) { this.mysqlBinlogEventListeners.add(listener); } public MysqlBinlogReader getMysqlBinlogReader() { return mysqlBinlogReader; } public void setMysqlBinlogReader(MysqlBinlogReader mysqlBinlogReader) { this.mysqlBinlogReader = mysqlBinlogReader; } public EventPositionStorage getEventPositionStorage() { return eventPositionStorage; } public void setEventPositionStorage(EventPositionStorage eventPositionStorage) { this.eventPositionStorage = eventPositionStorage; } }
39.792
103
0.645155
05f95e2af6de14575c5e2a61d09d1dce5b1a1e4d
162
py
Python
CSCI3104_Question1_O(n^2).py
shng5175/Random-Python-Stuff
6b6687da9195a36244f7b22de7ba2984ce78995d
[ "bzip2-1.0.6" ]
null
null
null
CSCI3104_Question1_O(n^2).py
shng5175/Random-Python-Stuff
6b6687da9195a36244f7b22de7ba2984ce78995d
[ "bzip2-1.0.6" ]
null
null
null
CSCI3104_Question1_O(n^2).py
shng5175/Random-Python-Stuff
6b6687da9195a36244f7b22de7ba2984ce78995d
[ "bzip2-1.0.6" ]
null
null
null
a = [8, 10, 2, 5, 20, 1] count = 0 for i in range(len(a)): for j in range(i + 1, len(a)): if (a[i] > a[j]): count += 1 print count
20.25
35
0.425926
9421ec43cf812c25d16dbe1cda7c886ac9defae0
224
sql
SQL
db/migrations/20210506044603_short_login_codes.sql
jackrr/bubble
963e1227128fe16784fe15ec1ac6bb525bc15b63
[ "MIT" ]
1
2021-03-17T03:00:00.000Z
2021-03-17T03:00:00.000Z
db/migrations/20210506044603_short_login_codes.sql
jackrr/bubble
963e1227128fe16784fe15ec1ac6bb525bc15b63
[ "MIT" ]
28
2021-04-25T15:56:59.000Z
2022-01-19T01:14:25.000Z
db/migrations/20210506044603_short_login_codes.sql
jackrr/bubble
963e1227128fe16784fe15ec1ac6bb525bc15b63
[ "MIT" ]
null
null
null
-- migrate:up alter table login_codes add column short boolean; alter table login_codes add column short_code TEXT; -- migrate:down alter table login_codes drop column short; alter table login_codes drop column short_code;
28
51
0.816964
146c1075c7f061a4320587420694ff0215dc241f
101
ts
TypeScript
packages/react-component-library/src/components/CheckboxRadioBase/index.ts
defencedigital/defence-design-system
ad2fb36c647e6cc61addafc527d7cb68685ab59a
[ "Apache-2.0" ]
16
2019-06-18T10:06:25.000Z
2020-02-12T11:25:35.000Z
packages/react-component-library/src/components/CheckboxRadioBase/index.ts
defencedigital/mod-uk-design-system
f0abe3fa91b6971f6458c1ae50b843173772162e
[ "Apache-2.0" ]
470
2021-09-30T15:08:26.000Z
2022-03-30T14:31:20.000Z
packages/react-component-library/src/components/CheckboxRadioBase/index.ts
defencedigital/design-system
9396d1a87207417b6bf1654adec0df34536668fa
[ "Apache-2.0" ]
5
2021-11-02T12:41:43.000Z
2022-03-29T13:01:55.000Z
export * from './CheckboxRadioBase' export * from './CheckboxRadioBaseProps' export * from './types'
25.25
40
0.732673
051a50a2fb6a56baa9c9652f22d3d4057818600c
799
rs
Rust
src/ui/utils.rs
yaguozhou/rmd
868cc7a1333bc74d17aebb46d2cf518471f30956
[ "MulanPSL-1.0" ]
null
null
null
src/ui/utils.rs
yaguozhou/rmd
868cc7a1333bc74d17aebb46d2cf518471f30956
[ "MulanPSL-1.0" ]
null
null
null
src/ui/utils.rs
yaguozhou/rmd
868cc7a1333bc74d17aebb46d2cf518471f30956
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Yaguo Zhou * rmd is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ use gtk::*; use sourceview::*; pub fn get_content(buff: &Buffer) -> Option<String> { let start = buff.get_start_iter(); let end = buff.get_end_iter(); if let Some(gstr) = buff.get_text(&start, &end, true) { Some(gstr.to_owned()) } else { None } }
33.291667
87
0.674593
7063ab64e4690b1a2e704deeb5bf08bc22da80f1
2,421
cpp
C++
day22/main.cpp
Kazhuu/advent-of-code-2020
6478c412788dfc6111477127b27957d4f5a8553d
[ "MIT" ]
8
2020-12-01T18:02:52.000Z
2021-11-30T10:44:26.000Z
day22/main.cpp
Kazhuu/advent-of-code-2020
6478c412788dfc6111477127b27957d4f5a8553d
[ "MIT" ]
null
null
null
day22/main.cpp
Kazhuu/advent-of-code-2020
6478c412788dfc6111477127b27957d4f5a8553d
[ "MIT" ]
3
2020-12-03T05:16:06.000Z
2021-01-25T20:49:41.000Z
#include <vector> #include <string> #include <deque> #include <iostream> #include <cassert> std::pair<std::deque<int64_t>, std::deque<int64_t>> parse_input() { std::deque<int64_t> player1; std::deque<int64_t> player2; std::string line; std::getline(std::cin, line); while(std::getline(std::cin, line)) { if (line.empty()) { break; } player1.emplace_back(std::stoi(line)); } std::getline(std::cin, line); while(std::getline(std::cin, line)) { if (line.empty()) { break; } player2.emplace_back(std::stoi(line)); } return std::make_pair(player1, player2); } void print_deck(const std::deque<int64_t> &deck) { std::cout << "Deck: "; for (auto card : deck) { std::cout << card << " "; } std::cout << std::endl; } void play_turn(std::deque<int64_t> &player1, std::deque<int64_t> &player2) { int64_t player1_card = player1.front(); int64_t player2_card = player2.front(); player1.pop_front(); player2.pop_front(); if (player1_card > player2_card) { player1.push_back(player1_card); player1.push_back(player2_card); std::cout << "Player 1 wins!" << std::endl; } else if (player2_card > player1_card) { player2.push_back(player2_card); player2.push_back(player1_card); std::cout << "Player 2 wins!" << std::endl; } else { std::cout << "draw" << std::endl; } } uint64_t calculate_points(const std::deque<int64_t> &deck) { uint64_t total = 0; for (int64_t i = 0; i < deck.size(); ++i) { total += deck[i] * (deck.size() - i); } return total; } int main() { auto [player1, player2] = parse_input(); int64_t turn = 1; while (player1.size() != 0 && player2.size() != 0) { std::cout << "Turn " << turn << std::endl; std::cout << "Player 1 "; print_deck(player1); std::cout << "Player 2 "; print_deck(player2); play_turn(player1, player2); ++turn; } uint64_t score = 0; if (player1.empty()) { score = calculate_points(player2); } else if (player2.empty()) { score = calculate_points(player1); } else { assert(false && "no winner"); } std::cout << "first answer: " << score << std::endl; assert(score == 36257 && "first solution doesn't match"); return 0; }
28.151163
76
0.565882
a91200df2403bc87cbba43cdffd238ba69cc60e0
1,215
css
CSS
css/contact.css
jmatejekmorris/jmatejekmorris.github.io
c829435c4968f9c9ed92b60e10177257636aa890
[ "MIT" ]
null
null
null
css/contact.css
jmatejekmorris/jmatejekmorris.github.io
c829435c4968f9c9ed92b60e10177257636aa890
[ "MIT" ]
null
null
null
css/contact.css
jmatejekmorris/jmatejekmorris.github.io
c829435c4968f9c9ed92b60e10177257636aa890
[ "MIT" ]
null
null
null
.contact-vertical-bar { margin-left: 39rem; } .contact-first-bar { top: 1rem; } .contact-second-bar { top: 12rem; } .contact-third-bar { top: 16rem; } .contact-menu-option:hover, .contact-menu-selected:hover { background-image:url('/images/bars/maroon-horizontal-contact-matte-menu-dark.png'); background-repeat: x-repeat; background-size: auto 100%; cursor: pointer; } .contact-menu-selected { background-image:url('/images/bars/maroon-horizontal-contact-matte-menu-light.png'); background-repeat: x-repeat; background-size: auto 100%; } .contact-books-menu li { background-color: #4B2F35; } .contact-books-menu li:hover { background-color: #B46278; } .contact-header { width: 64rem; font-family: 'Bigelow Rules', cursive; text-align: center; font-size: 7rem; height: 9rem; margin-top: 3.5rem; } .contact-information { width: 40rem; margin-left: 12rem; margin-top: 2rem; text-align: center; } .contact-information a { text-decoration: underline; color: inherit; } .contact-picture { width: 100%; box-shadow: -5px 5px 5px #444444; } .contact-picture-div { margin-top: 8rem; margin-bottom: 0.25rem; margin-left: 20rem; width: 24rem; }
15.779221
86
0.685597
2187278d6961418d350097535cd0ae9b11ff2a15
718
js
JavaScript
vue_frontend/src/store/modules/logger.js
TuftsVALT/Snowcat
4ff1a8ce32e172325a7be7f0095c8659f8709d18
[ "MIT" ]
2
2021-01-21T10:32:37.000Z
2021-05-04T11:36:29.000Z
vue_frontend/src/store/modules/logger.js
TuftsVALT/Snowcat
4ff1a8ce32e172325a7be7f0095c8659f8709d18
[ "MIT" ]
2
2020-10-16T18:14:00.000Z
2021-01-05T07:31:55.000Z
vue_frontend/src/store/modules/logger.js
TuftsVALT/Snowcat
4ff1a8ce32e172325a7be7f0095c8659f8709d18
[ "MIT" ]
null
null
null
// import phases from '@/store/settings/full_eval/phases' // import layouts from '@/store/settings/full_eval/layouts' // import style from '@/store/settings/full_eval/style' import _ from 'lodash' import Vue from "vue"; // initial state const state = { 'vast20ExpLog': {} } // getters const getters = { } // actions const actions = { } // mutations const mutations = { // SEND_LOG_MESSAGE (state, log_message) { // let v = new Vue(); // v.$socket.emit("", log_message); // state.task_number = number; // }, SEND_VAST20_LOG_MESSAGE(state, log_message) { let v = new Vue(); v.$socket.emit("logVast20Exp", log_message); } } export default { state, getters, actions, mutations }
18.410256
59
0.654596
e00478dd7fa1d570784385880120b2f127b95247
4,845
php
PHP
resources/views/admin/dashboard.blade.php
coderkhayrul/tech-blog-website
5504d199439d1cc5950960e6795daa174cdeab4a
[ "MIT" ]
null
null
null
resources/views/admin/dashboard.blade.php
coderkhayrul/tech-blog-website
5504d199439d1cc5950960e6795daa174cdeab4a
[ "MIT" ]
null
null
null
resources/views/admin/dashboard.blade.php
coderkhayrul/tech-blog-website
5504d199439d1cc5950960e6795daa174cdeab4a
[ "MIT" ]
null
null
null
@extends('admin.admin_master') @section('title') Admin Panel || Dashboard @endsection @section('content') <!-- Total Post Start --> <div class="col-12 col-sm-6 col-xl-4 mb-4"> <div class="card border-light shadow-sm"> <div class="card-body"> <div class="row d-block d-xl-flex align-items-center"> <div class="col-12 col-xl-5 text-xl-center mb-3 mb-xl-0 d-flex align-items-center justify-content-xl-center"> <div class="icon icon-shape icon-md icon-shape-blue rounded mr-4 mr-sm-0"> <span class="fas fa-dumpster-fire"></span></div> <div class="d-sm-none"> <h2 class="h5">Total Post</h2> <h3 class="mb-1">{{ count($posts) }}</h3> </div> </div> <div class="col-12 col-xl-7 px-xl-0"> <div class="d-none d-sm-block"> <h2 class="h5">Total Post</h2> <h3 class="mb-1">{{ count($posts) }}</h3> </div> <small>Active <span class="icon icon-small"> <span class="fas fa-check text-success"></span> </span> {{ count($activePosts) }}</small> <br> <small>Inactive <span class="icon icon-small text-danger"> <span class="fas fa-times"></span> </span> {{ count($inActivePosts) }}</small> </div> </div> </div> </div> </div> <!-- Total Post End --> <!-- Total Category Start --> <div class="col-12 col-sm-6 col-xl-4 mb-4"> <div class="card border-light shadow-sm"> <div class="card-body"> <div class="row d-block d-xl-flex align-items-center"> <div class="col-12 col-xl-5 text-xl-center mb-3 mb-xl-0 d-flex align-items-center justify-content-xl-center"> <div class="icon icon-shape icon-md icon-shape-secondary rounded mr-4 mr-sm-0"> <span class="fas fa-clipboard-list"></span></div> <div class="d-sm-none"> <h2 class="h5">Total Category</h2> <h3 class="mb-1">{{ count($categories) }}</h3> </div> </div> <div class="col-12 col-xl-7 px-xl-0"> <div class="d-none d-sm-block"> <h2 class="h5">Total Category</h2> <h3 class="mb-1">{{ count($categories) }}</h3> </div> <small>Active <span class="icon icon-small"> <span class="fas fa-check text-success"></span> </span> {{ count($activeCategory) }}</small> <br> <small>Inactive <span class="icon icon-small text-danger"> <span class="fas fa-times"></span> </span> {{ count($InActiveCategory) }}</small> </div> </div> </div> </div> </div> <!-- Total Category End --> <div class="col-12 col-sm-6 col-xl-4 mb-4"> <div class="card border-light shadow-sm"> <div class="card-body"> <div class="row d-block d-xl-flex align-items-center"> <div class="col-12 col-xl-5 text-xl-center mb-3 mb-xl-0 d-flex align-items-center justify-content-xl-center"> <div class="ct-chart-traffic-share ct-golden-section ct-series-a"></div> </div> <div class="col-12 col-xl-7 px-xl-0"> <h2 class="h5 mb-3">Traffic Share</h2> <h6 class="font-weight-normal text-gray"><span class="icon w-20 icon-xs icon-secondary mr-1"><span class="fas fa-desktop"></span></span> Desktop <a href="#" class="h6">60%</a> </h6> <h6 class="font-weight-normal text-gray"><span class="icon w-20 icon-xs icon-primary mr-1"><span class="fas fa-mobile-alt"></span></span> Mobile Web <a href="#" class="h6">30%</a></h6> <h6 class="font-weight-normal text-gray"><span class="icon w-20 icon-xs icon-tertiary mr-1"><span class="fas fa-tablet-alt"></span></span> Tablet Web <a href="#" class="h6">10%</a></h6> </div> </div> </div> </div> </div> @endsection
44.449541
124
0.444376
3377e81e38cc1cded2140c297170c0445184185c
344
rb
Ruby
spec/support/devise_helpers.rb
pulibrary/dpul
e8b6720201bfb1dd7ad30f871b556e827195f6a5
[ "Apache-2.0" ]
9
2016-08-12T18:50:07.000Z
2020-06-01T21:08:41.000Z
spec/support/devise_helpers.rb
pulibrary/pomegranate
7d6dcb1e7f088085523f8662bc6509081b710d4a
[ "Apache-2.0" ]
742
2016-01-11T18:21:09.000Z
2021-02-26T19:02:27.000Z
spec/support/devise_helpers.rb
pulibrary/dpul
e8b6720201bfb1dd7ad30f871b556e827195f6a5
[ "Apache-2.0" ]
1
2016-01-11T18:08:19.000Z
2016-01-11T18:08:19.000Z
# frozen_string_literal: true require_relative 'request_spec_helper' RSpec.configure do |config| config.include Devise::Test::ControllerHelpers, type: :view config.include Devise::Test::ControllerHelpers, type: :controller config.include RequestSpecHelper, type: :request config.include RequestSpecHelper, type: :feature, js: true end
34.4
67
0.799419
12dc38079eee23927591b3cb3f8f6416709f30f9
3,734
cs
C#
Oak.Tests/describe_DynamicModels/eager_loading_for_belongs_to_with_duplicates.cs
ronaldnsabiyera/Oak
5aaeb583f60910d707c084a8c7db60d87636f822
[ "MIT" ]
50
2015-01-05T18:32:33.000Z
2021-05-12T06:37:13.000Z
Oak.Tests/describe_DynamicModels/eager_loading_for_belongs_to_with_duplicates.cs
ronaldnsabiyera/Oak
5aaeb583f60910d707c084a8c7db60d87636f822
[ "MIT" ]
4
2016-01-08T01:43:59.000Z
2016-08-16T15:17:12.000Z
Oak.Tests/describe_DynamicModels/eager_loading_for_belongs_to_with_duplicates.cs
ronaldnsabiyera/Oak
5aaeb583f60910d707c084a8c7db60d87636f822
[ "MIT" ]
23
2015-02-08T01:53:24.000Z
2017-06-16T13:57:48.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NSpec; using Oak.Tests.describe_DynamicModels.Classes; using Massive; namespace Oak.Tests.describe_DynamicModels { class eager_loading_for_belongs_to_with_duplicates : nspec { Players players; Seed seed; dynamic allPlayers; object player1Id, player2Id, game1Id, game2Id; List<string> sqlQueries; void belongs_where_entity_belongs_more_than_one_relation() { before = () => { seed = new Seed(); GameSchema.CreateSchema(seed); players = new Players(); player1Id = new { Name = "Jane" }.InsertInto("Players"); player2Id = new { Name = "John" }.InsertInto("Players"); game1Id = new { Title = "Mirror's Edge" }.InsertInto("Games"); game2Id = new { Title = "Gears of War" }.InsertInto("Games"); new { PlayerId = player1Id, GameId = game2Id }.InsertInto("Library"); new { PlayerId = player2Id, GameId = game1Id }.InsertInto("Library"); new { PlayerId = player2Id, GameId = game2Id }.InsertInto("Library"); sqlQueries = new List<string>(); DynamicRepository.WriteDevLog = true; DynamicRepository.LogSql = new Action<object, string, object[]>( (sender, sql, @params) => { sqlQueries.Add(sql); }); allPlayers = players.All(); allPlayers.Include("Library"); allPlayers.Library().Include("Game"); }; it["updates all references that map to the belongs to entity"] = () => { (allPlayers.First().Library().First().Game().Title as object).should_be("Gears of War"); (allPlayers.Last().Library().First().Game().Title as object).should_be("Mirror's Edge"); (allPlayers.Last().Library().Last().Game().Title as object).should_be("Gears of War"); sqlQueries.Count.should_be(3); }; } dynamic tasks = new Tasks(); object rabbitId, task1Id, task2Id, task3Id; void describe_track_back_property() { before = () => { Seed seed = new Seed(); seed.PurgeDb(); seed.CreateTable("Rabbits", seed.Id(), new { Name = "nvarchar(255)" }).ExecuteNonQuery(); seed.CreateTable("Tasks", seed.Id(), new { Description = "nvarchar(255)" }, new { RabbitId = "int" }).ExecuteNonQuery(); rabbitId = new { Name = "YT" }.InsertInto("Rabbits"); task1Id = new { Description = "task 1", rabbitId }.InsertInto("Tasks"); task2Id = new { Description = "task 2", rabbitId }.InsertInto("Tasks"); task3Id = new { Description = "task 3", rabbitId }.InsertInto("Tasks"); }; it["tracks back to multiple instances, converting a single value to a collection"] = () => { var allTasks = tasks.All().Include("Rabbit") as DynamicModels; var task = allTasks.First(); (task.Rabbit().Task as List<dynamic>).Count.should_be(3); (task.Rabbit().Task as List<dynamic>).should_contain(allTasks.First() as object); (task.Rabbit().Task as List<dynamic>).should_contain(allTasks.Second() as object); (task.Rabbit().Task as List<dynamic>).should_contain(allTasks.Last() as object); }; } } }
31.378151
136
0.539636
a48879bb25c3b7dc1ea1c8ba341c858f9a38d334
1,465
php
PHP
src/DatabaseMigrateTestListener.php
softonic/laravel-database-migrate-test-listener
b647640ea019406ae36303b2299d37acaf786866
[ "Apache-2.0" ]
1
2019-07-26T12:03:00.000Z
2019-07-26T12:03:00.000Z
src/DatabaseMigrateTestListener.php
softonic/laravel-database-migrate-test-listener
b647640ea019406ae36303b2299d37acaf786866
[ "Apache-2.0" ]
null
null
null
src/DatabaseMigrateTestListener.php
softonic/laravel-database-migrate-test-listener
b647640ea019406ae36303b2299d37acaf786866
[ "Apache-2.0" ]
null
null
null
<?php namespace Softonic\DatabaseMigrateTestListener; use Composer\Autoload\ClassLoader; use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use ReflectionClass; class DatabaseMigrateTestListener implements TestListener { use TestListenerDefaultImplementation; public $testSuites; public $itShouldSeed; public $connection; public $seeder; public function __construct(array $testSuites, bool $itShouldSeed, string $connection = 'sqlite', string $seeder = null) { $this->testSuites = $testSuites; $this->itShouldSeed = $itShouldSeed; $this->connection = $connection; $this->seeder = $seeder; } /** * Set up the database for testing. * * @param TestSuite $suite * * @throws \ReflectionException */ public function startTestSuite(TestSuite $suite): void { if (!in_array($suite->getName(), $this->testSuites)) { return; } $reflection = new ReflectionClass(ClassLoader::class); $appDirectory = dirname($reflection->getFileName(), 3); chdir($appDirectory); $seed = $this->itShouldSeed ? '--seed' : ''; $seeder = $this->itShouldSeed && !empty($this->seeder) ? "--seeder={$this->seeder}" : ''; echo shell_exec("php artisan migrate:refresh --database {$this->connection} $seed $seeder"); } }
27.641509
124
0.649147
259abbfe7cd5f1de4a758da6627b3136163c9c91
2,241
cs
C#
LocWarden.Core/LocalizedLanguage.cs
aschearer/locwarden
eee1440bc2f9f84f48062e8f8887a503c32eee12
[ "MIT" ]
1
2018-02-22T20:27:23.000Z
2018-02-22T20:27:23.000Z
LocWarden.Core/LocalizedLanguage.cs
aschearer/locwarden
eee1440bc2f9f84f48062e8f8887a503c32eee12
[ "MIT" ]
14
2018-02-19T02:19:45.000Z
2018-06-19T00:17:09.000Z
LocWarden.Core/LocalizedLanguage.cs
aschearer/LocWarden
eee1440bc2f9f84f48062e8f8887a503c32eee12
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; namespace LocWarden.Core { /// <summary> /// Represents a language to be validated. /// </summary> public sealed class LocalizedLanguage : IEquatable<LocalizedLanguage> { private ILanguageDefinition definition; /// <summary> /// The name of the language. /// </summary> public string Name { get { return this.definition.Name; } } /// <summary> /// The path to the language's file. /// </summary> public string Path { get { return this.definition.Path; } } /// <summary> /// Whether the language is the master language. The master language is /// the source of truth when validating languages. /// </summary> public bool IsMasterLanguage { get { return this.definition.IsMaster; } } /// <summary> /// Map of text Key's to Text. /// </summary> public readonly Dictionary<string, ILocalizedText> Rows = new Dictionary<string, ILocalizedText>(); /// <summary> /// List of errors encountered during validation for this language. /// </summary> public readonly List<LocalizationError> Errors = new List<LocalizationError>(); public void AddText(string key, string description, string value, int rowNumber) { this.Rows.Add(key, new LocalizedText(key, description, value, rowNumber)); } public LocalizedLanguage(ILanguageDefinition definition) { this.definition = definition; } public bool Equals(LocalizedLanguage other) { return this.Name == other.Name; } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { var localizedText = obj as LocalizedLanguage; return localizedText != null && localizedText.Name == this.Name; } public override string ToString() { return string.Format("Language({0})", this.Name); } } }
28.0125
107
0.56805
078229a330bf41a3cf1b1c703388beb0cf5e6408
2,541
css
CSS
styles/translator.css
juanuribe28/travelcssi
76a47863dc930d9006c3beb42e3fe2b00922ce7a
[ "MIT" ]
null
null
null
styles/translator.css
juanuribe28/travelcssi
76a47863dc930d9006c3beb42e3fe2b00922ce7a
[ "MIT" ]
1
2019-08-14T21:27:49.000Z
2019-08-14T21:27:49.000Z
styles/translator.css
JuanJUribe/travelcssi
76a47863dc930d9006c3beb42e3fe2b00922ce7a
[ "MIT" ]
2
2019-12-01T10:22:17.000Z
2020-05-08T19:45:44.000Z
.translate{ margin: 50px; grid-column: 1; grid-row: 1; align-items: left; text-align: left; font-size: 80px; height: 1px; width: 100%; color: #8BACB9; font-family: josefin-sans,sans-serif; font-weight: 700; font-style: normal; } section{ margin-top: 60px; text-align: center; grid-column: 1; grid-row: 1; font-size: 40px; font-weight: bold; width: 70%; /* margin: 100px;*/ } .caption{ margin-top: 30px; grid-column: 1; grid-row: 1; font-size: 20px; font-weight: bold; width: 100%; /* margin: 100px;*/ } } span { padding: 10px; } body{ display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr 1fr 1fr; font-family: kepler-std-semicondensed-dis, serif; font-weight: 700; font-style: normal; font-size: 15px; color: #013B52; height: 100vh; background-size: cover; background: linear-gradient(white, #C7D5DA); background-color: #C7D5DA; background-repeat: no-repeat; } section{ grid-column: 1; grid-row: 2; } header { background-color: #C7D5DA; display: flex; align-items: center; justify-content: flex-end; } #header { width: 100%; position: fixed; z-index: 100; background-color: #C7D5DA; position: fixed; top: 0; overflow: hidden; } .image{ grid-column: 2; grid-row: 2; } .bio1{ grid-column: 2; grid-row: 3; font-size: 35px; text-align: left; } .bio2{ grid-column: 2; grid-row: 4; font-size: 13px; text-align: left; font-family: josefin-sans,sans-serif; font-weight: 200; font-style: normal; height: 100vh; margin-right: 30%; width: 50vh; } nav { float: left; } nav ul { list-style: none; overflow: hidden; } nav ul li { float: left; font-family: kepler-std-semicondensed-dis,serif; font-weight: 700; font-style: normal; font-size: 16px; background-color: #C7D5DA; } nav ul li a { display: block; padding: 10px; color: #013B52; text-decoration: none; } nav ul li:hover { background: lightgrey; } * { padding: 0; margin: 0; } footer{ display: flex; align-items: center; justify-content: center; color: black; position: fixed; /* Set the navbar to fixed position */ bottom: 0; /* Position the navbar at the top of the page */ background-color: #E1EAE9; } }
15.88125
66
0.57497
a1548509a32eaadf1e81c2566ec590c42b1047bb
752
tsx
TypeScript
client/src/pages/NotFound/index.tsx
leoronne/seeker
0c0b91a65fc73dd90a2d191641f030abed93aa63
[ "MIT" ]
1
2020-11-13T01:14:00.000Z
2020-11-13T01:14:00.000Z
client/src/pages/NotFound/index.tsx
leoronne/seeker
0c0b91a65fc73dd90a2d191641f030abed93aa63
[ "MIT" ]
null
null
null
client/src/pages/NotFound/index.tsx
leoronne/seeker
0c0b91a65fc73dd90a2d191641f030abed93aa63
[ "MIT" ]
null
null
null
import React from 'react'; import { useTranslation } from 'react-i18next'; import { Link } from 'react-router-dom'; import { Container, Content, HomeIcon, Left, Main, Right } from './styles'; const NotFound: React.FC = () => { const { t } = useTranslation(); return ( <Container data-testid="not-found-page"> <Content> <Main> <Left> <h2>{t('error-page-1')}</h2> <p>{t('error-page-2')}</p> <div className="home-link"> <Link to="/"> <HomeIcon /> <span>{t('return')}</span> </Link> </div> </Left> <Right /> </Main> </Content> </Container> ); }; export default NotFound;
22.787879
75
0.482713
cd51b568d3d861ad6f72a9d45c361319850e31a2
226
cs
C#
Packages/Core/Runtime/Actions/IntAction.cs
lucasrferreira/unity-atoms
b51de335e0fb3568a478a7cbd0561a5649f01cf3
[ "MIT" ]
null
null
null
Packages/Core/Runtime/Actions/IntAction.cs
lucasrferreira/unity-atoms
b51de335e0fb3568a478a7cbd0561a5649f01cf3
[ "MIT" ]
null
null
null
Packages/Core/Runtime/Actions/IntAction.cs
lucasrferreira/unity-atoms
b51de335e0fb3568a478a7cbd0561a5649f01cf3
[ "MIT" ]
null
null
null
namespace UnityAtoms { /// <summary> /// Action of type `int`. Inherits from `AtomAction&lt;int&gt;`. /// </summary> [EditorIcon("atom-icon-purple")] public abstract class IntAction : AtomAction<int> { } }
25.111111
68
0.628319
9e0d0bd4cd94414ad3b128f6e0e3958c94dbcac7
3,835
cs
C#
Assets/Scripts/ggj2018/UI/PlayerHUDCard.cs
pdxpartyparrot/ggj2018
92e1bf305e60b61b95848c1d881bed48f736343e
[ "Apache-2.0" ]
1
2018-02-14T07:02:54.000Z
2018-02-14T07:02:54.000Z
Assets/Scripts/ggj2018/UI/PlayerHUDCard.cs
pdxparrot/ggj2018
92e1bf305e60b61b95848c1d881bed48f736343e
[ "Apache-2.0" ]
null
null
null
Assets/Scripts/ggj2018/UI/PlayerHUDCard.cs
pdxparrot/ggj2018
92e1bf305e60b61b95848c1d881bed48f736343e
[ "Apache-2.0" ]
null
null
null
using System.Collections; using pdxpartyparrot.Core.Util; using pdxpartyparrot.ggj2018.GameState; using pdxpartyparrot.ggj2018.GameTypes; using pdxpartyparrot.ggj2018.Players; using pdxpartyparrot.Game.State; using UnityEngine; using UnityEngine.UI; namespace pdxpartyparrot.ggj2018.UI { public class PlayerHUDCard : MonoBehavior { // TODO: split these up into separate widgets #region Intro [SerializeField] private GameObject _introPanel; [SerializeField] private Text _goalText; [SerializeField] private float _introPanelTime = 3.0f; #endregion #region Timer [SerializeField] private GameObject _timer; [SerializeField] private Text _timerText; #endregion #region Speed [SerializeField] private GameObject _speed; [SerializeField] private Text _speedText; #endregion #region Altitude [SerializeField] private Text _altitudeText; #endregion #region Boost [SerializeField] private Image _boostMeter; #endregion #region Goal Distance [SerializeField] private GameObject _goalDistance; [SerializeField] private Text _goalDistanceText; #endregion #region Kills [SerializeField] private GameObject _killPanel; [SerializeField] private GameObject _killCardPrefab; [SerializeField] private LayoutGroup _killCardLayout; #endregion #region Debug [SerializeField] private DebugVisualizer _debugVisualizer; public DebugVisualizer DebugVisualizer => _debugVisualizer; #endregion public void Initialize(Player player, GameType gameType) { _timer.SetActive(gameType.ShowTimer); _goalDistance.SetActive(!gameType.PredatorsKillPrey || player.Bird.Type.IsPrey); _killPanel.SetActive(gameType.PredatorsKillPrey && player.Bird.Type.IsPredator); RemoveKills(); _introPanel.SetActive(true); _goalText.text = gameType.GameTypeData.GetWinConditionDescription(player.Bird.Type); EnableDebugVisualizer(false); StartCoroutine(CloseIntroPanel()); } private IEnumerator CloseIntroPanel() { yield return new WaitForSeconds(_introPanelTime); _introPanel.SetActive(false); } public void SetState(Player player) { SetTimer((GameStateManager.Instance.CurrentState as GameStateGame)?.GameTimer ?? 0.0f); //_speedText.text = $"{(int)UnitUtils.MetersPerSecondToKilometersPerHour(player.Controller.Speed)} km/h"; _speedText.text = $"{(int)player.Controller.Speed} m/s"; _altitudeText.text = $"{(int)player.Controller.Altitude} m"; _boostMeter.fillAmount = player.State.BoostRemainingPercent; /*if(distance > 1000.0f) { _goalDistanceText.text = $"{(player.NearestGoalDistance / 1000.0f):0.00} km"; } else {*/ _goalDistanceText.text = $"{(int)player.NearestGoalDistance} m"; //} } private void SetTimer(float timerSeconds) { float minutes = Mathf.Floor(timerSeconds / 60.0f); float seconds = Mathf.Floor(timerSeconds % 60.0f); _timerText.text = $"{minutes:0}:{seconds:00}"; } public void AddKill() { Instantiate(_killCardPrefab, _killCardLayout.transform); } private void RemoveKills() { _killCardLayout.transform.Clear(); } public void EnableDebugVisualizer(bool enable) { Debug.Log($"Enabling debug visualizer: {enable}"); _debugVisualizer.gameObject.SetActive(enable); } } }
26.631944
117
0.641199
332678828f321da4b31703af127b13daf03c5207
2,200
html
HTML
index.html
mugai17/a-mmd
9a39fb96b33bf2e874015be6b1a7bdec0dce46ae
[ "MIT" ]
83
2016-11-12T17:39:13.000Z
2021-12-02T06:57:16.000Z
index.html
mugai17/a-mmd
9a39fb96b33bf2e874015be6b1a7bdec0dce46ae
[ "MIT" ]
4
2017-04-26T02:28:09.000Z
2020-03-05T11:40:15.000Z
index.html
mugai17/a-mmd
9a39fb96b33bf2e874015be6b1a7bdec0dce46ae
[ "MIT" ]
20
2017-02-15T03:06:36.000Z
2021-06-02T16:54:19.000Z
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MMD Models</title> <meta name="description" content="A-Frame MMD loader component"> <script src="https://aframe.io/releases/0.7.1/aframe.min.js"></script> <script src="https://cdn.rawgit.com/kripken/ammo.js/dcab07bf0e7f2b4b64c01dc45da846344c8f50be/builds/ammo.js"></script> <script src="https://cdn.rawgit.com/takahirox/aframe-outline/v1.1.1/build/aframe-outline.min.js"></script> <script src="./build/a-mmd.js"></script> </head> <body> <!-- The license of MMD assets used here https://github.com/mrdoob/three.js/tree/dev/examples/models/mmd#readme --> <a-scene antialias="true" outline stats> <a-assets> <img id="sky" crossorigin="anonymous" src="https://cdn.rawgit.com/aframevr/aframe/v0.7.1/examples/primitives/models/peach-gradient.jpg"> </a-assets> <a-entity position="0 13 13"> <a-camera></a-camera> </a-entity> <a-entity mmd="audio:https://cdn.rawgit.com/mrdoob/three.js/r87/examples/models/mmd/audios/wavefile_short.mp3; audioDelayTime:5.333333333333333; afterglow:2.0;"> <a-entity mmd-model="model:https://cdn.rawgit.com/mrdoob/three.js/r87/examples/models/mmd/miku/miku_v2.pmd; vmd:https://cdn.rawgit.com/mrdoob/three.js/r87/examples/models/mmd/vmds/wavefile_v2.vmd; physics:true;" shadow="cast:true" position="0 0 0"></a-entity> </a-entity> <a-plane rotation="-90 0 0" color="#AAAAAA" height="200" width="200" shadow="receive:true"></a-plane> <a-sky src="#sky"></a-sky> <a-entity light="type:directional; castShadow:true; color:#888; shadowMapWidth:1024; shadowMapHeight:1024; shadowCameraRight:20; shadowCameraTop:20; shadowCameraLeft:-20; shadowCameraBottom:-20" position="-20 20 20"></a-entity> </a-scene> </body> </html>
37.931034
144
0.570455
c50059f9b52f5d48c141e3dac61f2e044c1a8df7
554
css
CSS
Content/Rotator/API.css
syncfusion/aspnet-ej1-demos
2b6f8494be547cdf44b778e92cdf8952f23d7b24
[ "Net-SNMP", "NBPL-1.0", "Xnet", "Info-ZIP" ]
3
2018-11-14T12:05:16.000Z
2022-01-24T04:43:37.000Z
Content/Rotator/API.css
syncfusion/aspnet-ej1-demos
2b6f8494be547cdf44b778e92cdf8952f23d7b24
[ "Net-SNMP", "NBPL-1.0", "Xnet", "Info-ZIP" ]
null
null
null
Content/Rotator/API.css
syncfusion/aspnet-ej1-demos
2b6f8494be547cdf44b778e92cdf8952f23d7b24
[ "Net-SNMP", "NBPL-1.0", "Xnet", "Info-ZIP" ]
5
2019-04-04T15:55:39.000Z
2021-04-08T11:00:44.000Z
 .frame { width: 100%; box-sizing : border-box; } .e-rotator > li img { width: 100%; height: 165px; } input { line-height: normal; width: 113px; } input.ejinputtext { text-indent: 10px; } .e-btn { width: 120px; } .e-togglebutton { width: 100px; } #itemMove { line-height: normal; width: 117px; }
17.3125
36
0.351986
c37dfe2915816f710282ad58d932df3eb8a0eacf
561
cs
C#
tests/Sharpliner.Tests/AzureDevOps/TestPipeline.cs
TopperDEL/sharpliner
ebdabc83952997ccf5fc2d6cce968a5600ef1379
[ "MIT" ]
null
null
null
tests/Sharpliner.Tests/AzureDevOps/TestPipeline.cs
TopperDEL/sharpliner
ebdabc83952997ccf5fc2d6cce968a5600ef1379
[ "MIT" ]
null
null
null
tests/Sharpliner.Tests/AzureDevOps/TestPipeline.cs
TopperDEL/sharpliner
ebdabc83952997ccf5fc2d6cce968a5600ef1379
[ "MIT" ]
null
null
null
using Sharpliner.AzureDevOps; namespace Sharpliner.Tests.AzureDevOps { internal abstract class TestPipeline : PipelineDefinition { public override string TargetFile => "azure-pipelines.yml"; public override TargetPathType TargetPathType => TargetPathType.RelativeToGitRoot; } internal abstract class SimpleTestPipeline : SingleStagePipelineDefinition { public override string TargetFile => "azure-pipelines.yml"; public override TargetPathType TargetPathType => TargetPathType.RelativeToGitRoot; } }
29.526316
90
0.748663
43d02b7306d8acf3f6336c97d601d5df4d37fa13
1,581
ts
TypeScript
src/styles/global.ts
PitzTech/suno-movies
1fde25d6a173d49227fd566eceda09b7d7468e1c
[ "MIT" ]
null
null
null
src/styles/global.ts
PitzTech/suno-movies
1fde25d6a173d49227fd566eceda09b7d7468e1c
[ "MIT" ]
null
null
null
src/styles/global.ts
PitzTech/suno-movies
1fde25d6a173d49227fd566eceda09b7d7468e1c
[ "MIT" ]
null
null
null
import { createGlobalStyle } from "styled-components" export default createGlobalStyle` :root { --primary-background: #1B1B1F; --secondary-background: #212125; --secondary-background-light-contrast: #2e2d31; --secondary-background-contrast: #2e2e35; --primary-text: #EAEAEA; --secondary-text: #9F9FA0; --primary-pink: #FF559E; --secondary-pink: #252529; --secondary-pink-contrast: #313136; --footer-background: #18181C; } ::-webkit-scrollbar { width: .3rem; } ::-webkit-scrollbar-track { background: var(--primary-background); -webkit-box-shadow: inset 0 0 6px rgba(255,255,255,0.1); } ::-webkit-scrollbar-thumb { background: var(--primary-pink); outline: 1px solid slategrey; height: 1rem; } * { margin: 0; padding: 0; outline: 0; box-sizing: border-box; } h1 { font-weight: normal; } a { text-decoration: none; color: var(---primary-text); } // Custom Classes .pink { color: var(--primary-pink); } /* user-agent font-size is 16px */ @media(max-width: 1080px) { :root { font-size: 93.75%; /* 15px */ } } @media(max-width: 943px) { :root { font-size: 87.5%; /* 14px */ } } @media(max-width:700px) { :root { font-size: 75%; /* 12px */ } } @media(max-width: 590px) { :root { font-size: 62.25%; /* 10px */ } } body { background-color: var(--primary-background); color: var(--primary-text); font-family: Poppins, sans-serif; } `
17.764045
58
0.568627
dbac556a9ff5547c522ef5c2b91ccfc3aff50711
12,941
kt
Kotlin
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/presencetracing/checkins/split/CheckInSplitterTest.kt
rkw95/cwa-app-android
a1110d3d0906273936ef1db7e8024ec581f8dfbc
[ "Apache-2.0" ]
2,775
2020-05-30T15:29:21.000Z
2022-03-31T06:36:40.000Z
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/presencetracing/checkins/split/CheckInSplitterTest.kt
rkw95/cwa-app-android
a1110d3d0906273936ef1db7e8024ec581f8dfbc
[ "Apache-2.0" ]
4,520
2020-05-30T16:21:20.000Z
2022-03-31T19:08:12.000Z
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/presencetracing/checkins/split/CheckInSplitterTest.kt
rkw95/cwa-app-android
a1110d3d0906273936ef1db7e8024ec581f8dfbc
[ "Apache-2.0" ]
759
2020-05-30T17:57:24.000Z
2022-03-31T07:36:28.000Z
package de.rki.coronawarnapp.presencetracing.checkins.split import de.rki.coronawarnapp.presencetracing.checkins.CheckIn import io.kotest.matchers.shouldBe import okio.ByteString.Companion.encode import org.joda.time.Instant import org.junit.jupiter.api.Test import testhelpers.BaseTest /** * Test examples reference [https://github.com/corona-warn-app/cwa-app-tech-spec/blob/proposal/event-registration-mvp/ * docs/spec/event-registration-client.md#split-checkin-by-midnight-utc] */ class CheckInSplitterTest : BaseTest() { private val defaultCheckIn = CheckIn( id = 1L, traceLocationId = "traceLocationId1".encode(), version = 1, type = 1, description = "Restaurant", address = "Around the corner", traceLocationStart = null, traceLocationEnd = null, defaultCheckInLengthInMinutes = null, cryptographicSeed = "cryptographicSeed".encode(), cnPublicKey = "cnPublicKey", checkInStart = Instant.now(), checkInEnd = Instant.now(), completed = false, createJournalEntry = false ) @Test fun `same-day check-in`() { /* localCheckIn = { start: '2021-03-04 09:30', end: '2021-03-04 09:45' } splitInto = [{ start: '2021-03-04 09:30', end: '2021-03-04 09:45' } // no split */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-04T09:45:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 1 // No splitting get(0) shouldBe checkIn } } @Test fun `end time before start time same day is filtered`() { /* localCheckIn = { start: '2021-03-05 09:45', end: '2021-03-04 09:30' } splitInto = [{ } // filtered */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:45:00Z"), checkInEnd = Instant.parse("2021-03-04T09:30:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 0 // inconsistent data is filtered out } } @Test fun `end time and date before start time is filtered`() { /* localCheckIn = { start: '2021-03-05 09:45', end: '2021-03-04 09:30' } splitInto = [{ } // filtered */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-05T09:45:00Z"), checkInEnd = Instant.parse("2021-03-04T09:30:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 0 // inconsistent data is filtered out } } @Test fun `end time equals start time returns check-in`() { /* localCheckIn = { start: '2021-03-04 09:30', end: '2021-03-04 09:30' } splitInto = [{ } // filtered */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-04T09:30:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 1 // inconsistent data is filtered out get(0) shouldBe checkIn } } @Test fun `same-start-end-times check-in`() { /* localCheckIn = { start: '2021-03-04 09:30', end: '2021-03-04 09:30' } splitInto = [{ start: '2021-03-04 09:30', end: '2021-03-04 09:30' } // no split */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-04T09:30:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 1 // No splitting get(0) shouldBe checkIn } } @Test fun `2-days check-in`() { /* localCheckIn = { start: '2021-03-04 09:30', end: '2021-03-05 09:45' } splitInto = [ { start: '2021-03-04 09:30', end: '2021-03-05 00:00' }, { start: '2021-03-05 00:00', end: '2021-03-05 09:45' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-05T09:45:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 2 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-05T00:00:00Z"), checkInEnd = Instant.parse("2021-03-05T09:45:00Z") ) } } @Test fun `3-days check-in`() { /* localCheckIn = { start: '2021-03-04 09:30', end: '2021-03-06 09:45' } splitInto = [ { start: '2021-03-04 09:30', end: '2021-03-05 00:00' }, { start: '2021-03-05 00:00', end: '2021-03-06 00:00' } { start: '2021-03-06 00:00', end: '2021-03-06 09:45' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-06T09:45:00Z"), ) checkIn.splitByMidnightUTC().apply { size shouldBe 3 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-05T00:00:00Z"), checkInEnd = Instant.parse("2021-03-06T00:00:00Z") ) get(2) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-06T00:00:00Z"), checkInEnd = Instant.parse("2021-03-06T09:45:00Z") ) } } @Test fun `2-days-different-months check-in`() { /* localCheckIn = { start: '2021-02-28 09:30', end: '2021-03-01 12:45' } splitInto = [ { start: '2021-02-28 09:30', end: '2021-03-01 00:00' }, { start: '2021-03-01 00:00', end: '2021-03-01 12:45' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-02-28T09:30:00Z"), checkInEnd = Instant.parse("2021-03-01T12:45:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 2 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-02-28T09:30:00Z"), checkInEnd = Instant.parse("2021-03-01T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-01T00:00:00Z"), checkInEnd = Instant.parse("2021-03-01T12:45:00Z") ) } } @Test fun `2-days-different-years check-in`() { /* localCheckIn = { start: '2021-12-31 09:30', end: '2022-01-01 12:45' } splitInto = [ { start: '2021-12-31 09:30', end: '2022-01-01 00:00' }, { start: '2022-01-01 00:00', end: '2022-01-01 12:45' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-12-31T09:30:00Z"), checkInEnd = Instant.parse("2022-01-01T12:45:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 2 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-12-31T09:30:00Z"), checkInEnd = Instant.parse("2022-01-01T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2022-01-01T00:00:00Z"), checkInEnd = Instant.parse("2022-01-01T12:45:00Z") ) } } @Test fun `3-days-different-months-leap-year check-in`() { /* localCheckIn = { start: '2020-02-28 09:30', end: '2020-03-01 12:45' } splitInto = [ { start: '2020-02-28 09:30', end: '2020-02-29 00:00' }, { start: '2020-02-29 00:00', end: '2020-03-01 00:00' }, { start: '2020-03-01 00:00', end: '2020-03-01 12:45' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2020-02-28T09:30:00Z"), checkInEnd = Instant.parse("2020-03-01T12:45:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 3 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2020-02-28T09:30:00Z"), checkInEnd = Instant.parse("2020-02-29T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2020-02-29T00:00:00Z"), checkInEnd = Instant.parse("2020-03-01T00:00:00Z") ) get(2) shouldBe checkIn.copy( checkInStart = Instant.parse("2020-03-01T00:00:00Z"), checkInEnd = Instant.parse("2020-03-01T12:45:00Z") ) } } @Test fun `2-dates duration lower than day check-in`() { /* localCheckIn = { start: '2021-03-04 09:30', end: '2021-03-05 09:15' } splitInto = [ { start: '2021-03-04 09:30', end: '2021-03-05 00:00' }, { start: '2021-03-05 00:00', end: '2021-03-05 09:15' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-05T09:15:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 2 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-04T09:30:00Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-05T00:00:00Z"), checkInEnd = Instant.parse("2021-03-05T09:15:00Z") ) } } @Test fun `2-dates duration lower than day - same start and end times check-in`() { /* localCheckIn = { start: '2021-03-04 09:00', end: '2021-03-05 09:00' } splitInto = [ { start: '2021-03-04 09:00', end: '2021-03-05 00:00' }, { start: '2021-03-05 00:00', end: '2021-03-05 09:00' } ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T09:00:00Z"), checkInEnd = Instant.parse("2021-03-05T09:00:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 2 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-04T09:00:00Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-05T00:00:00Z"), checkInEnd = Instant.parse("2021-03-05T09:00:00Z") ) } } @Test fun `midnight times check-in`() { /* localCheckIn = { start: '2021-03-04 00:00', end: '2021-03-05 00:00' } splitInto = [ { start: '2021-03-04 00:00', end: '2021-03-05 00:00' } // No split ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T00:00:00Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 1 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-04T00:00:00Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) } } @Test fun `2min-2dates check-in`() { /* localCheckIn = { start: '2021-03-04 23:59', end: '2021-03-05 00:01' } splitInto = [ { start: '2021-03-04 00:00', end: '2021-03-05 00:00' } // No split ] */ val checkIn = defaultCheckIn.copy( checkInStart = Instant.parse("2021-03-04T00:23:59Z"), checkInEnd = Instant.parse("2021-03-05T00:00:01Z") ) checkIn.splitByMidnightUTC().apply { size shouldBe 2 get(0) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-04T00:23:59Z"), checkInEnd = Instant.parse("2021-03-05T00:00:00Z") ) get(1) shouldBe checkIn.copy( checkInStart = Instant.parse("2021-03-05T00:00:00.000Z"), checkInEnd = Instant.parse("2021-03-05T00:00:01Z") ) } } }
33.876963
118
0.530871
e13717e5abd31be1ae23e9a1b91918a6bdcb814e
8,427
rs
Rust
src/librustc/middle/borrowck/gather_loans/lifetime.rs
rust-highfive/rust
3212d70302074bb6fc28d077e1cc4ed870fcb091
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2019-04-01T19:51:22.000Z
2022-03-19T22:44:50.000Z
src/librustc/middle/borrowck/gather_loans/lifetime.rs
rust-highfive/rust
3212d70302074bb6fc28d077e1cc4ed870fcb091
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
src/librustc/middle/borrowck/gather_loans/lifetime.rs
rust-highfive/rust
3212d70302074bb6fc28d077e1cc4ed870fcb091
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2018-07-29T22:20:48.000Z
2021-02-10T10:21:24.000Z
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * This module implements the check that the lifetime of a borrow * does not exceed the lifetime of the value being borrowed. */ use middle::borrowck::*; use middle::expr_use_visitor as euv; use middle::mem_categorization as mc; use middle::ty; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime(bccx: &BorrowckCtxt, item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, cmt: mc::cmt, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope_id: item_scope_id, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the node id of the function body for the enclosing item item_scope_id: ast::NodeId, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the "guarantor". debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_copied_upvar(..) | // L-Local mc::cat_local(..) | // L-Local mc::cat_arg(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base) | mc::cat_deref(ref base, _, mc::OwnedPtr) | // L-Deref-Send mc::cat_interior(ref base, _) | // L-Field mc::cat_deref(ref base, _, mc::GcPtr) => { self.check(base, discr_scope) } mc::cat_discr(ref base, new_discr_scope) => { // Subtle: in a match, we must ensure that each binding // variable remains valid for the duration of the arm in // which it appears, presuming that this arm is taken. // But it is inconvenient in trans to root something just // for one arm. Therefore, we insert a cat_discr(), // basically a special kind of category that says "if this // value must be dynamically rooted, root it for the scope // `match_id`". // // As an example, consider this scenario: // // let mut x = @Some(3); // match *x { Some(y) {...} None {...} } // // Technically, the value `x` need only be rooted // in the `some` arm. However, we evaluate `x` in trans // before we know what arm will be taken, so we just // always root it for the duration of the match. // // As a second example, consider *this* scenario: // // let x = @@Some(3); // match x { @@Some(y) {...} @@None {...} } // // Here again, `x` need only be rooted in the `some` arm. // In this case, the value which needs to be rooted is // found only when checking which pattern matches: but // this check is done before entering the arm. Therefore, // even in this case we just choose to keep the value // rooted for the entire match. This means the value will be // rooted even if the none arm is taken. Oh well. // // At first, I tried to optimize the second case to only // root in one arm, but the result was suboptimal: first, // it interfered with the construction of phi nodes in the // arm, as we were adding code to root values before the // phi nodes were added. This could have been addressed // with a second basic block. However, the naive approach // also yielded suboptimal results for patterns like: // // let x = @@...; // match x { @@some_variant(y) | @@some_other_variant(y) => // // The reason is that we would root the value once for // each pattern and not once per arm. This is also easily // fixed, but it's yet more code for what is really quite // the corner case. // // Nonetheless, if you decide to optimize this case in the // future, you need only adjust where the cat_discr() // node appears to draw the line between what will be rooted // in the *arm* vs the *match*. self.check(base, Some(new_discr_scope)) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `valid_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. // See the SCOPE(LV) function in doc.rs match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) | mc::cat_copied_upvar(_) => { ty::ReScope(self.item_scope_id) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) | mc::cat_arg(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt) | mc::cat_deref(ref cmt, _, mc::OwnedPtr) | mc::cat_deref(ref cmt, _, mc::GcPtr) | mc::cat_interior(ref cmt, _) | mc::cat_discr(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
41.107317
81
0.495194
26e3b1f5f77b5abe1f957064e5f2e489d53767a2
145
dart
Dart
flutter_ipanda/lib/main.dart
7449/flutter-zhihu_zhuanlan
dd23523114bf786ad73087e18ac1051030d2de33
[ "Apache-2.0" ]
93
2018-05-02T11:16:35.000Z
2021-09-02T08:07:53.000Z
flutter_ipanda/lib/main.dart
7449/flutter-zhihu_zhuanlan
dd23523114bf786ad73087e18ac1051030d2de33
[ "Apache-2.0" ]
2
2018-05-21T12:33:57.000Z
2019-02-28T10:38:05.000Z
flutter_ipanda/lib/main.dart
7449/flutter-zhihu_zhuanlan
dd23523114bf786ad73087e18ac1051030d2de33
[ "Apache-2.0" ]
16
2018-05-10T07:00:37.000Z
2021-11-10T06:14:51.000Z
import 'package:flutter/material.dart'; import 'package:flutter_ipanda/app_screen.dart'; void main() => runApp(MaterialApp(home: AppScreen()));
29
54
0.765517
235e381296ee98fffe036480f491e9aab7ab22b4
686
css
CSS
src/index/index.css
1549664680/train-ticket
def5e8ffc6f60891b5e68b208dbe8cb9f2111cdd
[ "MIT" ]
5
2019-10-22T07:14:24.000Z
2021-06-02T09:02:14.000Z
src/ticket/index.css
kongdexiaochina/react-hooks
a55e4cab44e377530a51ff7099110cbf738c2e20
[ "MIT" ]
10
2020-09-07T06:49:25.000Z
2022-03-08T23:03:08.000Z
src/ticket/index.css
kongdexiaochina/react-hooks
a55e4cab44e377530a51ff7099110cbf738c2e20
[ "MIT" ]
2
2020-09-07T05:15:34.000Z
2021-11-13T13:41:50.000Z
html { background: #f5f5f5; color: #333; font-size: 32px; } body, ul, ol, dl, dd, h1, h2, h3, h4, h5, h6, figure, form, fieldset, legend, input, textarea, button, p, blockquote, th, td, pre, xmp { margin: 0; padding: 0; } body, input, textarea, button, select, pre, tt, code, kbd, samp, optgroup, option { line-height: 1.5; font-family: arial, "\5B8B\4F53", "\5FAE\8F6F\96C5\9ED1", verdana, helvetica, sans-serif; } body { min-width: 320px; max-width: 540px; font-size: 16px; margin: 0 auto; padding-top: 44px; } .hidden, [hidden] { display: none !important; } ::-webkit-input-placeholder { color: #c7ced4; } button { -webkit-appearance: none; }
9.527778
79
0.635569
06d7298424246a81e9d0832bc337f68a707f857a
635
py
Python
services/burnurl.py
joshthecoder/shorty-python
35687d010683944d75e3f0dce7799903296172c5
[ "MIT" ]
11
2015-05-29T04:58:28.000Z
2020-05-31T17:07:52.000Z
services/burnurl.py
joshthecoder/shorty-python
35687d010683944d75e3f0dce7799903296172c5
[ "MIT" ]
null
null
null
services/burnurl.py
joshthecoder/shorty-python
35687d010683944d75e3f0dce7799903296172c5
[ "MIT" ]
2
2015-03-10T06:22:31.000Z
2018-06-18T18:20:59.000Z
## Shorty ## Copyright 2009 Joshua Roesslein ## See LICENSE ## @url burnurl.com class Burnurl(Service): def _test(self): # all we can test is shrink turl = self.shrink('http://test.com') if turl.startswith('http://burnurl.com'): return True else: return False def shrink(self, bigurl): resp = request('http://burnurl.com/', {'url': bigurl, 'output': 'plain'}) return resp.read() def expand(self, tinyurl): # burnurl uses iframes for displaying original url # so we cannot expand them using the 301 redirect :( return None
25.4
81
0.593701
17f85bb5d116afe26f0fa24cb42978cc65872494
2,780
rb
Ruby
db/schema.rb
TwilioDevEd/automated-survey-rails
1c7a890bd2868740cd1c5501eee82b1991b5fb03
[ "MIT" ]
10
2016-05-31T01:57:05.000Z
2022-02-26T20:05:03.000Z
db/schema.rb
TwilioDevEd/automated-survey-rails
1c7a890bd2868740cd1c5501eee82b1991b5fb03
[ "MIT" ]
100
2016-04-08T15:37:43.000Z
2022-03-08T20:14:42.000Z
db/schema.rb
TwilioDevEd/automated-survey-rails
1c7a890bd2868740cd1c5501eee82b1991b5fb03
[ "MIT" ]
10
2016-05-31T02:27:50.000Z
2019-11-28T18:09:01.000Z
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160404115135) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "answers", force: :cascade do |t| t.integer "question_id", null: false t.integer "source", default: 0, null: false t.string "content", null: false t.string "from", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "call_sid", default: "" end add_index "answers", ["call_sid"], name: "index_answers_on_call_sid", using: :btree add_index "answers", ["from"], name: "index_answers_on_from", using: :btree add_index "answers", ["question_id"], name: "index_answers_on_question_id", using: :btree add_index "answers", ["source"], name: "index_answers_on_source", using: :btree create_table "questions", force: :cascade do |t| t.integer "survey_id", null: false t.string "body", null: false t.integer "type", default: 0, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "questions", ["survey_id"], name: "index_questions_on_survey_id", using: :btree add_index "questions", ["type"], name: "index_questions_on_type", using: :btree create_table "surveys", force: :cascade do |t| t.string "title", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "transcriptions", force: :cascade do |t| t.integer "answer_id" t.string "text", default: "" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "transcriptions", ["answer_id"], name: "index_transcriptions_on_answer_id", using: :btree add_foreign_key "answers", "questions" add_foreign_key "questions", "surveys" end
44.126984
101
0.673381
fd76c112e478eebee7fc3c77ce3778835fe08b97
653
css
CSS
src/styles.css
langlk/boardgame-manager
446f5d6d96640f44191a4fccd8d592da94ca5908
[ "MIT" ]
null
null
null
src/styles.css
langlk/boardgame-manager
446f5d6d96640f44191a4fccd8d592da94ca5908
[ "MIT" ]
null
null
null
src/styles.css
langlk/boardgame-manager
446f5d6d96640f44191a4fccd8d592da94ca5908
[ "MIT" ]
null
null
null
/* You can add global styles to this file, and also import other style files */ .container { color: #094361; max-width: 700px; } .checkboxes h5 { font-weight: bolder; margin-top: 0px; } .checkboxes label { font-weight: normal; } #navbar { background-color: #1e4b73; } #navbar a { color: #88a6bf; } #navbar a:hover { color: #a9cbe8; } @media screen and (max-width: 767px) { #navbar .navbar-header { display: flex; justify-content: center; } #navbar .navbar-brand { padding-top: .9em; } #navbar .navbar-right { display: flex; justify-content: space-around; } #navbar a { padding: 2px; } }
13.604167
79
0.623277
45948ed9e00183ba5b99f8f8fce9be7b7648bd2b
25,843
py
Python
Grp22A-5 SprintProject 1.py
DeToxFox/MidtermSprintGrp22A-5
42505c155152a233b66139dd85c4fcad2a41035e
[ "MIT" ]
null
null
null
Grp22A-5 SprintProject 1.py
DeToxFox/MidtermSprintGrp22A-5
42505c155152a233b66139dd85c4fcad2a41035e
[ "MIT" ]
null
null
null
Grp22A-5 SprintProject 1.py
DeToxFox/MidtermSprintGrp22A-5
42505c155152a233b66139dd85c4fcad2a41035e
[ "MIT" ]
null
null
null
# Employee Claims Processing System (work trips) at the NL Chocolate Company # Written by: Group 22A-5, Makenzie Roberts, Neil Stratton, and David Turner # Date written: Feb 25, 2022 # Project ID: Midterm Sprint Week. Project 1: NL Chocolate Company, Claims Processing System # Libraries imported import matplotlib.pyplot as plt import datetime import random def Display_Menu(): print() print("NL Chocolate Company Claims Processing System") print("-"*46) print("Enter an Employee Travel Claim - Press 1") print("Fun Interview Question - Press 2") print("Cool Stuff with Strings and Dates - Press 3") print("Graph Monthly Claim Totals - Press 4") print("Quit the Program - Press 5") print() def Difference_Between_Dates(EnDate, StDate): # Written By: David Turner # Date Written: Feb 25, 2022 # Description: # This function calculates the difference between 2 dates returning value as number of days ex: 7. # Parameters: # Two dates are sent to this function as arguments, # that will be used to calculate to a numerical value. # Returns: # Returns the numerical value as an integer. # Ex: The arguments (2022, 12, 22, 0, 0) and (2022, 12, 15, 0, 0) returned as the int 7, # .Days takes your two date inputs after they're subtracted them converts that to days stripping out time Dif_Days = (EnDate - StDate).days return Dif_Days def dollar_format(num): # Written By: Makenzie Roberts # Last Edited: Feb 28, 2022 # Description: # This function formats a numerical value to display as a dollar value. # Parameters: # The numerical value that will be formatted. # Returns: # Returns the numerical value as a string, formatted to look like a dollar value. # Eg. The argument 123456 is returned as $123,456.00 formatStr = "${:,.2f}".format(num) return formatStr def Emp_Trav_Claim(): # Written By: David Turner # Date Written: Feb 25, 2022 # Description: # This function allows an employee to enter as many travel claims as needed. # Parameters: # Does not require a parameter and does not accept any arguments. # Based on user inputs within this function # Returns: # There is no return with this function as the output is # presented prior to returning to main # Constants DAILY_RATE = 85.00 RENTAL_CAR_RATE = 65.00 PER_KM_RATE = 0.17 BONUS_KM_RATE = 0.04 EXECUTIVE_RATE = 45.00 BONUS_DAYS_AMOUNT = 100.00 DEC_BONUS_RATE = 50.00 HST = 0.15 while True: # Welcome message print() print(" ------------------------------------") print(" Option 1: Employee Travel Claim") print(" ------------------------------------") while True: # input and validation of the employee number Emp_Num = input("Please enter in your 5 digit employee numer (12345): ") if Emp_Num == "": print("Your employee number cannot be blank - please re-enter.") elif len(Emp_Num) != 5: print("Your employee number must be 5 digits - please re-enter.") elif Emp_Num.isdigit() == False: print("Your employee number must contain numbers only - please re-enter.") else: break # Input and validation of the employee's first name while True: Allowed_Char = set("ABCDEFGHIJKLMONPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890-'") First_Name = input("Enter the your first name (type End to exit): ").title() if First_Name == "End": print() return elif First_Name == "": print("First name must not be blank - please re-enter.") elif set(First_Name).issubset(Allowed_Char) == False: print("First name contains invalid characters - please re-enter") else: break # Input and validation of the employee's last name while True: Allowed_Char = set("ABCDEFGHIJKLMONPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890-'") Last_Name = input("Enter the your last name: ").title() if Last_Name == "": print("Last name must not be blank - please re-enter.") elif set(Last_Name).issubset(Allowed_Char) == False: print("Last name contains invalid characters - please re-enter") else: break # Input and validation for the employee trip location while True: Allowed_Char = set("ABCDEFGHIJKLMONPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.-'") Location = input("Enter the trip location: ").title() if Location == "": print("Trip location can't be blank - please re-enter") elif set(Location).issubset(Allowed_Char) == False: print("Trip location cannot contain invalid characters - please re-enter") else: break # Input and validation for the employee start and end date while True: try: Start_Date = input("Enter the start date of the claim (YYYY-MM-DD): ") Start_Date = datetime.datetime.strptime(Start_Date, "%Y-%m-%d") except: print("Start date not a valid format - please re-enter.") else: break while True: try: End_Date = input("Enter the end date of the claim (YYYY-MM-DD): ") End_Date = datetime.datetime.strptime(End_Date, "%Y-%m-%d") except: print("End date not a valid format - please re-enter.") else: if End_Date <= Start_Date: print("End date must be after the start date - please re-enter.") else: # Calculate the number of days of the claim and ensure number of days doesn't exceed 7, Num_Days = Difference_Between_Dates(End_Date, Start_Date) # sends 2 arguments, returns the calced value if Num_Days > 7: print("The number of days exceeds 7 - please re-enter") else: break # Input and validation of vehicle used while True: Allowed_Char = set("RO") Vehicle_Type = input("Enter the vehicle used, own or rental (O or R): ").upper() if Vehicle_Type == "": print("Vehicle type can't be blank - please re-enter") elif set(Vehicle_Type).issubset(Allowed_Char) == False: print("Vehilcle type cannot contain invalid characters - please re-enter") else: break # Calculations for the vehicle allowance, rental or own vehicle, and trip distance Vehicle_Payout = 0 Msg = "" Kms_Travel = 0 Kms_TravelDsp = 0 Kms_Msg = "" Vehicle_Type_Selected = "" if Vehicle_Type == "R": Vehicle_Type_Selected = "Rental" Vehicle_Payout = Num_Days * RENTAL_CAR_RATE Msg = "Rental Amount:" Kms_Msg = "" Kms_TravelDsp = "" elif Vehicle_Type == "O": Vehicle_Type_Selected = "Personal" while True: try: Kms_Travel = float(input("How many kms were traveled on the work trip?: ")) except: print("Kms traveled is not a valid number - please re-enter.") if Kms_Travel > 2000: print("Kms travelled for work must be under 2000 kms - please re-enter") elif Kms_Travel <= 0: print("Kms travelled for work must be greater than 0 kms - please re-enter") elif Kms_Travel > 1000: Vehicle_Payout = Kms_Travel * (PER_KM_RATE) Msg = "Mileage Amount:" Kms_Msg = "kms Traveled:" Kms_TravelDsp = "{:.2f}".format(Kms_Travel) break else: # int(Kms_T) < 1000: Vehicle_Payout = Kms_Travel * PER_KM_RATE Msg = "Mileage Amount:" Kms_Msg = "kms Traveled:" Kms_TravelDsp = "{:.2f}".format(Kms_Travel) break # Input and validation of claim type while True: Allowed_Char = set("SE") Claim_Type = input("Enter claim type Standard or Executive (S or E): ").upper() if Claim_Type == "": print("Claim type can't be blank - please re-enter") elif set(Claim_Type).issubset(Allowed_Char) == False: print("Claim type cannot contain invalid characters - please re-enter") else: break # Below are all the values needed to calculate the bonus # Calculate bonus rate for days bonus if Num_Days > 3: Days_Amt_Bonus = BONUS_DAYS_AMOUNT else: Days_Amt_Bonus = 0 # Calculation bonus if kms is over 1000 if Vehicle_Type == "R": Kms_Bonus = 0 elif Vehicle_Type == "O" and Kms_Travel > 1000: Kms_Bonus = Kms_Travel * (BONUS_KM_RATE) else: Kms_Bonus = 0 # Calculate bonus rate for executive claims if Claim_Type == "S": Claim_Type_Bonus = 0 Claim_TypeDsp = "STANDARD" else: Claim_Type_Bonus = Num_Days * EXECUTIVE_RATE Claim_TypeDsp = "EXECUTIVE" # Calculate start and end date bonus for December SD_Date = Start_Date Start_Date_Year = SD_Date.year Start_Date_Month = 12 Start_Date_Day = 15 SD_Date = datetime.datetime(Start_Date_Year, Start_Date_Month, Start_Date_Day) ED_Date = End_Date End_Date_Year = ED_Date.year End_Date_Month = 12 End_Date_Day = 22 ED_Date = datetime.datetime(End_Date_Year, End_Date_Month, End_Date_Day) if Start_Date >= SD_Date and End_Date <= ED_Date: Special_Dates_Bonus = Num_Days * DEC_BONUS_RATE else: Special_Dates_Bonus = 0 # Calculating the bonus Bonus_Total = Days_Amt_Bonus + Kms_Bonus + Claim_Type_Bonus + Special_Dates_Bonus # Calculating per diem amount Per_Diem = Num_Days * DAILY_RATE # Calculating tax Tax = Per_Diem * HST # Calculating claim amount Claim_Amount = Per_Diem + Vehicle_Payout + Bonus_Total # Calculate total claim including tax Total_Claim = Claim_Amount + Tax # This calls the def dollar_format function to format anything that is a dollar value DF = dollar_format # Formatting for final display TaxDsp = DF(Tax) Claim_AmountDsp = DF(Claim_Amount) Total_ClaimDsp = DF(Total_Claim) Vehicle_PayoutDsp = DF(Vehicle_Payout) Per_DiemDsp = DF(Per_Diem) Days_Amt_BonusDsp = DF(Days_Amt_Bonus) Kms_BonusDsp = DF(Kms_Bonus) Claim_Type_BonusDsp = DF(Claim_Type_Bonus) Special_Dates_BonusDsp = DF(Special_Dates_Bonus) Bonus_TotalDsp = DF(Bonus_Total) Start_DateDsp = Start_Date.strftime("%d-%b-%y") End_DateDsp = End_Date.strftime("%d-%b-%y") # Display of all inputs and calculated values print() print() print() print("-" * 38) print(" " * 7, "YOUR CLAIMS STATEMENT") print("-" * 38) print("{:<25} {:<5}".format("Employee Number:", Emp_Num)) print("{:<25} {:<12}".format("Employee First Name:", First_Name)) print("{:<25} {:<12}".format("Employee Last Name:", Last_Name)) print("{:<25} {:<12}".format("Location Traveled:", Location)) print("{:<25} {:<9}".format("Travel Start Date:", Start_DateDsp)) print("{:<25} {:<9}".format("Travel End Date:", End_DateDsp)) print("{:<25} {:<16}".format("Vehicle Type Used:", Vehicle_Type_Selected)) print("{:<25} {:<12}".format("Claim Type Selected:", Claim_TypeDsp)) print("{:<25} {:<3}".format("Trip Duration:", str(Num_Days) + " days")) print("{:<25} {:<7}".format(Kms_Msg, Kms_TravelDsp)) print() print("-" * 38) print(" " * 10, "Bonus Breakdown") print("-" * 38) print("{:<28} {:>9}".format("Away 3 Days or More:", Days_Amt_BonusDsp)) print() print("{:<54} {:>6}".format("Traveled over 1000 kms\n(Personal Vehicle Only):", Kms_BonusDsp)) print() print("{:<45} {:>9}".format("Claim Type Bonus\n(Executive Claim Only):", Claim_Type_BonusDsp)) print() print("{:<43} {:>9}".format("December Bonus\n(Between Dec 15-22):", Special_Dates_BonusDsp)) print(" " * 26, "-" * 11) print("{:<28} {:>9}".format("Total Bonus:", Bonus_TotalDsp)) # maybe take out "Total Bonus" as its displayed lower down in the subtotal print() print("-" * 38) print(" " * 12, "Claim Amount") print("-" * 38) print("{:<30} {:>7}".format("Per Diem Amount:", Per_DiemDsp)) print("{:<30} {:>7}".format("Total Bonus:", Bonus_TotalDsp)) print("{:<30} {:>7}".format(Msg, Vehicle_PayoutDsp)) print(" " * 26, "-" * 11) print("{:<28} {:>9}".format("Claim Amount:", Claim_AmountDsp)) print() print("-" * 38) print(" " * 12, "Total Claim") print("-" * 38) print("{:<28} {:>9}".format("Claim Amount:", Claim_AmountDsp)) print("{:<30} {:>7}".format("HST Amount:", TaxDsp)) print(" " * 26, "-" * 11) print("{:<28} {:>9}".format("Claim Total:", Total_ClaimDsp)) print() while True: Continue = input("Do you want to process another claim (Y / N): ").upper() print() if Continue != "Y" and Continue != "N": print("Not Valid Try Again") else: break if Continue == "N": return def Fun_Question(): # Fizz Buzz program # Neil Stratton March, 3, 2022 # Sprint Week # Description: # This function checks if it's divisible by 5 (Fizz) or 8 (Buzz) # and if it's divisible by both you get FizzBuzz, if not divisible it will display the number. # Parameters: # Does not require a parameter and does not accept any arguments. # No user inputs required. # Returns: # There is no return with this function as the output is # presented prior to returning to main # Welcome message print() print("------------------------------------") print("Option 2: Fun Interview Question") print("------------------------------------") print() while True: for fizzbuzz in range(101): if fizzbuzz % 5 == 0 and fizzbuzz % 8 == 0: print("FizzBuzz") continue elif fizzbuzz % 5 == 0: print("Fizz") continue elif fizzbuzz % 8 == 0: print("Buzz") continue print(fizzbuzz) enter_new_info = input("Press any key to continue...") print("") if enter_new_info == "": return def Strings_Dates(): # Employee Username, Password, Email address and other info generator program. # Neil Stratton - March 3, 2022 # Sprint week - Fun wih Strings # Description: # This function is an employee credentials generator, # Parameters: # Does not require a parameter and does not accept any arguments. # User inputs a phone-number, first and last name, employee start date, # birthdate to generate username, password, email address, and other employee information # Returns: # There is no return with this function as the output is # presented prior to returning to main # Welcome message print() print("-------------------------------------------") print("Option 3: Cool Stuff with Strings and Dates") print("-------------------------------------------") # Inputs and validation: while True: while True: emp_phone_number = str(input("Enter employee phone number 10 digits 999-999-9999 format: ")).upper() length = len(emp_phone_number) if length == 12 \ and emp_phone_number[3] == "-" \ and emp_phone_number[7] == "-" \ and emp_phone_number[:3].isdigit() \ and emp_phone_number[4:7].isdigit() \ and emp_phone_number[8:].isdigit(): print("") else: print("Invalid Phone Number") continue break while True: try: emp_first_name = str(input("Enter employee first name: ")) if emp_first_name.isalpha(): pass else: raise TypeError except TypeError: print("Invalid First Name") else: break while True: try: emp_last_name = str(input("Enter employee last name: ")) if emp_last_name.isalpha(): print("") else: raise TypeError except TypeError: print("Invalid Last Name") else: break while True: try: emp_start_date = str(input("Enter the employee start date : YYYY-MM-DD format: ")) emp_start_date = datetime.datetime.strptime(emp_start_date, "%Y-%m-%d") except ValueError: print("This is the incorrect date string format. It should be YYYY-MM-DD") else: break while True: try: emp_birth_date = str(input("Enter the employee Birthday : YYYY-MM-DD format: ")) emp_birth_date = datetime.datetime.strptime(emp_birth_date, "%Y-%m-%d") except ValueError: print("This is the incorrect date string format. It should be YYYY-MM-DD") else: break # Convert date to string and remove dashes and unwanted characters, so they won't be in password date_string = emp_start_date.strftime('%Y%m%d') bday_string = emp_birth_date.strftime('%Y%m%d') emp_phone_number_pass = emp_phone_number.replace('-', "") emp_first_name_pass = emp_first_name.replace("O", "") emp_last_name_pass = emp_last_name.replace("O", "") # Current date and time and convert to string emp_start = emp_start_date.strftime("%B %d, %Y") cur_day = datetime.datetime.today() cur_time = datetime.datetime.now() cur_day_string = cur_day.strftime('%B %d, %Y') cur_time_string = cur_time.strftime('%H:%M:%S') # Convert employee Birthdate to string and calculation age bday_full = emp_birth_date.strftime("%B") year_difference = cur_day.year - emp_birth_date.year days_company = emp_birth_date.day - cur_day.day # Username and password conversion variables symbols = ("%!#$@&*") alpha_chars = ("AaBbCcDdEeFfGgHhIiJjKkLlMmNnPpQqRrSsTtUuVvWwXxYyZz") # Combine first name and last name to check length for password options length = str(emp_first_name + emp_last_name) if len(length) <= 5: password_list = ( alpha_chars + emp_first_name_pass + emp_last_name_pass + date_string + bday_string + emp_phone_number_pass + symbols) else: password_list = ( emp_first_name_pass + emp_last_name_pass + date_string + bday_string + emp_phone_number_pass + symbols) # Randomize the password mix and output password length password_mix = random.choices(password_list, k=10) password_final = (password_mix[0] + password_mix[1] + password_mix[2] + password_mix[3] + password_mix[4] + password_mix[5] + password_mix[6] + password_mix[7] + password_mix[8] + password_mix[9]) # Create username user_name = (f"{emp_first_name[0].title()}.{emp_last_name[0].title()}{emp_last_name[1:]}") # Adjust header lines depending on length of email address email_length = ( f"Email Address is: {emp_first_name.lower()}.{emp_last_name.lower()}@nlchocolatecompany.com") num = int(len(email_length)) LINE = (f"-" * num) # Output display print("") print(f"EMPLOYEE REPORT:") print(f"{LINE}") print("Current Day and Time:") print(f"{LINE}") print(f" Today's Date is : {cur_day_string}") print(f" Current Time is: {cur_time_string}") print("") print(f"{LINE}") print(f"Employee Username, Password and Email Address: ") print(f"{LINE}") print(f" Username is: {user_name}") print(f" Password is: {password_final}") print(f" Email Address is: {emp_first_name.lower()}.{emp_last_name.lower()}@nlchocolatecompany.com") print("") print(f"{LINE}") print(f"Other Employee info:") print(f"{LINE}") print(f" First name: {emp_first_name.title()}") print(f" Last Name: {emp_last_name.title()}") print(f" Phone Number: {emp_phone_number}") print("") print(f" {emp_first_name.title()}'s Birthday is in {bday_full} ") print(f" {emp_first_name.title()} will be {year_difference} years old this year") print(f" {emp_first_name.title()} start date is {emp_start}") print("") print(f"{LINE}") enter_new_info = input("Press any key to continue...") print("") if enter_new_info == "": return def Graph_Monthly_Totals(): # Written By: Makenzie Roberts # Last Edited: Feb 28, 2022 # Description: # This function produces a graph for Monthly Claim Totals (Total($) vs Month). # Parameters: # Does not require a parameter and does not accept any arguments. # To gather the data needed to plot the graph, it asks for (and requires) user input. # Returns: # Returns a graph, created using matplotlib library. # Create lists that contain data for X and Y axis month_list = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # Y is initialized and empty so we can append user input y = [] # Welcome message print() print("------------------------------------") print("Option 4: Graph Monthly Claim Totals") print("------------------------------------") print() print("This option produces a line graph using the data you provide. (Total($) vs Month)") print("Please enter the claim total($) for each month of the year.") print() # Ask user to input for monthly totals, then append to y axis list monthNum = 0 for month in range(1, 13): inputOk = False while not inputOk: try: monthValue = float(input("Enter the amount for {}: ".format(month_list[monthNum]))) inputOk = True except: print( "The value for {} must be a valid number and cannot contain special characters. Please re-enter.".format( month_list[monthNum])) else: y.append(monthValue) monthNum += 1 # Abbreviates month names to first 3 characters for easy display monthNum = 0 month_abbrev_list = [] for month in range(1, 13): abbrev = month_list[monthNum] abbrev = abbrev[0:3] month_abbrev_list.append(abbrev) monthNum += 1 # Set up the graph xAxis = month_abbrev_list yAxis = y plt.plot(xAxis, yAxis, color='#10a674', linestyle='-', marker='o') plt.xlabel('Month') plt.ylabel('Total($)') plt.title('Monthly Claim Totals') plt.grid(True) # Prompts user to press any key to continue print() print("Close graph to return to main menu") input("Press any key to continue...") print() # Return/display the graph to the user plt.show() return # User choices def User_Choices(): while True: Display_Menu() Choice = input("Enter choice: (1-5): ") print() if Choice == "1": Emp_Trav_Claim() elif Choice == "2": Fun_Question() elif Choice == "3": Strings_Dates() elif Choice == "4": Graph_Monthly_Totals() elif Choice == "5": print("Thank you for utilizing the \"Claims Processing System\", have a wonderful day.") break else: print("Not a valid choice - please re-enter") print() # The programs is the main that calls the user chooses menu. # Without it the other functions listed would not return to the menu for another user choice. # In all the main user functions there is a return that is blank as there is not a specific value # to pass on, so it take the user back to the main menu of choices User_Choices()
37.024355
141
0.564989
0dd53c338fb4ee5a9a014f4cc16dfcd2203cf0bf
5,121
sql
SQL
database/denormalized/index_4.sql
Espigah/index_performance_improvement
78f4408141e37a8eb1807417af51f32bcaaa3c40
[ "Apache-2.0" ]
null
null
null
database/denormalized/index_4.sql
Espigah/index_performance_improvement
78f4408141e37a8eb1807417af51f32bcaaa3c40
[ "Apache-2.0" ]
null
null
null
database/denormalized/index_4.sql
Espigah/index_performance_improvement
78f4408141e37a8eb1807417af51f32bcaaa3c40
[ "Apache-2.0" ]
null
null
null
-------------------------------------------------------- --mode4 - index parcial -------------------------------------------------------- -- active_clients_last_year -- drop index denormalized.purchase_purchase_created_idx; -- drop index denormalized.purchase_purchase_updated_idx; CREATE INDEX IF NOT EXISTS purchase_purchase_created_idx ON "denormalized".purchase (purchase_created) where purchase_created > '2019-01-01' ; CREATE INDEX IF NOT EXISTS purchase_purchase_updated_idx ON "denormalized".purchase (purchase_updated) where purchase_updated > '2019-01-01' ; -- drop index denormalized.customer_customer_name_idx; CREATE INDEX IF NOT EXISTS customer_customer_name_idx ON denormalized.customer (customer_name) INCLUDE (customer_id,customer_email,customer_zipcode) where customer_name = 'wHzRGocvluHkJngldDrtBBipXoKikYRrmXWHnYfdEsTZbrOeUJiZfosSkflOqikaTrkbEuxuwptPisgh' ; -- drop index denormalized.product_id_name_idx; CREATE INDEX IF NOT EXISTS product_id_name_idx ON denormalized.product (product_id, product_name); ; --=============================================================================================================== -- -- brand_purchase_count -- ---- drop index denormalized.purchase_product_id_idx; CREATE INDEX IF NOT EXISTS purchase_product_id_idx ON denormalized.purchase (product_id,purchase_detail_status) where purchase_detail_status = 'COMPLETED' ; ---- drop index denormalized.product_name_idx; CREATE INDEX IF NOT EXISTS product_name_idx ON denormalized.product (product_name, product_brand_name, product_id) where product_name = 'sKhKNXAjVETXggXsaJmGVNsLMcVJqhMRXJCDQSshPSDSvixWnAtEnPUBxsXRUeUqFGznNqeZbAIvTKxWsbpPoGweXFqAyBtwUcKd' ; --=============================================================================================================== -- -- purchase_count -- CREATE INDEX IF NOT EXISTS purchase_purchase_created_idx ON "denormalized".purchase (purchase_created) where purchase_created > '20200101' ; CREATE INDEX IF NOT EXISTS purchase_purchase_updated_idx ON "denormalized".purchase (purchase_updated) where purchase_updated > '20200101' ; CREATE INDEX IF NOT EXISTS purchase_detail_status_idx ON "denormalized".purchase (purchase_detail_status) where purchase_detail_status = 'CANCELED'; --=============================================================================================================== -- -- customer_purchase_detail -- ---- drop index denormalized.purchase_customer_id_idx; CREATE INDEX IF NOT EXISTS purchase_customer_id_idx ON denormalized.purchase (customer_id, purchase_detail_status, product_id) where purchase_detail_status = 'PENDING' ; ---- drop index denormalized.customer_customer_created_idx; CREATE INDEX IF NOT EXISTS customer_customer_created_idx ON denormalized.customer (customer_created, customer_id) include (customer_name) where customer_created > '20190101' ; CREATE INDEX IF NOT EXISTS purchase_purchase_detail_status_idx ON denormalized.product (product_id) include (product_name,product_brand_name,product_size_description,product_weight) ; --------------------------- CREATE OR REPLACE VIEW denormalized.active_clients_last_year as SELECT c.customer_email , c.customer_zipcode , max_purchase.purchase_updated , max_purchase.product_name FROM denormalized.customer c LEFT JOIN ( SELECT pu.customer_id ,max(pr.product_size_description) AS product_size_description , pu.purchase_updated , pr.product_name FROM denormalized.purchase pu JOIN denormalized.product pr using(product_id) WHERE ( pu.purchase_updated >= current_date - INTERVAL '1 YEAR' AND pu.purchase_updated <= now() and purchase_created > '2019-01-01' ) OR ( pu.purchase_created >= now() - INTERVAL '1 YEAR' AND pu.purchase_created <= current_date and purchase_created > '2019-01-01' ) GROUP BY pu.customer_id, pu.purchase_updated, pr.product_name ) AS max_purchase ON max_purchase.customer_id = c.customer_id WHERE c.customer_name = 'wHzRGocvluHkJngldDrtBBipXoKikYRrmXWHnYfdEsTZbrOeUJiZfosSkflOqikaTrkbEuxuwptPisgh' ; CREATE OR REPLACE VIEW denormalized.purchase_count as SELECT p.purchase_detail_status, count(1) FROM denormalized.purchase p WHERE p.purchase_detail_status = 'CANCELED' and ( p.purchase_updated > '20190101' AND p.purchase_updated >= current_date - INTERVAL '1 YEAR' AND p.purchase_updated <= now() OR p.purchase_created > '20190101' AND p.purchase_created >= current_date - INTERVAL '1 YEAR' AND p.purchase_created <= now() ) GROUP BY p.purchase_detail_status ORDER BY 2 DESC ; CREATE OR REPLACE VIEW denormalized.customer_purchase_detail as SELECT c.customer_id ,c.customer_name ,pr.product_brand_name ,pr.product_name ,pr.product_size_description ,pr.product_weight ,pu.purchase_detail_status FROM denormalized.customer c JOIN denormalized.purchase pu USING (customer_id) JOIN denormalized.product pr USING (product_id) WHERE pu.purchase_detail_status = 'PENDING' AND c.customer_created >= current_date - INTERVAL '3 YEAR' AND c.customer_created < current_date - INTERVAL '2 YEAR' AND customer_created > '20190101' ;
37.654412
239
0.73345
8ed2f33875ce6f31b07bbb2d7ad44a0b01ff6c6f
838
js
JavaScript
public/assets/filters/comma-split.filter.spec.js
coryellenberger/mean-blog
1a2daa6987bc430ad53fc8557e1102691827ece8
[ "MIT" ]
1
2016-07-24T15:48:40.000Z
2016-07-24T15:48:40.000Z
public/assets/filters/comma-split.filter.spec.js
coryellenberger/mean-blog
1a2daa6987bc430ad53fc8557e1102691827ece8
[ "MIT" ]
null
null
null
public/assets/filters/comma-split.filter.spec.js
coryellenberger/mean-blog
1a2daa6987bc430ad53fc8557e1102691827ece8
[ "MIT" ]
null
null
null
describe('commaSplit', function () { beforeEach(module('meanBlog')) var commaSplitFilter var _TEST1 = 'TEST1' var _TEST2 = 'TEST2' var _TEST3 = 'TEST3' var _INPUT = _TEST1 + ',' + _TEST2 + ',' + _TEST3 var _ARRAY = [_TEST1, _TEST2, _TEST3] beforeEach(inject(function (_commaSplitFilter_) { commaSplitFilter = _commaSplitFilter_ })) it('should take in CSV and return an array of values', function () { expect(commaSplitFilter).toBeDefined() expect(commaSplitFilter(_INPUT)).toEqual(_ARRAY) }) it('should return nothing if no input', function () { expect(commaSplitFilter).toBeDefined() expect(commaSplitFilter()).toEqual() }) it('should return nothing if no input 0 is empty', function () { expect(commaSplitFilter).toBeDefined() expect(commaSplitFilter(',')).toEqual() }) })
27.933333
70
0.682578
a16641b2cefe6e15201f5a8365548d56fa11c0d5
125
ts
TypeScript
node_modules/standardized-audio-context/src/types/wrap-event-listener-function.ts
SamueleDelMoro/ACTAM.Project2122-TraningGame
73a5070ea619abcb155a3e0a892f410866af49ed
[ "MIT" ]
411
2016-02-02T11:30:13.000Z
2022-03-30T01:58:04.000Z
node_modules/standardized-audio-context/src/types/wrap-event-listener-function.ts
SamueleDelMoro/ACTAM.Project2122-TraningGame
73a5070ea619abcb155a3e0a892f410866af49ed
[ "MIT" ]
710
2016-02-04T01:15:47.000Z
2022-02-08T07:30:58.000Z
node_modules/standardized-audio-context/src/types/wrap-event-listener-function.ts
SamueleDelMoro/ACTAM.Project2122-TraningGame
73a5070ea619abcb155a3e0a892f410866af49ed
[ "MIT" ]
33
2016-02-04T01:16:54.000Z
2022-02-09T14:53:34.000Z
export type TWrapEventListenerFunction = <T>(target: T, eventListener: EventListenerOrEventListenerObject) => EventListener;
62.5
124
0.832
e74c3b8f1a642772f947f8f14ede52f52d0ebd76
1,136
php
PHP
src/Chinese/Driver/Pinyin/Base.php
Luke2486/ChineseUtil
81ec4e42ff3182f8bba8fac596138b63c84c1a9c
[ "MIT" ]
1
2020-07-13T13:38:00.000Z
2020-07-13T13:38:00.000Z
src/Chinese/Driver/Pinyin/Base.php
Luke2486/ChineseUtil
81ec4e42ff3182f8bba8fac596138b63c84c1a9c
[ "MIT" ]
null
null
null
src/Chinese/Driver/Pinyin/Base.php
Luke2486/ChineseUtil
81ec4e42ff3182f8bba8fac596138b63c84c1a9c
[ "MIT" ]
null
null
null
<?php namespace Yurun\Util\Chinese\Driver\Pinyin; abstract class Base implements BaseInterface { /** * 把字符串转为拼音结果,返回的数组成员为字符串 * @param string $string * @param int $mode * @param string $wordSplit * @return array */ public function convert($string, $mode = Pinyin::CONVERT_MODE_FULL, $wordSplit = null) { return $this->parseResult($this->getResult($string), $mode, $wordSplit); } /** * 结果去重 * * @param array $array * @return array */ protected function uniqueResult($array) { $newArray = array_map('unserialize', array_unique(array_map('serialize', $array))); if($array !== $newArray) { $newArray = array_values($newArray); } return $newArray; } /** * 处理结果 * @param array $list * @param int $mode * @param string $wordSplit * @return void */ protected abstract function parseResult($list, $mode, $wordSplit); /** * 把字符串转为拼音数组结果 * @param string $string * @return array */ protected abstract function getResult($string); }
23.183673
91
0.579225
851d99192b4e2de8d8e142dc0a331916e0a94102
906
cs
C#
src/ImageSharp.Textures/Formats/Ktx/Enums/GlType.cs
prophetl33t/ImageSharp.Textures
683910200051bec46b389ff281d57e3a717954da
[ "Apache-2.0" ]
25
2020-01-08T01:37:13.000Z
2022-02-14T21:45:25.000Z
src/ImageSharp.Textures/Formats/Ktx/Enums/GlType.cs
prophetl33t/ImageSharp.Textures
683910200051bec46b389ff281d57e3a717954da
[ "Apache-2.0" ]
4
2020-06-12T23:28:28.000Z
2021-08-08T07:49:06.000Z
src/ImageSharp.Textures/Formats/Ktx/Enums/GlType.cs
prophetl33t/ImageSharp.Textures
683910200051bec46b389ff281d57e3a717954da
[ "Apache-2.0" ]
4
2020-05-15T11:11:23.000Z
2022-03-14T07:10:29.000Z
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. namespace SixLabors.ImageSharp.Textures.Formats.Ktx.Enums { internal enum GlType : uint { /// <summary> /// Zero indicates, that the texture is compressed. /// </summary> Compressed = 0, Byte = 0x1400, UnsignedByte = 0x1401, Short = 0x1402, UnsignedShort = 0x1403, Int = 0x1404, UnsignedInt = 0x1405, Int64 = 0x140E, UnsignedInt64 = 0x140F, HalfFloat = 0x140B, HalfFloatOes = 0x8D61, Float = 0x1406, Double = 0x140A, UsignedByte332 = 0x8032, UnsignedByte233 = 0x8362, UnsignedShort565 = 0x8363, UnsignedShort4444 = 0x8033, UnsignedShort5551 = 0x8034, UnsignedInt8888 = 0x8035, UnsignedInt1010102 = 0x8036, } }
17.423077
59
0.571744
048443841b54eba8824a5ac478fce0d0b71ff272
1,155
h
C
sources/mog/mog.h
tkyaji/mog2d
c3bc3ef62162352311282bce453afe20bd9814e5
[ "MIT" ]
null
null
null
sources/mog/mog.h
tkyaji/mog2d
c3bc3ef62162352311282bce453afe20bd9814e5
[ "MIT" ]
null
null
null
sources/mog/mog.h
tkyaji/mog2d
c3bc3ef62162352311282bce453afe20bd9814e5
[ "MIT" ]
null
null
null
#ifndef mog_h #define mog_h #include "mog/Constants.h" #include "mog/core/plain_objects.h" #include "mog/core/Tween.h" #include "mog/core/Touch.h" #include "mog/core/TouchEventListener.h" #include "mog/core/AudioPlayer.h" #include "mog/core/FileUtils.h" #include "mog/core/Preference.h" #include "mog/core/Data.h" #include "mog/core/Json.h" #include "mog/core/DataStore.h" #include "mog/core/PubSub.h" #include "mog/core/Http.h" #include "mog/core/MogUILoader.h" #include "mog/base/Drawable.h" #include "mog/base/Graphics.h" #include "mog/base/Sprite.h" #include "mog/base/Rectangle.h" #include "mog/base/RoundedRectangle.h" #include "mog/base/Line.h" #include "mog/base/Circle.h" #include "mog/base/Slice9Sprite.h" #include "mog/base/TiledSprite.h" #include "mog/base/SpriteSheet.h" #include "mog/base/Label.h" #include "mog/base/DrawableGroup.h" #include "mog/base/Group.h" #include "mog/base/ScrollGroup.h" #include "mog/base/VerticalGroup.h" #include "mog/base/HorizontalGroup.h" #include "mog/base/Scene.h" #include "mog/base/AppBase.h" #include "mog/core/Screen.h" #include "mog/core/Shader.h" #include "mog/plugins/plugins.h" #endif /* mog_h */
27.5
40
0.742857
445bec9b38004e45288026720448ad6618ff4b60
497
py
Python
code/CGAN_Patterns/loader.py
skababji/ElecLoadsSim_V1
d383c5c31e9533a10de87a9d74c4c5780a01fbe5
[ "MIT" ]
2
2020-07-25T15:09:45.000Z
2020-07-28T15:34:47.000Z
code/CGAN_Patterns/loader.py
skababji/ElecLoads_V1
d383c5c31e9533a10de87a9d74c4c5780a01fbe5
[ "MIT" ]
null
null
null
code/CGAN_Patterns/loader.py
skababji/ElecLoads_V1
d383c5c31e9533a10de87a9d74c4c5780a01fbe5
[ "MIT" ]
2
2020-07-24T23:31:25.000Z
2020-07-27T09:27:27.000Z
import numpy as np class Loader(): def __init__(self, features,labels): self.x = features self.y = labels def shuffle_x(self,batch_size, ): features=self.x labels=self.y idx = np.arange(0, len(features)) np.random.shuffle(idx) idx = idx[:batch_size] data_shuffle = [features[i] for i in idx] labels_shuffle = [labels[i] for i in idx] return np.asarray(data_shuffle), np.asarray( labels_shuffle)
27.611111
52
0.595573
2183b930905f15121d7c950eb530f85541cf0b7d
248
js
JavaScript
js/src/TwoWays/util/makeGetter.js
cfv1984/two-ways
54191e62a14af02e57fddaf9fa6668a6473ca112
[ "MIT" ]
2
2017-04-20T05:28:58.000Z
2020-06-11T18:34:56.000Z
js/src/TwoWays/util/makeGetter.js
cfv1984/two-ways
54191e62a14af02e57fddaf9fa6668a6473ca112
[ "MIT" ]
null
null
null
js/src/TwoWays/util/makeGetter.js
cfv1984/two-ways
54191e62a14af02e57fddaf9fa6668a6473ca112
[ "MIT" ]
null
null
null
module.exports = function makeGetter(expr){ if(expr.indexOf('$') > -1){ //special case the fuck out of this expr = expr.replace(/\$/g,'scope.\$'); } else{ expr = 'scope.'+expr; } return new Function('scope', `return ${expr}`); }
24.8
65
0.58871
8d8b5416ab36eaf422562d663efe10f9d50d54aa
4,760
js
JavaScript
test/b_handler.js
hcphoon01/VATSIM-Data-Handler
9c6463761a6502cdb24a37f500ae18871ede8d35
[ "MIT" ]
10
2019-10-09T16:57:51.000Z
2022-01-04T05:14:25.000Z
test/b_handler.js
hcphoon01/VATSIM-Data-Handler
9c6463761a6502cdb24a37f500ae18871ede8d35
[ "MIT" ]
6
2019-10-09T20:20:49.000Z
2021-03-10T21:19:30.000Z
test/b_handler.js
hcphoon01/VATSIM-Data-Handler
9c6463761a6502cdb24a37f500ae18871ede8d35
[ "MIT" ]
4
2019-10-09T18:41:32.000Z
2020-04-21T12:26:39.000Z
const { handler } = require("../build/cjs/methods"); const chai = require("chai"); const chaiAsPromised = require("chai-as-promised"); chai.use(chaiAsPromised); chai.should(); const fs = require("fs"); const path = require("path"); const jsonFile = path.basename("../vatsimData.json"); const controller = { cid: 9999999, name: "Test User", callsign: "EGLL_SUP", frequency: 199.998, facility: 0, rating: 11, server: "UK-1", visual_range: 300, text_atis: ["Heathrow Supervisor", "This is the test"], last_updated: "2020-04-06T00:54:36.0769604Z", logon_time: "2020-04-06T00:54:36.0769602Z", }; const pilot = { cid: 1234567, name: "TEST USER", callsign: "VATSIMTEST1", server: "UK-1", pilot_rating: 1, latitude: -4.67434, longitude: 55.52184, altitude: 100, groundspeed: 0, transponder: "1234", heading: 360, qnh_i_hg: 29.92, qnh_mb: 1013, flight_plan: { flight_rules: "I", aircraft: "A320/MA320/M-SDE2FGHIRWXY/LB1", aircraft_faa: "A320/L", aircraft_short: "A320", departure: "EGLL", arrival: "EGLL", alternate: "EGLL", cruise_tas: "480", altitude: "6000", deptime: "1030", enroute_time: "0100", fuel_time: "0400", remarks: "/v/", route: "DCT", }, last_updated: "2020-04-05T14:00:38.8546725Z", logon_time: "2020-04-05T14:00:38.8546724Z", }; describe("#Data Handling", () => { before(() => { const file = fs.readFileSync(jsonFile); const parsed = JSON.parse(file); parsed.controllers.push(controller); parsed.pilots.push(pilot); const json = JSON.stringify(parsed); fs.writeFileSync("vatsimData.json", json); }); describe(`getCount('all')`, () => { it("should get all clients", () => { handler.getCount("all").should.eventually.be.above(0); }); }); describe(`getCount('pilots')`, () => { it("should get all pilots", () => { handler.getCount("pilots").should.eventually.be.above(0); }); }); describe(`getCount('controllers')`, () => { it("should get all controllers", () => { handler.getCount("controllers").should.eventually.be.above(0); }); }); describe(`getCount('test')`, () => { it("should return undefined when a random type is inputted", () => { handler.getCount("test").should.eventually.be.undefined; }); }); describe("getAirportInfo()", () => { it("should get airport information for a given airport, EGLL", () => { handler.getAirportInfo("EGLL").should.eventually.be.an("object").that.is .not.empty; }); it("should return an empty array when no airport is given", () => { handler.getAirportInfo().should.eventually.be.undefined; }); it("should not include users with the frequency of 199.998", () => { handler .getAirportInfo("EGLL") .should.eventually.be.an("object") .that.does.not.include(controller); }); }); describe("getPopularAirports()", () => { it("should get a list of the 10 most popular airports", () => { handler .getPopularAirports() .should.eventually.be.an("array") .to.have.lengthOf(10); }); }); describe("getFlightInfo(callsign)", () => { it("should get the flight infrmation for a connected callsign, VATSIMTEST1", () => { handler.getFlightInfo("VATSIMTEST1").should.eventually.be.an("object") .that.is.not.empty; }); it("should return undefined for a non connected callsign", () => { handler.getClientDetails("THISISAMADEUPCALLSIGN").should.eventually.be .undefined; }); }); describe("getClients()", () => { it("should return a list of all clients", () => { handler.getClients().should.eventually.be.an("array").that.is.not.empty; }); }); describe("getClientDetails(cid)", () => { it("should get flight information for a connected CID, 1234567", () => { handler.getClientDetails(1234567).should.eventually.be.an("object").that .is.not.empty; }); it("should return undefined for a non connected CID", () => { handler.getClientDetails(999999).should.eventually.be.undefined; }); }); describe("getSupervisors()", () => { it("should return a list of supervisors connected to the VATSIM network, including a test supervisor", () => { handler.getSupervisors().should.eventually.be.an("array").that.is.not .empty; }); }); describe("getControllers()", () => { it("should return a list of all controllers connected to the VATSIM network", () => { handler.getControllers().should.eventually.be.an("array").that.is.not .empty; }); }); after(() => { fs.unlinkSync("vatsimData.json"); fs.unlinkSync("oldData.json"); }); });
28
114
0.615756
c5660ecb0a2d357ffad5435abece8709767ec2e1
2,151
swift
Swift
ZwaaiLogic/Backend/CombineLocationWithTime.swift
Zwaai-app/zwaai-ios
6123bb889d6ce0b0f4d73e7c2896d45f7d3676f3
[ "MIT" ]
null
null
null
ZwaaiLogic/Backend/CombineLocationWithTime.swift
Zwaai-app/zwaai-ios
6123bb889d6ce0b0f4d73e7c2896d45f7d3676f3
[ "MIT" ]
2
2020-07-31T06:07:03.000Z
2020-07-31T06:11:51.000Z
ZwaaiLogic/Backend/CombineLocationWithTime.swift
Zwaai-app/zwaai-ios
6123bb889d6ce0b0f4d73e7c2896d45f7d3676f3
[ "MIT" ]
null
null
null
import Foundation protocol CombineLocationWithTimeProto { func run( encryptedLocation: GroupElement, completion: @escaping (Result<[GroupElement], AppError>) -> Void ) } class CombineLocationWithTime: Backend, CombineLocationWithTimeProto { func run( encryptedLocation: GroupElement, completion: @escaping (Result<[GroupElement], AppError>) -> Void ) { let session = deps.createSession(.ephemeral) withHostName { hostname in let url = URL(string: "http://\(hostname):3000/api/v1/space/checkin")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let hexString = encryptedLocation.hexEncodedString() let payload = "{\"encryptedLocation\":\"\(hexString)\"}" let hexBytes = payload.data(using: .utf8)! let task = session.uploadTaskTestable(with: request, from: hexBytes) { data, response, error in if let error = error { completion(.failure(AppError.backendProblem(error: error))) return } guard let response = response as? HTTPURLResponse else { completion(.failure(AppError.backendResponseError(statusCode: 0))) return } guard (200...299).contains(response.statusCode) else { completion(.failure(AppError.backendResponseError(statusCode: response.statusCode))) return } let decoder = JSONDecoder() if let mimeType = response.mimeType, mimeType == "application/json", let data = data, let response = try? decoder.decode(Response.self, from: data) { completion(.success(response.encryptedLocationTimeCodes)) } } task.resume() } } struct Response: Codable { let encryptedLocationTimeCodes: [GroupElement] } }
39.833333
107
0.572757
0d58f6b3eacb2b769ca2be3e6bb6f3be9cc9461c
967
cs
C#
Components/ResetPositionOnEnable.cs
Deepscorn/DeepLabs
90f19d86da944fe123b7fd085562645676941630
[ "Apache-2.0" ]
2
2016-06-08T22:15:15.000Z
2018-09-21T11:00:49.000Z
Components/ResetPositionOnEnable.cs
Deepscorn/DeepLabs
90f19d86da944fe123b7fd085562645676941630
[ "Apache-2.0" ]
1
2017-01-27T12:14:27.000Z
2017-01-27T12:14:27.000Z
Components/ResetPositionOnEnable.cs
Deepscorn/DeepLabs
90f19d86da944fe123b7fd085562645676941630
[ "Apache-2.0" ]
null
null
null
// Copyright 2014 Tokarev Mikhail (also known as Deepscorn) // http://www.apache.org/licenses/LICENSE-2.0 using UnityEngine; namespace Assets.Sources.Scripts.Basic { public class ResetPositionOnEnable: MonoBehaviour { private Vector3 startPosition; public void Awake() { var rectTransform = GetComponent<RectTransform>(); if (rectTransform == null) { startPosition = transform.localPosition; } else { startPosition = rectTransform.anchoredPosition; } } public void OnEnable() { var rectTransform = GetComponent<RectTransform>(); if (rectTransform == null) { transform.localPosition = startPosition; } else { rectTransform.anchoredPosition = startPosition; } } } }
25.447368
63
0.534643
389615b835aff0ca544b9127d562731cc305a066
1,801
php
PHP
dmFrontPlugin/lib/action/base/dmFrontBaseComponents.php
PolibudaInfo/diem
463d67bb936ff2b2486ff54e836b2e3070935e09
[ "MIT", "BSD-3-Clause" ]
12
2015-04-10T14:00:25.000Z
2021-11-08T11:21:48.000Z
dmFrontPlugin/lib/action/base/dmFrontBaseComponents.php
PolibudaInfo/diem
463d67bb936ff2b2486ff54e836b2e3070935e09
[ "MIT", "BSD-3-Clause" ]
5
2015-04-01T09:12:04.000Z
2020-07-15T12:41:43.000Z
dmFrontPlugin/lib/action/base/dmFrontBaseComponents.php
PolibudaInfo/diem
463d67bb936ff2b2486ff54e836b2e3070935e09
[ "MIT", "BSD-3-Clause" ]
10
2015-01-15T20:20:47.000Z
2021-11-23T12:15:46.000Z
<?php class dmFrontBaseComponents extends dmBaseComponents { protected $forms; /** * Initializes this component. * * @param sfContext $context The current application context. * @param string $moduleName The module name. * @param string $actionName The action name. * * @return boolean true, if initialization completes successfully, otherwise false */ public function initialize($context, $moduleName, $actionName) { parent::initialize($context, $moduleName, $actionName); $this->forms = $this->getService('form_manager'); } /** * @return DmPage the current page */ public function getPage() { return $this->context->getPage(); } /** * Preload all pages related to records */ protected function preloadPages($records) { dmDb::table('DmPage')->preloadPagesForRecords($records); } /** * Return model record id of current DmPage * * @return integer|null id of model record for current DmPage */ protected function getPageRecordId() { if (!$this->getPage()) { return null; } return $this->getPage()->getRecordId(); } /** * Return model record name of current DmPage * * @return string name of model record for current DmPage */ protected function getPageModel() { if (!$this->getPage()) { return null; } if (!is_object($this->getPage()->getRecord())) { return null; } return get_class($this->getPage()->getRecord()); } /** * Return record instance of current DmPage * * @return object record instance of current DmPage */ protected function getPageRecord() { if (!$this->getPage()) { return null; } return $this->getPage()->getRecord(); } }
20.465909
84
0.6191
581a91fab2184bd557c2fe2f61855362d73403e4
2,138
css
CSS
Formulario/style.css
leosilvalg/Projeto-Trybewarts-Trybe
10c7279aa82cefa9eb11ec125ad1a551438d65d3
[ "CECILL-B" ]
null
null
null
Formulario/style.css
leosilvalg/Projeto-Trybewarts-Trybe
10c7279aa82cefa9eb11ec125ad1a551438d65d3
[ "CECILL-B" ]
null
null
null
Formulario/style.css
leosilvalg/Projeto-Trybewarts-Trybe
10c7279aa82cefa9eb11ec125ad1a551438d65d3
[ "CECILL-B" ]
null
null
null
@font-face { font-family:'harry'; src: url('./fonts/MagicSchoolOne-ovYz.ttf') format('truetype'); } @import url('https://fonts.googleapis.com/css2?family=Noto+Sans&display=swap'); * { margin: 0; color: #f0ffffde; font-family: 'Noto Sans', sans-serif; } body * { box-sizing: border-box; } .main { width: 100vw; /* Porcentagem da largura do viewport no eixo X */ height: 100vh; background-color: #201b2c; display: flex; justify-content: center; align-items: center; } .left { width: 60vw; height: 100vh; display: flex; justify-content: center; align-items: center; } .evaluation-form { width: 75%; /* Vw é o tamanho da viewport, a tela onde esta a página. A % pega o tamanho da div, nesse caso, a div onde esta o card. 60% e 50 vw */ display: flex; justify-content: center; flex-direction: column; padding: 30px 35px; background: #2f2841; border-radius: 20px; box-shadow: 0px 10px 40px #00000056; } .evaluation-form > h1 { font-family: Cambria, Cochin, Georgia, Times, Times New Roman, serif; text-align: center; font-family: 'harry'; color: #00ff88; font-weight: 500; margin-bottom: 15px; } .form-control > option { color: #201b2c; } .btn-forms:disabled { width: 100%; padding: 10px 0px; border: none; border-radius: 8px; outline: none; text-transform: uppercase; font-weight: 800; letter-spacing: 3px; color: #2b134b; background: white; opacity: 0.5; } .btn-forms:enabled { width: 100%; padding: 10px 0px; border: none; border-radius: 8px; outline: none; text-transform: uppercase; font-weight: 800; letter-spacing: 3px; color: #2b134b; background: #00ff88; cursor: pointer; box-shadow: 0px 10px 40px -12px #00ff8052; } .right { width: 40vw; height: 100vh; display: flex; justify-content: center; align-items: center; } .logo { width: 30vw; } #textarea { display: block; width: 100%; resize: none; outline: none; color: #201b2c; } #caracteres { display: flex; flex-direction: row; /* align-items: center; */ justify-content: flex-end; } #caracteres > label { margin-right: 10px; }
18.118644
149
0.659495
38d587a3dc388b46a6472d8666db67ee96fc04f5
5,720
php
PHP
src/Cli/Command.php
ghispi/tombstone-analyzer
f698aa38b944794ed763cfa8ece99e5e9b128786
[ "MIT" ]
null
null
null
src/Cli/Command.php
ghispi/tombstone-analyzer
f698aa38b944794ed763cfa8ece99e5e9b128786
[ "MIT" ]
null
null
null
src/Cli/Command.php
ghispi/tombstone-analyzer
f698aa38b944794ed763cfa8ece99e5e9b128786
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace Scheb\Tombstone\Analyzer\Cli; use Scheb\Tombstone\Analyzer\Analyzer; use Scheb\Tombstone\Analyzer\Config\ConfigurationLoader; use Scheb\Tombstone\Analyzer\Config\YamlConfigProvider; use Scheb\Tombstone\Analyzer\Log\AnalyzerLogDirectoryReader; use Scheb\Tombstone\Analyzer\Log\LogReaderInterface; use Scheb\Tombstone\Analyzer\Matching\MethodNameStrategy; use Scheb\Tombstone\Analyzer\Matching\PositionStrategy; use Scheb\Tombstone\Analyzer\Report\ConsoleReportGenerator; use Scheb\Tombstone\Analyzer\Report\HtmlReportGenerator; use Scheb\Tombstone\Analyzer\Report\PhpReportGenerator; use Scheb\Tombstone\Analyzer\Report\ReportExporter; use Scheb\Tombstone\Analyzer\Source\TombstoneExtractorFactory; use Scheb\Tombstone\Analyzer\Source\TombstoneExtractorInterface; use Scheb\Tombstone\Analyzer\TombstoneIndex; use Scheb\Tombstone\Analyzer\VampireIndex; use SebastianBergmann\FinderFacade\FinderFacade; use Symfony\Component\Console\Command\Command as AbstractCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class Command extends AbstractCommand { /** * @var InputInterface */ private $input; /** * @var ConsoleOutput */ private $output; protected function configure() { $this ->setName('tombstone') ->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to config file'); } protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = new ConsoleOutput($output); try { $this->doExecute(); } catch (\Exception $e) { $this->output->writeln($e->getMessage()); $this->output->debug($e->getTraceAsString()); return $e->getCode() ?: 1; } return 0; } private function doExecute(): void { $configFile = $this->input->getOption('config') ?? getcwd().DIRECTORY_SEPARATOR.'tombstone.yml'; if (!file_exists($configFile)) { throw new \InvalidArgumentException('Could not find configuration file '.$configFile); } $this->output->debug('Load config from '.$configFile); $configLoader = ConfigurationLoader::create(); $config = $configLoader->loadConfiguration([new YamlConfigProvider($configFile)]); $rootDir = $config['rootDir']; $tombstoneIndex = new TombstoneIndex($rootDir); $vampireIndex = new VampireIndex(); $tombstoneExtractor = TombstoneExtractorFactory::create($config, $tombstoneIndex, $this->output); $logReaders = $this->createLogReaders($config); $analyzer = $this->createAnalyzer(); $this->output->writeln('Scan source code ...'); $files = $this->collectSourceFiles($config); $this->extractTombstones($files, $tombstoneExtractor); $this->output->writeln('Read logs ...'); foreach ($logReaders as $logReader) { $logReader->collectVampires($vampireIndex); } $this->output->writeln('Analyze tombstones ...'); $result = $analyzer->getResult($tombstoneIndex, $vampireIndex); $reportGenerators = []; if (isset($config['report']['console'])) { $reportGenerators[] = new ConsoleReportGenerator($this->output); } if (isset($config['report']['html'])) { $reportGenerators[] = new HtmlReportGenerator($config['report']['html'], $rootDir); } if (isset($config['report']['php'])) { $reportGenerators[] = new PhpReportGenerator($config['report']['php']); } $reportExporter = new ReportExporter($this->output, $reportGenerators); $reportExporter->generate($result); } private function createAnalyzer(): Analyzer { $matchingStrategies = [ new MethodNameStrategy(), new PositionStrategy(), ]; return new Analyzer($matchingStrategies); } /** * @param array $config * @return LogReaderInterface[] */ private function createLogReaders(array $config): array { $logReaders = []; if (isset($config['logs']['directory'])) { $logReaders[] = AnalyzerLogDirectoryReader::create($config['logs']['directory'], $this->output); } if (isset($config['logs']['custom'])) { require_once $config['logs']['custom']['file']; $reflectionClass = new \ReflectionClass($config['logs']['custom']['class']); if (!$reflectionClass->implementsInterface(LogReaderInterface::class)) { throw new \Exception('Class '.$config['logs']['custom']['class'].' must implement '.LogReaderInterface::class); } $logReaders[] = $reflectionClass->newInstance(); } return $logReaders; } private function collectSourceFiles(array $config): array { $finder = new FinderFacade( $config['source']['directories'], $config['source']['excludes'], $config['source']['names'], $config['source']['notNames'] ); return $finder->findFiles(); } private function extractTombstones(array $files, TombstoneExtractorInterface $tombstoneExtractor): void { $progress = $this->output->createProgressBar(count($files)); foreach ($files as $file) { $this->output->debug($file); $tombstoneExtractor->extractTombstones($file); $progress->advance(); } $this->output->writeln(); } }
34.666667
127
0.637063
d4e90ffe985d5c35a670f06d3ca7b2ca8f6d7477
418
ts
TypeScript
src/main.ts
any-design/vite-plugin-gfont
fc1d641a26aca0b348650fc328cab4d582638c5d
[ "MIT" ]
null
null
null
src/main.ts
any-design/vite-plugin-gfont
fc1d641a26aca0b348650fc328cab4d582638c5d
[ "MIT" ]
null
null
null
src/main.ts
any-design/vite-plugin-gfont
fc1d641a26aca0b348650fc328cab4d582638c5d
[ "MIT" ]
null
null
null
import type { Plugin } from 'vite'; import { getInjector } from './injector'; import { UserPluginConfig } from './types'; export default function Plugin(config: UserPluginConfig): Plugin { const injector = getInjector(config); return { name: 'vite-plugin-gfont', transformIndexHtml: (html: string) => { if (!injector) { return html; } return injector.inject(html); }, } };
24.588235
66
0.636364
cf09cfe570d39e1b593f88d582827ec327992100
148
php
PHP
test/_files/json.php
zendframework/ZendService_Api
7c781ba6da0592882acdece02e1d8910fb62aa42
[ "BSD-3-Clause" ]
18
2015-04-09T19:29:26.000Z
2019-04-12T12:39:08.000Z
test/_files/json.php
zendframework/ZendService_Api
7c781ba6da0592882acdece02e1d8910fb62aa42
[ "BSD-3-Clause" ]
1
2017-12-14T10:25:33.000Z
2018-05-14T17:52:36.000Z
test/_files/json.php
zendframework/ZendService_Api
7c781ba6da0592882acdece02e1d8910fb62aa42
[ "BSD-3-Clause" ]
5
2017-02-27T14:45:59.000Z
2022-02-24T19:02:47.000Z
<?php return array( 'method' => 'GET', 'response' => array( 'format' => 'json', 'valid_codes' => array('200') ) );
16.444444
37
0.439189
557f535f666a6c7f843b5287959c1545426971e8
1,371
dart
Dart
gesture_demo/lib/main.dart
ryanlid/flutter-demos
f067cbec46400cecad5aae6163281c1b5aa82326
[ "MIT" ]
null
null
null
gesture_demo/lib/main.dart
ryanlid/flutter-demos
f067cbec46400cecad5aae6163281c1b5aa82326
[ "MIT" ]
null
null
null
gesture_demo/lib/main.dart
ryanlid/flutter-demos
f067cbec46400cecad5aae6163281c1b5aa82326
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; // void mian()=>runApp(myApp()); void main() => runApp(MaterialApp( title: '按下手势', home: MyApp(), )); class MyButton extends StatelessWidget { @override Widget build(BuildContext context) { return GestureDetector( onTap: () { final snackbar = SnackBar( content: Text('单击'), duration: Duration(seconds: 1), ); Scaffold.of(context).showSnackBar(snackbar); }, onLongPress: () { final snackbar = SnackBar( content: Text('长按'), duration: Duration(seconds: 1), ); Scaffold.of(context).showSnackBar(snackbar); }, onDoubleTap: () { final snackbar = SnackBar( content: Text('双击'), duration: Duration(seconds: 1), ); Scaffold.of(context).showSnackBar(snackbar); }, child: Container( padding: EdgeInsets.all(12), decoration: BoxDecoration( color: Theme.of(context).buttonColor, borderRadius: BorderRadius.circular(10.0)), child: Text('按下测试'), ), ); } } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('按下测试 demo')), body: Center( child: MyButton(), ), ); } }
24.052632
55
0.563822
5faae1e878bddb697bd24d1942542f62cd15cb88
55
ps1
PowerShell
Chapter-4/Install-hybrid-worker.ps1
srmchem/Azure-for-Architects-Third-Edition
d4f3d8bb45ed69738de6fe41c03f633753ed2dbc
[ "MIT" ]
23
2020-04-05T09:00:37.000Z
2022-03-13T02:17:09.000Z
Chapter-4/Install-hybrid-worker.ps1
srmchem/Azure-for-Architects-Third-Edition
d4f3d8bb45ed69738de6fe41c03f633753ed2dbc
[ "MIT" ]
1
2021-09-25T19:27:11.000Z
2021-09-25T19:27:11.000Z
Chapter-4/Install-hybrid-worker.ps1
srmchem/Azure-for-Architects-Third-Edition
d4f3d8bb45ed69738de6fe41c03f633753ed2dbc
[ "MIT" ]
31
2020-07-05T00:30:21.000Z
2022-02-28T02:33:09.000Z
Install-Script -Name New-OnPremiseHybridWorker -verbose
55
55
0.872727
ba7636651241d7b2ddfd5a8c9f30d114529c114c
4,401
lua
Lua
bin/data/engine/editor/text-editor/text-editor-error-list.lua
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
31
2015-03-19T08:44:48.000Z
2021-12-15T20:52:31.000Z
bin/data/engine/editor/text-editor/text-editor-error-list.lua
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
19
2015-07-09T09:02:44.000Z
2016-06-09T03:51:03.000Z
bin/data/engine/editor/text-editor/text-editor-error-list.lua
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
3
2017-10-04T23:38:18.000Z
2022-03-07T08:27:13.000Z
-- Copyright (C) 2011 - 2013 David Reid. See included LICENCE file. function GTGUI.Element:TextEditorErrorListBoxItem(lineNumber, message) self.LineNumberBox = GTGUI.Server.CreateElement(self, "text-editor-error-list-box-item-linenumber"); self.LineNumberBox:SetText(tostring(lineNumber)); self.MessageBox = GTGUI.Server.CreateElement(self, "text-editor-error-list-box-item-message"); self.MessageBox:SetText(message); function self:GetLineNumber() return tonumber(self.LineNumberBox:GetText()); end function self:GetMessage() return self.MessageBox:GetText(); end return self; end function GTGUI.Element:TextEditorErrorListBox(textEditor) self.Items = {}; self.SelectedItem = nil; self.ItemHeight = 22; self.MouseWheelScrollSpeed = 3; self.Body = GTGUI.Server.CreateElement(self, "text-editor-error-list-box-body"); self.Scrollbar = GTGUI.Server.CreateElement(self, "text-editor-error-list-box-scrollbar"); self.Scrollbar:VerticalScrollbar(); self.Scrollbar:EnableAutoVisibility(); self.Scrollbar:SetPageSize(self:GetHeight()); self.Scrollbar:OnScroll(function(data) local offset = -data.position; self.Body:SetStyle("inner-offset-y", tostring(offset * self.ItemHeight)); end); self.Body:OnSize(function() if self.Body:IsVisible() then self:UpdateScrollbar(); end end); self.Body:OnShow(function() self:UpdateScrollbar(); end); self:OnSize(function() if self:IsVisible() then self:UpdateScrollbar(); end end); self:OnShow(function() self:UpdateScrollbar(); end); self:OnMouseEnter(function() self.IsMouseOver = true; end); self:OnMouseLeave(function() self.IsMouseOver = false; end); self:WatchMouseWheel(function(data) if self.IsMouseOver then self.Scrollbar:Scroll(-data.delta * self.MouseWheelScrollSpeed); end end); function self:Clear() self.Items = {}; self.SelectedItem = nil; self.Body:DeleteAllChildren(); end function self:AddItem(lineNumber, message) local itemElement = GTGUI.Server.CreateElement(self.Body, "text-editor-error-list-box-item"); itemElement:TextEditorErrorListBoxItem(lineNumber, message); itemElement:OnPressed(function() self:SelectItem(itemElement); end); self.Items[#self.Items + 1] = itemElement; return itemElement; end function self:SelectItem(itemToSelect) self:DeselectItem(); self.SelectedItem = itemToSelect; if self.SelectedItem then self.SelectedItem:AttachStyleClass("text-editor-error-list-box-item-selected"); textEditor:OnErrorSelected(self.SelectedItem:GetLineNumber(), self.SelectedItem:GetMessage()); end end function self:DeselectItem() if self.SelectedItem then self.SelectedItem:DetachStyleClass("text-editor-error-list-box-item-selected"); end end function self:CalculateScrollbarRange() if #self.Items == 0 then return 0; else return #self.Items + 1; -- +1 just to make sure everything is visible. end end function self:CalculateScrollbarPageSize() return math.floor(self:GetInnerHeight() / self.ItemHeight); end function self:UpdateScrollbar() local range = self:CalculateScrollbarRange(); local pageSize = self:CalculateScrollbarPageSize(); self.Scrollbar:SetRange(range); self.Scrollbar:SetPageSize(pageSize); end return self; end function GTGUI.Element:TextEditorErrorList(textEditor) self.ListBox = GTGUI.Server.CreateElement(self, "text-editor-error-list-box"); self.ListBox:TextEditorErrorListBox(textEditor); function self:Clear() self.ListBox:Clear(); end function self:AddItem(lineNumber, message) local itemElement = self.ListBox:AddItem(lineNumber, message); if itemElement then end end return self; end
28.211538
106
0.629857
a534c49c86c3ebba99bd8266090a3accc0ce1982
1,999
kt
Kotlin
app/src/main/java/com/cyrilpillai/androidthingsdemo/MainActivity.kt
cyrilpillai/AndroidThingsDemo
2cc9dbfe300fb85c317577dcb3f162940633d4d6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/cyrilpillai/androidthingsdemo/MainActivity.kt
cyrilpillai/AndroidThingsDemo
2cc9dbfe300fb85c317577dcb3f162940633d4d6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/cyrilpillai/androidthingsdemo/MainActivity.kt
cyrilpillai/AndroidThingsDemo
2cc9dbfe300fb85c317577dcb3f162940633d4d6
[ "Apache-2.0" ]
null
null
null
package com.cyrilpillai.androidthingsdemo import android.Manifest import android.app.Activity import android.content.ContentValues.TAG import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.media.ImageReader import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.util.Log import kotlinx.android.synthetic.main.activity_main.* /** * Created by cyril on 7/1/18. */ class MainActivity : Activity() { private val cameraHelper by lazy { CameraHelper.instance } private val cameraThread by lazy { HandlerThread("CameraBackground") } private val cameraHandler by lazy { Handler(cameraThread.looper) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "No permission") return } cameraThread.start() cameraHelper.initializeCamera(context = this, backgroundHandler = cameraHandler, imageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() val imageBuf = image.planes[0].buffer val imageBytes = ByteArray(imageBuf.remaining()) imageBuf.get(imageBytes) image.close() onPictureTaken(imageBytes) }) btnCaptureImage.setOnClickListener { cameraHelper.takePicture() } } override fun onDestroy() { super.onDestroy() cameraHelper.shutDown() cameraThread.quitSafely() } private fun onPictureTaken(imageBytes: ByteArray) { val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) runOnUiThread { imCameraImage.setImageBitmap(bitmap) } } }
31.730159
99
0.678339
a452952f7f038da1fc17281536a59ad3a1e2648e
1,880
php
PHP
resources/views/buyerdashboard.blade.php
adityav2008/bubiland
c85dbee723e4e843dfbff0f2ea656f70c5bdf418
[ "MIT" ]
null
null
null
resources/views/buyerdashboard.blade.php
adityav2008/bubiland
c85dbee723e4e843dfbff0f2ea656f70c5bdf418
[ "MIT" ]
null
null
null
resources/views/buyerdashboard.blade.php
adityav2008/bubiland
c85dbee723e4e843dfbff0f2ea656f70c5bdf418
[ "MIT" ]
null
null
null
@extends('layouts.buyerdashboardlayout') @section('content') <div class = "box"> <div class="box-heading">Weather</div> <div class="right_col" role="main"> <div class="col-md-12 col-sm-12 col-xs-12"> @if (session('error')) <div class="alert alert-danger"> {{ session('error') }} </div> @endif @if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif <a href="http://www.accuweather.com/en/us/new-york-ny/10007/weather-forecast/349727" class="aw-widget-legal"> <!-- By accessing and/or using this code snippet, you agree to AccuWeather’s terms and conditions (in English) which can be found at http://www.accuweather.com/en/free-weather-widgets/terms and AccuWeather’s Privacy Statement (in English) which can be found at http://www.accuweather.com/en/privacy. --> </a><div id="awcc1470033105269" class="aw-widget-current" data-locationkey="" data-unit="f" data-language="en-us" data-useip="true" data-uid="awcc1470033105269"></div><script type="text/javascript" src="http://oap.accuweather.com/launch.js"></script> </div> </div> </div> <div class = "box"> <div class="box-heading">Calendar</div> <div class="right_col" role="main"> <div class="col-md-12 col-sm-12 col-xs-12"> <div id = "fullCalendar"></div> </div> </div> </div> </div> </div> </div> @stop
41.777778
296
0.484043
ccc645ac077586910c071ff7dc0d574f4abc58db
795
sh
Shell
.config/polybar/herbstluftwm.sh
shikikan-neko08/neko-hlwm-dotfiles
92a76f2abba0985b8e4124d3d7e62ff8ca4d135d
[ "MIT" ]
null
null
null
.config/polybar/herbstluftwm.sh
shikikan-neko08/neko-hlwm-dotfiles
92a76f2abba0985b8e4124d3d7e62ff8ca4d135d
[ "MIT" ]
null
null
null
.config/polybar/herbstluftwm.sh
shikikan-neko08/neko-hlwm-dotfiles
92a76f2abba0985b8e4124d3d7e62ff8ca4d135d
[ "MIT" ]
null
null
null
#!/bin/sh hash herbstclient xrandr print_tags() { for tag in $(herbstclient tag_status "$1"); do name=${tag#?} state=${tag%$name} case "$state" in '#') printf '%%{R} %s %%{R}' "$name" ;; '+') printf '%%{F#cccccc}%%{R} %s %%{R}%%{F-}' "$name" ;; '!') printf '%%{R} %s! %%{R}' "$name" ;; '.') printf '%%{F#cccccc} %s %%{F-}' "$name" ;; *) printf ' %s ' "$name" esac done printf '\n' } geom_regex='[[:digit:]]\+x[[:digit:]]\++[[:digit:]]\++[[:digit:]]\+' geom=$(xrandr --query | grep "^$MONITOR" | grep -o "$geom_regex") monitor=$(herbstclient list_monitors | grep "$geom" | cut -d: -f1) print_tags "$monitor" IFS="$(printf '\t')" herbstclient --idle | while read -r hook args; do case "$hook" in tag*) print_tags "$monitor" ;; esac done
18.928571
70
0.516981
b71f1c6c3a7f59c2ff60328502cc41b8afff443a
12,054
cpp
C++
ESP8266/libraries/UPnP/UPnP.cpp
fabiomendescom/ioteey
3d3cbf7be4c2fd35816898e7c4f300efe8f4f643
[ "MIT" ]
null
null
null
ESP8266/libraries/UPnP/UPnP.cpp
fabiomendescom/ioteey
3d3cbf7be4c2fd35816898e7c4f300efe8f4f643
[ "MIT" ]
null
null
null
ESP8266/libraries/UPnP/UPnP.cpp
fabiomendescom/ioteey
3d3cbf7be4c2fd35816898e7c4f300efe8f4f643
[ "MIT" ]
null
null
null
/* * ESP8266 Simple UPnP framework * There's no separate class for multiple devices, * also currently we allocate only one service, * because we assume one (IoT) device is all we do. * * Copyright (c) 2015 Hristo Gochkov * Copyright (c) 2015 Danny Backx * * Original (Arduino) version by Filippo Sallemi, July 23, 2014. * Can be found at: https://github.com/nomadnt/uSSDP * * License (MIT license): * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * THIS WAS MODIFIED BY FABIO FROM ITS ORIGINAL VERSION!!!! USE THIS * I KEPT THE ORIGINAL COPYRIGHTS ABOVE TO GIVE CREDIT TO THE AUTHORS * */ #include "Arduino.h" #include "UPnP.h" #include "debug.h" //#include "UPnP/WebServer.h" //#include "UPnP/Headers.h" //extern WebServer HTTP; // Choose one #undef DEBUG_UPNP // #define DEBUG_UPNP Serial UPnPClass UPnP; // FIXME UPnPClass::UPnPClass() { //FABIO //services = 0; } UPnPClass::~UPnPClass() { #ifdef DEBUG_UPNP DEBUG_UPNP.printf("UPnPClass DTOR\n"); #endif } void UPnPClass::begin(ESP8266WebServer *http, const char* uuid, const char* ioteeyname, const char* ioteeytype, const char* deviceURN, const char* modelName, const char* modelNumber, const char* friendlyName, const char* serialNumber, const char* manufacturer, const char* manufacturerURL, const char* modelURL) { this->http = http; String url = "/" + String("description.xml"); this->http->on(url.c_str(),std::bind(&UPnPClass::schema, this)); this->http->on("/SwitchPower1.xml",std::bind(&UPnPClass::scpd, this)); strcpy(_uuid,uuid) ; _deviceport = 80 ; strcpy(_schemaURL,"description.xml"); strcpy(_modelName,modelName); strcpy(_modelNumber,modelNumber); strcpy(_friendlyName,friendlyName); strcpy(_serialNumber,serialNumber); strcpy(_manufacturer,manufacturer); strcpy(_manufacturerURL,manufacturerURL); strcpy(_modelURL,modelURL); strcpy(_deviceURN,deviceURN); strcpy(_ioteeyname,ioteeyname); strcpy(_ioteeytype,ioteeytype); } const char *_http_header = "HTTP/1.1 200 OK\r\n" "Content-Type: text/xml\r\n" "Connection: close\r\n" "Access-Control-Allow-Origin: *\r\n" "\r\n"; static const char *_upnp_device_template_1 = "<?xml version=\"1.0\"?>" "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">" "<specVersion>" "<major>1</major>" "<minor>0</minor>" "</specVersion>" "<URLBase>http://%s:%u/</URLBase>" /* WiFi.localIP(), _port */ "<device>" "<deviceType>%s</deviceType>" "<friendlyName>%s</friendlyName>" "<presentationURL>%s</presentationURL>" "<serialNumber>%s</serialNumber>" "<modelName>%s</modelName>" "<modelNumber>%s</modelNumber>" "<modelURL>%s</modelURL>" "<manufacturer>%s</manufacturer>" "<manufacturerURL>%s</manufacturerURL>" "<UDN>uuid:%s</UDN>" "<serviceList>"; static const char *_upnp_device_template_2 = "</serviceList>" "</device>" "</root>\r\n" "\r\n"; const char *UPnPClass::mimeTypeXML = "text/xml; charset=\"utf-8\""; const char *UPnPClass::mimeTypeText = "text/plain; charset=\"utf-8\""; const char *UPnPClass::envelopeHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" "<s:body>\r\n"; const char *UPnPClass::envelopeTrailer = "</s:body>\r\n" "</s:Envelope>\r\n"; void UPnPClass::scpd() { String ret; ret = ret + "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; ret = ret + "<scpd xmlns=\"urn:schemas-upnp-org:device-1-0\">"; ret = ret + " <specVersion>"; ret = ret + " <major>1</major>"; ret = ret + " <minor>0</minor>"; ret = ret + " </specVersion>"; ret = ret + " <actionList>"; ret = ret + " <action>"; ret = ret + " <name>SetTarget</name>"; ret = ret + " <argumentList>"; ret = ret + " <argument>"; ret = ret + " <name>NewTargetValue</name>"; ret = ret + " <relatedStateVariable>Target</relatedStateVariable>"; ret = ret + " <direction>in</direction>"; ret = ret + " </argument>"; ret = ret + " </argumentList>"; ret = ret + " </action>"; ret = ret + " <action>"; ret = ret + " <name>GetTarget</name>"; ret = ret + " <argumentList>"; ret = ret + " <argument>"; ret = ret + " <name>RetTargetValue</name>"; ret = ret + " <relatedStateVariable>Target</relatedStateVariable>"; ret = ret + " <direction>out</direction>"; ret = ret + " </argument>"; ret = ret + " </argumentList>"; ret = ret + " </action>"; ret = ret + " <action>"; ret = ret + " <name>GetStatus</name>"; ret = ret + " <argumentList>"; ret = ret + " <argument>"; ret = ret + " <name>ResultStatus</name>"; ret = ret + " <relatedStateVariable>Status</relatedStateVariable>"; ret = ret + " <direction>out</direction>"; ret = ret + " </argument>"; ret = ret + " </argumentList>"; ret = ret + " </action>"; ret = ret + " </actionList>"; ret = ret + " <serviceStateTable>"; ret = ret + " <stateVariable sendEvents=\"no\">"; ret = ret + " <name>Target</name>"; ret = ret + " <dataType>boolean</dataType>"; ret = ret + " <defaultValue>0</defaultValue>"; ret = ret + " </stateVariable>"; ret = ret + " <stateVariable sendEvents=\"yes\">"; ret = ret + " <name>Status</name>"; ret = ret + " <dataType>boolean</dataType>"; ret = ret + " <defaultValue>0</defaultValue>"; ret = ret + " </stateVariable>"; ret = ret + " </serviceStateTable>"; ret = ret + "</scpd>"; this->http->setContentLength(ret.length()); this->http->send(200, "text/xml", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. this->http->sendContent(ret); this->http->handleClient(); }; // Called by HTTP server when our description XML is queried void UPnPClass::schema() { IPAddress ip = WiFi.localIP(); String ret = String(""); ret = ret + "<?xml version=\"1.0\"?>"; ret = ret + "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"; ret = ret + "<specVersion>"; ret = ret + "<major>1</major>"; ret = ret + "<minor>0</minor>"; ret = ret + "</specVersion>"; ret = ret + "<device>"; ret = ret + "<deviceType>"; ret = ret + String(_deviceURN); ret = ret + "</deviceType>"; ret = ret + "<friendlyName>"; ret = ret + String(_friendlyName); ret = ret + "</friendlyName>"; ret = ret + "<serialNumber>"; ret = ret + String(_serialNumber); ret = ret + "</serialNumber>"; ret = ret + "<modelName>"; ret = ret + String(_modelName); ret = ret + "</modelName>"; ret = ret + "<modelNumber>"; ret = ret + String(_modelNumber); ret = ret + "</modelNumber>"; ret = ret + "<modelURL>"; ret = ret + String(_modelURL); ret = ret + "</modelURL>"; ret = ret + "<manufacturer>"; ret = ret + String(_manufacturer); ret = ret + "</manufacturer>"; ret = ret + "<manufacturerURL>"; ret = ret + String(_manufacturerURL); ret = ret + "</manufacturerURL>"; ret = ret + "<UDN>"; ret = ret + String("uuid:") + String(_uuid); ret = ret + "</UDN>"; ret = ret + "<IoteeyType>"; ret = ret + String(_ioteeytype); ret = ret + "</IoteeyType>"; ret = ret + "<IoteeyName>"; ret = ret + String(_ioteeyname); ret = ret + "</IoteeyName>"; ret = ret + "<IoteeyCode>"; ret = ret + String(_uuid); ret = ret + "</IoteeyCode>"; //ret = ret + "<serviceList>"; //ret = ret + " <service>"; //ret = ret + " <serviceType>urn:schemas-upnp-org:service:SwitchPower:1</serviceType>"; //ret = ret + " <serviceId>urn:upnp-org:serviceId:SwitchPower:1</serviceId>"; //ret = ret + " <SCPDURL>/SwitchPower1.xml</SCPDURL>"; //ret = ret + " <controlURL>/SwitchPower/Control</controlURL>"; //ret = ret + " <eventSubURL>/SwitchPower/Event</eventSubURL>"; //ret = ret + " </service>"; //ret = ret + "</serviceList>"; ret = ret + "</device>"; ret = ret + "</root>"; //this->http->setContentLength(ret.length()); this->http->send(200, "text/xml",ret); // Empty content inhibits Content-length header so we have to close the socket ourselves. //this->http->sendContent(ret); this->http->handleClient(); //FABIO //if (services) { //for (int i=0; i<nservices; i++) { // Need to free //char *tmp = services[i]->getServiceXML(); //client.print(tmp); //free(tmp); //} //} } /* void UPnPClass::addService(UPnPService *srv) { if (nservices == maxservices) { maxservices += N_SERVICES; services = (UPnPService **)realloc(services, maxservices * sizeof(UPnPService *)); } services[nservices++] = srv; } */ /* * This function is a pass-through for the member function just below. */ //void staticSendSCPD() { //#ifdef DEBUG_UPNP // DEBUG_UPNP.println("staticSendSCPD"); //#endif // UPnP.SendSCPD(); //} /* * Use the URL that the web server received, isolate the UPnPService name from it, * find that service, and call its SendSCPD method. */ //void UPnPClass::SendSCPD() { //#ifdef DEBUG_UPNP //FABIO //DEBUG_UPNP.printf("SendSCPD(%s)\n", HTTP.httpUri()); //#endif //FABIO /* // Find out which UPnPService this was called for // The URL here is e.g. "/LEDService/scpd.xml" const char *url = HTTP.httpUri(); const char *name = url+1; const char *p; for (p=name; *p && *p != '/'; p++) ; if (*p == '\0') return; // silently int len = (p-name); for (int i=0; i<nservices; i++) if (strncmp(name, services[i]->serviceName, len) == 0) { #ifdef DEBUG_UPNP DEBUG_UPNP.printf("SendSCPD : service %d, %s\n", i, services[i]->serviceName); #endif // Call it ! services[i]->SendSCPD(HTTP.client()); return; } */ //} // This is a pass-through for UPnPClass::EventHandler, called from UPnPService. //void staticEventHandler() { // UPnP.EventHandler(); //} //void UPnPClass::EventHandler() { //#ifdef DEBUG_UPNP //FABIO //DEBUG_UPNP.printf("UPnPClass::EventHandler(%s)\n", HTTP.httpUri()); //#endif //FABIO /* // Find out which UPnPService this was called for // The URL here is e.g. "/LEDService/scpd.xml" const char *url = HTTP.httpUri(); const char *name = url+1; const char *p; for (p=name; *p && *p != '/'; p++) ; if (*p == '\0') return; // silently int len = (p-name); */ //FABIO //for (int i=0; i<nservices; i++) // if (strncmp(name, services[i]->serviceName, len) == 0) { //#ifdef DEBUG_UPNP // DEBUG_UPNP.printf("UPnPClass::EventHandler : service %d, %s\n", i, services[i]->serviceName); //#endif // Call it ! //services[i]->EventHandler(); //return; // } //}
33.483333
313
0.605359
a9ea1b82a23035f6904c72b60dfce6764bd7c22d
2,890
php
PHP
resources/views/empleado/ajax/contactoEmergencia.blade.php
BryantOrtega10/gesath
2dd9771baf08458525f5eb4fd2055d5215fc0780
[ "MIT" ]
null
null
null
resources/views/empleado/ajax/contactoEmergencia.blade.php
BryantOrtega10/gesath
2dd9771baf08458525f5eb4fd2055d5215fc0780
[ "MIT" ]
null
null
null
resources/views/empleado/ajax/contactoEmergencia.blade.php
BryantOrtega10/gesath
2dd9771baf08458525f5eb4fd2055d5215fc0780
[ "MIT" ]
null
null
null
<div class="emergencia" data-id="{{$num}}"> <div class="row"> <div class="col-11"></div> <div class="col-1 text-right"> <a href="#" class="btn btn-outline-danger quitarContactoEmergencia" data-id="{{$num}}">Quitar</a> </div> </div> <input type="hidden" name="idContactoEmergencia[]" value="-1" /> <div class="row"> <div class="col-3"> <div class="form-group"> <label for="nombreEmergencia{{$num}}" class="control-label">Nombre *</label> <input type="text" class="form-control" id="nombreEmergencia{{$num}}" data-id="{{$num}}" name="nombreEmergencia[]" /> </div> </div> <div class="col-3"> <div class="form-group"> <label for="telefonoEmergencia{{$num}}" class="control-label">Telefono *</label> <input type="text" class="form-control" id="telefonoEmergencia{{$num}}" data-id="{{$num}}" name="telefonoEmergencia[]" /> </div> </div> <div class="col-3"> <div class="form-group"> <label for="direccionEmergencia{{$num}}" class="control-label">Direccion *</label> <input type="text" class="form-control" id="direccionEmergencia{{$num}}" data-id="{{$num}}" name="direccionEmergencia[]" /> </div> </div> <div class="col-3"> <div class="form-group"> <label for="paisEmergencia{{$num}}" class="control-label">Pais *</label> <select class="form-control paisEmergencia" id="paisEmergencia{{$num}}" data-id="{{$num}}" name="paisEmergencia[]"> <option value=""></option> @foreach ($paises as $pais) <option value="{{$pais->idubicacion}}">{{$pais->nombre}}</option> @endforeach </select> </div> </div> </div> <div class="row"> <div class="col-3"> <div class="form-group"> <label for="deptoEmergencia{{$num}}" class="control-label">Departamento *</label> <select class="form-control deptoEmergencia" id="deptoEmergencia{{$num}}" data-id="{{$num}}" name="deptoEmergencia[]"> <option value=""></option> </select> </div> </div> <div class="col-3"> <div class="form-group"> <label for="lugarEmergencia{{$num}}" class="control-label">Lugar *</label> <select class="form-control lugarEmergencia" id="lugarEmergencia{{$num}}" data-id="{{$num}}" name="lugarEmergencia[]"> <option value=""></option> </select> </div> </div> </div> </div>
49.827586
159
0.489273