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
47cbda5ba932499de1c3f0f5813424c3d9ec1ef5
9,226
lua
Lua
test/box/net.box.test.lua
Mons/tarantool
35daf23419c88e12758d49c7c60d2cc5f8a00ad1
[ "BSD-2-Clause" ]
null
null
null
test/box/net.box.test.lua
Mons/tarantool
35daf23419c88e12758d49c7c60d2cc5f8a00ad1
[ "BSD-2-Clause" ]
null
null
null
test/box/net.box.test.lua
Mons/tarantool
35daf23419c88e12758d49c7c60d2cc5f8a00ad1
[ "BSD-2-Clause" ]
null
null
null
remote = require 'net.box' fiber = require 'fiber' log = require 'log' msgpack = require 'msgpack' LISTEN = require('uri').parse(box.cfg.listen) space = box.schema.space.create('net_box_test_space') index = space:create_index('primary', { type = 'tree' }) -- low level connection log.info("create connection") cn = remote:new(LISTEN.host, LISTEN.service) cn:_wait_state({active = true, error = true}, 1) log.info("state is %s", cn.state) cn:ping() log.info("ping is done") cn:ping() log.info("ping is done") cn:ping() -- check permissions cn:call('unexists_procedure') function test_foo(a,b,c) return { {{ [a] = 1 }}, {{ [b] = 2 }}, c } end cn:call('test_foo', 'a', 'b', 'c') cn:eval('return 2+2') box.schema.user.grant('guest','execute','universe') cn:close() cn = remote:new(box.cfg.listen) cn:call('unexists_procedure') cn:call('test_foo', 'a', 'b', 'c') cn:call(nil, 'a', 'b', 'c') cn:eval('return 2+2') cn:eval('return 1, 2, 3') cn:eval('return ...', 1, 2, 3) cn:eval('return { k = "v1" }, true, { xx = 10, yy = 15 }, nil') cn:eval('return nil') cn:eval('return') cn:eval('error("exception")') cn:eval('box.error(0)') cn:eval('!invalid expression') remote.self:eval('return 1+1, 2+2') remote.self:eval('return') remote.self:eval('error("exception")') remote.self:eval('box.error(0)') remote.self:eval('!invalid expression') box.schema.user.revoke('guest','execute','universe') box.schema.user.grant('guest','read,write,execute','universe') cn:close() cn = remote:new(box.cfg.listen) cn:_select(space.id, space.index.primary.id, 123) space:insert{123, 345} cn:_select(space.id, space.index.primary.id, 123) cn:_select(space.id, space.index.primary.id, 123, { limit = 0 }) cn:_select(space.id, space.index.primary.id, 123, { limit = 1 }) cn:_select(space.id, space.index.primary.id, 123, { limit = 1, offset = 1 }) cn.space[space.id] ~= nil cn.space.net_box_test_space ~= nil cn.space.net_box_test_space ~= nil cn.space.net_box_test_space.index ~= nil cn.space.net_box_test_space.index.primary ~= nil cn.space.net_box_test_space.index[space.index.primary.id] ~= nil cn.space.net_box_test_space.index.primary:select(123) cn.space.net_box_test_space.index.primary:select(123, { limit = 0 }) cn.space.net_box_test_space.index.primary:select(nil, { limit = 1, }) cn.space.net_box_test_space:insert{234, 1,2,3} cn.space.net_box_test_space:insert{234, 1,2,3} cn.space.net_box_test_space.insert{234, 1,2,3} cn.space.net_box_test_space:replace{354, 1,2,3} cn.space.net_box_test_space:replace{354, 1,2,4} cn.space.net_box_test_space:select{123} space:select({123}, { iterator = 'GE' }) cn.space.net_box_test_space:select({123}, { iterator = 'GE' }) cn.space.net_box_test_space:select({123}, { iterator = 'GT' }) cn.space.net_box_test_space:select({123}, { iterator = 'GT', limit = 1 }) cn.space.net_box_test_space:select({123}, { iterator = 'GT', limit = 1, offset = 1 }) cn.space.net_box_test_space:select{123} cn.space.net_box_test_space:update({123}, { { '+', 2, 1 } }) cn.space.net_box_test_space:update(123, { { '+', 2, 1 } }) cn.space.net_box_test_space:select{123} cn.space.net_box_test_space:insert(cn.space.net_box_test_space:get{123}:update{ { '=', 1, 2 } }) cn.space.net_box_test_space:delete{123} cn.space.net_box_test_space:select{2} cn.space.net_box_test_space:select({234}, { iterator = 'LT' }) cn.space.net_box_test_space:update({1}, { { '+', 2, 2 } }) cn.space.net_box_test_space:delete{1} cn.space.net_box_test_space:delete{2} cn.space.net_box_test_space:delete{2} -- test one-based indexing in splice operation (see update.test.lua) cn.space.net_box_test_space:replace({10, 'abcde'}) cn.space.net_box_test_space:update(10, {{':', 2, 0, 0, '!'}}) cn.space.net_box_test_space:update(10, {{':', 2, 1, 0, '('}}) cn.space.net_box_test_space:update(10, {{':', 2, 2, 0, '({'}}) cn.space.net_box_test_space:update(10, {{':', 2, -1, 0, ')'}}) cn.space.net_box_test_space:update(10, {{':', 2, -2, 0, '})'}}) cn.space.net_box_test_space:delete{10} cn.space.net_box_test_space:select({}, { iterator = 'ALL' }) cn.space.net_box_test_space.index.primary:min() cn.space.net_box_test_space.index.primary:min(354) cn.space.net_box_test_space.index.primary:max() cn.space.net_box_test_space.index.primary:max(234) cn.space.net_box_test_space.index.primary:count() cn.space.net_box_test_space.index.primary:count(354) cn.space.net_box_test_space:get(354) -- reconnects after errors -- -- 1. no reconnect cn:_fatal('Test fatal error') cn.state cn:ping() cn:call('test_foo') -- -- 2 reconnect cn = remote:new(LISTEN.host, LISTEN.service, { reconnect_after = .1 }) cn:_wait_state({active = true}, 1) cn.space ~= nil cn.space.net_box_test_space:select({}, { iterator = 'ALL' }) cn:_fatal 'Test error' cn:_wait_state({active = true, activew = true}, 2) cn:ping() cn.state cn.space.net_box_test_space:select({}, { iterator = 'ALL' }) cn:_fatal 'Test error' cn:_select(space.id, 0, {}, { iterator = 'ALL' }) -- send broken packet (remote server will close socket) cn.s:syswrite(msgpack.encode(1) .. msgpack.encode('abc')) fiber.sleep(.2) cn.state cn:ping() -- -- dot-new-method cn1 = remote.new(LISTEN.host, LISTEN.service) cn1:_select(space.id, 0, {}, { iterator = 'ALL' }) -- -- error while waiting for response type(fiber.create(function() fiber.sleep(.5) cn:_fatal('Test error') end)) function pause() fiber.sleep(10) return true end cn:call('pause') cn:call('test_foo', 'a', 'b', 'c') -- call remote.self:call('test_foo', 'a', 'b', 'c') cn:call('test_foo', 'a', 'b', 'c') -- long replies function long_rep() return { 1, string.rep('a', 5000) } end res = cn:call('long_rep') res[1][1] == 1 res[1][2] == string.rep('a', 5000) function long_rep() return { 1, string.rep('a', 50000) } end res = cn:call('long_rep') res[1][1] == 1 res[1][2] == string.rep('a', 50000) -- auth cn.proto.b64decode('gJLocxbO32VmfO8x04xRVxKfgwzmNVM2t6a1ME8XsD0=') cn.proto.b64decode('gJLoc!!!!!!!') cn = remote:new(LISTEN.host, LISTEN.service, { user = 'netbox', password = '123', wait_connected = true }) cn:is_connected() cn.error cn.state box.schema.user.create('netbox', { password = 'test' }) box.schema.user.grant('netbox', 'read, write, execute', 'universe'); cn = remote:new(LISTEN.host, LISTEN.service, { user = 'netbox', password = 'test' }) cn.state cn.error cn:ping() function ret_after(to) fiber.sleep(to) return {{to}} end -- timeouts cn:timeout(1).space.net_box_test_space.index.primary:select{234} cn:call('ret_after', .01) cn:timeout(1):call('ret_after', .01) cn:timeout(.01):call('ret_after', 1) cn = remote:timeout(0.0000000001):new(LISTEN.host, LISTEN.service, { user = 'netbox', password = '123' }) cn = remote:timeout(1):new(LISTEN.host, LISTEN.service, { user = 'netbox', password = '123' }) remote.self:ping() remote.self.space.net_box_test_space:select{234} remote.self:timeout(123).space.net_box_test_space:select{234} remote.self:is_connected() remote.self:wait_connected() -- cleanup database after tests space:drop() -- admin console tests cnc = remote:new(os.getenv('ADMIN')) cnc.console ~= nil cnc:console('return 1, 2, 3, "string", nil') cnc:console('error("test")') cnc:console('a = {1, 2, 3, 4}; return a[3]') -- #545 user or password is not defined remote:new(LISTEN.host, LISTEN.service, { user = 'test' }) remote:new(LISTEN.host, LISTEN.service, { password = 'test' }) -- #544 usage for remote[point]method cn = remote:new(LISTEN.host, LISTEN.service) cn:eval('return true') cn.eval('return true') cn.ping() cn:close() remote.self:eval('return true') remote.self.eval('return true') -- uri as the first argument uri = string.format('%s:%s@%s:%s', 'netbox', 'test', LISTEN.host, LISTEN.service) cn = remote.new(uri) cn:ping() cn:close() uri = string.format('%s@%s:%s', 'netbox', LISTEN.host, LISTEN.service) remote.new(uri) cn = remote.new(uri, { password = 'test' }) cn:ping() cn:close() -- #594: bad argument #1 to 'setmetatable' (table expected, got number) --# setopt delimiter ';' function gh594() local cn = remote:new(box.cfg.listen) local ping = fiber.create(function() cn:ping() end) cn:call('dostring', 'return 2 + 2') cn:close() end; --# setopt delimiter '' gh594() -- #636: Reload schema on demand sp = box.schema.space.create('test_old') _ = sp:create_index('primary') sp:insert{1, 2, 3} con = remote.new(box.cfg.listen) con:ping() con.space.test_old:select{} con.space.test == nil sp = box.schema.space.create('test') _ = sp:create_index('primary') sp:insert{2, 3, 4} con.space.test == nil con:reload_schema() con.space.test:select{} box.space.test:drop() box.space.test_old:drop() con:close() file_log = require('fio').open('tarantool.log', {'O_RDONLY', 'O_NONBLOCK'}) file_log:seek(0, 'SEEK_END') ~= 0 --# setopt delimiter ';' _ = fiber.create( function() conn = require('net.box').new(box.cfg.listen) conn.call('no_such_function', {}) end ); while true do local line = file_log:read(2048) if line ~= nil then if string.match(line, "ER_UNKNOWN") == nil then return "Success" else return "Failure" end end fiber.sleep(0.01) end; --# setopt delimiter '' file_log:close() box.schema.user.revoke('guest', 'read,write,execute', 'universe')
28.387692
106
0.686104
7f0d901736e9dcac50f3360354385079a24b03f6
321
rs
Rust
6_kyu/Esolang_Interpreters_1_Introduction_to_Esolangs_and_My_First_Interpreter_MiniStringFuck.rs
UlrichBerntien/Codewars-Katas
bbd025e67aa352d313564d3862db19fffa39f552
[ "MIT" ]
null
null
null
6_kyu/Esolang_Interpreters_1_Introduction_to_Esolangs_and_My_First_Interpreter_MiniStringFuck.rs
UlrichBerntien/Codewars-Katas
bbd025e67aa352d313564d3862db19fffa39f552
[ "MIT" ]
null
null
null
6_kyu/Esolang_Interpreters_1_Introduction_to_Esolangs_and_My_First_Interpreter_MiniStringFuck.rs
UlrichBerntien/Codewars-Katas
bbd025e67aa352d313564d3862db19fffa39f552
[ "MIT" ]
null
null
null
fn my_first_interpreter(code: &str) -> String { let mut output = String::new(); let mut accu = 0_u8; for c in code.chars() { match c { '+' => accu = accu.wrapping_add(1), '.' => output.push(accu as char), _ => {} // ignore invalid code } } output }
24.692308
47
0.485981
6bb5dce01fdccae7864a8bf94d8fb4b4cd386df3
414
h
C
CodingMart/Views/Cell/RewardPrivateRolesCell.h
jiangxiaoxin/CodingMart_iOS
b94d9f90081c4130ed6d70dd64fdd2db0768e276
[ "MIT" ]
1
2021-09-09T06:53:25.000Z
2021-09-09T06:53:25.000Z
CodingMart/Views/Cell/RewardPrivateRolesCell.h
jiangxiaoxin/CodingMart_iOS
b94d9f90081c4130ed6d70dd64fdd2db0768e276
[ "MIT" ]
null
null
null
CodingMart/Views/Cell/RewardPrivateRolesCell.h
jiangxiaoxin/CodingMart_iOS
b94d9f90081c4130ed6d70dd64fdd2db0768e276
[ "MIT" ]
2
2020-06-20T05:55:03.000Z
2021-09-09T06:54:03.000Z
// // RewardPrivateRolesCell.h // CodingMart // // Created by Ease on 16/8/30. // Copyright © 2016年 net.coding. All rights reserved. // #define kCellIdentifier_RewardPrivateRolesCell @"RewardPrivateRolesCell" #import <UIKit/UIKit.h> #import "RewardPrivate.h" @interface RewardPrivateRolesCell : UITableViewCell @property (strong, nonatomic) RewardPrivate *rewardP; + (CGFloat)cellHeightWithObj:(id)obj; @end
24.352941
72
0.7657
2799aade337220953f32b31315faf034a68a5347
609
css
CSS
frontend/src/Maps/VisualMap.css
EstaticShark/ws-product-python
734f206fe06c60d0b930d056e5fb5912a9af2cc5
[ "MIT" ]
null
null
null
frontend/src/Maps/VisualMap.css
EstaticShark/ws-product-python
734f206fe06c60d0b930d056e5fb5912a9af2cc5
[ "MIT" ]
null
null
null
frontend/src/Maps/VisualMap.css
EstaticShark/ws-product-python
734f206fe06c60d0b930d056e5fb5912a9af2cc5
[ "MIT" ]
null
null
null
.Data-map { overflow:hidden; padding-bottom:56.25%; position:relative; height: auto; width: 80%; margin: 10%; } .Data-map Map { left:0; top:0; height:100%; width:100%; position:relative; } .Start-date-form { } .End-date-form { } .Visual-forms { margin-bottom: 2px; } .Info-window { min-width: 5em; color: black; font-family: sans-serif, Helvetica; } .Info-window-header { color: green; font-family: sans-serif, Helvetica; } .Form-label { display: inline-block; text-align: right; width: 150px; margin: 5px; }
13.23913
39
0.581281
fd1aebcba77f0b8d80ca6346c563b764ffa6bf29
3,627
swift
Swift
Sources/Curly/Helpers/ClientAPIMappingHelper.swift
iamjono/curly
3292a6e298bd4dd270e2adff584a74facec18d5e
[ "MIT" ]
4
2018-05-21T07:32:51.000Z
2018-07-19T03:29:16.000Z
Sources/Curly/Helpers/ClientAPIMappingHelper.swift
iamjono/curly
3292a6e298bd4dd270e2adff584a74facec18d5e
[ "MIT" ]
2
2018-06-25T18:15:43.000Z
2018-07-11T12:16:39.000Z
Sources/Curly/Helpers/ClientAPIMappingHelper.swift
iamjono/curly
3292a6e298bd4dd270e2adff584a74facec18d5e
[ "MIT" ]
2
2018-04-13T19:01:49.000Z
2018-06-25T17:46:42.000Z
import PerfectLib import PerfectCURL import PerfectLogger import Foundation /// Helper methods to handle the mapping of the response to Codable struct ClientAPIMappingHelper { static func processResponse<T: Codable>(_ responseType: T.Type, _ confirmation: () throws -> CURLResponse, _ completion: @escaping (_ response: T?, _ error: Error?) -> Void) { do { let response = try confirmation() var success = true if response.responseCode > 399 { success = false } self.parseResponse(response, responseType, success, completion) } catch let error as CURLResponse.Error { let err = error.response self.parseResponse(err, responseType, false, completion) } catch let error { LogFile.critical("CURL GET request perform error") let httpError = ClientAPIError(code: 500, userFriendlyMessage: "", message: "confirmation failed - \(error.localizedDescription)", success: false) completion(nil, httpError) } } private static func parseResponse<T: Codable>(_ resp: CURLResponse, _ responseType: T.Type, _ isSuccess: Bool, _ completion: @escaping (_ response: T?, _ error: Error?) -> Void) { do { guard let jsonData = resp.bodyString.data(using: .utf8) else { let httpError = ClientAPIError(code: 500, userFriendlyMessage: "", message: "Body string data conversion failed", success: false) completion(nil, httpError) LogFile.error("responseCode: \(resp.responseCode) - error json: \(resp.bodyString) - responseType:\(responseType) ") return } let decoder = JSONDecoder() if isSuccess { let model = try decoder.decode(responseType, from: jsonData) completion(model, nil) } else { let model = try decoder.decode(ClientAPIError.self, from: jsonData) completion(nil, model) } } catch let error as CURLResponse.Error { let err = error.response let httpError = ClientAPIError(code: err.responseCode, userFriendlyMessage: err.bodyString, message: "parsing data", success: false) LogFile.error("Failed response code \(err.responseCode) - url: \(err.url) - Failed response bodyString: \(err.bodyString)") completion(nil, httpError) } catch let error { LogFile.error("parseResponse - decoder failed for \(responseType): \(error)") let httpError = ClientAPIError(code: 500, userFriendlyMessage: "Not able to convert \(responseType): \(error)", message: "Something went wrong", success: false) completion(nil, httpError) } } }
47.103896
135
0.483044
2dc6d38c9ba1df15d3ed8ff54194faa67f7cab7a
5,222
html
HTML
data/CRAN/simsurv.html
JuliaTagBot/OSS.jl
985ed664e484bbcc59b009968e71f2eccaaf4cd4
[ "Zlib" ]
null
null
null
data/CRAN/simsurv.html
JuliaTagBot/OSS.jl
985ed664e484bbcc59b009968e71f2eccaaf4cd4
[ "Zlib" ]
null
null
null
data/CRAN/simsurv.html
JuliaTagBot/OSS.jl
985ed664e484bbcc59b009968e71f2eccaaf4cd4
[ "Zlib" ]
3
2019-05-18T18:47:05.000Z
2020-02-08T16:36:58.000Z
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CRAN - Package simsurv</title> <link rel="stylesheet" type="text/css" href="../../CRAN_web.css" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="citation_title" content="Simulate Survival Data [R package simsurv version 0.2.2]" /> <meta name="citation_author" content="Sam Brilleman" /> <meta name="citation_publication_date.Published" content="2018-05-18" /> <meta name="citation_public_url" content="https://CRAN.R-project.org/package=simsurv" /> <meta name="DC.identifier" content="https://CRAN.R-project.org/package=simsurv" /> <meta name="DC.publisher" content="Comprehensive R Archive Network (CRAN)" /> <style type="text/css"> table td { vertical-align: top; } </style> </head> <body> <h2>simsurv: Simulate Survival Data</h2> <p>Simulate survival times from standard parametric survival distributions (exponential, Weibull, Gompertz), 2-component mixture distributions, or a user-defined hazard, log hazard, cumulative hazard, or log cumulative hazard function. Baseline covariates can be included under a proportional hazards assumption. Time dependent effects (i.e. non-proportional hazards) can be included by interacting covariates with linear time or a user-defined function of time. Clustered event times are also accommodated. The 2-component mixture distributions can allow for a variety of flexible baseline hazard functions reflecting those seen in practice. If the user wishes to provide a user-defined hazard or log hazard function then this is possible, and the resulting cumulative hazard function does not need to have a closed-form solution. Note that this package is modelled on the 'survsim' package available in the 'Stata' software (see Crowther and Lambert (2012) &lt;<a href="http://www.stata-journal.com/sjpdf.html?articlenum=st0275">http://www.stata-journal.com/sjpdf.html?articlenum=st0275</a>&gt; or Crowther and Lambert (2013) &lt;<a href="https://doi.org/10.1002/sim.5823">doi:10.1002/sim.5823</a>&gt;).</p> <table summary="Package simsurv summary"> <tr> <td>Version:</td> <td>0.2.2</td> </tr> <tr> <td>Depends:</td> <td>R (&ge; 3.3.0)</td> </tr> <tr> <td>Imports:</td> <td>methods, stats</td> </tr> <tr> <td>Suggests:</td> <td><a href="../eha/index.html">eha</a> (&ge; 2.4.5), <a href="../flexsurv/index.html">flexsurv</a> (&ge; 1.1.0), <a href="../knitr/index.html">knitr</a> (&ge; 1.15.1), <a href="../MASS/index.html">MASS</a>, <a href="../rstpm2/index.html">rstpm2</a> (&ge; 1.4.1), <a href="../survival/index.html">survival</a> (&ge; 2.40.1), <a href="../testthat/index.html">testthat</a> (&ge; 1.0.2)</td> </tr> <tr> <td>Published:</td> <td>2018-05-18</td> </tr> <tr> <td>Author:</td> <td>Sam Brilleman [cre, aut, cph], Alessandro Gasparini [ctb]</td> </tr> <tr> <td>Maintainer:</td> <td>Sam Brilleman &#x3c;&#x73;&#x61;&#x6d;&#x2e;&#x62;&#x72;&#x69;&#x6c;&#x6c;&#x65;&#x6d;&#x61;&#x6e;&#x20;&#x61;&#x74;&#x20;&#x6d;&#x6f;&#x6e;&#x61;&#x73;&#x68;&#x2e;&#x65;&#x64;&#x75;&#x3e;</td> </tr> <tr> <td>BugReports:</td> <td><a href="https://github.com/sambrilleman/simsurv/issues">https://github.com/sambrilleman/simsurv/issues</a></td> </tr> <tr> <td>License:</td> <td><a href="../../licenses/GPL-3">GPL (&ge; 3)</a> | file <a href="LICENSE">LICENSE</a></td> </tr> <tr> <td>NeedsCompilation:</td> <td>no</td> </tr> <tr> <td>In&nbsp;views:</td> <td><a href="../../views/Survival.html">Survival</a></td> </tr> <tr> <td>CRAN&nbsp;checks:</td> <td><a href="../../checks/check_results_simsurv.html">simsurv results</a></td> </tr> </table> <h4>Downloads:</h4> <table summary="Package simsurv downloads"> <tr> <td> Reference&nbsp;manual: </td> <td> <a href="simsurv.pdf"> simsurv.pdf </a> </td> </tr> <tr> <td>Vignettes:</td> <td> <a href="vignettes/simsurv_technical.html">Technical background to the simsurv package</a><br/> <a href="vignettes/simsurv_usage.html">How to use the simsurv package</a><br/> </td> </tr> <tr> <td> Package&nbsp;source: </td> <td> <a href="../../../src/contrib/simsurv_0.2.2.tar.gz"> simsurv_0.2.2.tar.gz </a> </td> </tr> <tr> <td> Windows&nbsp;binaries: </td> <td> r-devel: <a href="../../../bin/windows/contrib/3.6/simsurv_0.2.2.zip">simsurv_0.2.2.zip</a>, r-release: <a href="../../../bin/windows/contrib/3.5/simsurv_0.2.2.zip">simsurv_0.2.2.zip</a>, r-oldrel: <a href="../../../bin/windows/contrib/3.4/simsurv_0.2.2.zip">simsurv_0.2.2.zip</a> </td> </tr> <tr> <td> OS&nbsp;X&nbsp;binaries: </td> <td> r-release: <a href="../../../bin/macosx/el-capitan/contrib/3.5/simsurv_0.2.2.tgz">simsurv_0.2.2.tgz</a>, r-oldrel: <a href="../../../bin/macosx/el-capitan/contrib/3.4/simsurv_0.2.2.tgz">simsurv_0.2.2.tgz</a> </td> </tr> <tr> <td> Old&nbsp;sources: </td> <td> <a href="https://CRAN.R-project.org/src/contrib/Archive/simsurv"> simsurv archive </a> </td> </tr> </table> <h4>Linking:</h4> <p>Please use the canonical form <a href="https://CRAN.R-project.org/package=simsurv"><samp>https://CRAN.R-project.org/package=simsurv</samp></a> to link to this page.</p> </body> </html>
42.455285
388
0.670241
1fb360565613bc1314255c9f4a161e26bfeffa38
147
html
HTML
plugins/IntelliLang/java-support/inspectionDescriptions/PatternNotApplicable.html
anatawa12/intellij-community
d2557a13699986aa174a8969952711130718e7a1
[ "Apache-2.0" ]
null
null
null
plugins/IntelliLang/java-support/inspectionDescriptions/PatternNotApplicable.html
anatawa12/intellij-community
d2557a13699986aa174a8969952711130718e7a1
[ "Apache-2.0" ]
null
null
null
plugins/IntelliLang/java-support/inspectionDescriptions/PatternNotApplicable.html
anatawa12/intellij-community
d2557a13699986aa174a8969952711130718e7a1
[ "Apache-2.0" ]
null
null
null
<html> <body> Reports when a <code>@Pattern</code> annotation is applied to an element with a type other than <code>String</code>. </body> </html>
24.5
116
0.714286
21da040027a8fb85404618a3249ef800b22b8f78
4,661
html
HTML
compendium/monster/Frost-Titan-Avalanche.html
nonjosh/dnd4e-data-html
83eb6201d7992e5f0c3812c9e18a17d5897891d8
[ "MIT" ]
null
null
null
compendium/monster/Frost-Titan-Avalanche.html
nonjosh/dnd4e-data-html
83eb6201d7992e5f0c3812c9e18a17d5897891d8
[ "MIT" ]
null
null
null
compendium/monster/Frost-Titan-Avalanche.html
nonjosh/dnd4e-data-html
83eb6201d7992e5f0c3812c9e18a17d5897891d8
[ "MIT" ]
null
null
null
<!DOCTYPE HTML> <html> <head id="Head1"><title> Frost Titan Avalanche </title><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /><link href="styles/detail.css" media="screen" rel="stylesheet" type="text/css" /><link href="styles/print.css" media="print" rel="stylesheet" type="text/css" /><link href="styles/mobile.css" media="handheld" rel="stylesheet" type="text/css" /> </head> <body> <form name="form1" method="post" action="display.aspx?page=monster&amp;id=3578" id="form1"> <div> <div> <div id="detail"> <h1 class="monster">Frost Titan Avalanche<br/><span class="type">Huge elemental humanoid (cold, giant)</span><br/><span class="level">Level 14 Solo Brute<span class="xp"> XP 5000</span></span> </h1> <p class="flavor"><b>Initiative</b> +9 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Senses</b> Perception +12<br/><b>Icy Terrain</b> (Cold) aura 2 (or 5 while bloodied); enemies treat the aura’s area as difficult terrain.<br/><b>HP</b> 568; <b>Bloodied</b> 284<br/><b>AC</b> 28; <b>Fortitude</b> 28, <b>Reflex</b> 23, <b>Will</b> 26<br/><b>Resist</b> 15 cold<br/><b>Saving Throws</b> +5<br/><b>Speed</b> 8 (ice walk)<br/><b>Action Points</b> 2</p><p class="flavor alt"><img src="http://www.wizards.com/dnd/images/symbol/S2.gif" /> <b>Slam</b> (standard, at-will) <img src="http://www.wizards.com/dnd/images/symbol/x.gif" /> <b>Cold</b></p><p class="flavorIndent">Reach 3; 2d10+6 cold damage. On a critical hit, the target also takes ongoing 10 cold damage (save ends). </p><p class="flavor alt"><img src="http://www.wizards.com/dnd/images/symbol/S3.gif" /> <b>Frost Spike</b> (minor, at-will) <img src="http://www.wizards.com/dnd/images/symbol/x.gif" /> <b>Cold</b></p><p class="flavorIndent">20; +15 vs Reflex; 2d6 + 6 cold damage, and the target is slowed until the end of the frost titan avalanche’s next turn. </p><p class="flavor alt"><img src="http://www.wizards.com/dnd/images/symbol/Z2a.gif" /> <b>Avalanche Rampage</b> (standard; must be bloodied, at-will) </p><p class="flavorIndent">The frost titan avalanche shifts its speed and can enter enemies’ spaces. The titan makes a slam attack against each enemy whose space it enters. </p><p class="flavor alt"><img src="http://www.wizards.com/dnd/images/symbol/Z1a.gif" /> <b>Bloodied Backlash</b> (free, when first bloodied, encounter) </p><p class="flavorIndent">Freezing backlash recharges, and the frost titan avalanche uses it. The attack is a close burst 10 when triggered this way. </p><p class="flavor alt"><img src="http://www.wizards.com/dnd/images/symbol/Z1a.gif" /> <b>Cascading Avalanche</b> (standard, recharge <img src = "http://www.wizards.com/dnd/images/symbol/5a.gif" /><img src = "http://www.wizards.com/dnd/images/symbol/6a.gif" />) <img src="http://www.wizards.com/dnd/images/symbol/x.gif" /> <b>Cold</b></p><p class="flavorIndent">Close blast 8; +15 vs Fortitude; 3d10 + 6 damage, and the target is knocked prone. Miss: Half damage. </p><p class="flavor alt"><img src="http://www.wizards.com/dnd/images/symbol/Z1a.gif" /> <b>Freezing Backlash</b> (immediate reaction, when hit by an attack, recharge <img src = "http://www.wizards.com/dnd/images/symbol/5a.gif" /><img src = "http://www.wizards.com/dnd/images/symbol/6a.gif" />) <img src="http://www.wizards.com/dnd/images/symbol/x.gif" /> <b>Cold</b></p><p class="flavorIndent">Close burst 2 (5 while bloodied); +15 vs Fortitude; 1d10 + 6 damage, and the target is restrained and takes ongoing 5 cold damage (save ends both). Aftereffect: The target is slowed (save ends). </p><p class="flavor alt"> <b>Threatening Reach</b></p><p class="flavorIndent">A frost titan avalanche can make opportunity attacks against all enemies within its reach (3 squares).</p><p class="flavor alt"> <b>Glacial Footing</b></p><p class="flavorIndent">When an effect pulls, pushes, or slides a frost titan avalanche, the titan moves 4 squares less than the effect specifies. Also, a frost titan avalanche can make a saving throw to avoid being knocked prone.</p><p class="flavor alt"><b>Alignment</b> Evil&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b> Languages</b> Giant, Primordial<br/><b>Skills</b> Athletics +19<br/><b>Str</b> 24 (+14) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Dex</b> 15 (+9) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Wis</b> 20 (+12)<br/><b>Con</b> 22 (+13) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Int</b> 10 (+7) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Cha</b> 13 (+8)</p><br/><p class="publishedIn">Published in <a href="http://www.wizards.com/default.asp?x=dnd/drtoc/377" target="_new">Dragon Magazine 377</a>, page(s) 51.</p> </div> </form> </body> </html>
150.354839
4,033
0.683973
476648e28de573dc69c59f1b8bde8729046626a5
3,646
sql
SQL
db.sql
NatanMenezes/api_agendamento_squad23
bc06c67e1667a3bd387f8529edffa5ffd6e6b8af
[ "MIT" ]
3
2021-09-11T15:05:26.000Z
2021-09-17T18:21:06.000Z
db.sql
NatanMenezes/api_agendamento_squad23
bc06c67e1667a3bd387f8529edffa5ffd6e6b8af
[ "MIT" ]
null
null
null
db.sql
NatanMenezes/api_agendamento_squad23
bc06c67e1667a3bd387f8529edffa5ffd6e6b8af
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Tempo de geração: 09-Set-2021 às 18:18 -- Versão do servidor: 5.7.31 -- versão do PHP: 7.3.21 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Banco de dados: `sistema_agendamento` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `agendamentos` -- DROP TABLE IF EXISTS `agendamentos`; CREATE TABLE IF NOT EXISTS `agendamentos` ( `id` int(255) NOT NULL AUTO_INCREMENT, `id_funcionario` int(255) NOT NULL, `data` varchar(20) COLLATE utf8_bin NOT NULL, `estacao` varchar(20) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Extraindo dados da tabela `agendamentos` -- INSERT INTO `agendamentos` (`id`, `id_funcionario`, `data`, `estacao`) VALUES (1, 1, '24/09/2021 T', 'SP'), (2, 1, '25/09/2021 M', 'Santos'), (3, 2, '24/09/2021 T', 'SP'), (4, 3, '24/09/2021 T', 'SP'), (5, 4, '24/09/2021 M', 'SP'), (6, 2, '22/09/2021 M', 'Santos'), (7, 4, '24/09/2021 T', 'Santos'), (8, 5, '16/09/2021 T', 'SP'), (9, 4, '16/09/2021 T', 'SP'), (10, 1, '16/09/2021 T', 'SP'), (20, 4, '07/09/2021 T', 'SP'), (12, 2, '06/09/2021 T', 'SP'), (13, 3, '06/09/2021 T', 'SP'), (14, 1, '16/09/2021 T', 'SP'), (21, 1, '07/09/2021 T', 'SP'), (25, 9, '07/09/2021', 'Santos'), (22, 5, '07/09/2021 T', 'SP'), (19, 2, '07/09/2021 T', 'SP'), (23, 3, '07/09/2021 T', 'Santos'), (24, 9, '07/09/2021 T', 'Santos'), (26, 9, '0', 'Santos'), (29, 8, '07/09/2021 T', 'Santos'), (30, 8, '20/09/2021 T', 'Santos'); -- -------------------------------------------------------- -- -- Estrutura da tabela `config` -- DROP TABLE IF EXISTS `config`; CREATE TABLE IF NOT EXISTS `config` ( `id` int(255) NOT NULL AUTO_INCREMENT, `campo` varchar(255) COLLATE utf8_bin NOT NULL, `valor` int(5) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Extraindo dados da tabela `config` -- INSERT INTO `config` (`id`, `campo`, `valor`) VALUES (1, 'regulamento', 40), (2, 'capacidade_SP', 600), (3, 'capacidade_Santos', 100); -- -------------------------------------------------------- -- -- Estrutura da tabela `funcionarios` -- DROP TABLE IF EXISTS `funcionarios`; CREATE TABLE IF NOT EXISTS `funcionarios` ( `id` int(255) NOT NULL AUTO_INCREMENT, `nome` varchar(255) COLLATE utf8_bin NOT NULL, `email` varchar(255) COLLATE utf8_bin NOT NULL, `senha` varchar(255) COLLATE utf8_bin NOT NULL, `admin` tinyint(1) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Extraindo dados da tabela `funcionarios` -- INSERT INTO `funcionarios` (`id`, `nome`, `email`, `senha`, `admin`) VALUES (1, 'Natã Vinícius Menezes Guimarães', 'natanmenezes31@gmail.com', 'AdMiNdOsIsTeMa', 1), (2, 'Stefânio Soares Junior', 'stefaniojr@live.com', 'stefaniosoaresjunior', 0), (3, 'Ana Luiza Gabatelli', 'al.gabatelli@gmail.com', 'anagabatelli', 0), (4, 'Samuel Rodrigues', 'ex@example.com', 'samrodrigues', 0), (5, 'Matheus Honorato', 'matheuswebmw@gmail.com', 'MaThEuSHn', 0); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
29.885246
88
0.629731
1aa612211e09a83aab2478fade73ea5c9c42318b
251
lua
Lua
tests/projects/swig/python_cpp/xmake.lua
Arthapz/xmake
3c4c9fd8c84abca60ce50ac57133a5323cbafcd3
[ "Apache-2.0" ]
3,721
2019-02-14T09:12:03.000Z
2022-03-31T22:58:53.000Z
tests/projects/swig/python_cpp/xmake.lua
Arthapz/xmake
3c4c9fd8c84abca60ce50ac57133a5323cbafcd3
[ "Apache-2.0" ]
1,536
2019-02-08T14:22:32.000Z
2022-03-31T17:00:35.000Z
tests/projects/swig/python_cpp/xmake.lua
Arthapz/xmake
3c4c9fd8c84abca60ce50ac57133a5323cbafcd3
[ "Apache-2.0" ]
361
2019-02-08T12:20:22.000Z
2022-03-31T15:07:59.000Z
add_rules("mode.release", "mode.debug") add_requires("python 3.x") target("example") add_rules("swig.cpp", {moduletype = "python"}) add_files("src/example.i", {scriptdir = "share"}) add_files("src/example.cpp") add_packages("python")
27.888889
53
0.669323
b238a6414a2a6ff004e584c52d7cbc58345fefbb
210
swift
Swift
Tests/LinuxMain.swift
tdeleon/Relax
5c3294db30332b3ba920b2fa82b59d2cc6695fdb
[ "MIT" ]
4
2020-05-22T08:01:49.000Z
2021-12-05T18:59:56.000Z
Tests/LinuxMain.swift
tdeleon/Relax
5c3294db30332b3ba920b2fa82b59d2cc6695fdb
[ "MIT" ]
5
2021-11-11T06:08:07.000Z
2022-01-03T06:29:00.000Z
Tests/LinuxMain.swift
tdeleon/Relax
5c3294db30332b3ba920b2fa82b59d2cc6695fdb
[ "MIT" ]
null
null
null
#if !os(watchOS) import XCTest import RelaxTests //var tests = [XCTestCaseEntry]() //tests += RelaxTests.allTests() //XCTMain(tests) fatalError("Run tests with `swift test --enable-test-discovery`.") #endif
17.5
66
0.72381
2f01e86b261e5b29f2d975a144d52bc9347f0c34
8,275
php
PHP
database/seeders/MenuSeeder.php
UtkarshSarkari/laravel-ecommerce-system
74d8f85855381854b4dbbffd2eb49e931402952f
[ "BSD-2-Clause" ]
null
null
null
database/seeders/MenuSeeder.php
UtkarshSarkari/laravel-ecommerce-system
74d8f85855381854b4dbbffd2eb49e931402952f
[ "BSD-2-Clause" ]
null
null
null
database/seeders/MenuSeeder.php
UtkarshSarkari/laravel-ecommerce-system
74d8f85855381854b4dbbffd2eb49e931402952f
[ "BSD-2-Clause" ]
null
null
null
<?php namespace Database\Seeders; use Botble\Base\Supports\BaseSeeder; use Botble\Blog\Models\Category; use Botble\Blog\Models\Tag; use Botble\Ecommerce\Models\Brand; use Botble\Ecommerce\Models\ProductCategory; use Botble\Ecommerce\Models\ProductTag; use Botble\Menu\Models\Menu as MenuModel; use Botble\Menu\Models\MenuLocation; use Botble\Menu\Models\MenuNode; use Botble\Page\Models\Page; use Illuminate\Support\Arr; use Menu; class MenuSeeder extends BaseSeeder { /** * Run the database seeds. * * @return void */ public function run() { $menus = [ [ 'name' => 'Main menu', 'slug' => 'main-menu', 'location' => 'main-menu', 'items' => [ [ 'title' => 'Home', 'url' => '/', ], [ 'title' => 'Products', 'url' => '/products', ], [ 'title' => 'Shop', 'url' => '#', 'children' => [ [ 'title' => 'Product Category', 'reference_id' => 1, 'reference_type' => ProductCategory::class, ], [ 'title' => 'Brand', 'reference_id' => 1, 'reference_type' => Brand::class, ], [ 'title' => 'Product Tag', 'reference_id' => 1, 'reference_type' => ProductTag::class, ], [ 'title' => 'Product Single', 'url' => 'products/beat-headphone', ], ], ], [ 'title' => 'Blog', 'reference_id' => 3, 'reference_type' => Page::class, 'children' => [ [ 'title' => 'Blog Left Sidebar', 'reference_id' => 3, 'reference_type' => Page::class, ], [ 'title' => 'Blog Category', 'reference_id' => 1, 'reference_type' => Category::class, ], [ 'title' => 'Blog Tag', 'reference_id' => 1, 'reference_type' => Tag::class, ], [ 'title' => 'Blog Single', 'url' => 'news/4-expert-tips-on-how-to-choose-the-right-mens-wallet', ], ], ], [ 'title' => 'Contact us', 'reference_id' => 2, 'reference_type' => Page::class, ], ], ], [ 'name' => 'Useful Links', 'slug' => 'useful-links', 'items' => [ [ 'title' => 'About Us', 'reference_id' => 4, 'reference_type' => Page::class, ], [ 'title' => 'FAQ', 'reference_id' => 5, 'reference_type' => Page::class, ], [ 'title' => 'Location', 'reference_id' => 6, 'reference_type' => Page::class, ], [ 'title' => 'Affiliates', 'reference_id' => 7, 'reference_type' => Page::class, ], [ 'title' => 'Contact', 'reference_id' => 2, 'reference_type' => Page::class, ], ], ], [ 'name' => 'Categories', 'slug' => 'categories', 'items' => [ [ 'title' => 'Television', 'reference_id' => 1, 'reference_type' => ProductCategory::class, ], [ 'title' => 'Mobile', 'reference_id' => 2, 'reference_type' => ProductCategory::class, ], [ 'title' => 'Headphone', 'reference_id' => 3, 'reference_type' => ProductCategory::class, ], [ 'title' => 'Watches', 'reference_id' => 4, 'reference_type' => ProductCategory::class, ], [ 'title' => 'Game', 'reference_id' => 5, 'reference_type' => ProductCategory::class, ], ], ], [ 'name' => 'My Account', 'slug' => 'my-account', 'items' => [ [ 'title' => 'My profile', 'url' => '/customer/overview', ], [ 'title' => 'Wishlist', 'url' => '/wishlist', ], [ 'title' => 'Orders', 'url' => 'customer/orders', ], [ 'title' => 'Order tracking', 'url' => '/orders/tracking', ], ], ], ]; MenuModel::truncate(); MenuLocation::truncate(); MenuNode::truncate(); foreach ($menus as $index => $item) { $menu = MenuModel::create(Arr::except($item, ['items', 'location'])); if (isset($item['location'])) { MenuLocation::create([ 'menu_id' => $menu->id, 'location' => $item['location'], ]); } foreach ($item['items'] as $menuNode) { $this->createMenuNode($index, $menuNode); } } Menu::clearCacheMenuItems(); } /** * @param int $index * @param array $menuNode * @param int $parentId */ protected function createMenuNode(int $index, array $menuNode, int $parentId = 0): void { $menuNode['menu_id'] = $index + 1; $menuNode['parent_id'] = $parentId; if (Arr::has($menuNode, 'children')) { $children = $menuNode['children']; $menuNode['has_child'] = true; unset($menuNode['children']); } else { $children = []; $menuNode['has_child'] = false; } $createdNode = MenuNode::create($menuNode); if ($children) { foreach ($children as $child) { $this->createMenuNode($index, $child, $createdNode->id); } } } }
34.915612
103
0.301511
d1be70acb2051af803475f0f41e63a12f266666d
2,980
sql
SQL
DMS5/ValidateAutoStoragePathParams.sql
viswaratha12/dbwarden
3931accda4fb401d21b6cb272fe3d6959915ceb8
[ "Apache-2.0" ]
null
null
null
DMS5/ValidateAutoStoragePathParams.sql
viswaratha12/dbwarden
3931accda4fb401d21b6cb272fe3d6959915ceb8
[ "Apache-2.0" ]
null
null
null
DMS5/ValidateAutoStoragePathParams.sql
viswaratha12/dbwarden
3931accda4fb401d21b6cb272fe3d6959915ceb8
[ "Apache-2.0" ]
null
null
null
/****** Object: StoredProcedure [dbo].[ValidateAutoStoragePathParams] ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE ValidateAutoStoragePathParams /**************************************************** ** ** Desc: Validates that the Auto storage path parameters are correct ** ** Returns: The storage path ID; 0 if an error ** ** Auth: mem ** Date: 05/13/2011 mem - Initial version ** 07/05/2016 mem - Archive path is now aurora.emsl.pnl.gov\archive\dmsarch\ ** 09/02/2016 mem - Archive path is now adms.emsl.pnl.gov\dmsarch\ ** *****************************************************/ ( @AutoDefineStoragePath tinyint, @AutoSPVolNameClient varchar(128), @AutoSPVolNameServer varchar(128), @AutoSPPathRoot varchar(128), @AutoSPArchiveServerName varchar(64), @AutoSPArchivePathRoot varchar(128), @AutoSPArchiveSharePathRoot varchar(128) ) AS Set NoCount On If @AutoDefineStoragePath = 1 Begin If IsNull(@AutoSPVolNameClient, '') = '' RAISERROR ('Auto Storage VolNameClient cannot be blank', 11, 4) If IsNull(@AutoSPVolNameServer, '') = '' RAISERROR ('Auto Storage VolNameServer cannot be blank', 11, 4) If IsNull(@AutoSPPathRoot, '') = '' RAISERROR ('Auto Storage Path Root cannot be blank', 11, 4) If IsNull(@AutoSPArchiveServerName, '') = '' RAISERROR ('Auto Storage Archive Server Name cannot be blank', 11, 4) If IsNull(@AutoSPArchivePathRoot, '') = '' RAISERROR ('Auto Storage Archive Path Root cannot be blank', 11, 4) If IsNull(@AutoSPArchiveSharePathRoot, '') = '' RAISERROR ('Auto Storage Archive Share Path Root cannot be blank', 11, 4) End If IsNull(@AutoSPVolNameClient, '') <> '' Begin If @AutoSPVolNameClient Not Like '\\%' RAISERROR ('Auto Storage VolNameClient should be a network share, for example: \\Proto-3\', 11, 4) If @AutoSPVolNameClient Not Like '%\' RAISERROR ('Auto Storage VolNameClient must end in a backslash, for example: \\Proto-3\', 11, 4) End If IsNull(@AutoSPVolNameServer, '') <> '' Begin If @AutoSPVolNameServer Not Like '[A-Z]:%' RAISERROR ('Auto Storage VolNameServer should be a drive letter, for example: G:\', 11, 4) If @AutoSPVolNameServer Not Like '%\' RAISERROR ('Auto Storage VolNameServer must end in a backslash, for example: G:\', 11, 4) End If IsNull(@AutoSPArchivePathRoot, '') <> '' Begin If @AutoSPArchivePathRoot Not Like '/%' RAISERROR ('Auto Storage Archive Path Root should be a linux path, for example: /archive/dmsarch/Broad_Orb1', 11, 4) End If IsNull(@AutoSPArchiveSharePathRoot, '') <> '' Begin If @AutoSPArchiveSharePathRoot Not Like '\\%' RAISERROR ('Auto Storage Archive Share Path Root should be a network share, for example: \\adms.emsl.pnl.gov\dmsarch\VOrbiETD01', 11, 4) End return 0 GO GRANT VIEW DEFINITION ON [dbo].[ValidateAutoStoragePathParams] TO [DDL_Viewer] AS [dbo] GO
34.252874
140
0.662752
a8461805270f3ca44b221220103e7e3f69a34fce
2,093
kt
Kotlin
presentation/src/main/java/simra/androidtest/gheisary/twtest/film/list/FilmListAdapter.kt
cormen3/infinite-recycleView
89b63f65b128cb0488ffeb57a91da5593c432ed5
[ "Apache-2.0" ]
6
2018-12-31T07:52:36.000Z
2019-04-18T09:31:06.000Z
presentation/src/main/java/simra/androidtest/gheisary/twtest/film/list/FilmListAdapter.kt
cormen3/infinite-recycleView
89b63f65b128cb0488ffeb57a91da5593c432ed5
[ "Apache-2.0" ]
null
null
null
presentation/src/main/java/simra/androidtest/gheisary/twtest/film/list/FilmListAdapter.kt
cormen3/infinite-recycleView
89b63f65b128cb0488ffeb57a91da5593c432ed5
[ "Apache-2.0" ]
null
null
null
package simra.androidtest.gheisary.twtest.film.list import android.annotation.SuppressLint import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import ir.cobal.data.network.model.SearchResult import kotlinx.android.synthetic.main.item_film_list.view.* import simra.androidtest.gheisary.twtest.R class FilmListAdapter( val context: Context) : RecyclerView.Adapter<FilmListViewHolder>() { private val clickSubject = PublishSubject.create<String>() val clickEvent : Observable<String> = clickSubject var items = SearchResult(Search = ArrayList()) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FilmListViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_film_list, parent, false) return FilmListViewHolder(view) } @SuppressLint("SetTextI18n", "ResourceAsColor") override fun onBindViewHolder(holder: FilmListViewHolder, position: Int) { holder.itemFilmListTitleTextView.text = items.Search[position].Title Glide.with(context) .load(items.Search[position].Poster) .transition(DrawableTransitionOptions.withCrossFade()) .into(holder.itemFilmListPosterImageView) holder.itemFilmListConstraintLayout.setOnClickListener { clickSubject.onNext(items.Search[position].imdbID) } } override fun getItemCount(): Int { return items.Search.size } fun setData(items : SearchResult) { this.items = items } } class FilmListViewHolder (view: View) : RecyclerView.ViewHolder(view) { val itemFilmListPosterImageView = view.itemFilmListPosterImageView!! val itemFilmListTitleTextView = view.itemFilmListTitleTextView!! val itemFilmListConstraintLayout = view.itemFilmListConstraintLayout!! }
35.474576
95
0.761586
04aecb28ef9ddaf10fe8df1be060a7512f8bb1f6
15,622
html
HTML
src/doc/logic/multigames/GameRules.html
ivanfermena/p3_game2048
8db5f7b99dda9528c4460e7731f83f677c650308
[ "Apache-2.0" ]
null
null
null
src/doc/logic/multigames/GameRules.html
ivanfermena/p3_game2048
8db5f7b99dda9528c4460e7731f83f677c650308
[ "Apache-2.0" ]
null
null
null
src/doc/logic/multigames/GameRules.html
ivanfermena/p3_game2048
8db5f7b99dda9528c4460e7731f83f677c650308
[ "Apache-2.0" ]
null
null
null
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Mon Dec 18 00:21:14 CET 2017 --> <title>GameRules</title> <meta name="date" content="2017-12-18"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="GameRules"; } } catch(err) { } //--> var methods = {"i0":18,"i1":6,"i2":18,"i3":6,"i4":18,"i5":18,"i6":6,"i7":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?logic/multigames/GameRules.html" target="_top">Frames</a></li> <li><a href="GameRules.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">logic.multigames</div> <h2 title="Interface GameRules" class="title">Interface GameRules</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../logic/multigames/games/Rules2048.html" title="class in logic.multigames.games">Rules2048</a>, <a href="../../logic/multigames/games/RulesFib.html" title="class in logic.multigames.games">RulesFib</a>, <a href="../../logic/multigames/games/RulesInverse.html" title="class in logic.multigames.games">RulesInverse</a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel">GameRules</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>default void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#addNewCell-logic.Board-java.util.Random-">addNewCell</a></span>(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board, java.util.Random&nbsp;rand)</code> <div class="block">Metodo que sirve para aniadir una nueva celda de manera aleatoria en cada movimiento</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#addNewCellAt-logic.Board-util.Position-java.util.Random-">addNewCellAt</a></span>(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board, <a href="../../util/Position.html" title="class in util">Position</a>&nbsp;pos, java.util.Random&nbsp;rand)</code> <div class="block">Metodo que dicta la estructura de que numero se inserta en una celda determinada.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>default <a href="../../logic/Board.html" title="class in logic">Board</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#createBoard-int-">createBoard</a></span>(int&nbsp;size)</code> <div class="block">Metodo que crea un tablero nuevo con un tamanio especifico.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#getWinValue-logic.Board-">getWinValue</a></span>(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board)</code> <div class="block">Metodo que trata cuando se gana en cada juego.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>default void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#initBoard-logic.Board-int-java.util.Random-">initBoard</a></span>(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board, int&nbsp;numCells, java.util.Random&nbsp;rand)</code> <div class="block">Metodo que inicia el tablero con unas condiciones especificas de casa juego</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>default boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#lose-logic.Board-">lose</a></span>(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board)</code> <div class="block">Metodo que comprueba si quedan movimientos posibles en el tablero</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#merge-logic.Cell-logic.Cell-">merge</a></span>(<a href="../../logic/Cell.html" title="class in logic">Cell</a>&nbsp;self, <a href="../../logic/Cell.html" title="class in logic">Cell</a>&nbsp;other)</code> <div class="block">Metodo que se encarga de la logica de la union entre dos celdas</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../logic/multigames/GameRules.html#win-logic.Board-">win</a></span>(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board)</code> <div class="block">Metodo que trata si se ha llega a la condicion de victoria</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="addNewCell-logic.Board-java.util.Random-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>addNewCell</h4> <pre>default&nbsp;void&nbsp;addNewCell(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board, java.util.Random&nbsp;rand)</pre> <div class="block">Metodo que sirve para aniadir una nueva celda de manera aleatoria en cada movimiento</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>board</code> - Board --> Estado actual del tablero</dd> <dd><code>rand</code> - Random --> Objeto Random para la seleccion aleatoria</dd> </dl> </li> </ul> <a name="addNewCellAt-logic.Board-util.Position-java.util.Random-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>addNewCellAt</h4> <pre>void&nbsp;addNewCellAt(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board, <a href="../../util/Position.html" title="class in util">Position</a>&nbsp;pos, java.util.Random&nbsp;rand)</pre> <div class="block">Metodo que dicta la estructura de que numero se inserta en una celda determinada.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>board</code> - Board --> Tablero con el estado actual del juego</dd> <dd><code>pos</code> - Position --> Posicion aleatoria a la que se quiere insertar el nuevo numero</dd> <dd><code>rand</code> - Random --> Objeto Random para la seleccion aleatoria</dd> </dl> </li> </ul> <a name="createBoard-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createBoard</h4> <pre>default&nbsp;<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;createBoard(int&nbsp;size)</pre> <div class="block">Metodo que crea un tablero nuevo con un tamanio especifico.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>size</code> - int --> Tamanio especifico del nuevo tablero</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Board --> Devuelve ese tablero espefico</dd> </dl> </li> </ul> <a name="getWinValue-logic.Board-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getWinValue</h4> <pre>int&nbsp;getWinValue(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board)</pre> <div class="block">Metodo que trata cuando se gana en cada juego.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>board</code> - Board --> Tablero con el estado actual del juego.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>int --> Devuelve el valor con el cual se gana la partida.</dd> </dl> </li> </ul> <a name="initBoard-logic.Board-int-java.util.Random-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>initBoard</h4> <pre>default&nbsp;void&nbsp;initBoard(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board, int&nbsp;numCells, java.util.Random&nbsp;rand)</pre> <div class="block">Metodo que inicia el tablero con unas condiciones especificas de casa juego</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>board</code> - Board --> Estado actual del tablero</dd> <dd><code>numCells</code> - int --> Numero de celdas que se van a rellenar de comienzo.</dd> <dd><code>rand</code> - Random --> Objeto Random para la seleccion aleatoria</dd> </dl> </li> </ul> <a name="lose-logic.Board-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>lose</h4> <pre>default&nbsp;boolean&nbsp;lose(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board)</pre> <div class="block">Metodo que comprueba si quedan movimientos posibles en el tablero</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>board</code> - Board --> Estado actual del tablero</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>boolean --> Devuelve si se ha perdido la partida o no.</dd> </dl> </li> </ul> <a name="merge-logic.Cell-logic.Cell-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>merge</h4> <pre>int&nbsp;merge(<a href="../../logic/Cell.html" title="class in logic">Cell</a>&nbsp;self, <a href="../../logic/Cell.html" title="class in logic">Cell</a>&nbsp;other)</pre> <div class="block">Metodo que se encarga de la logica de la union entre dos celdas</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>self</code> - Cell --> Celda uno a tratar</dd> <dd><code>other</code> - Cell --> Celda dos a tratar</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>int --> Numero despues de la union.</dd> </dl> </li> </ul> <a name="win-logic.Board-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>win</h4> <pre>boolean&nbsp;win(<a href="../../logic/Board.html" title="class in logic">Board</a>&nbsp;board)</pre> <div class="block">Metodo que trata si se ha llega a la condicion de victoria</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>board</code> - Board --> Estado actual del tablero</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>boolean --> Devuleve si se ha ganado el juego o no.</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?logic/multigames/GameRules.html" target="_top">Frames</a></li> <li><a href="GameRules.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
39.350126
526
0.652797
165a9982462a242455709e1585b72da5044df9be
6,907
h
C
lib/cesanta/net_skeleton.h
mindforger/ledSPI
bc6cd892b893c668619fe4388cf206422713636d
[ "Apache-2.0" ]
16
2015-06-10T23:12:21.000Z
2021-07-30T00:48:25.000Z
lib/cesanta/net_skeleton.h
mindforger/ledSPI
bc6cd892b893c668619fe4388cf206422713636d
[ "Apache-2.0" ]
3
2015-06-13T16:40:09.000Z
2019-01-24T17:34:38.000Z
lib/cesanta/net_skeleton.h
mindforger/ledSPI
bc6cd892b893c668619fe4388cf206422713636d
[ "Apache-2.0" ]
1
2016-03-24T02:21:23.000Z
2016-03-24T02:21:23.000Z
// Copyright (c) 2014 Cesanta Software Limited // All rights reserved // // This library is dual-licensed: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. For the terms of this // license, see <http://www.gnu.org/licenses/>. // // You are free to use this library under the terms of the GNU General // Public License, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // Alternatively, you can license this library under a commercial // license, as set out in <http://cesanta.com/>. #ifndef NS_SKELETON_HEADER_INCLUDED #define NS_SKELETON_HEADER_INCLUDED #define NS_SKELETON_VERSION "1.0" #undef UNICODE // Use ANSI WinAPI functions #undef _UNICODE // Use multibyte encoding on Windows #define _MBCS // Use multibyte encoding on Windows #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+ #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h #define _XOPEN_SOURCE 600 // For flockfile() on Linux #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++ #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX #define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets #ifdef _MSC_VER #pragma warning (disable : 4127) // FD_SET() emits warning, disable it #pragma warning (disable : 4204) // missing c99 support #endif #include <sys/types.h> #include <sys/stat.h> #include <assert.h> #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <signal.h> #ifdef _WIN32 #pragma comment(lib, "ws2_32.lib") // Linking with winsock library #include <windows.h> #include <process.h> #ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS #endif #ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK #endif #ifndef __func__ #define STRX(x) #x #define STR(x) STRX(x) #define __func__ __FILE__ ":" STR(__LINE__) #endif #ifndef va_copy #define va_copy(x,y) x = y #endif // MINGW #defines va_copy #define snprintf _snprintf #define vsnprintf _vsnprintf #define to64(x) _atoi64(x) typedef int socklen_t; typedef unsigned char uint8_t; typedef unsigned int uint32_t; typedef unsigned short uint16_t; typedef unsigned __int64 uint64_t; typedef __int64 int64_t; typedef SOCKET sock_t; #else #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <pthread.h> #include <stdarg.h> #include <unistd.h> #include <arpa/inet.h> // For inet_pton() when NS_ENABLE_IPV6 is defined #include <netinet/in.h> #include <sys/socket.h> #include <sys/select.h> #define closesocket(x) close(x) #define __cdecl #define INVALID_SOCKET (-1) #define to64(x) strtoll(x, NULL, 10) typedef int sock_t; #endif #ifdef NS_ENABLE_DEBUG #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \ fflush(stdout); } while(0) #else #define DBG(x) #endif #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) #ifdef NS_ENABLE_SSL #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include <openssl/ssl.h> #else typedef void *SSL; typedef void *SSL_CTX; #endif #ifdef __cplusplus extern "C" { #endif // __cplusplus union socket_address { struct sockaddr sa; struct sockaddr_in sin; #ifdef NS_ENABLE_IPV6 struct sockaddr_in6 sin6; #endif }; // IO buffers interface struct iobuf { char *buf; size_t len; size_t size; }; void iobuf_init(struct iobuf *, size_t initial_size); void iobuf_free(struct iobuf *); size_t iobuf_append(struct iobuf *, const void *data, size_t data_size); void iobuf_remove(struct iobuf *, size_t data_size); // Net skeleton interface // Events. Meaning of event parameter (evp) is given in the comment. enum ns_event { NS_POLL, // Sent to each connection on each call to ns_server_poll() NS_ACCEPT, // New connection accept()-ed. union socket_address *remote_addr NS_CONNECT, // connect() succeeded or failed. int *success_status NS_RECV, // Data has benn received. int *num_bytes NS_SEND, // Data has been written to a socket. int *num_bytes NS_CLOSE // Connection is closed. NULL }; // Callback function (event handler) prototype, must be defined by user. // Net skeleton will call event handler, passing events defined above. struct ns_connection; typedef void (*ns_callback_t)(struct ns_connection *, enum ns_event, void *evp); struct ns_server { void *server_data; sock_t listening_sock; struct ns_connection *active_connections; ns_callback_t callback; SSL_CTX *ssl_ctx; SSL_CTX *client_ssl_ctx; sock_t ctl[2]; }; struct ns_connection { struct ns_connection *prev, *next; struct ns_server *server; sock_t sock; union socket_address sa; struct iobuf recv_iobuf; struct iobuf send_iobuf; SSL *ssl; void *connection_data; time_t last_io_time; unsigned int flags; #define NSF_FINISHED_SENDING_DATA (1 << 0) #define NSF_BUFFER_BUT_DONT_SEND (1 << 1) #define NSF_SSL_HANDSHAKE_DONE (1 << 2) #define NSF_CONNECTING (1 << 3) #define NSF_CLOSE_IMMEDIATELY (1 << 4) #define NSF_ACCEPTED (1 << 5) #define NSF_USER_1 (1 << 6) #define NSF_USER_2 (1 << 7) #define NSF_USER_3 (1 << 8) #define NSF_USER_4 (1 << 9) }; void ns_server_init(struct ns_server *, void *server_data, ns_callback_t); void ns_server_free(struct ns_server *); int ns_server_poll(struct ns_server *, int milli); void ns_server_wakeup(struct ns_server *); void ns_iterate(struct ns_server *, ns_callback_t cb, void *param); struct ns_connection *ns_add_sock(struct ns_server *, sock_t sock, void *p); int ns_bind(struct ns_server *, const char *addr); int ns_set_ssl_cert(struct ns_server *, const char *ssl_cert); struct ns_connection *ns_connect(struct ns_server *, const char *host, int port, int ssl, void *connection_param); int ns_send(struct ns_connection *, const void *buf, int len); int ns_printf(struct ns_connection *, const char *fmt, ...); int ns_vprintf(struct ns_connection *, const char *fmt, va_list ap); // Utility functions void *ns_start_thread(void *(*f)(void *), void *p); int ns_socketpair(sock_t [2]); int ns_socketpair2(sock_t [2], int sock_type); // SOCK_STREAM or SOCK_DGRAM void ns_set_close_on_exec(sock_t); void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags); int ns_hexdump(const void *buf, int len, char *dst, int dst_len); #ifdef __cplusplus } #endif // __cplusplus #endif // NS_SKELETON_HEADER_INCLUDED
31.538813
80
0.725641
4a6063f3ac9703e9a37f493ea99d839cb0b02984
1,417
js
JavaScript
javascript/kursbereichAnlegen.js
8bitcoderookie/moodle-theme_clean_brg4
0ad7a960c4a26513c0b2d1f4322b6ba69a9e3d47
[ "Apache-2.0" ]
null
null
null
javascript/kursbereichAnlegen.js
8bitcoderookie/moodle-theme_clean_brg4
0ad7a960c4a26513c0b2d1f4322b6ba69a9e3d47
[ "Apache-2.0" ]
null
null
null
javascript/kursbereichAnlegen.js
8bitcoderookie/moodle-theme_clean_brg4
0ad7a960c4a26513c0b2d1f4322b6ba69a9e3d47
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////// // Name: kursbereichAnlegen.js // Author: Michael Rundel // Description: Fills Moodle Course Category Form with values // 05.09.2011 // 28.08.2013 - YUI3 rewrite /////////////////////////////////////////////// YUI().use('node', function (Y) { var uri = window.location.href; if (uri.search(/parent=0/) != -1) { // create new top level course category... var schuljahrBeginn = brg4.getSchulJahrBeginn(); var schuljahrString = schuljahrBeginn.getFullYear()+"/"+String(schuljahrBeginn.getFullYear()+1).substr(2) Y.one('#id_name').set('value', 'Schuljahr '+schuljahrString); Y.one('#id_description_editor').set('value','<p>Alle Kurse im Schuljahr '+schuljahrString+'</p>'); alert("Du bist im Begriff eine neue Kurs Kategorie im Hauptverzeichnis anzulegen.\nBeachte, dass dort nur Schuljahr (z.B. 'Schuljahr 2011/12') Kategorien angelegt werden sollten!!!"); } else if (uri.search(/parent=/) != -1) { // create new course category... var schuljahrBeginn = brg4.getSchulJahrBeginn(); var schuljahrString = schuljahrBeginn.getFullYear()+"/"+String(schuljahrBeginn.getFullYear()+1).substr(2) var gegenstandLang = prompt('Gegenstand (Langform)','Mediendesign').trim(); Y.one('#id_name').set('value', gegenstandLang); Y.one('#id_description_editor').set('value', '<p>Alle '+gegenstandLang+' Kurse im Schuljahr '+schuljahrString+'</p>'); } });
52.481481
185
0.661256
5688b1c5c6cbe90c62972eb17d04f1d0478aa31c
2,372
swift
Swift
iOS/Sources/Beagle/Sources/Networking/Request.swift
BizarreNULL/beagle
e1b0a87f9d1fd8c0c123aac7d5fb98b0bfdb7d2c
[ "Apache-2.0" ]
null
null
null
iOS/Sources/Beagle/Sources/Networking/Request.swift
BizarreNULL/beagle
e1b0a87f9d1fd8c0c123aac7d5fb98b0bfdb7d2c
[ "Apache-2.0" ]
null
null
null
iOS/Sources/Beagle/Sources/Networking/Request.swift
BizarreNULL/beagle
e1b0a87f9d1fd8c0c123aac7d5fb98b0bfdb7d2c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import BeagleSchema public struct Request { public let url: URL public let type: RequestType public let additionalData: RemoteScreenAdditionalData? public init( url: URL, type: RequestType, additionalData: RemoteScreenAdditionalData? ) { self.url = url self.type = type self.additionalData = additionalData } public enum RequestType { case fetchComponent case submitForm(FormData) case fetchImage case rawRequest(RequestData) } public struct FormData { public let method: FormRemoteAction.Method public let values: [String: String] public init( method: FormRemoteAction.Method, values: [String: String] ) { self.method = method self.values = values } } public struct RequestData { public let method: String? public let headers: [String: String]? public let body: Any? public init( method: String? = "GET", headers: [String: String]? = [:], body: Any? = nil ) { self.method = method self.headers = headers self.body = body } } public enum Error: Swift.Error { case networkError(NetworkError) case decoding(Swift.Error) case loadFromTextError case urlBuilderError /// Beagle needs to be configured with your custom NetworkClient that is responsible to do network requests. /// So, this error occurs when trying to make a network request and there is no NetworkClient. case networkClientWasNotConfigured } }
28.926829
116
0.632378
fb45e62e6406ef21da3f020c4d9a8be334da2c5f
2,452
h
C
C++_-_StickyNotes/FindNote.h
RussianPenguin/samples
4300c1423a5f9f5820a6c50a3fa3bd823d005030
[ "MIT" ]
null
null
null
C++_-_StickyNotes/FindNote.h
RussianPenguin/samples
4300c1423a5f9f5820a6c50a3fa3bd823d005030
[ "MIT" ]
null
null
null
C++_-_StickyNotes/FindNote.h
RussianPenguin/samples
4300c1423a5f9f5820a6c50a3fa3bd823d005030
[ "MIT" ]
null
null
null
// FindNote.h // ////////////////////////////////////////////////////////////////////// // This file contains function objects, which are used to search // the saved notes. // Function object is a class that overloads the operator(). // It can be used instead of function pointers in the STL algorithms. #if !defined FINDNOTE_H #define FINDNOTE_H // CFindNotesByString is used to search notes by string class CFindNotesByString { private: string m_strSearchFor; // string to search for vector<CNote>* m_pvecRes; // pointer to the vector which'll contain search matches, if any // Converts string to uppercase string& ToUpper(string& str) { string::iterator iter; for (iter = str.begin(); iter != str.end(); iter++) *iter = toupper(*iter); return str; } public: // Constructor accepts string to search for and a pointer to the vector // which'll contain search matches as parameters CFindNotesByString(string str, vector<CNote>* pvec) { ATLTRACE(_T("CFindNotesByString::CFindNotesByString()\n")); m_strSearchFor = str; m_pvecRes = pvec; } // Overloads operator() void operator()(const CNote& note) { ATLTRACE(_T("CFindNotesByString::operator()()\n")); string strToSearch = note.GetNoteText(); // Convert both strings to uppercase strToSearch = ToUpper(strToSearch); m_strSearchFor = ToUpper(m_strSearchFor); // Note: case sensitive algorithm. // I'm only searching note's text if (strToSearch.find(m_strSearchFor) != -1) { // If the match is found place // the class in the result container (*m_pvecRes).push_back(note); } } }; // CFindNoteById is used to search notes by id class CFindNoteById { private: DWORD m_dwSearchFor; // id to search for vector<CNote>* m_pvecRes; // pointer to the vector which'll contain search match, if any public: // Constructor accepts id to search for and a pointer to the vector // which'll contain search matches as parameters CFindNoteById(DWORD dwID, vector<CNote>* pvec) { ATLTRACE(_T("CFindNoteById::CFindNoteById()\n")); m_dwSearchFor = dwID; m_pvecRes = pvec; } // Overloads operator() void operator()(const CNote& note) { ATLTRACE(_T("CFindNoteById::operator()()\n")); // I'm only searching note's text if (m_dwSearchFor == note.GetNoteID()) { // If the match is found place // the class in the result container (*m_pvecRes).push_back(note); } } }; #endif // !defined FINDNOTE_H
25.278351
91
0.681485
9bb150da4a6de390459befe081373d03ab527073
2,793
js
JavaScript
target/doc/implementors/core/iter/traits/double_ended/trait.DoubleEndedIterator.js
second-state/SSVMContainer
b721a7642b58c41b0e120f4e2972b165d51e89d0
[ "MIT" ]
2
2019-12-11T02:53:10.000Z
2019-12-11T08:30:44.000Z
target/doc/implementors/core/iter/traits/double_ended/trait.DoubleEndedIterator.js
second-state/SSVMContainer
b721a7642b58c41b0e120f4e2972b165d51e89d0
[ "MIT" ]
null
null
null
target/doc/implementors/core/iter/traits/double_ended/trait.DoubleEndedIterator.js
second-state/SSVMContainer
b721a7642b58c41b0e120f4e2972b165d51e89d0
[ "MIT" ]
3
2020-02-06T05:47:41.000Z
2021-05-13T06:32:57.000Z
(function() {var implementors = {}; implementors["serde_json"] = [{text:"impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/double_ended/trait.DoubleEndedIterator.html\" title=\"trait core::iter::traits::double_ended::DoubleEndedIterator\">DoubleEndedIterator</a> for <a class=\"struct\" href=\"serde_json/map/struct.Iter.html\" title=\"struct serde_json::map::Iter\">Iter</a>&lt;'a&gt;",synthetic:false,types:["serde_json::map::Iter"]},{text:"impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/double_ended/trait.DoubleEndedIterator.html\" title=\"trait core::iter::traits::double_ended::DoubleEndedIterator\">DoubleEndedIterator</a> for <a class=\"struct\" href=\"serde_json/map/struct.IterMut.html\" title=\"struct serde_json::map::IterMut\">IterMut</a>&lt;'a&gt;",synthetic:false,types:["serde_json::map::IterMut"]},{text:"impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/double_ended/trait.DoubleEndedIterator.html\" title=\"trait core::iter::traits::double_ended::DoubleEndedIterator\">DoubleEndedIterator</a> for <a class=\"struct\" href=\"serde_json/map/struct.IntoIter.html\" title=\"struct serde_json::map::IntoIter\">IntoIter</a>",synthetic:false,types:["serde_json::map::IntoIter"]},{text:"impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/double_ended/trait.DoubleEndedIterator.html\" title=\"trait core::iter::traits::double_ended::DoubleEndedIterator\">DoubleEndedIterator</a> for <a class=\"struct\" href=\"serde_json/map/struct.Keys.html\" title=\"struct serde_json::map::Keys\">Keys</a>&lt;'a&gt;",synthetic:false,types:["serde_json::map::Keys"]},{text:"impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/double_ended/trait.DoubleEndedIterator.html\" title=\"trait core::iter::traits::double_ended::DoubleEndedIterator\">DoubleEndedIterator</a> for <a class=\"struct\" href=\"serde_json/map/struct.Values.html\" title=\"struct serde_json::map::Values\">Values</a>&lt;'a&gt;",synthetic:false,types:["serde_json::map::Values"]},{text:"impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/double_ended/trait.DoubleEndedIterator.html\" title=\"trait core::iter::traits::double_ended::DoubleEndedIterator\">DoubleEndedIterator</a> for <a class=\"struct\" href=\"serde_json/map/struct.ValuesMut.html\" title=\"struct serde_json::map::ValuesMut\">ValuesMut</a>&lt;'a&gt;",synthetic:false,types:["serde_json::map::ValuesMut"]},]; if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })()
310.333333
2,540
0.722879
16eb94ef3ed8f9655603aeae3e8b0e0505e6741b
848
ts
TypeScript
src/github-user/githuber-user.service.ts
marcos-antonio/super-github-consumer-api
ad454224b383c2c5f1443c0fd5e24bd69ba0b86e
[ "MIT" ]
null
null
null
src/github-user/githuber-user.service.ts
marcos-antonio/super-github-consumer-api
ad454224b383c2c5f1443c0fd5e24bd69ba0b86e
[ "MIT" ]
2
2021-03-10T13:37:47.000Z
2022-01-22T11:24:13.000Z
src/github-user/githuber-user.service.ts
marcos-antonio/super-github-consumer-api
ad454224b383c2c5f1443c0fd5e24bd69ba0b86e
[ "MIT" ]
null
null
null
import { Injectable, HttpService } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { GithubUser } from './githuber-user'; import { GithubRepo } from '../github-repo/github-repo'; @Injectable() export class GithubUserService { constructor(private readonly httpService: HttpService) {} getAll(since: number): Observable<GithubUser[]> { return this.httpService .get('', { params: { since, }, }) .pipe(map(response => response.data)); } getByLogin(login: string): Observable<GithubUser> { return this.httpService.get(login).pipe(map(response => response.data)); } getUserRepos(login: string): Observable<GithubRepo[]> { return this.httpService .get(`${login}/repos`) .pipe(map(response => response.data)); } }
26.5
76
0.649764
fb2d3a6d66f54d7945a9baaf1316c7c0186389c2
457
h
C
Sources/Sentry/include/SentryOutOfMemoryLogic.h
harry-b/sentry-cocoa
919e07840e98dfcea039acd93bd96f3fbf9bc87e
[ "MIT" ]
460
2017-06-02T14:04:37.000Z
2022-03-31T10:22:44.000Z
Sources/Sentry/include/SentryOutOfMemoryLogic.h
harry-b/sentry-cocoa
919e07840e98dfcea039acd93bd96f3fbf9bc87e
[ "MIT" ]
1,230
2017-06-02T09:41:00.000Z
2022-03-31T17:20:24.000Z
Sources/Sentry/include/SentryOutOfMemoryLogic.h
harry-b/sentry-cocoa
919e07840e98dfcea039acd93bd96f3fbf9bc87e
[ "MIT" ]
204
2017-06-05T08:27:13.000Z
2022-03-31T10:22:38.000Z
#import "SentryDefines.h" @class SentryOptions, SentryCrashAdapter, SentryAppState, SentryFileManager, SentryAppStateManager; NS_ASSUME_NONNULL_BEGIN @interface SentryOutOfMemoryLogic : NSObject SENTRY_NO_INIT - (instancetype)initWithOptions:(SentryOptions *)options crashAdapter:(SentryCrashAdapter *)crashAdatper appStateManager:(SentryAppStateManager *)appStateManager; - (BOOL)isOOM; @end NS_ASSUME_NONNULL_END
24.052632
99
0.781182
bc87f47da60e5b1dcaa22b4a9e374e019fe3cc1b
273
swift
Swift
PeasNovel/Classes/BookDetail/Model/BookAddModel.swift
LieonShelly/PeasNovel
ba21ccb9e0446c4239171dcbd01c6882606be257
[ "MIT" ]
null
null
null
PeasNovel/Classes/BookDetail/Model/BookAddModel.swift
LieonShelly/PeasNovel
ba21ccb9e0446c4239171dcbd01c6882606be257
[ "MIT" ]
null
null
null
PeasNovel/Classes/BookDetail/Model/BookAddModel.swift
LieonShelly/PeasNovel
ba21ccb9e0446c4239171dcbd01c6882606be257
[ "MIT" ]
null
null
null
// // BookAddModel.swift // PeasNovel // // Created by xinyue on 2019/5/17. // Copyright © 2019 NotBroken. All rights reserved. // import UIKit class BookAddResponse: BaseResponse<BookInfo> { } class BooksheetAddResponse: BaseResponse<BookSheetModel> { }
15.166667
59
0.699634
c3d2882532ef843bc300d9c8dc273cee69ed4fde
1,907
go
Go
m/customListItem.go
goui2/ui
6e8b2b89d37455cd2b72f38dbff482125e6f594e
[ "MIT" ]
null
null
null
m/customListItem.go
goui2/ui
6e8b2b89d37455cd2b72f38dbff482125e6f594e
[ "MIT" ]
null
null
null
m/customListItem.go
goui2/ui
6e8b2b89d37455cd2b72f38dbff482125e6f594e
[ "MIT" ]
null
null
null
package m import ( "syscall/js" "github.com/goui2/ui/base" "github.com/goui2/ui/com" "github.com/goui2/ui/core" ) type CustomerListItem interface { ListItemBase } type customerListItem struct { ListItemBase handleUpdateHTML com.EventHandler htmlChildren []js.Value } func constructorCustomListItem(md base.MetaData, parent base.Constructor) base.Constructor { return func(id string, s ...base.InstanceSetting) base.Object { mo := &customerListItem{} parentSettings := append(s, core.ISRenderer{mo.renderer}) mo.ListItemBase = parent.New(id, parentSettings...).(ListItemBase) return mo } } func (p *customerListItem) renderer(rm core.RenderManager, item core.Element) { rm.OpenStartElement("div", p) rm.OpenEnd() for _, child := range p.Aggregation("content").Get() { ctrl := child.(core.Control) rm.WriteControl(ctrl) } rm.Close("div") } func (p *customerListItem) OnAfterRendering(v js.Value) { p.ListItemBase.OnAfterRendering(v) children := p.Aggregation("content").Get() for _, abschild := range children { child := abschild.(ListItemBase) html, _ := p.FindDomChild(child) child.OnAfterRendering(html) p.htmlChildren = append(p.htmlChildren, html) } p.handleUpdateHTML = com.MakeHandler(func(e com.Event) { p.updateHTML(e) }) p.Aggregation("content").AttachUpdateHTML(nil, p.handleUpdateHTML) } func (p *customerListItem) updateHTML(e com.Event) { logIt("updateHTML") parentRef, ok := p.DomRef() if !ok { return } for _, lbi := range p.htmlChildren { parentRef.Call("removeChild", lbi) } p.htmlChildren = make([]js.Value, 0) children := p.Aggregation("content").Get() for _, abschild := range children { child := abschild.(core.Control) rm := core.NewRenderManager() rm.WriteControl(child) html, _ := rm.Build() parentRef.Call("append", html) child.OnAfterRendering(html) p.htmlChildren = append(p.htmlChildren, html) } }
25.426667
92
0.71526
964445b76f8d18c3645549498175b073ca9b092b
666
php
PHP
app/Http/routes/backend/mapel.php
ctca8/testmiskonsepsi
58d0756f240757a5674579c9daa08f5663d0e4c9
[ "MIT" ]
1
2021-06-10T02:13:12.000Z
2021-06-10T02:13:12.000Z
app/Http/routes/backend/mapel.php
ctca8/testmiskonsepsi
58d0756f240757a5674579c9daa08f5663d0e4c9
[ "MIT" ]
2
2016-12-22T02:32:19.000Z
2020-11-18T06:50:17.000Z
app/Http/routes/backend/mapel.php
ctca8/testmiskonsepsi
58d0756f240757a5674579c9daa08f5663d0e4c9
[ "MIT" ]
6
2017-01-10T02:36:28.000Z
2021-09-30T14:04:10.000Z
<?php Route::group(['middleware' => 'auth'], function(){ get('mapel', [ 'as' => 'backend.mapel.index', 'uses' => 'MapelController@index', ]); get('mapel/add', [ 'as' => 'backend.mapel.add', 'uses' => 'MapelController@add', ]); post('mapel/insert', [ 'as' => 'backend.mapel.insert', 'uses' => 'MapelController@insert', ]); post('mapel/delete', [ 'as' => 'backend.mapel.delete', 'uses' => 'MapelController@delete', ]); get('mapel/edit/{id}', [ 'as' => 'backend.mapel.edit', 'uses' => 'MapelController@edit', ]); post('mapel/update', [ 'as' => 'backend.mapel.update', 'uses' => 'MapelController@update', ]); });
16.243902
50
0.557057
c778f1c556466aabd5720197af154973f1b3324c
86
asm
Assembly
gfx/pokemon/ivysaur/anim_idle.asm
Dev727/ancientplatinum
8b212a1728cc32a95743e1538b9eaa0827d013a7
[ "blessing" ]
28
2019-11-08T07:19:00.000Z
2021-12-20T10:17:54.000Z
gfx/pokemon/ivysaur/anim_idle.asm
Dev727/ancientplatinum
8b212a1728cc32a95743e1538b9eaa0827d013a7
[ "blessing" ]
13
2020-01-11T17:00:40.000Z
2021-09-14T01:27:38.000Z
gfx/pokemon/ivysaur/anim_idle.asm
Dev727/ancientplatinum
8b212a1728cc32a95743e1538b9eaa0827d013a7
[ "blessing" ]
22
2020-05-28T17:31:38.000Z
2022-03-07T20:49:35.000Z
setrepeat 2 frame 0, 07 frame 3, 07 dorepeat 1 frame 0, 08 frame 1, 06 endanim
10.75
12
0.674419
407d091b57554e758108e85c9db8dd403692073c
15,972
py
Python
tests/test_m3u_dump.py
sturmianseq/m3u-dump
1ec3eeedb4c650af76c6c66859375ca2d2a6e1bc
[ "MIT" ]
1
2021-02-20T20:46:11.000Z
2021-02-20T20:46:11.000Z
tests/test_m3u_dump.py
sturmianseq/m3u-dump
1ec3eeedb4c650af76c6c66859375ca2d2a6e1bc
[ "MIT" ]
null
null
null
tests/test_m3u_dump.py
sturmianseq/m3u-dump
1ec3eeedb4c650af76c6c66859375ca2d2a6e1bc
[ "MIT" ]
2
2021-08-05T10:32:00.000Z
2021-08-17T02:35:52.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_m3u_dump ---------------------------------- Tests for `m3u_dump` module. """ import os import pytest from click.testing import CliRunner from m3u_dump import cli from m3u_dump.m3u_dump import M3uDump @pytest.fixture(scope='session') def music_dir(tmpdir_factory): return tmpdir_factory.mktemp('music') @pytest.fixture(scope='session') def music_files(music_dir): d = music_dir d.join('dummy001.mp3').write('dummy') d.mkdir('sub').join('dummy002.mp3').write('dummy') d.mkdir('sub4').join('dummy002.mp3').write('dummy') d.mkdir('sub2').mkdir('sub3').join('あいう えお.mp3').write('dummy') d.mkdir('sub3').mkdir('かきく けこ').join('あいう えお.mp3').write('dummy') return d # noinspection PyShadowingNames @pytest.fixture(scope='session') def multi_playlist_music_files(music_dir): d = music_dir d.join('aaaa.m3u').write('dummy') d.mkdir('sub7').join('multi-dummy001.mp3').write('dummy') d.mkdir('sub8').mkdir('sub2').join('multi-dummy002.mp3').write('dummy') d.mkdir('sub9').join('multi-あいう えお.mp3').write('dummy') d.mkdir('sub10').join('multi-あいう えお.mp3').write('dummy') d.mkdir('sub11').join('multi-dummy004.mp3').write('dummy') d.mkdir('sub12').join('hello hello.mp3').write('dummy') return d @pytest.fixture def playlist_dir(tmpdir_factory): return tmpdir_factory.mktemp('playlist') # noinspection PyShadowingNames @pytest.fixture def playlist_current(playlist_dir): f = playlist_dir.join('playlist.m3u') f.write("""#EXTM3U #EXTINF:409,artist - music_name /full/path/dummy001.mp3 #EXTINF:281,artist - music_name /full/path/dummy002.mp3 #EXTINF:275,artist - music_name music/あいう えお.mp3 #EXTINF:263,artist - music_name /full/path/music/あいう えお.mp3 #EXTINF:288,artist - music_name /full/path/aaa/dummy002.mp3 #EXTINF:222,artist = music_name ../../hello.mp3""") return f @pytest.fixture(scope='session') def already_exists_playlist(tmpdir_factory): d = tmpdir_factory.mktemp('already-dir') music_path = str(d.mkdir('music').join('already_path.mp3').write('dummy')) playlist_content = """#EXTM3U #EXTINF:409,artist - music_name {}""".format(os.path.join(str(d), 'music', 'already_path.mp3')) playlist_path = str(d.join('playlist.m3u').write(playlist_content)) return d # noinspection PyShadowingNames @pytest.fixture def playlist_current2(playlist_dir): f = playlist_dir.join('playlist2.m3u8') f.write("""#EXTM3U #EXTINF:409,artist - music_name /full/path/multi-dummy001.mp3 #EXTINF:282,artist - music_name /full/path/multi-dummy001.mp3 #EXTINF:281,artist - music_name /full/path/multi-dummy002.mp3 #EXTINF:275,artist - music_name music/multi-あいう えお.mp3 #EXTINF:263,artist - music_name /full/path/music/multi-あいう えお.mp3 #EXTINF:288,artist - music_name /full/path/aaa/multi-dummy004.mp3 #EXTINF:222,artist = music_name ../../multi-hello.mp3""") return f @pytest.fixture(scope='session') def dump_music_path(tmpdir_factory): d = tmpdir_factory.mktemp('dst') return str(d) def test_command_line_interface(): runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 2 # must arguments assert 'Error: Missing argument' in result.output help_result = runner.invoke(cli.main, ['--help']) assert help_result.exit_code == 0 assert '--help' in help_result.output assert 'Show this message and exit.' in help_result.output # noinspection PyShadowingNames def test_command_line_dryrun(playlist_current, tmpdir_factory, music_files): dst_dir = str(tmpdir_factory.mktemp('no-dump-music')) runner = CliRunner() result = runner.invoke(cli.main, ['--dry-run', str(playlist_current), dst_dir, '--fix-search-path', str(music_files)]) assert 'Welcome m3u-dump' in result.output assert 'copy was completed(successful' in result.output assert result.exit_code == 0 # must arguments # copy できていないこと assert os.path.exists(os.path.join(dst_dir, 'dummy001.mp3')) is False assert os.path.exists(os.path.join(dst_dir, 'dummy002.mp3')) is False assert os.path.exists(os.path.join(dst_dir, 'あいう えお.mp3')) is False assert os.path.exists(os.path.join(dst_dir, 'あいう えお.mp3')) is False assert os.path.exists(os.path.join(dst_dir, 'hello.mp3')) is False playlist_name = os.path.basename(str(playlist_current)) playlist_path = os.path.join(dst_dir, playlist_name) assert os.path.exists(playlist_path) is False # noinspection PyShadowingNames def test_command_line_start(playlist_current, tmpdir_factory, music_files): dst_dir = str(tmpdir_factory.mktemp('dump-music')) runner = CliRunner() result = runner.invoke(cli.main, [str(playlist_current), dst_dir, '--fix-search-path', str(music_files)]) for line in result.output.split('\n'): print(line) assert 'Welcome m3u-dump' in result.output assert 'copy was completed(successful' in result.output assert result.exit_code == 0 # must arguments # copy できているか確認する assert os.path.exists(os.path.join(dst_dir, 'dummy001.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'dummy002.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'あいう えお.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'あいう えお.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'hello.mp3')) is False playlist_name = os.path.basename(str(playlist_current)) playlist_path = os.path.join(dst_dir, playlist_name) assert os.path.exists(playlist_path) is True with open(playlist_path, 'r') as f: assert '#EXTM3U' == f.readline().rstrip('\n') assert '#EXTINF:409,artist - music_name' == f.readline().rstrip('\n') assert 'dummy001.mp3' == f.readline().rstrip('\n') assert '#EXTINF:281,artist - music_name' == f.readline().rstrip('\n') assert 'dummy002.mp3' == f.readline().rstrip('\n') assert '#EXTINF:275,artist - music_name' == f.readline().rstrip('\n') assert 'あいう えお.mp3' == f.readline().rstrip('\n') assert '#EXTINF:263,artist - music_name' == f.readline().rstrip('\n') assert 'あいう えお.mp3' == f.readline().rstrip('\n') assert '#EXTINF:288,artist - music_name' == f.readline().rstrip('\n') assert 'dummy002.mp3' == f.readline().rstrip('\n') assert '' == f.readline().rstrip('\n') # noinspection PyShadowingNames def test_command_line_no_fix_start(playlist_current, tmpdir_factory, music_files): dst_dir = str(tmpdir_factory.mktemp('dump-music')) runner = CliRunner() result = runner.invoke(cli.main, [str(playlist_current), dst_dir]) for line in result.output.split('\n'): print(line) assert 'Welcome m3u-dump' in result.output assert 'copy was completed(successful' in result.output assert result.exit_code == 0 # must arguments # noinspection PyShadowingNames def test_command_line_already_playlist(already_exists_playlist): music_path = os.path.join(str(already_exists_playlist), 'music') dst_dir = os.path.join(str(already_exists_playlist), 'dst') os.mkdir(dst_dir) playlist_path = os.path.join(str(already_exists_playlist), 'playlist.m3u') runner = CliRunner() result = runner.invoke(cli.main, [playlist_path, dst_dir, '--fix-search-path', str(music_path)]) for line in result.output.split('\n'): print(line) assert 'Welcome m3u-dump' in result.output assert 'copy was completed(successful' in result.output assert result.exit_code == 0 # must arguments # copy できているか確認する assert os.path.exists(os.path.join(dst_dir, 'already_path.mp3')) is True playlist_path = os.path.join(dst_dir, 'playlist.m3u') assert os.path.exists(playlist_path) is True with open(playlist_path, 'r') as f: assert '#EXTM3U' == f.readline().rstrip('\n') assert '#EXTINF:409,artist - music_name' == f.readline().rstrip('\n') assert 'already_path.mp3' == f.readline().rstrip('\n') # noinspection PyShadowingNames def test_command_line_multi_playlist(playlist_current, playlist_current2, tmpdir_factory, music_files, multi_playlist_music_files): playlist_dir = os.path.dirname(str(playlist_current)) dst_dir = str(tmpdir_factory.mktemp('dump-music')) runner = CliRunner() result = runner.invoke(cli.main, [playlist_dir, dst_dir, '--fix-search-path', str(music_files)]) for line in result.output.split('\n'): print(line) assert 'Welcome m3u-dump' in result.output assert 'copy was completed(successful' in result.output assert result.exit_code == 0 # must arguments # copy できているか確認する assert os.path.exists(os.path.join(dst_dir, 'dummy001.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'dummy002.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'あいう えお.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'あいう えお.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'hello.mp3')) is False assert os.path.exists(os.path.join(dst_dir, 'multi-dummy001.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'multi-dummy002.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'multi-あいう えお.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'multi-あいう えお.mp3')) is True assert os.path.exists(os.path.join(dst_dir, 'multi-dummy004.mp3')) is True playlist_name = os.path.basename(str(playlist_current)) playlist_path = os.path.join(dst_dir, playlist_name) assert os.path.exists(playlist_path) is True with open(playlist_path, 'r') as f: assert '#EXTM3U' == f.readline().rstrip('\n') assert '#EXTINF:409,artist - music_name' == f.readline().rstrip( '\n') assert 'dummy001.mp3' == f.readline().rstrip('\n') assert '#EXTINF:281,artist - music_name' == f.readline().rstrip( '\n') assert 'dummy002.mp3' == f.readline().rstrip('\n') assert '#EXTINF:275,artist - music_name' == f.readline().rstrip( '\n') assert 'あいう えお.mp3' == f.readline().rstrip('\n') assert '#EXTINF:263,artist - music_name' == f.readline().rstrip( '\n') assert 'あいう えお.mp3' == f.readline().rstrip('\n') assert '#EXTINF:288,artist - music_name' == f.readline().rstrip( '\n') assert 'dummy002.mp3' == f.readline().rstrip('\n') assert '' == f.readline().rstrip('\n') playlist_name = os.path.basename(str(playlist_current2)) playlist_path = os.path.join(dst_dir, playlist_name) assert os.path.exists(playlist_path) is True with open(playlist_path, 'r') as f: assert '#EXTM3U' == f.readline().rstrip('\n') assert '#EXTINF:409,artist - music_name' == f.readline().rstrip( '\n') assert 'multi-dummy001.mp3' == f.readline().rstrip('\n') assert '#EXTINF:282,artist - music_name' == f.readline().rstrip( '\n') assert 'multi-dummy001.mp3' == f.readline().rstrip('\n') assert '#EXTINF:281,artist - music_name' == f.readline().rstrip( '\n') assert 'multi-dummy002.mp3' == f.readline().rstrip('\n') assert '#EXTINF:275,artist - music_name' == f.readline().rstrip( '\n') assert 'multi-あいう えお.mp3' == f.readline().rstrip('\n') assert '#EXTINF:263,artist - music_name' == f.readline().rstrip( '\n') assert 'multi-あいう えお.mp3' == f.readline().rstrip('\n') assert '#EXTINF:288,artist - music_name' == f.readline().rstrip( '\n') assert 'multi-dummy004.mp3' == f.readline().rstrip('\n') assert '' == f.readline().rstrip('\n') # noinspection PyShadowingNames def test_parse_playlist(playlist_current): playlist_path = str(playlist_current) files = list(M3uDump.parse_playlist(playlist_path)) assert files[2] == '/full/path/dummy001.mp3' assert files[4] == '/full/path/dummy002.mp3' assert files[6] == 'music/あいう えお.mp3' assert files[8] == '/full/path/music/あいう えお.mp3' assert len(files) == 13 # noinspection PyShadowingNames def test_get_search_path_files(music_files): search_path_files = M3uDump.get_search_path_files(str(music_files)) assert 'tmp/music0' in search_path_files['dummy001.mp3'][0] assert 'tmp/music0/sub' in search_path_files['dummy002.mp3'][0] assert 'tmp/music0/sub2/sub3' in search_path_files['あいう えお.mp3'][0] assert 'tmp/music0/sub3/かきく けこ' in search_path_files['あいう えお.mp3'][0] assert len(search_path_files.keys()) == 11 # noinspection PyShadowingNames def test_fix_playlist(playlist_current, music_files): playlist_path = str(playlist_current) files = list(M3uDump.parse_playlist(playlist_path)) search_path_files = M3uDump.get_search_path_files(str(music_files)) p = M3uDump.fix_playlist(search_path_files, files) assert 'tmp/music0/dummy001.mp3' in p[2] assert 'tmp/music0/sub/dummy002.mp3' in p[4] assert 'tmp/music0/sub2/sub3/あいう えお.mp3' in p[6] assert 'tmp/music0/sub3/かきく けこ/あいう えお.mp3' in p[8] assert len(p) == 11 # noinspection PyShadowingNames def test_copy_music_dryrun(playlist_current, music_files, dump_music_path): playlist_path = str(playlist_current) files = list(M3uDump.parse_playlist(playlist_path)) search_path_files = M3uDump.get_search_path_files(str(music_files)) playlist = M3uDump.fix_playlist(search_path_files, files) M3uDump.copy_music(playlist, dump_music_path, True) assert os.path.exists( os.path.join(dump_music_path, 'dummy001.mp3')) is False assert os.path.exists( os.path.join(dump_music_path, 'dummy002.mp3')) is False assert os.path.exists(os.path.join(dump_music_path, 'あいう えお.mp3')) is False assert os.path.exists(os.path.join(dump_music_path, 'あいう えお.mp3')) is False # noinspection PyShadowingNames def test_copy_music_nodryrun(playlist_current, music_files, dump_music_path): playlist_path = str(playlist_current) files = list(M3uDump.parse_playlist(playlist_path)) search_path_files = M3uDump.get_search_path_files(str(music_files)) playlist = M3uDump.fix_playlist(search_path_files, files) M3uDump.copy_music(playlist, dump_music_path, False) assert os.path.exists(os.path.join(dump_music_path, 'dummy001.mp3')) assert os.path.exists(os.path.join(dump_music_path, 'dummy002.mp3')) assert os.path.exists(os.path.join(dump_music_path, 'あいう えお.mp3')) assert os.path.exists(os.path.join(dump_music_path, 'あいう えお.mp3')) # noinspection PyShadowingNames def test_copy_music_override(playlist_current, music_files, dump_music_path): playlist_path = str(playlist_current) files = list(M3uDump.parse_playlist(playlist_path)) search_path_files = M3uDump.get_search_path_files(str(music_files)) playlist = M3uDump.fix_playlist(search_path_files, files) M3uDump.copy_music(playlist, dump_music_path, False) M3uDump.copy_music(playlist, dump_music_path, False) assert os.path.exists(os.path.join(dump_music_path, 'dummy001.mp3')) assert os.path.exists(os.path.join(dump_music_path, 'dummy002.mp3')) assert os.path.exists(os.path.join(dump_music_path, 'あいう えお.mp3')) assert os.path.exists(os.path.join(dump_music_path, 'あいう えお.mp3')) # noinspection PyShadowingNames def test_load_from_playlist_path(playlist_dir, playlist_current2, playlist_current): playlist_path = str(playlist_dir) allowed_pattern = ['*.m3u', '*.m3u8'] path_list = M3uDump.load_from_playlist_path(playlist_path, allowed_pattern) # os.walk は順序が分からない assert 'playlist.m3u' in path_list[0] assert 'playlist2.m3u8' in path_list[1] assert len(path_list) == 2
39.830424
94
0.681818
367df2859be2cff2cce8776d883c9973d630e1f9
620
sql
SQL
app/db/v2.sql
wieloming/GPI
0a8d331cbc941fe06a109ff40edfe181f261ed57
[ "MIT" ]
null
null
null
app/db/v2.sql
wieloming/GPI
0a8d331cbc941fe06a109ff40edfe181f261ed57
[ "MIT" ]
null
null
null
app/db/v2.sql
wieloming/GPI
0a8d331cbc941fe06a109ff40edfe181f261ed57
[ "MIT" ]
null
null
null
DELETE FROM `db_version` WHERE 1 = 1; INSERT INTO `db_version` (`version`) VALUES (2); ALTER TABLE auction ADD max_realization_date DATETIME DEFAULT NULL; ALTER TABLE auction_audit ADD max_realization_date DATETIME DEFAULT NULL; CREATE TABLE auction_comments (id INT AUTO_INCREMENT NOT NULL, auction_id INT DEFAULT NULL, content LONGTEXT NOT NULL, created DATETIME NOT NULL, INDEX IDX_EA1648C457B8F0DE (auction_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB; ALTER TABLE auction_comments ADD CONSTRAINT FK_EA1648C457B8F0DE FOREIGN KEY (auction_id) REFERENCES auction (id);
56.363636
271
0.817742
7a5469d5d5347bbe5128c1116a9dfdcfd7a3907b
397
rb
Ruby
db/migrate/20190328021335_create_products.rb
AfonsoNeto/simple_3-step_quotation
770f473bfedc8d72ba91463c8a5d21e44927aad0
[ "MIT" ]
null
null
null
db/migrate/20190328021335_create_products.rb
AfonsoNeto/simple_3-step_quotation
770f473bfedc8d72ba91463c8a5d21e44927aad0
[ "MIT" ]
null
null
null
db/migrate/20190328021335_create_products.rb
AfonsoNeto/simple_3-step_quotation
770f473bfedc8d72ba91463c8a5d21e44927aad0
[ "MIT" ]
null
null
null
class CreateProducts < ActiveRecord::Migration[5.2] def change create_table :products do |t| t.date :start_date t.date :end_date t.decimal :price_per_day t.integer :day_of_week t.integer :weeks_number t.integer :starting_hour t.integer :ending_hour t.decimal :good_unity_price t.string :type t.timestamps end end end
22.055556
51
0.647355
36c0c38b1be4dde8009a4dc3861743166620716b
457
kt
Kotlin
app/src/main/java/com/vycius/tasty/model/Recipe.kt
vycius/udacity-baking-app-tasty
f00503f587ce3d91c622d71a84f2fa56f7f0235e
[ "MIT" ]
38
2017-06-29T10:27:33.000Z
2022-03-27T18:56:06.000Z
app/src/main/java/com/vycius/tasty/model/Recipe.kt
sugiartocokrowibowo/udacity-baking-app-tasty
f00503f587ce3d91c622d71a84f2fa56f7f0235e
[ "MIT" ]
2
2017-06-23T12:45:10.000Z
2018-03-14T02:36:13.000Z
app/src/main/java/com/vycius/tasty/model/Recipe.kt
sugiartocokrowibowo/udacity-baking-app-tasty
f00503f587ce3d91c622d71a84f2fa56f7f0235e
[ "MIT" ]
16
2017-09-21T05:45:51.000Z
2020-12-01T13:11:25.000Z
package com.vycius.tasty.model import paperparcel.PaperParcel import paperparcel.PaperParcelable @PaperParcel data class Recipe(val id: Int, val name: String, val ingredients: List<Ingredient>, val steps: List<Step>, val servings: Int, val image: String) : PaperParcelable { companion object { @JvmField val CREATOR = PaperParcelRecipe.CREATOR } }
25.388889
57
0.606127
3efb176d11e2e63968a262e3406000d7f98146bd
1,533
h
C
src/ll.h
NateZimmer/linked_list_c
4bdf21d3c518ff8d21e3a089e84621fdd423aa46
[ "MIT" ]
null
null
null
src/ll.h
NateZimmer/linked_list_c
4bdf21d3c518ff8d21e3a089e84621fdd423aa46
[ "MIT" ]
null
null
null
src/ll.h
NateZimmer/linked_list_c
4bdf21d3c518ff8d21e3a089e84621fdd423aa46
[ "MIT" ]
null
null
null
#ifndef LL_H #define LL_H #include <stdint.h> typedef struct { uint16_t len; void * data; void * next; void * prev; }list_el_t; typedef struct { list_el_t * head; list_el_t * tail; uint16_t len; }list_t; /** @name list_push @brief add data to end of linked list @param [in] list - a pointer to a list @param [in] data - a pointer to a data @param [in] len - the length of the data */ void list_push(list_t * list, void * data, uint16_t len); /** @name list_pop @brief removes data from end of linked list @param [in] list - a pointer to a list @param [out] data - a pointer to the removed element's data @return a pointer to the popped out data */ void * list_pop(list_t * list, uint16_t * len); /** @name list_shift @brief removes data from start of linked list @param [in] list - a pointer to a list @param [out] len - a pointer, value is the length of the data @return pointer to shifted out data */ void * list_shift(list_t * list, uint16_t * len); /** @name list_shift_in @brief adds data to start of linked list @param [in] list - a pointer to a list @param [in] data - a pointer to a data @param [in] len - the length of the data */ void list_shift_in(list_t * list, void * data, uint16_t len); /** @name list_len @brief returns length of linked list @param [in] list - a pointer to a list @return length of linked list */ uint16_t list_len(list_t * list); #endif // LL_H
23.227273
65
0.639269
b603f8031e0c53b7e173dcd2a853805c9950b619
328
rb
Ruby
config/deploy/production.rb
puhsh/lystey
0afad9765714cf6a035aa166777a096b793177d5
[ "Apache-2.0" ]
null
null
null
config/deploy/production.rb
puhsh/lystey
0afad9765714cf6a035aa166777a096b793177d5
[ "Apache-2.0" ]
null
null
null
config/deploy/production.rb
puhsh/lystey
0afad9765714cf6a035aa166777a096b793177d5
[ "Apache-2.0" ]
null
null
null
server '52.5.240.228', user: 'realtors', roles: %w{app db}, my_property: :my_value set :application, 'lystey' set :deploy_to, "/var/www/www.lystey.com" set :stage, :production set :rails_env, 'production' set :unicorn_pid, -> { File.join(current_path, "tmp", "pids", "unicorn.lystey.pid") } set :unicorn_rack_env, 'production'
36.444444
85
0.710366
9752efd43240eb07f94a38061eba91691e7cbce8
1,367
kt
Kotlin
app/src/main/java/com/hiteshsahu/cool_keyboard/view/fragments/LicensesDialogFragment.kt
hiteshsahu/Android-Character-Emmision-keyBoard
876948c4524d172d76feae9d73b80fcbd26f7af8
[ "Apache-2.0" ]
1
2016-03-28T12:13:21.000Z
2016-03-28T12:13:21.000Z
app/src/main/java/com/hiteshsahu/cool_keyboard/view/fragments/LicensesDialogFragment.kt
hiteshsahu/Android-Character-Emmision-keyBoard
876948c4524d172d76feae9d73b80fcbd26f7af8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/hiteshsahu/cool_keyboard/view/fragments/LicensesDialogFragment.kt
hiteshsahu/Android-Character-Emmision-keyBoard
876948c4524d172d76feae9d73b80fcbd26f7af8
[ "Apache-2.0" ]
null
null
null
/* * . * Copyright Copyright (c) 2017 Hitesh Sahu(hiteshsahu.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.hiteshsahu.cool_keyboard.view.fragments import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.support.v4.app.DialogFragment import com.hiteshsahu.cool_keyboard.R class LicensesDialogFragment : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialogInflater = activity!!.layoutInflater val openSourceLicensesView = dialogInflater.inflate(R.layout.dialog_licenses, null) val dialogBuilder = AlertDialog.Builder(activity) dialogBuilder.setView(openSourceLicensesView) .setTitle("Open Source License") .setNeutralButton(android.R.string.ok, null) return dialogBuilder.create() } }
40.205882
308
0.75128
d5bc8ee4ad04c83726caa5eb1745907d05a41363
501
c
C
Test/111-unions-5/main.c
flix-/environment-variable-tracing
85a1ad880b47acad28f5b1a418f1ee2259f77fad
[ "MIT" ]
null
null
null
Test/111-unions-5/main.c
flix-/environment-variable-tracing
85a1ad880b47acad28f5b1a418f1ee2259f77fad
[ "MIT" ]
null
null
null
Test/111-unions-5/main.c
flix-/environment-variable-tracing
85a1ad880b47acad28f5b1a418f1ee2259f77fad
[ "MIT" ]
null
null
null
extern char *getenv(const char *name); extern int foo(); extern int bar(); union u3 { char *taint; char *tainted; }; union u2 { char *taint; double d; union u3 u; }; union u1 { union u2 u; char *taint; }; struct s1 { union u1 u; union u2 uu; char *taint; }; int main() { struct s1 s; s.taint = getenv("hi"); char *tainted = s.taint; char *not_tainted = s.u.u.u.tainted; s.u.taint = s.taint; tainted = s.u.taint; return 0; }
11.928571
40
0.550898
83b2745a1f10a48419d600c009f5da859a11c924
814
rs
Rust
api/src/leafs/array_comp.rs
rezer0dai/bananafzz
739713366ebd418d884e04f6b0ef1897c239dc49
[ "MIT" ]
39
2022-01-05T07:34:07.000Z
2022-03-31T02:43:54.000Z
api/src/leafs/array_comp.rs
rezer0dai/bananafzz
739713366ebd418d884e04f6b0ef1897c239dc49
[ "MIT" ]
null
null
null
api/src/leafs/array_comp.rs
rezer0dai/bananafzz
739713366ebd418d884e04f6b0ef1897c239dc49
[ "MIT" ]
3
2022-01-05T05:26:55.000Z
2022-03-26T15:26:25.000Z
extern crate core; use self::core::generator::composite::ArgComposite; use self::core::generator::leaf::IArgLeaf; pub trait ArrayComposite { fn array_leaf<F>(name: &'static str, ecount: usize, leafgen: F) -> ArgComposite where F: Fn() -> Box<dyn IArgLeaf>; } /// PERFOMANCE WARNING : discouraged to use ArrayArgs with more than 10 elemets - slow down fuzzing /// without some reasonable (?) gain .. impl ArrayComposite for ArgComposite { fn array_leaf<F>(name: &'static str, ecount: usize, leafgen: F) -> ArgComposite where F: Fn() -> Box<dyn IArgLeaf>, { let mut leafs = Vec::new(); let size = leafgen().size(); for i in 0..ecount { leafs.push((i * size, leafgen())) } ArgComposite::new(size * ecount, name, leafs) } }
31.307692
99
0.62285
714dfb74c272ac119bd3be38ee5ffab3d38f8e08
5,034
ts
TypeScript
test/sugiyama/coord/simplex.test.ts
travishaby/d3-dag
033fb198fce2f7db3f4b84a2185eaf73d985718f
[ "MIT" ]
null
null
null
test/sugiyama/coord/simplex.test.ts
travishaby/d3-dag
033fb198fce2f7db3f4b84a2185eaf73d985718f
[ "MIT" ]
null
null
null
test/sugiyama/coord/simplex.test.ts
travishaby/d3-dag
033fb198fce2f7db3f4b84a2185eaf73d985718f
[ "MIT" ]
null
null
null
import { flatMap } from "../../../src/iters"; import { createConstAccessor, simplex } from "../../../src/sugiyama/coord/simplex"; import { SugiNode } from "../../../src/sugiyama/utils"; import { createLayers, nodeSize } from "../utils"; test("simplex() modifiers work", () => { const layers = createLayers([[[0, 1]], [[0], 0], [[]]]); const weight = () => [2, 3, 4] as const; const layout = simplex().weight(weight); expect(layout.weight()).toBe(weight); layout(layers, nodeSize); for (const node of flatMap(layers, (l) => l)) { expect(node.x).toBeDefined(); } }); test("simplex() works for square like layout", () => { const layers = createLayers([[[0, 1]], [[0], [0]], [[]]]); const [[head], [left, right], [tail]] = layers; const layout = simplex(); const width = layout(layers, nodeSize); expect(width).toBeCloseTo(2); // NOTE head and tail could be at either 0.5 or 1.5 expect(head.x).toBeCloseTo(1.5); expect(left.x).toBeCloseTo(0.5); expect(right.x).toBeCloseTo(1.5); expect(tail.x).toBeCloseTo(1.5); }); test("simplex() works for triangle", () => { const layers = createLayers([[[0, 1]], [0, [0]], [[]]]); const [[one], [dummy, two], [three]] = layers; const layout = simplex(); const dummyNodeSize = (node: SugiNode): number => "node" in node.data ? 1 : 0; const width = layout(layers, dummyNodeSize); // NOTE with dummy node first, we guarantee that that's the straight line expect(width).toBeCloseTo(1.5); expect(one.x).toBeCloseTo(0.5); expect(dummy.x).toBeCloseTo(0.5); expect(three.x).toBeCloseTo(0.5); expect(two.x).toBeCloseTo(1.0); }); test("simplex() works for dee", () => { const layers = createLayers([[[0, 1]], [0, [1]], [0, [0]], [[]]]); const [[one], [d1, two], [d2, three], [four]] = layers; const layout = simplex(); layout(layers, nodeSize); // NOTE with dummy node first, we guarantee that that's the straight line expect(one.x).toBeCloseTo(0.5); expect(d1.x).toBeCloseTo(0.5); expect(d2.x).toBeCloseTo(0.5); expect(four.x).toBeCloseTo(0.5); expect(two.x).toBeCloseTo(1.5); expect(three.x).toBeCloseTo(1.5); }); test("simplex() works for dee with custom weights", () => { const layers = createLayers([[[0, 1]], [0, [1]], [0, [0]], [[]]]); const [[one], [d1, two], [d2, three], [four]] = layers; const layout = simplex().weight(() => [2, 3, 4]); layout(layers, nodeSize); // NOTE with dummy node first, we guarantee that that's the straight line expect(one.x).toBeCloseTo(0.5); expect(d1.x).toBeCloseTo(0.5); expect(d2.x).toBeCloseTo(0.5); expect(four.x).toBeCloseTo(0.5); expect(two.x).toBeCloseTo(1.5); expect(three.x).toBeCloseTo(1.5); }); test("simplex() works with flat disconnected component", () => { const layers = createLayers([[[], []], [[0]], [[]]]); const [[left, right], [high], [low]] = layers; const layout = simplex(); layout(layers, nodeSize); expect(left.x).toBeCloseTo(0.5); expect(right.x).toBeCloseTo(1.5); expect(high.x).toBeCloseTo(1.0); expect(low.x).toBeCloseTo(1.0); }); test("simplex() works with complex disconnected component", () => { const layers = createLayers([[[0], [], [0]], [[], [0]], [[]]]); const [[left, middle, right], [vee, above], [below]] = layers; const layout = simplex(); layout(layers, nodeSize); expect(left.x).toBeCloseTo(0.5); expect(middle.x).toBeCloseTo(1.5); expect(right.x).toBeCloseTo(2.5); expect(vee.x).toBeCloseTo(2.5); expect(above.x).toBeCloseTo(3.5); expect(below.x).toBeCloseTo(3.5); }); test("simplex() fails with non-positive const weight", () => { const weights = [0, 1, 2] as const; function weight(): readonly [number, number, number] { return weights; } // make a const accessor, but don't go through checks of "create" weight.value = weights; const layers = createLayers([[[0, 1]], [[0], 0], [[]]]); const layout = simplex().weight(weight); expect(() => layout(layers, nodeSize)).toThrow( "simplex weights must be positive, but got" ); }); test("simplex() fails with non-positive weight", () => { const layers = createLayers([[[0, 1]], [[0], 0], [[]]]); const layout = simplex().weight(() => [0, 1, 2]); expect(() => layout(layers, nodeSize)).toThrow( "simplex weights must be positive, but got" ); }); test("simplex() fails passing an arg to constructor", () => { expect(() => simplex(null as never)).toThrow("got arguments to simplex"); }); test("simplex() throws for zero width", () => { const layers = createLayers([[[]]]); const layout = simplex(); expect(() => layout(layers, () => 0)).toThrow( "must assign nonzero width to at least one node" ); }); test("createConstAccessor() works", () => { const acc = createConstAccessor([1, 2, 3]); expect(acc.value).toEqual([1, 2, 3]); expect(acc()).toEqual([1, 2, 3]); }); test("createConstAccessor() throws for non-positive value", () => { expect(() => createConstAccessor([0, 1, 2])).toThrow( "const accessors should return non-negative values" ); });
32.477419
75
0.618792
cf49b3c97873f3d703696c3637da08d333f15d36
1,780
kt
Kotlin
src/main/java/net/dankrushen/aitagsearch/extensions/FloatVectorExtensions.kt
Dankrushen/ai-tag-search
2cbb0ef4445bc3ed474137e9b7b804108010939b
[ "MIT" ]
null
null
null
src/main/java/net/dankrushen/aitagsearch/extensions/FloatVectorExtensions.kt
Dankrushen/ai-tag-search
2cbb0ef4445bc3ed474137e9b7b804108010939b
[ "MIT" ]
null
null
null
src/main/java/net/dankrushen/aitagsearch/extensions/FloatVectorExtensions.kt
Dankrushen/ai-tag-search
2cbb0ef4445bc3ed474137e9b7b804108010939b
[ "MIT" ]
null
null
null
package net.dankrushen.aitagsearch.extensions import net.dankrushen.aitagsearch.conversion.FloatVectorConverter import net.dankrushen.aitagsearch.datatypes.FloatVector import org.agrona.DirectBuffer import org.agrona.MutableDirectBuffer fun MutableDirectBuffer.putFloatVectorWithoutLength(index: Int, value: FloatVector): Int { return FloatVectorConverter.converter.writeWithoutLength(this, index, value) } fun MutableDirectBuffer.putFloatVector(index: Int, value: FloatVector): Int { return FloatVectorConverter.converter.write(this, index, value) } fun DirectBuffer.getFloatVectorWithoutLengthCount(index: Int, length: Int): Pair<FloatVector, Int> { return FloatVectorConverter.converter.readWithoutLengthCount(this, index, length) } fun DirectBuffer.getFloatVectorWithoutLength(index: Int, length: Int): FloatVector { return FloatVectorConverter.converter.readWithoutLength(this, index, length) } fun DirectBuffer.getFloatVectorCount(index: Int): Pair<FloatVector, Int> { return FloatVectorConverter.converter.readCount(this, index) } fun DirectBuffer.getFloatVector(index: Int): FloatVector { return FloatVectorConverter.converter.read(this, index) } fun Iterable<FloatVector>.sum(): FloatVector? { var sumVector: FloatVector? = null for (vector in this) { if (sumVector == null) sumVector = vector sumVector = sumVector + vector } return sumVector } fun Iterable<FloatVector>.average(): FloatVector? { var count = 0 var sumVector: FloatVector? = null for (vector in this) { sumVector = if (sumVector == null) vector else sumVector + vector count++ } if (sumVector == null) return null return sumVector / count }
28.709677
100
0.735393
3083ddc6a83606560afb4c0e1174bfdb61569374
1,670
html
HTML
src/main/resources/templates/github.html
fasar/script-api-jug
ba8e0ed10c00149c01de285567034a1847b41ec4
[ "Apache-2.0" ]
null
null
null
src/main/resources/templates/github.html
fasar/script-api-jug
ba8e0ed10c00149c01de285567034a1847b41ec4
[ "Apache-2.0" ]
null
null
null
src/main/resources/templates/github.html
fasar/script-api-jug
ba8e0ed10c00149c01de285567034a1847b41ec4
[ "Apache-2.0" ]
null
null
null
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel='stylesheet' href='/assets/bootstrap/4.3.1/css/bootstrap.css'> <script src="/assets/jquery/3.4.1/jquery.slim.min.js"></script> <script src="/assets/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <title>Hello, world!</title> </head> <body> <nav th:replace="headers :: navbar"></nav> <div class="container-fluid" role="main"> <h1>Github</h1> <p>Github User</p> <ul> <li>Login : <span class="message" th:text="${guser.login}">Login</span></li> <li>Id : <span class="message" th:text="${guser.id}">id</span></li> <li>Avatar Url : <span class="message" th:text="${guser.avatarUrl}">id</span></li> </ul> <p>Github Pages</p> <table class="table"> <caption>Last build for the Site</caption> <thead> <tr> <th scope="col">Time</th> <th scope="col">Pusher</th> <th scope="col">Status</th> <th scope="col">Error</th> </tr> </thead> <tbody> <tr th:each="page : ${gpages}" scope="row"> <th th:text="${page.createdAt}">Time</th> <th th:text="${page.pusher.login}">Pusher</th> <th th:text="${page.status}">Status</th> <th th:text="${page.error.message}">Error</th> </tr> </tbody> </table> </div> <footer th:replace="headers :: footer"> <p>Copyright &copy; JUG Geneva</p> </footer> </body> </html>
26.507937
90
0.553892
c1bcbad2cb852c4f2a464bea5a78d4c9fcad4f04
12,205
rs
Rust
src/execute.rs
akalmykov/dcw721-contract
0f7775a2bce4eef66555d609a2572c64bcafd7da
[ "Apache-2.0" ]
8
2021-12-14T02:19:19.000Z
2022-03-07T20:50:06.000Z
src/execute.rs
crabust/dNFT-contracts
0f7775a2bce4eef66555d609a2572c64bcafd7da
[ "Apache-2.0" ]
null
null
null
src/execute.rs
crabust/dNFT-contracts
0f7775a2bce4eef66555d609a2572c64bcafd7da
[ "Apache-2.0" ]
1
2021-11-13T09:59:30.000Z
2021-11-13T09:59:30.000Z
use serde::de::DeserializeOwned; use serde::Serialize; use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult}; use cw2::set_contract_version; use cw721::{ContractInfoResponse, CustomMsg, Cw721Execute, Cw721ReceiveMsg, Expiration}; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, MintMsg, MetaAccess}; use crate::state::{Approval, Cw721Contract, TokenInfo}; // version info for migration info const CONTRACT_NAME: &str = "crates.io:cw721-base"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); impl<'a, T, C> Cw721Contract<'a, T, C> where T: Serialize + DeserializeOwned + Clone + MetaAccess, C: CustomMsg, { pub fn instantiate( &self, deps: DepsMut, _env: Env, _info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response<C>> { set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; let info = ContractInfoResponse { name: msg.name, symbol: msg.symbol, }; self.contract_info.save(deps.storage, &info)?; let minter = deps.api.addr_validate(&msg.minter)?; self.minter.save(deps.storage, &minter)?; Ok(Response::default()) } pub fn execute( &self, deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg<T>, ) -> Result<Response<C>, ContractError> { match msg { ExecuteMsg::Mint(msg) => self.mint(deps, env, info, msg), ExecuteMsg::Approve { spender, token_id, expires, } => self.approve(deps, env, info, spender, token_id, expires), ExecuteMsg::Revoke { spender, token_id } => { self.revoke(deps, env, info, spender, token_id) } ExecuteMsg::ApproveAll { operator, expires } => { self.approve_all(deps, env, info, operator, expires) } ExecuteMsg::RevokeAll { operator } => self.revoke_all(deps, env, info, operator), ExecuteMsg::TransferNft { recipient, token_id, } => self.transfer_nft(deps, env, info, recipient, token_id), ExecuteMsg::SendNft { contract, token_id, msg, } => self.send_nft(deps, env, info, contract, token_id, msg), } } } // TODO pull this into some sort of trait extension?? impl<'a, T, C> Cw721Contract<'a, T, C> where T: Serialize + DeserializeOwned + Clone + MetaAccess, C: CustomMsg, { pub fn mint( &self, deps: DepsMut, _env: Env, info: MessageInfo, msg: MintMsg<T>, ) -> Result<Response<C>, ContractError> { let minter = self.minter.load(deps.storage)?; let is_derivative = msg.extension.is_derivative(); if info.sender != minter { if !is_derivative { return Err(ContractError::Unauthorized {}); } else { let meta = msg.extension.get_metadata(); if meta.derivative.is_some() { for token_id in meta.derivative.as_ref().unwrap().source_ids.iter() { let token_info = self.tokens.load(deps.storage, &token_id)?; if token_info.owner != info.sender { return Err(ContractError::Unauthorized {}); } } } else { return Err(ContractError::Unauthorized {}); } } }; // create the token let token = TokenInfo { owner: deps.api.addr_validate(&msg.owner)?, approvals: vec![], token_uri: msg.token_uri, extension: msg.extension, }; self.tokens .update(deps.storage, &msg.token_id, |old| match old { Some(_) => Err(ContractError::Claimed {}), None => Ok(token), })?; self.increment_tokens(deps.storage)?; Ok(Response::new() .add_attribute("action", "mint") .add_attribute("minter", info.sender) .add_attribute("token_id", msg.token_id)) } } impl<'a, T, C> Cw721Execute<T, C> for Cw721Contract<'a, T, C> where T: Serialize + DeserializeOwned + Clone, C: CustomMsg, { type Err = ContractError; fn transfer_nft( &self, deps: DepsMut, env: Env, info: MessageInfo, recipient: String, token_id: String, ) -> Result<Response<C>, ContractError> { self._transfer_nft(deps, &env, &info, &recipient, &token_id)?; Ok(Response::new() .add_attribute("action", "transfer_nft") .add_attribute("sender", info.sender) .add_attribute("recipient", recipient) .add_attribute("token_id", token_id)) } fn send_nft( &self, deps: DepsMut, env: Env, info: MessageInfo, contract: String, token_id: String, msg: Binary, ) -> Result<Response<C>, ContractError> { // Transfer token self._transfer_nft(deps, &env, &info, &contract, &token_id)?; let send = Cw721ReceiveMsg { sender: info.sender.to_string(), token_id: token_id.clone(), msg, }; // Send message Ok(Response::new() .add_message(send.into_cosmos_msg(contract.clone())?) .add_attribute("action", "send_nft") .add_attribute("sender", info.sender) .add_attribute("recipient", contract) .add_attribute("token_id", token_id)) } fn approve( &self, deps: DepsMut, env: Env, info: MessageInfo, spender: String, token_id: String, expires: Option<Expiration>, ) -> Result<Response<C>, ContractError> { self._update_approvals(deps, &env, &info, &spender, &token_id, true, expires)?; Ok(Response::new() .add_attribute("action", "approve") .add_attribute("sender", info.sender) .add_attribute("spender", spender) .add_attribute("token_id", token_id)) } fn revoke( &self, deps: DepsMut, env: Env, info: MessageInfo, spender: String, token_id: String, ) -> Result<Response<C>, ContractError> { self._update_approvals(deps, &env, &info, &spender, &token_id, false, None)?; Ok(Response::new() .add_attribute("action", "revoke") .add_attribute("sender", info.sender) .add_attribute("spender", spender) .add_attribute("token_id", token_id)) } fn approve_all( &self, deps: DepsMut, env: Env, info: MessageInfo, operator: String, expires: Option<Expiration>, ) -> Result<Response<C>, ContractError> { // reject expired data as invalid let expires = expires.unwrap_or_default(); if expires.is_expired(&env.block) { return Err(ContractError::Expired {}); } // set the operator for us let operator_addr = deps.api.addr_validate(&operator)?; self.operators .save(deps.storage, (&info.sender, &operator_addr), &expires)?; Ok(Response::new() .add_attribute("action", "approve_all") .add_attribute("sender", info.sender) .add_attribute("operator", operator)) } fn revoke_all( &self, deps: DepsMut, _env: Env, info: MessageInfo, operator: String, ) -> Result<Response<C>, ContractError> { let operator_addr = deps.api.addr_validate(&operator)?; self.operators .remove(deps.storage, (&info.sender, &operator_addr)); Ok(Response::new() .add_attribute("action", "revoke_all") .add_attribute("sender", info.sender) .add_attribute("operator", operator)) } } // helpers impl<'a, T, C> Cw721Contract<'a, T, C> where T: Serialize + DeserializeOwned + Clone, C: CustomMsg, { pub fn _transfer_nft( &self, deps: DepsMut, env: &Env, info: &MessageInfo, recipient: &str, token_id: &str, ) -> Result<TokenInfo<T>, ContractError> { let mut token = self.tokens.load(deps.storage, &token_id)?; // ensure we have permissions self.check_can_send(deps.as_ref(), env, info, &token)?; // set owner and remove existing approvals token.owner = deps.api.addr_validate(recipient)?; token.approvals = vec![]; self.tokens.save(deps.storage, &token_id, &token)?; Ok(token) } #[allow(clippy::too_many_arguments)] pub fn _update_approvals( &self, deps: DepsMut, env: &Env, info: &MessageInfo, spender: &str, token_id: &str, // if add == false, remove. if add == true, remove then set with this expiration add: bool, expires: Option<Expiration>, ) -> Result<TokenInfo<T>, ContractError> { let mut token = self.tokens.load(deps.storage, &token_id)?; // ensure we have permissions self.check_can_approve(deps.as_ref(), env, info, &token)?; // update the approval list (remove any for the same spender before adding) let spender_addr = deps.api.addr_validate(spender)?; token.approvals = token .approvals .into_iter() .filter(|apr| apr.spender != spender_addr) .collect(); // only difference between approve and revoke if add { // reject expired data as invalid let expires = expires.unwrap_or_default(); if expires.is_expired(&env.block) { return Err(ContractError::Expired {}); } let approval = Approval { spender: spender_addr, expires, }; token.approvals.push(approval); } self.tokens.save(deps.storage, &token_id, &token)?; Ok(token) } /// returns true iff the sender can execute approve or reject on the contract pub fn check_can_approve( &self, deps: Deps, env: &Env, info: &MessageInfo, token: &TokenInfo<T>, ) -> Result<(), ContractError> { // owner can approve if token.owner == info.sender { return Ok(()); } // operator can approve let op = self .operators .may_load(deps.storage, (&token.owner, &info.sender))?; match op { Some(ex) => { if ex.is_expired(&env.block) { Err(ContractError::Unauthorized {}) } else { Ok(()) } } None => Err(ContractError::Unauthorized {}), } } /// returns true iff the sender can transfer ownership of the token pub fn check_can_send( &self, deps: Deps, env: &Env, info: &MessageInfo, token: &TokenInfo<T>, ) -> Result<(), ContractError> { // owner can send if token.owner == info.sender { return Ok(()); } // any non-expired token approval can send if token .approvals .iter() .any(|apr| apr.spender == info.sender && !apr.is_expired(&env.block)) { return Ok(()); } // operator can send let op = self .operators .may_load(deps.storage, (&token.owner, &info.sender))?; match op { Some(ex) => { if ex.is_expired(&env.block) { Err(ContractError::Unauthorized {}) } else { Ok(()) } } None => Err(ContractError::Unauthorized {}), } } }
30.898734
93
0.535272
f81373181c39290cc0d4a707747b7f68b73f0643
561
asm
Assembly
oeis/310/A310367.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/310/A310367.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/310/A310367.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A310367: Coordination sequence Gal.6.129.6 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,4,10,14,18,22,26,30,34,38,44,48,52,58,62,66,70,74,78,82,86,92,96,100,106,110,114,118,122,126,130,134,140,144,148,154,158,162,166,170,174,178,182,188,192,196,202,206,210,214 mov $4,$0 trn $0,1 mov $1,$0 mov $2,$0 lpb $2 mov $3,2 lpb $1 mov $1,0 sub $2,3 sub $2,$3 mov $3,0 lpe add $0,2 add $1,$3 trn $2,3 lpe lpb $4 add $0,3 sub $4,1 lpe add $0,1
22.44
177
0.643494
1938f0a6fc1864229e6b44f1e55384638268ae64
4,432
sql
SQL
notebooks/aline/aline_cohort_simple.sql
jay-jojo-cheng/mimic-code
3b46724891226b0c24d70ae8c5914af13decb1d4
[ "MIT" ]
null
null
null
notebooks/aline/aline_cohort_simple.sql
jay-jojo-cheng/mimic-code
3b46724891226b0c24d70ae8c5914af13decb1d4
[ "MIT" ]
null
null
null
notebooks/aline/aline_cohort_simple.sql
jay-jojo-cheng/mimic-code
3b46724891226b0c24d70ae8c5914af13decb1d4
[ "MIT" ]
null
null
null
-- This query defines the cohort used for the ALINE study. -- This query is a simpler version of aline_cohort.sql, and does not generate a view. -- Many of the variables from the aline study are trimmed to simplify the query. -- See aline_cohort.sql for the actual cohort table generation. -- Tables required: -- ventdurations, angus_sepsis, aline_vaso_flag -- Exclusion criteria: -- non-adult patients -- Secondary ICU admission -- In ICU for less than 24 hours -- not mechanical ventilation within the first 24 hours -- non medical or non surgical ICU admission -- **Angus sepsis -- IAC placed before admission -- get start time of arterial line -- Definition of arterial line insertion: -- First measurement of invasive blood pressure with a as ( select icustay_id , min(charttime) as starttime_aline from chartevents where icustay_id is not null and valuenum is not null and itemid in ( 51, -- Arterial BP [Systolic] 6701, -- Arterial BP #2 [Systolic] 220050, -- Arterial Blood Pressure systolic 8368, -- Arterial BP [Diastolic] 8555, -- Arterial BP #2 [Diastolic] 220051, -- Arterial Blood Pressure diastolic 52, --"Arterial BP Mean" 6702, -- Arterial BP Mean #2 220052, --"Arterial Blood Pressure mean" 225312 --"ART BP mean" ) group by icustay_id ) -- first time ventilation was started -- last time ventilation was stopped , ve as ( select icustay_id , min(starttime) as vent_starttime , max(endtime) as vent_endtime from ventilation_durations vd group by icustay_id ) -- first service , serv as ( select icu.icustay_id, se.curr_service , ROW_NUMBER() over ( PARTITION BY icu.icustay_id ORDER BY se.transfertime DESC ) as rn from icustays icu inner join services se on icu.hadm_id = se.hadm_id and se.transfertime < icu.intime + interval '2' hour ) -- cohort view - used to define/aggregate concepts for exclusion , co as ( select icu.subject_id, icu.hadm_id, icu.icustay_id , icu.intime, icu.outtime , ROW_NUMBER() over ( PARTITION BY icu.subject_id ORDER BY icu.intime ) as stay_num , extract(epoch from (icu.intime - pat.dob))/365.242/24.0/60.0/60.0 as age , extract(epoch from (icu.outtime - icu.intime))/24.0/60.0/60.0 as icu_length_of_stay -- from pre-generated tables , vf.vaso_flag , sep.angus -- service -- will be used to exclude patients in CSRU -- also only include those in CMED or SURG , s.curr_service as service_unit -- time of a-line , a.starttime_aline -- time of ventilation , ve.vent_starttime , ve.vent_endtime from icustays icu inner join admissions adm on icu.hadm_id = adm.hadm_id inner join patients pat on icu.subject_id = pat.subject_id left join a on icu.icustay_id = a.icustay_id left join ve on icu.icustay_id = ve.icustay_id left join serv s on icu.icustay_id = s.icustay_id and s.rn = 1 left join angus sep on icu.hadm_id = sep.hadm_id left join aline_vaso_flag vf on icu.subject_id = vf.subject_id ) select co.subject_id, co.hadm_id, co.icustay_id , case when age < 16 then 1 else 0 end as exclusion_non_adult -- only adults , case when stay_num > 1 then 1 else 0 end as exclusion_secondary_stay -- first ICU stay , case when icu_length_of_stay < 1 then 1 else 0 end exclusion_short_stay -- one day in the ICU , case -- not ventilated when vent_starttime is null -- ventilated more than 24 hours after admission or vent_starttime > intime + interval '24' hour then 1 else 0 end exclusion_not_ventilated_first24hr , case when angus = 1 then 1 else 0 end as exclusion_septic , case when vaso_flag = 1 then 1 else 0 end as exclusion_vasopressors , case when starttime_aline is not null and starttime_aline <= intime then 1 else 0 end exclusion_aline_before_admission -- aline must be placed later than admission -- we need to approximate CCU and CSRU using hospital service -- paper only says CSRU but the code did both CCU/CSRU -- this is the best guess -- "medical or surgical ICU admission" , case when service_unit in ( 'CMED','CSURG','VSURG','TSURG' -- cardiac/vascular/thoracic surgery ) then 1 else 0 end as exclusion_service_surgical from co order by icustay_id;
31.211268
97
0.69269
2f709c95054455ee5da52284ddb9330c2db589c6
1,286
php
PHP
app/Http/Controllers/ProjectStagesController.php
developermwangimuthui/canadaprojectmanagement
9bb93c673777e248118447e0dc6582a3c87f6070
[ "MIT" ]
null
null
null
app/Http/Controllers/ProjectStagesController.php
developermwangimuthui/canadaprojectmanagement
9bb93c673777e248118447e0dc6582a3c87f6070
[ "MIT" ]
null
null
null
app/Http/Controllers/ProjectStagesController.php
developermwangimuthui/canadaprojectmanagement
9bb93c673777e248118447e0dc6582a3c87f6070
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Http\Requests\ProjectStageRequest; use App\Http\Resources\ProjectStageResource; use App\Models\ProjectStage; use Illuminate\Http\Request; Use Symfony\Component\HttpFoundation\Response; class ProjectStagesController extends Controller { public function index() { $allprojectStages = ProjectStage::all(); $projectStages = ProjectStageResource::collection($allprojectStages); return response([ 'error' => False, 'message' => 'Success', 'projectStages' => $projectStages ], Response::HTTP_OK); } public function store(ProjectStageRequest $request) { $projectStages = new ProjectStage(); $projectStages ->project_id = $request->input('project_id'); $projectStages ->stages = $request->input('stages'); $projectStages ->save(); $id = $projectStages->id; $allprojectStages = ProjectStage::where('id',$id)->get(); $projectStages = ProjectStageResource::collection($allprojectStages); return response([ 'error' => False, 'message' => 'Success', 'projectStages' => $projectStages ], Response::HTTP_OK); } }
30.619048
77
0.642302
58112a0bd1ebfc6a3fb9983be53cd0aa17746dad
7,767
c
C
src/core/map.c
Astropilot/Bomberman
25429d324d892a78a11e9ae098c5b3ab2f3a48ac
[ "MIT" ]
2
2019-04-26T19:06:50.000Z
2019-05-02T07:55:54.000Z
src/core/map.c
Astropilot/Bomberman
25429d324d892a78a11e9ae098c5b3ab2f3a48ac
[ "MIT" ]
null
null
null
src/core/map.c
Astropilot/Bomberman
25429d324d892a78a11e9ae098c5b3ab2f3a48ac
[ "MIT" ]
null
null
null
/******************************************************************************* * PROJECT: Bomberman * * AUTHORS: Yohann Martin, Aziz Hamide, Gauthier Desplanque, William Weber * * DATE CREATED: 01/16/2019 * * Copyright (c) 2019 Yohann MARTIN (@Astropilot). All rights reserved. * * Licensed under the MIT License. See LICENSE file in the project root for full * license information. *******************************************************************************/ #include <stdio.h> #include <SDL2/SDL.h> #include "main.h" #include "core/map.h" #include "core/extra.h" #include "core/player.h" #include "core/minion.h" #include "core/bomb.h" #include "core/utils.h" #include "network/game/server.h" static void TMap_Init(TMap *this, unsigned int max_clients); static unsigned int TMap_Take_Extra(TMap *this, player_t *player, int x, int y); TMap *New_TMap(unsigned int max_clients) { TMap *this = malloc(sizeof(TMap)); if(!this) return (NULL); TMap_Init(this, max_clients); this->Free = TMap_New_Free; return (this); } static void TMap_Init(TMap *this, unsigned int max_clients) { if (!this) return; unsigned int i; unsigned int j; this->Generate = TMap_Generate; this->Move_Player = TMap_Move_Player; this->Place_Bomb = TMap_Place_Bomb; this->Explose_Bomb = TMap_Explose_Bomb; this->block_map = malloc(MAP_HEIGHT * sizeof(object_type_t*)); if (this->block_map) { for (i = 0; i < MAP_HEIGHT; i++) { this->block_map[i] = malloc(MAP_WIDTH * sizeof(object_type_t)); for (j = 0; j < MAP_WIDTH; j++) { this->block_map[i][j] = NOTHING; } } } this->players = malloc(sizeof(player_t) * max_clients); if (this->players) { for (i = 0; i < max_clients; i++) { this->players[i].connected = 0; } } this->minion = malloc(sizeof(minion_t)); if (this->minion) init_minion(this->minion); this->max_players = max_clients; this->bombs_head = NULL; this->bomb_offset = 0; } void TMap_Generate(TMap *this, int chance_breakable_wall) { if (!this || !this->block_map) return; unsigned int y; unsigned int x; for (y = 0; y < MAP_HEIGHT; y++) { for (x = 0; x < MAP_WIDTH; x++) { if (y % 2 != 0 && x % 2 != 0) { // Si emplacement pour un mur this->block_map[y][x] = WALL; } else if ( (y > 1 || x > 1) && (y < MAP_HEIGHT - 2 || x > 1) && (y > 1 || x < MAP_WIDTH - 2) && (y < MAP_HEIGHT - 2 || x < MAP_WIDTH - 2) ) { // Si chance d'avoir un mur cassable if (rand_int(100) <= chance_breakable_wall) { this->block_map[y][x] = BREAKABLE_WALL; } } } } } static unsigned int TMap_Take_Extra(TMap *this, player_t *player, int x, int y) { if (!this || !player || !this->block_map) return (0); if (this->block_map[y][x] == NOTHING) return (0); unsigned int res = do_extra_logic(player, this->block_map[y][x]); if (res) this->block_map[y][x] = NOTHING; return (res); } unsigned int TMap_Move_Player(TMap *this, unsigned int player_id, direction_t direction) { if (!this || !this->block_map || !this->players) return (0); player_t *player = &(this->players[player_id]); pos_t new_coords = player->pos; int block_x, block_y; unsigned int i; int tmp_x, tmp_y; bomb_node_t *current_bomb = this->bombs_head; unsigned int current_time = SDL_GetTicks(); if (current_time <= player->last_move_time + player->specs.move_speed || player->specs.life <= 0) return (0); player->last_move_time = current_time; player->direction = (unsigned int)direction; if (direction == WEST || direction == EAST) new_coords.x = new_coords.x + (direction == EAST ? MAP_BLOCK_SIZE : -MAP_BLOCK_SIZE); else new_coords.y = new_coords.y + (direction == SOUTH ? MAP_BLOCK_SIZE : -MAP_BLOCK_SIZE); pix_to_map((int)new_coords.x, (int)new_coords.y, &block_x, &block_y); // Gestion des collisions avec les blocs infranchissables. if (block_x < 0 || block_x >= MAP_WIDTH) return (0); if (block_y < 0 || block_y >= MAP_HEIGHT) return (0); if (this->block_map[block_y][block_x] == WALL || this->block_map[block_y][block_x] == BREAKABLE_WALL) return (0); // Gestion des collisions avec les autres joueurs. for(i = 0; i < this->max_players; i++) { if (this->players[i].connected == 1 && this->players[i].specs.life > 0 && this->players[i].p_id != player_id) { pix_to_map((int)this->players[i].pos.x, (int)this->players[i].pos.y, &tmp_x, &tmp_y); if (block_y == tmp_y && block_x == tmp_x) return (0); } } // Gestion des collisions avec les bombes. while (current_bomb != NULL) { if ((int)current_bomb->bomb->bomb_pos.x == block_x && (int)current_bomb->bomb->bomb_pos.y == block_y) { return (0); } current_bomb = current_bomb->next; } player->pos.x = new_coords.x; player->pos.y = new_coords.y; return TMap_Take_Extra(this, player, block_x, block_y); } bomb_status_t TMap_Place_Bomb(TMap *this, unsigned int player_id, bomb_reason_t *reason) { if (!this || !reason || !this->block_map || !this->players) { if (reason) *reason = INTERNAL_ERROR; return (BOMB_CANCELED); } player_t *player = &(this->players[player_id]); int block_x, block_y; unsigned int time = SDL_GetTicks(); bomb_t *bomb; bomb_node_t *current_bomb = this->bombs_head; if (player->specs.bombs_left <= 0 || player->specs.life <= 0) { *reason = NO_MORE_CAPACITY; return (BOMB_CANCELED); } pix_to_map((int)player->pos.x, (int)player->pos.y, &block_x, &block_y); while (current_bomb != NULL) { if (current_bomb->bomb->bomb_pos.x == (unsigned int)block_x && current_bomb->bomb->bomb_pos.y == (unsigned int)block_y) { *reason = ALREADY_ITEM; return (BOMB_CANCELED); } current_bomb = current_bomb->next; } bomb = malloc(sizeof(bomb_t)); if (!bomb) { *reason = INTERNAL_ERROR; return (BOMB_CANCELED); } player->specs.bombs_left--; this->bomb_offset++; bomb->id = this->bomb_offset - 1; bomb->bomb_pos.x = (unsigned int)block_x; bomb->bomb_pos.y = (unsigned int)block_y; bomb->type = CLASSIC; bomb->range = player->specs.bombs_range; bomb->time_explode = time + rand_range_int(2000, 5000); bomb->owner_id = player_id; add_bomb(&(this->bombs_head), bomb); return (BOMB_POSED); } void TMap_Explose_Bomb(TMap *this, bomb_t *bomb, TGameServer *gserver) { if (!this || !this->block_map || !this->players || !bomb || !gserver) return; do_bomb_logic(this, bomb, gserver); } void TMap_New_Free(TMap *this) { if (this) { unsigned int i; bomb_node_t *current = this->bombs_head; bomb_node_t *tmp = NULL; while (current != NULL) { free(current->bomb); tmp = current; current = current->next; free(tmp); } if (this->block_map) { for (i = 0; i < MAP_HEIGHT; i++) { free(this->block_map[i]); } free(this->block_map); this->block_map = NULL; } free(this->players); this->players = NULL; free(this->minion); this->minion = NULL; } free(this); }
30.821429
97
0.571134
f07c58fdf12a59fd4931149ca97b0f1cc648b6be
400
js
JavaScript
helpers/constants.js
grisha19961116/finalGroupProjectNode
959ba195ec892eee0be2586050261aa4e7fe7866
[ "MIT" ]
null
null
null
helpers/constants.js
grisha19961116/finalGroupProjectNode
959ba195ec892eee0be2586050261aa4e7fe7866
[ "MIT" ]
1
2021-04-03T17:42:01.000Z
2021-04-03T17:42:01.000Z
helpers/constants.js
grisha19961116/finalGroupProjectNode
959ba195ec892eee0be2586050261aa4e7fe7866
[ "MIT" ]
5
2021-04-16T18:30:09.000Z
2021-11-22T09:42:57.000Z
const HttpCode = { OK: 200, CREATED: 201, NO_CONTENT: 204, BAD_REQUEST: 400, UNAUTHORIZED: 401, FORBIDDEN: 403, NOT_FOUND: 404, CONFLICT: 409, INTERNAL_SERVER_ERROR: 500, } const questionsAmount = 12 const JWT_ACCESS_EXPIRE_TIME = '1h' const JWT_REFRESH_EXPIRE_TIME = '30d' module.exports = { HttpCode, JWT_ACCESS_EXPIRE_TIME, JWT_REFRESH_EXPIRE_TIME, questionsAmount, }
16.666667
37
0.73
dfd63e2a14e58e5899bbc9847defb06a78520716
1,438
tsx
TypeScript
src/components/components/Content/Course/components/WorkingPanel/components/ThemeWorkingPanel/components/hoc/ResultTitleHOC.tsx
AdilBikeev/Study-Now-Site
655b3cfac16e55d5fad2f65330c5f339bd0fbb06
[ "MIT" ]
null
null
null
src/components/components/Content/Course/components/WorkingPanel/components/ThemeWorkingPanel/components/hoc/ResultTitleHOC.tsx
AdilBikeev/Study-Now-Site
655b3cfac16e55d5fad2f65330c5f339bd0fbb06
[ "MIT" ]
null
null
null
src/components/components/Content/Course/components/WorkingPanel/components/ThemeWorkingPanel/components/hoc/ResultTitleHOC.tsx
AdilBikeev/Study-Now-Site
655b3cfac16e55d5fad2f65330c5f339bd0fbb06
[ "MIT" ]
null
null
null
import React from "react"; import SentimentVerySatisfiedIcon from '@material-ui/icons/SentimentVerySatisfied'; import SentimentVeryDissatisfiedIcon from '@material-ui/icons/SentimentVeryDissatisfied'; import { yellow } from "@material-ui/core/colors"; import { Theme } from '@material-ui/core'; import { makeStyles, createStyles } from '@material-ui/core/styles'; type Props = { userAnswer: string, answer: string }; const useStyles = makeStyles((theme: Theme) => createStyles({ result_title: { fontSize: '2.5em', marginRight: theme.spacing(1) } })); /** * В щависимости от ответа пользоваетля возвращает текст с результатом теста. * @param userAnswer Ответ пользователя. * @param answer Ответ по заданной под-теме. */ export const ResultTitleHOC: React.FC<Props> = ({ userAnswer, answer }) => { const classes = useStyles(); const iconSize = '3.5em'; if (answer === userAnswer) { return (<> <div style={{ color: '#4BD37B'}} className={classes.result_title}>Верно !</div> <SentimentVerySatisfiedIcon style={{ color: yellow[500], fontSize: iconSize }} /> </>) } else { return (<> <div style={{ color: '#E06161' }} className={classes.result_title}>Неверно</div> <SentimentVeryDissatisfiedIcon style={{ color: yellow[500], fontSize: iconSize }}/> </>) } };
29.958333
95
0.633519
1fc51be5529fe147271fd9b498d51f67696da202
165
css
CSS
react/project/youtube-mini-clone/src/components/VideoList/VideoList.css
shin-eunji/TIL
4e3400225f4720c8350e75b60843807bec1252cc
[ "MIT" ]
5
2020-02-20T10:42:26.000Z
2021-05-31T01:15:37.000Z
react/project/youtube-mini-clone/src/components/VideoList/VideoList.css
shin-eunji/TIL
4e3400225f4720c8350e75b60843807bec1252cc
[ "MIT" ]
128
2019-09-03T06:17:51.000Z
2021-12-09T02:08:17.000Z
react/project/youtube-mini-clone/src/components/VideoList/VideoList.css
shin-eunji/TIL
4e3400225f4720c8350e75b60843807bec1252cc
[ "MIT" ]
13
2019-10-02T17:13:52.000Z
2022-01-07T08:50:46.000Z
.list-item { cursor: pointer; margin: 2em 0 0; display: flex; align-items: flex-start; } .video-list-wrapper { overflow: scroll; padding-right: 30px; }
13.75
26
0.654545
011e37fb3dcc07c7d78ac752bbcb211ea21fb61a
2,889
rs
Rust
src/mandelbrot.rs
bfops/hello-mandelbrot
7739dbc6e089b349cb7c5430baea84a84d20514a
[ "MIT" ]
null
null
null
src/mandelbrot.rs
bfops/hello-mandelbrot
7739dbc6e089b349cb7c5430baea84a84d20514a
[ "MIT" ]
null
null
null
src/mandelbrot.rs
bfops/hello-mandelbrot
7739dbc6e089b349cb7c5430baea84a84d20514a
[ "MIT" ]
null
null
null
use main::{WINDOW_WIDTH, WINDOW_HEIGHT, RGB}; use opencl; use opencl::hl::{Kernel}; use opencl::mem::CLBuffer; use opencl_context::CL; use std::borrow::Borrow; pub struct Mandelbrot { pub low_x: f64, pub low_y: f64, pub width: f64, pub height: f64, pub max_iter: u32, pub radius: f64, output_buffer: CLBuffer<RGB>, len: usize, kernel: Kernel, } impl Mandelbrot { pub fn new(cl: &CL) -> Mandelbrot { let len = WINDOW_WIDTH as usize * WINDOW_HEIGHT as usize; let program = { let ker = format!(" __kernel void color( const double low_x, const double low_y, const double width, const double height, const int max_iter, const double radius, __global float * output) {{ int W = {}; int H = {}; int i = get_global_id(0); double c_x = i % W; double c_y = i / W; c_x = c_x * width / W + low_x; c_y = c_y * height / H + low_y; double x = 0; double y = 0; int it; for (it = 0; it < max_iter; ++it) {{ double x2 = x * x; double y2 = y * y; if (x2 + y2 > radius * radius) break; // Ordering is important here. y = 2*x*y + c_y; x = x2 - y2 + c_x; }} i = i * 3; if (it < max_iter) {{ float progress = (float)it / (float)max_iter; output[i] = progress; output[i + 1] = 1 - 2 * fabs(0.5 - progress); output[i + 2] = 0.5 * (1 - progress); }} else {{ output[i] = 0; output[i + 1] = 0; output[i + 2] = 0; }} }} ", WINDOW_WIDTH, WINDOW_HEIGHT); cl.context.create_program_from_source(ker.borrow()) }; program.build(&cl.device).unwrap(); let kernel = program.create_kernel("color"); Mandelbrot { low_x: 0.0, low_y: 0.0, width: 0.0, height: 0.0, max_iter: 0, radius: 0.0, output_buffer: cl.context.create_buffer(len, opencl::cl::CL_MEM_WRITE_ONLY), kernel: kernel, len: len, } } pub fn render(&self, cl: &CL) -> Vec<RGB> { self.kernel.set_arg(0, &self.low_x); self.kernel.set_arg(1, &self.low_y); self.kernel.set_arg(2, &self.width); self.kernel.set_arg(3, &self.height); self.kernel.set_arg(4, &self.max_iter); self.kernel.set_arg(5, &self.radius); // This is sketchy; we "implicitly cast" output_buffer from a CLBuffer<RGB> to a CLBuffer<f32>. self.kernel.set_arg(6, &self.output_buffer); let event = cl.queue.enqueue_async_kernel(&self.kernel, self.len, None, ()); cl.queue.get(&self.output_buffer, &event) } }
26.504587
99
0.512634
21e9c6af0544a1ecc539f0949a0ad1cf7fd59080
349
html
HTML
public/main.html
jrb467/Treedoc
832cd001a2a942c23dca8bbb134a0ebfa48567a5
[ "BSD-3-Clause" ]
null
null
null
public/main.html
jrb467/Treedoc
832cd001a2a942c23dca8bbb134a0ebfa48567a5
[ "BSD-3-Clause" ]
null
null
null
public/main.html
jrb467/Treedoc
832cd001a2a942c23dca8bbb134a0ebfa48567a5
[ "BSD-3-Clause" ]
null
null
null
<div ng-show='error'> <h2 class='error'>{{error}}</h2> </div> <div ng-show='!error && !showingItem' class='item' ng-repeat='item in items track by $index' ng-click='clicked($index)'> <h1>{{item.$name}}</h1> <p ng-show='item.description'>{{item.description}}</p> </div> <div ng-show='!error && showingItem' ng-bind-html='itemData'></div>
38.777778
120
0.627507
584be216483ac5e23f32c9b454ee533b0f151a7e
485
h
C
include/perf.h
OAID/CVGesture
3ee930e58cb076c85fca341585a820896ebc718d
[ "OML" ]
33
2017-10-14T02:43:26.000Z
2021-07-29T11:02:11.000Z
include/perf.h
OAID/CVGesture
3ee930e58cb076c85fca341585a820896ebc718d
[ "OML" ]
3
2019-03-08T10:20:28.000Z
2021-12-28T12:54:22.000Z
include/perf.h
OAID/CVGesture
3ee930e58cb076c85fca341585a820896ebc718d
[ "OML" ]
35
2017-10-19T09:36:13.000Z
2021-05-16T18:05:07.000Z
#ifndef PERF_H__ #define PERF_H__ #include <sys/time.h> #define USECS_COUNT 1000000 class perf { public: perf(); void start(); void stop(); // pause to counte time void pause(); // recovery to counte time void recovery(); // get the timeinterval(us), from start to now, // exclude the interval from pause to recovery double gettimegap(); private: struct timeval pretv; struct timeval sumtv; bool status; }; #endif
14.69697
52
0.630928
5f661d82cb6d8d540e9f29876dc5333fb60b2abc
11,016
ts
TypeScript
src/controllers/apisManagementController.ts
apimatic/apimatic-sdk-for-js
345360d353c6c7cc4b5329d60779f3ad982e2b8c
[ "MIT" ]
null
null
null
src/controllers/apisManagementController.ts
apimatic/apimatic-sdk-for-js
345360d353c6c7cc4b5329d60779f3ad982e2b8c
[ "MIT" ]
1
2021-12-01T10:17:08.000Z
2021-12-01T10:17:08.000Z
src/controllers/apisManagementController.ts
apimatic/apimatic-sdk-for-js
345360d353c6c7cc4b5329d60779f3ad982e2b8c
[ "MIT" ]
null
null
null
/** * Apimatic APILib * * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). */ import { ApiResponse, FileWrapper, RequestOptions } from '../core'; import { Accept, acceptSchema } from '../models/accept'; import { Accept2, accept2Schema } from '../models/accept2'; import { ApiEntity, apiEntitySchema } from '../models/apiEntity'; import { ExportFormats, exportFormatsSchema } from '../models/exportFormats'; import { ImportApiVersionViaUrlRequest, importApiVersionViaUrlRequestSchema, } from '../models/importApiVersionViaUrlRequest'; import { ImportApiViaUrlRequest, importApiViaUrlRequestSchema, } from '../models/importApiViaUrlRequest'; import { InplaceImportApiViaUrlRequest, inplaceImportApiViaUrlRequestSchema, } from '../models/inplaceImportApiViaUrlRequest'; import { string } from '../schema'; import { BaseController } from './baseController'; export class ApisManagementController extends BaseController { /** * Import an API into the APIMatic Dashboard by uploading the API specification file. * * You can also specify [API Metadata](https://docs.apimatic.io/manage-apis/apimatic-metadata) while * importing the API using this endpoint. When specifying Metadata, the uploaded file will be a zip * file containing the API specification file and the `APIMATIC-META` json file. * * @param file The API specification file.<br>The type of the specification file should be * any of the [supported formats](https://docs.apimatic.io/api- * transformer/overview-transformer#supported-input-formats). * @return Response from the API call */ async importAPIViaFile( file: FileWrapper, requestOptions?: RequestOptions ): Promise<ApiResponse<ApiEntity>> { const req = this.createRequest('POST', '/api-entities/import-via-file'); req.header('Content-Type', 'multipart/form-data'); req.formData({ file: file, }); return req.callAsJson(apiEntitySchema, requestOptions); } /** * Import an API into the APIMatic Dashboard by providing the URL of the API specification file. * * You can also specify [API Metadata](https://docs.apimatic.io/manage-apis/apimatic-metadata) while * importing the API using this endpoint. When specifying Metadata, the URL provided will be that of a * zip file containing the API specification file and the `APIMATIC-META` json file. * * @param body Request Body * @return Response from the API call */ async importAPIViaURL( body: ImportApiViaUrlRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<ApiEntity>> { const req = this.createRequest('POST', '/api-entities/import-via-url'); const mapped = req.prepareArgs({ body: [body, importApiViaUrlRequestSchema], }); req.header( 'Content-Type', 'application/vnd.apimatic.apiEntityUrlImportDto.v1+json' ); req.json(mapped.body); return req.callAsJson(apiEntitySchema, requestOptions); } /** * Import a new version for an API, against an existing API Group, by uploading the API specification * file. * * You can also specify [API Metadata](https://docs.apimatic.io/manage-apis/apimatic-metadata) while * importing the API version using this endpoint. When specifying Metadata, the uploaded file will be a * zip file containing the API specification file and the `APIMATIC-META` json file. * * @param apiGroupId The ID of the API Group for which to import a new API version. * @param accept * @param versionOverride The version number with which the new API version will be imported. This * version number will override the version specified in the API specification * file.<br>APIMatic recommends versioning the API with the [versioning * scheme](https://docs.apimatic.io/define-apis/basic-settings/#version) * documented in the docs. * @param file The API specification file.<br>The type of the specification file should * be any of the [supported formats](https://docs.apimatic.io/api- * transformer/overview-transformer#supported-input-formats). * @return Response from the API call */ async importNewAPIVersionViaFile( apiGroupId: string, accept: Accept, versionOverride: string, file: FileWrapper, requestOptions?: RequestOptions ): Promise<ApiResponse<ApiEntity>> { const req = this.createRequest('POST'); const mapped = req.prepareArgs({ apiGroupId: [apiGroupId, string()], accept: [accept, acceptSchema], versionOverride: [versionOverride, string()], }); req.header('Accept', mapped.accept); req.header('Content-Type', 'multipart/form-data'); req.formData({ version_override: mapped.versionOverride, file: file, }); req.appendTemplatePath`/api-groups/${mapped.apiGroupId}/api-entities/import-via-file`; return req.callAsJson(apiEntitySchema, requestOptions); } /** * Import a new version for an API, against an existing API Group, by providing the URL of the API * specification file. * * You can also specify [API Metadata](https://docs.apimatic.io/manage-apis/apimatic-metadata) while * importing the API version using this endpoint. When specifying Metadata, the URL provided will be * that of a zip file containing the API specification file and the `APIMATIC-META` json file. * * @param apiGroupId The ID of the API Group for which to import a new API * version. * @param accept * @param body Request Body * @return Response from the API call */ async importNewAPIVersionViaURL( apiGroupId: string, accept: Accept, body: ImportApiVersionViaUrlRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<ApiEntity>> { const req = this.createRequest('POST'); const mapped = req.prepareArgs({ apiGroupId: [apiGroupId, string()], accept: [accept, acceptSchema], body: [body, importApiVersionViaUrlRequestSchema], }); req.header('Accept', mapped.accept); req.header( 'Content-Type', 'application/vnd.apimatic.apiGroupApiEntityUrlImportDto.v1+json' ); req.json(mapped.body); req.appendTemplatePath`/api-groups/${mapped.apiGroupId}/api-entities/import-via-url`; return req.callAsJson(apiEntitySchema, requestOptions); } /** * Replace an API version of an API Group, by uploading the API specification file that will replace * the current version. * * You can also specify [API Metadata](https://docs.apimatic.io/manage-apis/apimatic-metadata) while * importing the API version using this endpoint. When specifying Metadata, the uploaded file will be a * zip file containing the API specification file and the `APIMATIC-META` json file. * * @param apiEntityId The ID of the API Entity to replace. * @param accept * @param file The API specification file.<br>The type of the specification file should be * any of the [supported formats](https://docs.apimatic.io/api- * transformer/overview-transformer#supported-input-formats). * @return Response from the API call */ async inplaceAPIImportViaFile( apiEntityId: string, accept: Accept2, file: FileWrapper, requestOptions?: RequestOptions ): Promise<ApiResponse<void>> { const req = this.createRequest('PUT'); const mapped = req.prepareArgs({ apiEntityId: [apiEntityId, string()], accept: [accept, accept2Schema], }); req.header('Accept', mapped.accept); req.header('Content-Type', 'multipart/form-data'); req.formData({ file: file, }); req.appendTemplatePath`/api-entities/${mapped.apiEntityId}/import-via-file`; return req.call(requestOptions); } /** * Replace an API version of an API Group, by providing the URL of the API specification file that will * replace the current version. * * You can also specify [API Metadata](https://docs.apimatic.io/manage-apis/apimatic-metadata) while * importing the API version using this endpoint. When specifying Metadata, the URL provided will be * that of a zip file containing the API specification file and the `APIMATIC-META` json file. * * @param apiEntityId The ID of the API Entity to replace. * @param body Request Body * @return Response from the API call */ async inplaceAPIImportViaURL( apiEntityId: string, body: InplaceImportApiViaUrlRequest, requestOptions?: RequestOptions ): Promise<ApiResponse<void>> { const req = this.createRequest('PUT'); const mapped = req.prepareArgs({ apiEntityId: [apiEntityId, string()], body: [body, inplaceImportApiViaUrlRequestSchema], }); req.header( 'Content-Type', 'application/vnd.apimatic.apiEntityUrlImportDto.v1+json' ); req.json(mapped.body); req.appendTemplatePath`/api-entities/${mapped.apiEntityId}/import-via-url`; return req.call(requestOptions); } /** * Fetch an API Entity. * * @param apiEntityId The ID of the API Entity to fetch. * @return Response from the API call */ async fetchAPIEntity( apiEntityId: string, requestOptions?: RequestOptions ): Promise<ApiResponse<ApiEntity>> { const req = this.createRequest('GET'); const mapped = req.prepareArgs({ apiEntityId: [apiEntityId, string()] }); req.appendTemplatePath`/api-entities/${mapped.apiEntityId}`; return req.callAsJson(apiEntitySchema, requestOptions); } /** * Download the API Specification file for a an API Version in any of the API Specification formats * supported by APIMatic. * * @param apiEntityId The ID of the API Entity to download. * @param format The format in which to download the API.<br>The format can be any of the * [supported formats](https://docs.apimatic.io/api-transformer/overview- * transformer#supported-input-formats). * @return Response from the API call */ async downloadAPISpecification( apiEntityId: string, format: ExportFormats, requestOptions?: RequestOptions ): Promise<ApiResponse<NodeJS.ReadableStream | Blob>> { const req = this.createRequest('GET'); const mapped = req.prepareArgs({ apiEntityId: [apiEntityId, string()], format: [format, exportFormatsSchema], }); req.query('format', mapped.format); req.appendTemplatePath`/api-entities/${mapped.apiEntityId}/api-description`; return req.callAsStream(requestOptions); } }
41.727273
119
0.673475
012e4ebe05f72abb145c93b9bde2e6652a82a0b5
10,251
swift
Swift
Example/CloudServiceKitExample/ViewController.swift
underthestars-zhy/CloudServiceKit
8ba11fee9a0adeae1e6a0132171f34a57147feb4
[ "MIT" ]
null
null
null
Example/CloudServiceKitExample/ViewController.swift
underthestars-zhy/CloudServiceKit
8ba11fee9a0adeae1e6a0132171f34a57147feb4
[ "MIT" ]
null
null
null
Example/CloudServiceKitExample/ViewController.swift
underthestars-zhy/CloudServiceKit
8ba11fee9a0adeae1e6a0132171f34a57147feb4
[ "MIT" ]
null
null
null
// // ViewController.swift // CloudServiceKitExample // // Created by alexiscn on 2021/9/18. // import UIKit import CloudServiceKit import OAuthSwift class ViewController: UIViewController { enum Section { case main case saved } enum Item: Hashable { case provider(CloudDriveType) case cached(CloudAccount) func hash(into hasher: inout Hasher) { switch self { case .cached(let account): hasher.combine(account.identifier) case .provider(let type): hasher.combine(type) } } } private var collectionView: UICollectionView! private var dataSource: UICollectionViewDiffableDataSource<Section, Item>! private var connector: CloudServiceConnector? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationItem.title = "CloudServiceKit" setupCollectionView() setupDataSource() applyInitialSnapshot() } private func connect(_ drive: CloudDriveType) { let connector = connector(for: drive) connector.connect(viewController: self) { [weak self] result in guard let self = self else { return } switch result { case .success(let token): // fetch current user info to save account let credential = URLCredential(user: "user", password: token.credential.oauthToken, persistence: .permanent) let provider = self.provider(for: drive, credential: credential) provider.getCurrentUserInfo { [weak self] userResult in guard let self = self else { return } switch userResult { case .success(let user): let account = CloudAccount(type: drive, username: user.username, oauthToken: token.credential.oauthToken) account.refreshToken = token.credential.oauthRefreshToken CloudAccountManager.shared.upsert(account) self.applyInitialSnapshot() case .failure(let error): print(error) } let vc = DriveBrowserViewController(provider: provider, directory: provider.rootItem) self.navigationController?.pushViewController(vc, animated: true) } case .failure(let error): print(error) } } self.connector = connector } private func connector(for drive: CloudDriveType) -> CloudServiceConnector { let message = "Please configure app info in CloudConfiguration.swift" let connector: CloudServiceConnector switch drive { case .baiduPan: assert(CloudConfiguration.baidu != nil, message) let baidu = CloudConfiguration.baidu! connector = BaiduPanConnector(appId: baidu.appId, appSecret: baidu.appSecret, callbackUrl: baidu.redirectUrl) case .box: assert(CloudConfiguration.box != nil, message) let box = CloudConfiguration.box! connector = BoxConnector(appId: box.appId, appSecret: box.appSecret, callbackUrl: box.appSecret) case .dropbox: assert(CloudConfiguration.dropbox != nil, message) let dropbox = CloudConfiguration.dropbox! connector = DropboxConnector(appId: dropbox.appId, appSecret: dropbox.appSecret, callbackUrl: dropbox.appSecret) case .googleDrive: assert(CloudConfiguration.googleDrive != nil, message) let googledrive = CloudConfiguration.googleDrive! connector = GoogleDriveConnector(appId: googledrive.appId, appSecret: googledrive.appSecret, callbackUrl: googledrive.redirectUrl) case .oneDrive: assert(CloudConfiguration.oneDrive != nil, message) let onedrive = CloudConfiguration.oneDrive! connector = OneDriveConnector(appId: onedrive.appId, appSecret: onedrive.appSecret, callbackUrl: onedrive.redirectUrl) case .pCloud: assert(CloudConfiguration.pCloud != nil, message) let pcloud = CloudConfiguration.pCloud! connector = PCloudConnector(appId: pcloud.appId, appSecret: pcloud.appSecret, callbackUrl: pcloud.redirectUrl) } return connector } private func provider(for driveType: CloudDriveType, credential: URLCredential) -> CloudServiceProvider { let provider: CloudServiceProvider switch driveType { case .baiduPan: provider = BaiduPanServiceProvider(credential: credential) case .box: provider = BoxServiceProvider(credential: credential) case .dropbox: provider = DropboxServiceProvider(credential: credential) case .googleDrive: provider = GoogleDriveServiceProvider(credential: credential) case .oneDrive: provider = OneDriveServiceProvider(credential: credential) case .pCloud: provider = PCloudServiceProvider(credential: credential) } return provider } private func connect(_ account: CloudAccount) { let connector = connector(for: account.driveType) if let refreshToken = account.refreshToken, !refreshToken.isEmpty { connector.renewToken(with: refreshToken) { result in switch result { case .success(let token): // update oauth token and refresh token of existing account account.oauthToken = token.credential.oauthToken if !token.credential.oauthRefreshToken.isEmpty { account.refreshToken = token.credential.oauthRefreshToken } CloudAccountManager.shared.upsert(account) // create CloudServiceProvider with new oauth token let credential = URLCredential(user: account.username, password: token.credential.oauthToken, persistence: .permanent) let provider = self.provider(for: account.driveType, credential: credential) let vc = DriveBrowserViewController(provider: provider, directory: provider.rootItem) self.navigationController?.pushViewController(vc, animated: true) case .failure(let error): print("=>", error.localizedDescription) } } } else { // For pCloud which do not contains refresh token and its oauth is valid for long time // we just use cached oauth token to create CloudServiceProvider let credential = URLCredential(user: account.username, password: account.oauthToken, persistence: .permanent) let provider = provider(for: account.driveType, credential: credential) let vc = DriveBrowserViewController(provider: provider, directory: provider.rootItem) self.navigationController?.pushViewController(vc, animated: true) } self.connector = connector } } // MARK: - Setup extension ViewController { private func setupCollectionView() { collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.delegate = self collectionView.backgroundColor = .systemBackground view.addSubview(collectionView) } private func createLayout() -> UICollectionViewLayout { let configuration = UICollectionLayoutListConfiguration(appearance: .insetGrouped) return UICollectionViewCompositionalLayout.list(using: configuration) } private func setupDataSource() { let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { (cell, indexPath, item) in var content = cell.defaultContentConfiguration() switch item { case .cached(let account): content.image = account.driveType.image content.text = account.username case .provider(let driveItem): content.image = driveItem.image content.text = driveItem.title } cell.contentConfiguration = content } dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: { collectionView, indexPath, item in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item) }) } private func applyInitialSnapshot() { var snapshot = NSDiffableDataSourceSnapshot<Section, Item>() snapshot.appendSections([.main]) snapshot.appendItems(CloudDriveType.allCases.map { Item.provider($0) }, toSection: .main) let accounts = CloudAccountManager.shared.accounts if !accounts.isEmpty { snapshot.appendSections([.saved]) snapshot.appendItems(accounts.map { Item.cached($0) }, toSection: .saved) } dataSource.apply(snapshot, animatingDifferences: false) } } // MARK: - UICollectionViewDelegate extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let item = dataSource.itemIdentifier(for: indexPath) else { return } switch item { case .provider(let driveType): connect(driveType) case .cached(let account): connect(account) } } }
43.436441
153
0.610867
c7fa50fe6fbc87d4931d0d42760364efa2051bba
1,777
java
Java
src/com/android/tv/perf/StartupMeasure.java
werktrieb/TV-App
906d4098e8264baf527b072179273517c1209eb5
[ "Apache-2.0" ]
4
2020-03-30T20:36:22.000Z
2021-06-01T09:19:40.000Z
src/com/android/tv/perf/StartupMeasure.java
werktrieb/TV-App
906d4098e8264baf527b072179273517c1209eb5
[ "Apache-2.0" ]
null
null
null
src/com/android/tv/perf/StartupMeasure.java
werktrieb/TV-App
906d4098e8264baf527b072179273517c1209eb5
[ "Apache-2.0" ]
5
2020-03-30T20:36:23.000Z
2021-04-06T19:38:51.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * 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.android.tv.perf; import android.app.Activity; import android.app.Application; /** * Measures App startup. * * <p>This interface is lightweight to help measure both cold and warm startup latency. * Implementations must not throw any Exception. * * <p>Because this class needs to be used in static initialization blocks, it can not be injected * via dagger. * * <p>Creating implementations of this interface must be idempotent and lightweight. It does not * need to be cached. */ public interface StartupMeasure { /** To be be placed as the first static block in the app's Application class. */ void onAppClassLoaded(); /** * To be placed in your {@link Application#onCreate} to let Performance Monitoring know when * this happen. */ void onAppCreate(Application application); /** * To be placed in an initialization block of your {@link Activity} to let Performance * Monitoring know when this activity is instantiated. Please note that this initialization * block should be before other initialization blocks (if any) in your activity class. */ void onActivityInit(); }
34.843137
97
0.725943
af5b1d99f21a818f0e02485b7d4a6ceb9b9d5b8c
2,046
rb
Ruby
work/sandbox/component.rb
kotp/facets
06a57bb933dca7034703cf914ff2754c4d4c76e2
[ "Ruby" ]
1
2015-11-05T01:31:27.000Z
2015-11-05T01:31:27.000Z
work/sandbox/component.rb
kotp/facets
06a57bb933dca7034703cf914ff2754c4d4c76e2
[ "Ruby" ]
null
null
null
work/sandbox/component.rb
kotp/facets
06a57bb933dca7034703cf914ff2754c4d4c76e2
[ "Ruby" ]
null
null
null
# = Component # # module Foo # extend Component # # def self_x; "X::x"; end # # def x; "x"; end # end # # class X # include Foo # end # # X.x #=> "X::x" # X.new.x #=> "x" # module Component def class_module i = self @class_module ||= Module.new do include i end # @class_module.module_eval do # instance_methods.each do |name| # if md = /^self_/.match(name.to_s) # alias_method md.post_match, name # undef_method(name) # else # undef_method(name) # end # end # end @class_module end def instance_module i = self @instance_module ||= Module.new do include i end # @instance_module.module_eval do # instance_methods.each do |name| # if md = /^self_/.match(name.to_s) # undef_method(name) # end # end # end @instance_module end def method_added(name) if md = /^self_/.match(name.to_s) class_module.send(:alias_method, md.post_match, name) class_module.send(:undef_method, name) instance_module.send(:undef_method, name) else class_module.send(:undef_method, name) end end def included(base) return if base.name.empty? base.extend(class_module) end def append_features(base) return super if base.name.empty? instance_module.send(:append_features, base) end #def included(base) # base.extend class_module # instance_methods(false).each do |name| # if md = /^self_/.match(name.to_s) # base.send(:undef_method, name) # end # end #end end # __TEST__ =begin test require 'test/unit' class TestComponent < Test::Unit::TestCase module Foo extend Component def x; "x"; end def self_x; "X::x"; end #def x; "x"; end end class X include Foo end def test_class_method assert_equal("X::x", X.x) end def test_instance_method assert_equal("x", X.new.x) end end =end
16.909091
59
0.585044
9bad1df964fec4c2839fc70873d72faaadfe5648
3,385
js
JavaScript
src/tasklist.js
Abdona/ToDOList_Review
aae436c00e8e9e2ed3246ab3a59abe1f5956b643
[ "MIT" ]
null
null
null
src/tasklist.js
Abdona/ToDOList_Review
aae436c00e8e9e2ed3246ab3a59abe1f5956b643
[ "MIT" ]
1
2021-07-19T13:10:26.000Z
2021-07-19T13:10:26.000Z
src/tasklist.js
Abdona/ToDOList_Review
aae436c00e8e9e2ed3246ab3a59abe1f5956b643
[ "MIT" ]
null
null
null
import MyImage from './images/3-vertical-dots.svg'; import { dragDrop } from './Drag_Drop'; // eslint-disable-next-line import/no-cycle import { checkSelect } from './StatusUpdate'; // eslint-disable-next-line no-unused-vars import { Task } from './Task'; // eslint-disable-next-line import/no-cycle import { editContent } from './ContentUpdate'; // eslint-disable-next-line import/prefer-default-export export class TaskList { constructor(Tasks) { this.taskListcollection = Tasks; this.Task1 = []; this.length = 0; } // eslint-disable-next-line class-methods-use-this addTask(Task, flag = true) { if (flag === true) { this.length += 1; this.taskListcollection.push(Task); } const newListitem = document.createElement('li'); newListitem.setAttribute('id', Task.id); newListitem.setAttribute('class', 'ListItem'); const newListtask = document.createElement('textarea'); newListtask.setAttribute('maxlength', '255'); newListtask.setAttribute('contenteditable', 'true'); newListtask.addEventListener('change', () => { editContent(Task); }); newListtask.innerHTML = Task.description; if (Task.status === true) { newListtask.style.color = 'rgba(0, 0, 0, 0.45)'; } newListtask.setAttribute('id', Task.id * 2); const newListcheck = document.createElement('input'); newListcheck.setAttribute('type', 'checkbox'); newListcheck.setAttribute('id', Task.id * 3); newListcheck.addEventListener('click', () => { checkSelect(Task); }); const newListdots = document.createElement('img'); newListdots.setAttribute('src', MyImage); const taskDiv = document.createElement('div'); taskDiv.setAttribute('id', 'taskcont'); document.getElementById('listcontainer').appendChild(newListitem).appendChild(newListcheck); document.getElementById('listcontainer').appendChild(newListitem).appendChild(taskDiv).appendChild(newListtask); document.getElementById('listcontainer').appendChild(newListitem).appendChild(newListdots); dragDrop(); } clearCompleted() { const newTasklist = this.taskListcollection.filter((task) => task.status === false); this.length = newTasklist.length; localStorage.setItem('length', JSON.stringify(this.length)); // eslint-disable-next-line no-restricted-syntax for (const i in this.taskListcollection) { if (this.taskListcollection[i].status === true) { document.getElementById(this.taskListcollection[i].id).remove(); } } this.taskListcollection = newTasklist; localStorage.setItem('library', JSON.stringify(this.taskListcollection)); } // eslint-disable-next-line class-methods-use-this checkSelectonrefresh(Task) { const TaskP = document.getElementById(Task.id * 2); const newCheckBox = document.getElementById(Task.id * 3); if (Task.status === true) { newCheckBox.checked = true; TaskP.style.textDecoration = 'line-through'; } } addTostorage() { localStorage.setItem('length', JSON.stringify(this.length)); localStorage.setItem('library', JSON.stringify(this.taskListcollection)); } /* eslint-disable */ ShowTasks() { for (const i in this.taskListcollection) { this.length +=1 ; this.addTask(this.taskListcollection[i],false); this.checkSelectonrefresh(this.taskListcollection[i]); } } }
39.823529
116
0.691876
5801a2a8f1b35ac78a2626120f33260e7d72ef59
5,625
h
C
sources/FEM/files0.h
stefanheldt2/ogs_kb1
cab628d7966ae1a4523b79fe0595667e6c840966
[ "BSD-4-Clause" ]
3
2017-06-18T13:03:25.000Z
2019-12-16T13:01:27.000Z
sources/FEM/files0.h
wolf-pf/ogs_kb1
97ace8bc8fb80b033b8a32f6ed4a20983caa241f
[ "BSD-4-Clause" ]
14
2015-07-14T16:55:10.000Z
2022-03-29T14:44:00.000Z
sources/FEM/files0.h
wolf-pf/ogs_kb1
97ace8bc8fb80b033b8a32f6ed4a20983caa241f
[ "BSD-4-Clause" ]
3
2015-10-21T13:51:29.000Z
2021-11-04T11:02:00.000Z
#ifndef strings_INC #define strings_INC #define FORMAT_DOUBLE #define FPD_GESAMT 4 #define FPD_NACHKOMMA 14 /* Andere oeffentlich benutzte Module */ #include "Configure.h" #include <cstdio> #include <string> //#include <fstream> typedef int (*FctTestInt)( int*, FILE* ); typedef int (*FctTestLong)( long*, FILE* ); typedef int (*FctTestFloat)( float*, FILE* ); typedef int (*FctTestDouble)( double*, FILE* ); typedef int (*FctTestString)( char*, FILE* ); /* Funktionsprototypen zum Testen von eingelesenen Werten auf zulaessige Wertebereiche, mit Protokolldatei; Ergebnis: 0 bei Fehler, der zum Abbruch fuehren soll, sonst 1. Wenn korrigiert wurde: Protokoll schreiben und Ergebnis 1 */ extern int LineFeed ( FILE* f ); /* Schreibt Zeilenvorschub in Textdatei */ extern int FilePrintString ( FILE* f, const char* s ); /* Schreibt Zeichenkette in Textdatei */ extern int FilePrintInt ( FILE* f, int x ); /* Schreibt Integer-Wert in Textdatei */ extern int FilePrintLong ( FILE* f, long x ); /* Schreibt Long-Wert in Textdatei */ extern int FilePrintDouble ( FILE* f, double x ); /* Schreibt Double-Wert in Textdatei */ extern int FilePrintIntWB ( FILE* f, int x ); /* Schreibt Integer-Wert ohne fuehrende Leerzeichen in Textdatei */ extern int FilePrintLongWB ( FILE* f, long x ); /* Schreibt Long-Wert ohne fuehrende Leerzeichen in Textdatei */ extern int FilePrintDoubleWB ( FILE* f, double x ); /* Schreibt Double-Wert ohne fuehrende Leerzeichen in Textdatei */ extern int FileCommentDoubleMatrix ( FILE* f, double* d, int adjust, long m, long n ); /* Schreibt Double-m x n-Matrix als Kommentar mit Einrueckung adjust in Textdatei */ extern int StrReadSubSubKeyword ( char* x, char* s, int beginn, int* found, int* ende ); /* Liest Sub-Sub-Keyword aus String */ extern int StrReadSubKeyword ( char* x, char* s, int beginn, int* found, int* ende ); /* Liest Sub-Keyword aus String */ extern int StrReadInt ( int* x, char* s, FILE* f, FctTestInt func, int* pos ); /* Liest Integer-Wert aus String und schreibt Protokoll in Datei */ extern int StrReadLong ( long* x, char* s, FILE* f, FctTestLong func, int* pos ); /* Liest Long-Wert aus String und schreibt Protokoll in Datei */ extern int StrReadFloat ( float* x, char* s, FILE* f, FctTestFloat func, int* pos ); /* Liest Float-Wert aus String und schreibt Protokoll in Datei */ extern int StrReadDouble ( double* x, char* s, FILE* f, int* pos ); /* Liest Double-Wert aus String und schreibt Protokoll in Datei */ extern int StrReadString ( char** x, char* s, FILE* f, /*FctTestString func,*/ int* pos ); /* Liest Zeichenkette aus String und schreibt Protokoll in Datei */ extern int StrReadStr ( char* x, char* s, FILE* f, /*FctTestString func,*/ int* pos ); /* Liest Zeichenkette aus String und schreibt Protokoll in Datei */ extern int StrTestInt ( char* s ); /* Testet, ob in s noch ein Integer kommt; 0:=nein */ extern int StrTestLong ( char* s ); /* Testet, ob in s noch ein LongInt kommt; 0:=nein */ extern int StrTestFloat ( char* s ); /* Testet, ob in s noch ein Float kommt; 0:=nein */ extern int StrTestDouble ( char* s ); /* Testet, ob in s noch ein Double kommt; 0:=nein */ extern int StrTestString ( char* s ); /* Testet, ob in s noch ein String kommt; 0:=nein */ extern int StrTestHash ( char* s, int* pos); /* Testet, ob in s ein # folgt; 0:=nein; 1:=ja, pos liefert Position nach dem # */ extern int StrTestDollar ( char* s, int* pos); /* Testet, ob in s ein $ folgt; 0:=nein; 1:=ja, pos liefert Position nach dem $ */ extern int StrTestInv ( char* s, int* pos); /* Testet, ob in s ein ? folgt; 0:=nein; 1:=ja, pos liefert Position nach dem ? */ extern int StrReadLongNoComment (long* x,char* s,FILE* f,FctTestLong func,int* pos ); extern int StrReadStrNoComment ( char* x, char* s, FILE* f, FctTestString func, int* pos ); /* zusaetzliche Lesefunktionen fuer RF-SHELL */ extern int StringReadFloat ( float* x, char* s, int* pos ); extern int StringReadDouble ( double* x, char* s, int* pos ); extern int StringReadInt ( int* x, char* s, int* pos ); extern int StringReadLong ( long* x, char* s, int* pos ); extern int StringReadStr ( char** x, char* s, int* pos ); /* allgemeine Dummy-Testfunktionen */ //extern int TFInt ( int *x, FILE *f ); //extern int TFLong ( long *x, FILE *f ); //extern int TFFloat ( float *x, FILE *f ); //extern int TFDouble ( double *x, FILE *f ); //extern int TFDoubleNew (char *s, FILE *f ); extern int TFString ( char* x, FILE* f ); extern char* ReadString ( void ); /* Liest Zeichenkette von Standardeingabe */ extern char* StrUp ( const char* s ); /* wandelt s in Grossbuchstaben um */ extern char* StrDown ( char* s ); /* wandelt s in Kleinbuchstaben um */ extern void GetRFINodesData (); /* Weitere externe Objekte */ #define MAX_NAME 80 /*MX*/ extern int StrOnlyReadStr ( char* x, char* s, FILE* f, /*FctTestString func,*/ int* pos ); extern std::string get_sub_string(const std::string&,const std::string&,int,int*); extern void remove_white_space(std::string*); //extern std::string get_sub_string2(std::string buffer,std::string delimiter,std::string cut_string); extern std::string get_sub_string2(const std::string&,const std::string&,std::string*); extern bool SubKeyword(const std::string&); extern bool Keyword(const std::string&); //CC move here extern std::string GetLineFromFile1(std::ifstream*); //SB extern std::string GetUncommentedLine(std::string); //extern std::string NumberToString(long); extern void is_line_empty(std::string*); //OK #endif
43.269231
102
0.694044
fb47fb4982e80414193cff25c5a1eee565ff253b
1,118
go
Go
src/first/ch3/string-to-slice-of-runes.go
kedarmhaswade/goprograms
23c7376f9ce0d982e8162d939e0a7e83038617db
[ "MIT" ]
null
null
null
src/first/ch3/string-to-slice-of-runes.go
kedarmhaswade/goprograms
23c7376f9ce0d982e8162d939e0a7e83038617db
[ "MIT" ]
null
null
null
src/first/ch3/string-to-slice-of-runes.go
kedarmhaswade/goprograms
23c7376f9ce0d982e8162d939e0a7e83038617db
[ "MIT" ]
null
null
null
// how does the conversion by rune[] of string look? package ch3 import ( "fmt" "unicode/utf8" ) func convert() { s := "プログラム" // "program" in Japanese Katakana fmt.Printf("% x\n", s) // space between % and x -- fmt tricks // the above simply prints the bytes in the string! // the bytes an be returned by a []byte conversion for _, b := range []byte(s) { fmt.Printf("% x", b) } fmt.Println() a := []rune(s) // convert to a fmt.Printf("\n%x\n", a) // simply prints the runes in the string! //DecodeRune implements a UTF-decoder. For a three-byte sequence, for example, the unicode code point is determined as: //rune(b[0]&0x0F)<<12 | rune(b[1]&0x3F)<<6 | rune(b[2]&0x3F) //Thus, it clears the // 4 higher order bits of the most significant byte, i.e. byte 0, // 2 higher order bits of the byte 1, // 2 higher order bits of the least significant byte, i.e. byte 2 // //And simply concatenates the resulting bytes in the same order. var i, j int for _, c := range s { i = j j += utf8.RuneLen(c) fb, _ := utf8.DecodeRune([]byte(s)[i:j]) fmt.Printf("rune: %v = %v\n", c, fb) } }
29.421053
120
0.636852
26934ca04837181307625fedf16f1490d727d997
181
java
Java
jd-commerce-api/jd-commerce-api-service/src/main/java/com/start/quick/service/CarouselService.java
quick-get-start/java-architect
33f9cfeb11c8f04ae26e78203bc15506c2dd0e3e
[ "Apache-2.0" ]
null
null
null
jd-commerce-api/jd-commerce-api-service/src/main/java/com/start/quick/service/CarouselService.java
quick-get-start/java-architect
33f9cfeb11c8f04ae26e78203bc15506c2dd0e3e
[ "Apache-2.0" ]
null
null
null
jd-commerce-api/jd-commerce-api-service/src/main/java/com/start/quick/service/CarouselService.java
quick-get-start/java-architect
33f9cfeb11c8f04ae26e78203bc15506c2dd0e3e
[ "Apache-2.0" ]
null
null
null
package com.start.quick.service; import com.start.quick.entity.Carousel; import java.util.List; public interface CarouselService { List<Carousel> findAll(Integer isShow); }
16.454545
43
0.773481
66648a76839de414a60153b6ae2461203a169a71
1,944
lua
Lua
3DreamEngine/loader/obj.lua
Luke100000/3DreamEngine
77dd382b6bb890e174f9175870db636415b835fa
[ "MIT" ]
null
null
null
3DreamEngine/loader/obj.lua
Luke100000/3DreamEngine
77dd382b6bb890e174f9175870db636415b835fa
[ "MIT" ]
null
null
null
3DreamEngine/loader/obj.lua
Luke100000/3DreamEngine
77dd382b6bb890e174f9175870db636415b835fa
[ "MIT" ]
null
null
null
--[[ #obj - Wavefront OBJ file --]] return function(self, obj, path) --store vertices, normals and texture coordinates local vertices = { } local normals = { } local texture = { } --initial mesh local material = self:newMaterial() local mesh = self:newMesh("object", material) local meshID = "object" obj.meshes[meshID] = mesh for l in love.filesystem.lines(path) do local v = string.split(l, " ") if v[1] == "v" then table.insert(vertices, {tonumber(v[2]), tonumber(v[3]), tonumber(v[4])}) elseif v[1] == "vn" then table.insert(normals, {tonumber(v[2]), tonumber(v[3]), tonumber(v[4])}) elseif v[1] == "vt" then table.insert(texture, {tonumber(v[2]), 1.0 - tonumber(v[3])}) elseif v[1] == "usemtl" then material = self.materialLibrary[l:sub(8)] if not material then if not obj.args.ignoreMissingMaterials then print("material " .. l:sub(8) .. " is unknown") end material = self:newMaterial() end mesh.material = material elseif v[1] == "f" then local verts = #v-1 --combine vertex and data into one local index = #mesh.vertices for i = 1, verts do local v2 = string.split(v[i+1]:gsub("//", "/0/"), "/") index = index + 1 mesh.vertices[index] = vertices[tonumber(v2[1])] mesh.texCoords[index] = texture[tonumber(v2[2])] mesh.normals[index] = normals[tonumber(v2[3])] end local index = #mesh.vertices if verts == 3 then --tris table.insert(mesh.faces, {index-2, index-1, index}) else --triangulates, fan style for i = 1, verts-2 do table.insert(mesh.faces, {index-verts+1, index-verts+1+i, index-verts+2+i}) end end elseif v[1] == "o" then if obj.args.decodeBlenderNames then meshID = string.match(l:sub(3), "(.*)_.*") or l:sub(3) else meshID = l:sub(3) end obj.meshes[meshID] = obj.meshes[meshID] or self:newMesh(meshID, material) mesh = obj.meshes[meshID] end end end
28.588235
80
0.626029
59c945e7eeb6e3e0891754dd1911b4b5eca5fbc2
1,030
kt
Kotlin
data/src/main/java/apps/ricasares/com/data/network/RedditApi.kt
ricasares/RedditApp
494494cbe7cf78af578946e922812f56697a0250
[ "Apache-2.0" ]
null
null
null
data/src/main/java/apps/ricasares/com/data/network/RedditApi.kt
ricasares/RedditApp
494494cbe7cf78af578946e922812f56697a0250
[ "Apache-2.0" ]
null
null
null
data/src/main/java/apps/ricasares/com/data/network/RedditApi.kt
ricasares/RedditApp
494494cbe7cf78af578946e922812f56697a0250
[ "Apache-2.0" ]
null
null
null
package network import apps.ricasares.com.data.entity.RedditResponse import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query /** * Created by ricardo casarez on 11/17/17. */ interface RedditApi { @GET("/r/{subreddit}/{listing}/.json") fun getListings(@Path("subreddit") subreddit: String, @Path("listing") listing: String, @Query("after") after: String, @Query("limit") limit: String) : Single<RedditResponse> @GET("") fun getListingsBefore(@Path("subreddit") subreddit: String, @Path("listing") listing: String, @Query("before") after: String, @Query("limit") limit: String) : Single<RedditResponse> @GET("/{listing}.json") fun getFrontPageListing(@Path("listing") listing: String, @Query("after") after: String, @Query("limit") limit: String) : Single<RedditResponse> }
35.517241
81
0.595146
271895516ea5bac5efdb904a300b6687669439c3
552
css
CSS
src/styles/colors.css
omiaow/thoughts-storage-front-end
ebc352626289603b91d14ac36377e1876584b15a
[ "Apache-2.0" ]
null
null
null
src/styles/colors.css
omiaow/thoughts-storage-front-end
ebc352626289603b91d14ac36377e1876584b15a
[ "Apache-2.0" ]
null
null
null
src/styles/colors.css
omiaow/thoughts-storage-front-end
ebc352626289603b91d14ac36377e1876584b15a
[ "Apache-2.0" ]
null
null
null
[data-theme="light"] { --background: #D0D3D4; --font: #1f2933; --button-color: #1f2933; --button-hovered-color: #3E4C59; --button-border: #1f2933; --button-hovered-border: #3E4C59; --button-font: #ffffff; --button-hovered-font: #ffffff; --loader: #1f2933; } [data-theme="dark"] { --background: #1f2933; --font: #ffffff; --button-color: #1f2933; --button-hovered-color: #ffffff; --button-border: #ffffff; --button-hovered-border: #ffffff; --button-font: #ffffff; --button-hovered-font: #1f2933; --loader: #ffffff; }
23
35
0.632246
73b13c57fa55c6f141af26b38f157c33a08117b6
178
sql
SQL
face-detection/postgres/tables/users.sql
aliraees1993/docker-configs
9a58cb83fb08d2f1fd1dc3e6d4d0633bd25b8db6
[ "MIT" ]
null
null
null
face-detection/postgres/tables/users.sql
aliraees1993/docker-configs
9a58cb83fb08d2f1fd1dc3e6d4d0633bd25b8db6
[ "MIT" ]
null
null
null
face-detection/postgres/tables/users.sql
aliraees1993/docker-configs
9a58cb83fb08d2f1fd1dc3e6d4d0633bd25b8db6
[ "MIT" ]
null
null
null
BEGIN TRANSACTION; CREATE TABLE users( id serial PRIMARY KEY, name VARCHAR(100), email text UNIQUE NOT NULL, entries BIGINT DEFAULT 0, joined TIMESTAMP NOT NULL ); COMMIT;
16.181818
28
0.758427
0cc3636c2c8cdfc0167b425c8f83724d3610d2e3
1,063
py
Python
extract/tef/incident_reflected_power_test.py
PuffyPuffin/LO_user
c7cafc2045b027aad0098d034cbe2b70126c8379
[ "MIT" ]
null
null
null
extract/tef/incident_reflected_power_test.py
PuffyPuffin/LO_user
c7cafc2045b027aad0098d034cbe2b70126c8379
[ "MIT" ]
null
null
null
extract/tef/incident_reflected_power_test.py
PuffyPuffin/LO_user
c7cafc2045b027aad0098d034cbe2b70126c8379
[ "MIT" ]
null
null
null
""" Test of the cancellation of terms in the calculation of tidal energy flux. This will follow Mofjeld's notation. F is proportional to the energy flux of the original signal, and FF is proportional to the sum of the energy fluxes of the incident and reflected waves. RESULT: The two net fluxes are only equal for zero friction. I think this may be because pressure work is a nonlinear term and some part of the two waves pressure work can leak into the other. """ import numpy as np A0 = 1 + 0j U0 = 1 + 0.2j F = A0.real*U0.real + A0.imag*U0.imag alpha = 1 / np.sqrt(1 + 0j) Ap = (A0 + U0/alpha)/2 Am = (A0 - U0/alpha)/2 Up = alpha * Ap Um = alpha * Am FF = (Ap.real*Up.real + Ap.imag*Up.imag) - (Am.real*Um.real + Am.imag*Um.imag) print('No friction:') print('F = %0.1f, FF = %0.1f' % (F, FF)) alpha = 1 / np.sqrt(1 + 1j) Ap = (A0 + U0/alpha)/2 Am = (A0 - U0/alpha)/2 Up = alpha * Ap Um = alpha * Am FF = (Ap.real*Up.real + Ap.imag*Up.imag) - (Am.real*Um.real + Am.imag*Um.imag) print('\nOrder-1 friction:') print('F = %0.1f, FF = %0.1f' % (F, FF))
25.309524
78
0.659454
8cd15b81fbe6b71b8781a144b4984c85376eb914
282
sql
SQL
openGaussBase/testcase/KEYWORDS/analyze/Opengauss_Function_Keyword_Analyze_Case0018.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/analyze/Opengauss_Function_Keyword_Analyze_Case0018.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/analyze/Opengauss_Function_Keyword_Analyze_Case0018.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
-- @testpoint:opengauss关键字Analyze(保留),作为数据库名 --关键字不带引号-失败 create database Analyze; --关键字带双引号-成功 create database "Analyze"; drop database if exists "Analyze"; --关键字带单引号-合理报错 create database 'Analyze'; --关键字带反引号-合理报错 drop database if exists `Analyze`; create database `Analyze`;
17.625
45
0.758865
6b83b5a8db5232a51f4cf4f34fef59ddfb033e5d
1,171
h
C
libs2eplugins/src/s2e/Plugins/Lua/LuaS2EExecutionState.h
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
7
2020-04-27T03:53:16.000Z
2021-12-31T02:04:48.000Z
libs2eplugins/src/s2e/Plugins/Lua/LuaS2EExecutionState.h
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
null
null
null
libs2eplugins/src/s2e/Plugins/Lua/LuaS2EExecutionState.h
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
1
2020-07-15T05:19:28.000Z
2020-07-15T05:19:28.000Z
/// /// Copyright (C) 2014-2016, Cyberhaven /// All rights reserved. /// /// Licensed under the Cyberhaven Research License Agreement. /// #ifndef _LUA_S2E_EXECUTION_STATE_ #define _LUA_S2E_EXECUTION_STATE_ #include <s2e/S2EExecutionState.h> #include "Lua.h" #include "LuaS2EExecutionStateMemory.h" #include "LuaS2EExecutionStateRegisters.h" namespace s2e { namespace plugins { class LuaS2EExecutionState { private: S2EExecutionState *m_state; LuaS2EExecutionStateMemory m_memory; LuaS2EExecutionStateRegisters m_registers; public: static const char className[]; static Lunar<LuaS2EExecutionState>::RegType methods[]; LuaS2EExecutionState(lua_State *L) : m_state(nullptr), m_memory((S2EExecutionState *) nullptr), m_registers((S2EExecutionState *) nullptr) { } LuaS2EExecutionState(S2EExecutionState *state) : m_state(state), m_memory(state), m_registers(state) { } int mem(lua_State *L); int regs(lua_State *L); int createSymbolicValue(lua_State *L); int kill(lua_State *L); int setPluginProperty(lua_State *L); int getPluginProperty(lua_State *L); int debug(lua_State *L); }; } } #endif
23.897959
113
0.733561
04bc9bc9553ae3fcf2b0a3edd7964c83798e83f8
6,129
html
HTML
Application/Admin/View/Order/delive.html
hbysdzl/myshop
d8b79a98d44909cf2f9ef72f5a5962a1a924fd9b
[ "BSD-2-Clause" ]
null
null
null
Application/Admin/View/Order/delive.html
hbysdzl/myshop
d8b79a98d44909cf2f9ef72f5a5962a1a924fd9b
[ "BSD-2-Clause" ]
null
null
null
Application/Admin/View/Order/delive.html
hbysdzl/myshop
d8b79a98d44909cf2f9ef72f5a5962a1a924fd9b
[ "BSD-2-Clause" ]
null
null
null
<layout name="Index/header_footer" /> <style type="text/css"> .main-div table {background: #BBDDE5;} </style> <div class="list-div"> <table width="100%" cellpadding="3" cellspacing="1"> <tbody> <tr> <th colspan="4">订单信息</th> </tr> <tr> <td align="right" width="18%">订单号:</td> <td align="left" width="34%">{$arr.id}</td> <td align="right" width="15%">订单金额:</td> <td align="left">{$arr.total_price}</td> </tr> <tr> <td align="right" width="18%">下单时间:</td> <td align="left" width="34%"><?php echo date('Y-m-d H:i:s',$arr['addtime'])?></td> <td align="right" width="15%">会员:</td> <td align="left">{$arr.email}</td> </tr> <tr> <td align="right" width="18%">支付宝交易号:</td> <td align="left" width="34%">{$arr.alipaid}</td> <td align="right" width="18%">收货人:</td> <td align="left" width="34%">{$arr.shr_name}</td> </tr> <tr> <td align="right" width="18%">联系电话:</td> <td align="left" width="34%">{$arr.shr_tel}</td> <td align="right" width="15%">收货地址:</td> <td align="left">{$arr.shr_province},{$arr.shr_city},{$arr.shr_area},{$arr.shr_address}</td> </tr> <tr> <td align="right" width="18%">商品详情:</td> <td align="left" width="34%"> <ul style="list-style: decimal"> <?php foreach($arr['goods_name'] as $k1=>$v1):?> <li> <span>{$v1};</span> <?php foreach($arr['sttr'] as $k2=>$v2):?> <?php $v2=str_replace('<br/>',';',$v2);?> <?php if($k2==$k1):?> <span>{$v2};</span> <?php endif;?> <?php endforeach;?> <?php foreach($arr['number'] as $k3=>$v3):?> <?php if($k3==$k1):?> <span>购买数量:{$v3}</span> <?php endif;?> <?php endforeach;?> </li> <?php endforeach;?> </ul> </td> <td align="right" width="15%">订单状态:</td> <td align="left"> <?php if($arr['pay_status']==0):?> 待支付 <?php elseif($arr['pay_status']==1 && $arr['post_status']==0):?> 已支付,待发货 <?php elseif($arr['post_status']==1):?> 待收货 <?php else:?> 已确认收货 <?php endif;?> </td> </tr> </tbody> </table> </div> <form action="__SELF__" method="post" name="theForm" enctype="multipart/form-data"> <div class="list-div"> <table width="100%" cellpadding="3" cellspacing="1"> <tr> <th colspan="4">发货信息</th> </tr> <tr> <td class="label">快递公司:</td> <td> <select name="com"> <option value="sf">顺丰</option> <option value="sto">申通</option> <option value="yt">圆通</option> <option value="yd">韵达</option> <option value="tt">天天快递</option> <option value="zto">中通</option> </select> </td> </tr> <tr> <td class="label">快递单号:</td> <td> <input type='text' name='no' value='{$arr.no}' /> </td> </tr> </table> </div> <input type="hidden" name="id" value="{$arr.id}"> <input type="hidden" name="post_status" value=1> <div class="button-div"> <input type="submit" value=" 确定 " /> <input type="reset" value=" 重置 " /> </div> </form> <div class="list-div"> <table width="100%" cellpadding="3" cellspacing="1"> <tbody> <tr> <th colspan="4">地图信息</th> </tr> <tr> <td> <div class="list-div" id="container" style="width:100%;height:300px;"></div> </td> </tr> </tbody> </table> </div> <!-- 创建收货地址地图 --> <script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp"></script> <script> //初始化地图函数 function init() { //定义变量获取地图显示的容器 var option={'zoom':15,};//定义具体的缩放 var map = new qq.maps.Map(document.getElementById("container"),option );//实例化地图核心类初始化地图 // var center=map.panTo(new qq.maps.LatLng(39.916527,116.397128));// 地图的具体位置坐标 //地址解析后的回调函数 var callbacks={ complete:function(result){ map.setCenter(result.detail.location); /* var marker = new qq.maps.Marker({ map:map, position: result.detail.location }); var marker = new qq.maps.Label({ position: result.detail.location, map: map, content:'文本标注' });*/ //实例化覆盖物 var infoWin = new qq.maps.InfoWindow({ map: map }); infoWin.open(); infoWin.setContent('<div style="width:-50px;padding-top:10px;">收货位置</div>'); // 自定义内容 infoWin.setPosition(result.detail.location);//指定具体位置 }, } //实例化地图解析类 geocoder = new qq.maps.Geocoder(callbacks); //调用相关方法将实际地址解析为经纬度坐标 geocoder.getLocation("{$arr.shr_province},{$arr.shr_city},{$arr.shr_area},{$arr.shr_address}"); } //调用 init(); </script>
35.633721
112
0.406428
f76d2f8cea9fe59e456b6d433cea96d1c0286778
936
h
C
System/Library/PrivateFrameworks/ContactsAutocomplete.framework/_CNAutocompleteObservableBuilderBatchingHelper.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/ContactsAutocomplete.framework/_CNAutocompleteObservableBuilderBatchingHelper.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/ContactsAutocomplete.framework/_CNAutocompleteObservableBuilderBatchingHelper.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:17:14 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/ContactsAutocomplete.framework/ContactsAutocomplete * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @class NSArray; @interface _CNAutocompleteObservableBuilderBatchingHelper : NSObject { NSArray* _batches; } @property (nonatomic,readonly) NSArray * batches; //@synthesize batches=_batches - In the implementation block -(NSArray *)batches; -(id)initWithBatchCount:(unsigned long long)arg1 ; -(id)batchedObservables; -(void)addObservable:(id)arg1 toBatchAtIndex:(unsigned long long)arg2 ; @end
37.44
130
0.655983
7be02ca138d0ddde9562318332b20918e30b9115
7,201
css
CSS
public/black/css/theme.css
riadh-benchouche/Portail
6226b9536e82ed96b779da46129dd8ffa6b57bfd
[ "MIT" ]
null
null
null
public/black/css/theme.css
riadh-benchouche/Portail
6226b9536e82ed96b779da46129dd8ffa6b57bfd
[ "MIT" ]
null
null
null
public/black/css/theme.css
riadh-benchouche/Portail
6226b9536e82ed96b779da46129dd8ffa6b57bfd
[ "MIT" ]
null
null
null
.tim-row { margin-bottom: 20px; } .tim-white-buttons { background-color: #777777; } .typography-line { padding-left: 25%; margin-bottom: 35px; position: relative; display: block; width: 100%; } .typography-line span { bottom: 10px; color: #c0c1c2; display: block; font-weight: 400; font-size: 13px; line-height: 13px; left: 0; position: absolute; width: 260px; text-transform: none; } .tim-row { padding-top: 60px; } .tim-row h3 { margin-top: 0; } .offline-doc .page-header { display: flex; align-items: center; } .offline-doc .footer { position: absolute; width: 100%; background: transparent; bottom: 0; color: #fff; z-index: 1; } @media all and (min-width: 992px) { .sidebar .nav>li.active-pro { position: absolute; width: 100%; bottom: 10px; } } .card.card-upgrade .card-category { max-width: 530px; margin: 0 auto; } .noselect { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; } .gbutton { width: 150px; height: 50px; cursor: pointer; border: none; color: rgb(255, 255, 255); font-size: 20px; border-radius: 4px; box-shadow: inset 0px 3px 5px rgba(255,255,255,0.5), 0px 0px 10px rgba(0,0,0,0.15); background: rgb(2,0,36); background: linear-gradient(45deg, rgba(2,0,36,0) 5%, rgba(255,255,255,.5) 6%, rgba(255,255,255,0) 9%, rgba(255,255,255,.5) 10%, rgba(255,255,255,0) 17%, rgba(255,255,255,.5) 19%, rgba(255,255,255,0) 21%); background-size: 150%; background-position: right; transition: 1s; } .gbutton:hover { background-position: left; color: white; box-shadow: inset 0px 3px 5px rgba(255,255,255,1), 0px 0px 10px rgba(0,0,0,0.25); } .gbutton:focus { outline: none; } .glbutton { width: 150px; height: 50px; cursor: pointer; border: none; color: rgb(251, 252, 253); font-size: 20px; border-radius: 4px; box-shadow: inset 0px 3px 5px rgb(0, 0, 0), 0px 0px 10px rgb(28, 28, 28); background: rgb(6, 117, 200); background: linear-gradient(45deg, rgba(0, 0, 0, 0) 5%, rgba(255, 255, 255, 0.5) 6%, rgba(255, 255, 255, 0) 9%, rgba(255,255,255,.5) 10%, rgba(255,255,255,0) 17%, rgba(255,255,255,.5) 19%, rgba(255,255,255,0) 21%); background-size: 150%; background-position: right; transition: 1s; } .glbutton:hover { background-position: left; color: white; box-shadow: inset 0px 3px 5px rgba(255,255,255,1), 0px 0px 10px rgba(0,0,0,0.25); } .glbutton:focus { outline: none; } .footer_area { position: relative; z-index: 1; overflow: hidden; webkit-box-shadow: 0 8px 48px 8px rgba(47, 91, 234, 0.175); box-shadow: 0 8px 48px 8px rgba(47, 91, 234, 0.175); padding:60px; } .footer_area .row { margin-left: -25px; margin-right: -25px; } .footer_area .row .col, .footer_area .row .col-1, .footer_area .row .col-10, .footer_area .row .col-11, .footer_area .row .col-12, .footer_area .row .col-2, .footer_area .row .col-3, .footer_area .row .col-4, .footer_area .row .col-5, .footer_area .row .col-6, .footer_area .row .col-7, .footer_area .row .col-8, .footer_area .row .col-9, .footer_area .row .col-auto, .footer_area .row .col-lg, .footer_area .row .col-lg-1, .footer_area .row .col-lg-10, .footer_area .row .col-lg-11, .footer_area .row .col-lg-12, .footer_area .row .col-lg-2, .footer_area .row .col-lg-3, .footer_area .row .col-lg-4, .footer_area .row .col-lg-5, .footer_area .row .col-lg-6, .footer_area .row .col-lg-7, .footer_area .row .col-lg-8, .footer_area .row .col-lg-9, .footer_area .row .col-lg-auto, .footer_area .row .col-md, .footer_area .row .col-md-1, .footer_area .row .col-md-10, .footer_area .row .col-md-11, .footer_area .row .col-md-12, .footer_area .row .col-md-2, .footer_area .row .col-md-3, .footer_area .row .col-md-4, .footer_area .row .col-md-5, .footer_area .row .col-md-6, .footer_area .row .col-md-7, .footer_area .row .col-md-8, .footer_area .row .col-md-9, .footer_area .row .col-md-auto, .footer_area .row .col-sm, .footer_area .row .col-sm-1, .footer_area .row .col-sm-10, .footer_area .row .col-sm-11, .footer_area .row .col-sm-12, .footer_area .row .col-sm-2, .footer_area .row .col-sm-3, .footer_area .row .col-sm-4, .footer_area .row .col-sm-5, .footer_area .row .col-sm-6, .footer_area .row .col-sm-7, .footer_area .row .col-sm-8, .footer_area .row .col-sm-9, .footer_area .row .col-sm-auto, .footer_area .row .col-xl, .footer_area .row .col-xl-1, .footer_area .row .col-xl-10, .footer_area .row .col-xl-11, .footer_area .row .col-xl-12, .footer_area .row .col-xl-2, .footer_area .row .col-xl-3, .footer_area .row .col-xl-4, .footer_area .row .col-xl-5, .footer_area .row .col-xl-6, .footer_area .row .col-xl-7, .footer_area .row .col-xl-8, .footer_area .row .col-xl-9, .footer_area .row .col-xl-auto { padding-right: 25px; padding-left: 25px; } .single-footer-widget { position: relative; z-index: 1; } .single-footer-widget .copywrite-text a { color: #282b40; font-size: 1rem; } .single-footer-widget .copywrite-text a:hover, .single-footer-widget .copywrite-text a:focus { color: #70b8d6; } .single-footer-widget .widget-title { margin-bottom: 1.5rem; } .single-footer-widget .footer_menu li a { color: #282b40; margin-bottom: 1rem; display: block; font-size: 1rem; } .single-footer-widget .footer_menu li a:hover, .single-footer-widget .footer_menu li a:focus { color: #70b8d6; } .single-footer-widget .footer_menu li:last-child a { margin-bottom: 0; } .footer_social_area { position: relative; z-index: 1; } .footer_social_area a { border-radius: 50%; height: 40px; text-align: center; width: 40px; display: inline-block; background-color: #f5f5ff; line-height: 40px; -webkit-box-shadow: none; box-shadow: none; margin-right: 10px; } .footer_social_area a i { line-height: 36px; } .footer_social_area a:hover, .footer_social_area a:focus { color: #ffffff; } @-webkit-keyframes bi-cycle { 0% { left: 0; } 100% { left: 100%; } } @keyframes bi-cycle { 0% { left: 0; } 100% { left: 100%; } } ol li, ul li { list-style: none; } ol, ul { margin: 0; padding: 0; } ul.checkmark li { font-size: 16px; // modify to test; margin-bottom: 1em; list-style-type: none; padding: .25em 0 0 2.5em; position: relative; } ul.checkmark li :before { content: " "; display: block ; border: solid .8em orange; border-radius: .8em; height: 0; width: 0; position: absolute; left: .5em; top: 40%; margin-top: -.5em ; } ul.checkmark li:after { content: " "; display: block; width: .3em; height: .6em; border: solid #fff; border-width: 0 .2em .2em 0; position: absolute; left: 1em; top: 40%; margin-top: -.2em; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg) ; }
21.495522
218
0.636856
5c6c9bf76a1531e06283b7bd69ed6db35b7c7f10
1,098
css
CSS
src/components/editor/editor.css
jeric17/arv
07c7d2737c3945d89146f573ecbd361a7c1200a4
[ "MIT" ]
25
2019-02-13T01:37:47.000Z
2022-02-15T08:01:41.000Z
src/components/editor/editor.css
jeric17/arv
07c7d2737c3945d89146f573ecbd361a7c1200a4
[ "MIT" ]
7
2019-03-13T05:36:18.000Z
2022-02-26T02:00:46.000Z
src/components/editor/editor.css
jeric17/arv
07c7d2737c3945d89146f573ecbd361a7c1200a4
[ "MIT" ]
3
2019-10-10T15:15:15.000Z
2020-05-25T04:10:41.000Z
:host, .root, .editor { display: block; width: 100%; height: 100%; --icon-color: #333; } .root { position: relative; } .editor { overflow-y: scroll; border-radius: var(--radius); border: 1px solid #efefef; padding: 1em; outline: none; box-sizing: border-box; } .headingList { display: flex; flex-direction: column; width: 120px; } .control { border: 1px solid #efefef; display: flex; min-height: 33px; flex-wrap: wrap; display: flex; flex-shrink: 0; } .wrapper { position: absolute; top: 0; left: 0; background-color: rgba(255, 255, 255, 0.2); z-index: 1; height: 100%; width: 100%; } .input { opacity: 0; opacity: 0; display: block; width: 33px; height: 33px; position: absolute; } .inputWrapper { background-color: #f5f5f5; cursor: pointer; position: relative; display: flex; align-items: center; overflow: hidden; width: 33px; height: 33px; --default-icon-color: #333; transition: all 0.3s; } .inputWrapper:hover { background-color: #cdcdcd; } .editor img { max-width: 100%; display: block; }
13.898734
45
0.631148
fb27c6f3f4b4e8e3849bccfe1d2082222ad2ac1a
660
go
Go
cluster-manager/clusternodeclient.go
zl14917/MastersProject
e532b396e046db820091e9e9e52b6a092029f65f
[ "MIT" ]
null
null
null
cluster-manager/clusternodeclient.go
zl14917/MastersProject
e532b396e046db820091e9e9e52b6a092029f65f
[ "MIT" ]
null
null
null
cluster-manager/clusternodeclient.go
zl14917/MastersProject
e532b396e046db820091e9e9e52b6a092029f65f
[ "MIT" ]
null
null
null
package cluster_manager import ( "github.com/zl14917/MastersProject/api/cluster-services" "google.golang.org/grpc" ) type ClusterNodeClient struct { NetworkAddress string *grpc.ClientConn cluster_services.ClusterNodeClient } func NewClusterNodeClient(address string) (*ClusterNodeClient, error) { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { return nil, err } client := cluster_services.NewClusterNodeClient(conn) return &ClusterNodeClient{ NetworkAddress: address, ClientConn: conn, ClusterNodeClient: client, }, nil } func (c *ClusterNodeClient) Disconnect() error { return c.ClientConn.Close() }
20
71
0.75
39765348efa580c81fa43e433a89c7274fc1491d
256
html
HTML
l2j_datapack/dist/game/data/scripts/ai/npc/Alarm/32367-184_10.html
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
null
null
null
l2j_datapack/dist/game/data/scripts/ai/npc/Alarm/32367-184_10.html
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
38
2018-02-06T17:11:29.000Z
2018-06-05T20:47:59.000Z
l2j_datapack/dist/game/data/scripts/ai/npc/Alarm/32367-184_10.html
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
null
null
null
<html><body>Alarm System:<br> ########################<br> Enter the passcode for communication.<br> Passcode : ****<br> ########################<br> Validation has failed. <br> <br> <a action="bypass -h Quest Alarm 2">Re-enter passcode.</a> </body></html>
28.444444
58
0.550781
5c89c779369bc65e5ca9e88f5b6df99711a767fa
385
c
C
tests/other/id_prefix.c
Omcsesz/json_schema_to_c
f3f01740edb016cbde8f53d9c61e55f846771981
[ "MIT" ]
2
2021-08-31T19:33:25.000Z
2021-11-13T19:22:21.000Z
tests/other/id_prefix.c
Omcsesz/json_schema_to_c
f3f01740edb016cbde8f53d9c61e55f846771981
[ "MIT" ]
48
2020-04-28T09:46:58.000Z
2021-08-18T22:30:52.000Z
tests/other/id_prefix.c
Omcsesz/json_schema_to_c
f3f01740edb016cbde8f53d9c61e55f846771981
[ "MIT" ]
2
2020-08-12T07:50:58.000Z
2021-08-17T12:00:10.000Z
#include "id_prefix.parser.h" #include <stdio.h> #include <assert.h> int main(int argc, char** argv){ (void)argc; (void)argv; /* We are mainly interested in the type name and the parse functio name.*/ AnInteresting_schema1d_t the_object = {}; assert(!json_parse_AnInteresting_schema1d("{\"a\": 1}", &the_object)); assert(the_object.a == 1); return 0; }
22.647059
78
0.65974
f0430cff558b5fef1d911f57ac7078cdb43ce8f8
5,307
js
JavaScript
src/auth/facebookHandler.js
QScore/qscore-serverless
c0ea737611793860fc5248c97f126cc384bd5dcd
[ "Unlicense" ]
null
null
null
src/auth/facebookHandler.js
QScore/qscore-serverless
c0ea737611793860fc5248c97f126cc384bd5dcd
[ "Unlicense" ]
null
null
null
src/auth/facebookHandler.js
QScore/qscore-serverless
c0ea737611793860fc5248c97f126cc384bd5dcd
[ "Unlicense" ]
null
null
null
import https from 'https' import querystring from 'querystring' import CognitoIdentityServiceProvider from 'aws-sdk/clients/cognitoidentityserviceprovider' const region = process.env.AWS_REGION const userPoolId = process.env.COGNITO_USER_POOL_ID const cognito = new CognitoIdentityServiceProvider({ region: region }); export const facebookLoginHandler = async (event, context, callback) => { const json = querystring.parse(event.body) const accessToken = json.token try { const fbInfo = await getFacebookInfo(accessToken) console.log(fbInfo) const clientId = process.env.COGNITO_APP_CLIENT_ID const userId = fbInfo.id const password = generatePassword(30) const email = fbInfo.email ? fbInfo.email : `${userId}@test.qscore` const avatar = fbInfo.picture.data.url const userExists = await checkUserExists(email, userId) if (userExists) { await setPassword(email, password) } else { const tempPassword = "L5oKeM0mmG1SIa" await createUser({ clientId: clientId, username: email, email: email, password: tempPassword, avatar: avatar }) await setPassword(email, password) await addUserToGroup("Facebook", email) } const body = { username: email, password: password } console.log(`Finished, username: ${email}, password: ${password}`) return { statusCode: 200, body: JSON.stringify(body) } } catch (error) { console.log(error.stack) return { statusCode: 500, body: error.stack } } } function addUserToGroup(groupName, username) { const params = { GroupName: groupName, UserPoolId: userPoolId, Username: username }; return new Promise((resolve, reject) => { cognito.adminAddUserToGroup(params, function (err, data) { if (err) reject(err) else resolve(true) }); }) } function setPassword(username, password) { const params = { Username: username, Password: password, UserPoolId: userPoolId, Permanent: true }; return new Promise((resolve, reject) => { cognito.adminSetUserPassword(params, function (err, data) { if (err) reject(err) else resolve(true) }); }) } function checkUserExists(username) { const params = { UserPoolId: userPoolId, Username: username }; return new Promise((resolve, reject) => { cognito.adminGetUser(params, (err, data) => { if (err) resolve(false) else resolve(true) }) }) } function createUser({ username, email, password, avatar }) { const params = { UserPoolId: userPoolId, MessageAction: 'SUPPRESS', TemporaryPassword: password, Username: username, //username, UserAttributes: [ { Name: 'email', Value: email } ] }; return new Promise((resolve, reject) => { cognito.adminCreateUser(params, function (err, data) { if (err) { console.log(err) reject(err) } else { resolve(data) } }) }) } function generatePassword(passwordLength) { var numberChars = "0123456789"; var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var lowerChars = "abcdefghijklmnopqrstuvwxyz"; var allChars = numberChars + upperChars + lowerChars; var randPasswordArray = Array(passwordLength); randPasswordArray[0] = numberChars; randPasswordArray[1] = upperChars; randPasswordArray[2] = lowerChars; randPasswordArray = randPasswordArray.fill(allChars, 3); return shuffleArray(randPasswordArray.map(function (x) { return x[Math.floor(Math.random() * x.length)] })).join(''); } function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } function getFacebookInfo(token) { const url = `https://graph.facebook.com/me?fields=id,name,email,picture&access_token=${token}` return new Promise((resolve, reject) => { https.get(url, (res) => { var body = '' res.on('data', (chunk) => { body += chunk }) res.on('end', () => { try { var json = JSON.parse(body); console.log('id', json.id); console.log('name', json.name); console.log('email', json.email); console.log('url', json.picture.data.url) console.log('success'); resolve(json) } catch (error) { console.log('error', error); reject(error) } }); }).on('error', function (error) { console.log(error) reject(error) }) }) }
30.153409
121
0.552666
d2cc1ae13c833a61738885532575d7e6eff40582
1,153
php
PHP
application/views/includes/vue_templates.php
PBGyawali/hamro-store
28db1fdf19ba606a27b8abb1129370f8df477f60
[ "MIT" ]
null
null
null
application/views/includes/vue_templates.php
PBGyawali/hamro-store
28db1fdf19ba606a27b8abb1129370f8df477f60
[ "MIT" ]
null
null
null
application/views/includes/vue_templates.php
PBGyawali/hamro-store
28db1fdf19ba606a27b8abb1129370f8df477f60
[ "MIT" ]
null
null
null
<!--modal of register, forgot password, enter code, reset password--> <template id="rg-fp-modal"> <transition enter-active-class="animated fadeInLeft" leave-active-class="animated rollOut"><div class="modal d-md-block mt-5" tabindex="-1" role="dialog"> <div class="modal-dialog dialog-lg" role="document"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title"><slot name="head"></slot></h5> <button type="button" class="close text-white" @click="$emit('close')"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <slot name="body"></slot> </div> <div class="modal-footer"> <slot name="foot"></slot> </div> </div> </div> </div></transition> </template> <!--success alert of register and forgot password--> <template id="success-alert"> <transition enter-active-class="animated fadeIn" leave-active-class="animated fadeOut"> <p class='alert alert-success position-absolute w-50' style="z-index:1">{{message}}</p> </transition> </template>
33.911765
105
0.621856
3eee82740c1b123bc1cef73ee66414658a286b93
13,269
kt
Kotlin
src/main/kotlin/at/syntaxerror/json5/JSONParser.kt
adamko-dev/json5-kotlin
68f910241b8b5a913c9a909da86451ccdfde2dee
[ "MIT" ]
1
2021-12-19T23:28:00.000Z
2021-12-19T23:28:00.000Z
src/main/kotlin/at/syntaxerror/json5/JSONParser.kt
adamko-dev/json5-kotlin
68f910241b8b5a913c9a909da86451ccdfde2dee
[ "MIT" ]
2
2021-12-20T08:42:31.000Z
2022-01-11T08:27:52.000Z
src/main/kotlin/at/syntaxerror/json5/JSONParser.kt
adamko-dev/json5-kotlin
68f910241b8b5a913c9a909da86451ccdfde2dee
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2021 SyntaxError404 * * 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 NON-INFRINGEMENT. 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. */ package at.syntaxerror.json5 import at.syntaxerror.json5.JSONException.SyntaxError import java.io.BufferedReader import java.io.Reader import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonPrimitive /** * A JSONParser is used to convert a source string into tokens, which then are used to construct * [JSONObjects][DecodeJson5Object] and [JSONArrays][DecodeJson5Array] * * The reader is not [closed][Reader.close] * * @author SyntaxError404 */ class JSONParser( reader: Reader, private val j5: Json5Module, ) { private val reader: Reader = if (reader.markSupported()) reader else BufferedReader(reader) /** whether the end of the file has been reached */ private var eof: Boolean = false /** whether the current character should be re-read */ private var back: Boolean = false /** the absolute position in the string */ private var index: Long = -1 /** the relative position in the line */ private var character: Long = 0 /** the line number */ private var line: Long = 1 /** the previous character */ private var previous: Char = Char.MIN_VALUE /** the current character */ private var current: Char = Char.MIN_VALUE private val nextCleanToDelimiters: String = ",]}" private fun more(): Boolean { return if (back || eof) { back && !eof } else peek().code > 0 } /** Forces the parser to re-read the last character */ fun back() { back = true } private fun peek(): Char { if (eof) { return Char.MIN_VALUE } val c: Int try { reader.mark(1) c = reader.read() reader.reset() } catch (e: Exception) { throw createSyntaxException("Could not peek from source", e) } return if (c == -1) Char.MIN_VALUE else c.toChar() } private operator fun next(): Char { if (back) { back = false return current } val c: Int = try { reader.read() } catch (e: Exception) { throw createSyntaxException("Could not read from source", e) } if (c < 0) { eof = true return Char.MIN_VALUE } previous = current current = c.toChar() index++ if (isLineTerminator(current) && (current != '\n' || previous != '\r')) { line++ character = 0 } else { character++ } return current } // https://262.ecma-international.org/5.1/#sec-7.3 private fun isLineTerminator(c: Char): Boolean { return when (c) { '\n', '\r', '\u2028', '\u2029' -> true else -> false } } // https://spec.json5.org/#white-space private fun isWhitespace(c: Char): Boolean { return when (c) { '\t', '\n', '\u000B', Json5EscapeSequence.FormFeed.char, '\r', ' ', '\u00A0', '\u2028', '\u2029', '\uFEFF' -> true else -> // Unicode category "Zs" (space separators) Character.getType(c) == Character.SPACE_SEPARATOR.toInt() } } private fun nextMultiLineComment() { while (true) { val n = next() if (n == '*' && peek() == '/') { next() return } } } private fun nextSingleLineComment() { while (true) { val n = next() if (isLineTerminator(n) || n.code == 0) { return } } } /** * Reads until encountering a character that is not a whitespace according to the * [JSON5 Specification](https://spec.json5.org/#white-space) * * @return a non-whitespace character, or `0` if the end of the stream has been reached */ fun nextClean(): Char { while (true) { if (!more()) { throw createSyntaxException("Unexpected end of data") } val n = next() if (n == '/') { when (peek()) { '*' -> { next() nextMultiLineComment() } '/' -> { next() nextSingleLineComment() } else -> { return n } } } else if (!isWhitespace(n)) { return n } } } private fun nextCleanTo(delimiters: String = nextCleanToDelimiters): String { val result = StringBuilder() while (true) { if (!more()) { throw createSyntaxException("Unexpected end of data") } val n = nextClean() if (delimiters.indexOf(n) > -1 || isWhitespace(n)) { back() break } result.append(n) } return result.toString() } private fun deHex(c: Char): Int? { return when (c) { in '0'..'9' -> c - '0' in 'a'..'f' -> c - 'a' + 0xA in 'A'..'F' -> c - 'A' + 0xA else -> null } } private fun unicodeEscape(member: Boolean, part: Boolean): Char { var value = "" var codepoint = 0 for (i in 0..3) { val n = next() value += n val hex = deHex(n) ?: throw createSyntaxException("Illegal unicode escape sequence '\\u$value' in ${if (member) "key" else "string"}") codepoint = codepoint or (hex shl (3 - i shl 2)) } if (member && !isMemberNameChar(codepoint.toChar(), part)) { throw createSyntaxException("Illegal unicode escape sequence '\\u$value' in key") } return codepoint.toChar() } private fun checkSurrogate(hi: Char, lo: Char) { if (j5.options.allowInvalidSurrogates) { return } if (!Character.isHighSurrogate(hi) || !Character.isLowSurrogate(lo)) { return } if (!Character.isSurrogatePair(hi, lo)) { throw createSyntaxException( String.format( "Invalid surrogate pair: U+%04X and U+%04X", hi, lo ) ) } } // https://spec.json5.org/#prod-JSON5String private fun nextString(quote: Char): String { val result = StringBuilder() var value: String var codepoint: Int var n = 0.toChar() var prev: Char while (true) { if (!more()) { throw createSyntaxException("Unexpected end of data") } prev = n n = next() if (n == quote) { break } if (isLineTerminator(n) && n.code != 0x2028 && n.code != 0x2029) { throw createSyntaxException("Unescaped line terminator in string") } if (n == '\\') { n = next() if (isLineTerminator(n)) { if (n == '\r' && peek() == '\n') { next() } // escaped line terminator/ line continuation continue } else { when (n) { '\'', '"', '\\' -> { result.append(n) continue } 'b' -> { result.append('\b') continue } 'f' -> { result.append(Json5EscapeSequence.FormFeed.char) continue } 'n' -> { result.append('\n') continue } 'r' -> { result.append('\r') continue } 't' -> { result.append('\t') continue } 'v' -> { result.append(0x0B.toChar()) continue } '0' -> { val p = peek() if (p.isDigit()) { throw createSyntaxException("Illegal escape sequence '\\0$p'") } result.append(0.toChar()) continue } 'x' -> { value = "" codepoint = 0 var i = 0 while (i < 2) { n = next() value += n val hex = deHex(n) ?: throw createSyntaxException("Illegal hex escape sequence '\\x$value' in string") codepoint = codepoint or (hex shl (1 - i shl 2)) ++i } n = codepoint.toChar() } 'u' -> n = unicodeEscape(member = false, part = false) else -> if (n.isDigit()) { throw SyntaxError("Illegal escape sequence '\\$n'") } } } } checkSurrogate(prev, n) result.append(n) } return result.toString() } private fun isMemberNameChar(n: Char, isNotEmpty: Boolean): Boolean { if (n == '$' || n == '_' || n.code == 0x200C || n.code == 0x200D) { return true } return when (n.category) { CharCategory.UPPERCASE_LETTER, CharCategory.LOWERCASE_LETTER, CharCategory.TITLECASE_LETTER, CharCategory.MODIFIER_LETTER, CharCategory.OTHER_LETTER, CharCategory.LETTER_NUMBER -> return true CharCategory.NON_SPACING_MARK, CharCategory.COMBINING_SPACING_MARK, CharCategory.DECIMAL_DIGIT_NUMBER, CharCategory.CONNECTOR_PUNCTUATION -> isNotEmpty else -> return false } } /** * Reads a member name from the source according to the * [JSON5 Specification](https://spec.json5.org/#prod-JSON5MemberName) */ fun nextMemberName(): String { val result = StringBuilder() var prev: Char var n = next() if (n == '"' || n == '\'') { return nextString(n) } back() n = 0.toChar() while (true) { if (!more()) { throw createSyntaxException("Unexpected end of data") } val isNotEmpty = result.isNotEmpty() prev = n n = next() if (n == '\\') { // unicode escape sequence n = next() if (n != 'u') { throw createSyntaxException("Illegal escape sequence '\\$n' in key") } n = unicodeEscape(true, isNotEmpty) } else if (!isMemberNameChar(n, isNotEmpty)) { back() break } checkSurrogate(prev, n) result.append(n) } if (result.isEmpty()) { throw createSyntaxException("Empty key") } return result.toString() } /** * Reads a value from the source according to the * [JSON5 Specification](https://spec.json5.org/#prod-JSON5Value) */ fun nextValue(): JsonElement { when (val n = nextClean()) { '"', '\'' -> { val string = nextString(n) return JsonPrimitive(string) } '{' -> { back() return j5.objectDecoder.decode(this) } '[' -> { back() return j5.arrayDecoder.decode(this) } } back() val string = nextCleanTo() return when { string == "null" -> JsonNull PATTERN_BOOLEAN.matches(string) -> JsonPrimitive(string == "true") // val bigint = BigInteger(string) // return bigint PATTERN_NUMBER_INTEGER.matches(string) -> JsonPrimitive(string.toLong()) PATTERN_NUMBER_FLOAT.matches(string) || PATTERN_NUMBER_NON_FINITE.matches(string) -> { try { JsonPrimitive(string.toDouble()) } catch (e: NumberFormatException) { throw createSyntaxException("could not parse number '$string'") } } PATTERN_NUMBER_HEX.matches(string) -> { val hex = string.uppercase().split("0X").joinToString("") JsonPrimitive(hex.toLong(16)) } else -> throw JSONException("Illegal value '$string'") } } fun createSyntaxException(message: String, cause: Throwable? = null): SyntaxError = SyntaxError("$message, at index $index, character $character, line $line]", cause) companion object { private val PATTERN_BOOLEAN = Regex("true|false") private val PATTERN_NUMBER_FLOAT = Regex("[+-]?((0|[1-9]\\d*)(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?") private val PATTERN_NUMBER_INTEGER = Regex("[+-]?(0|[1-9]\\d*)") private val PATTERN_NUMBER_HEX = Regex("[+-]?0[xX][0-9a-fA-F]+") private val PATTERN_NUMBER_NON_FINITE = Regex("[+-]?(Infinity|NaN)") } }
28.971616
123
0.543296
81d43dc50cb1e413a11e43be25d7625930a64a4e
5,616
html
HTML
exercicios/alinetattoo/index.html
jarbassouza/html-css
d104e1544c224f1c1524497777287cc2ac60c31b
[ "MIT" ]
null
null
null
exercicios/alinetattoo/index.html
jarbassouza/html-css
d104e1544c224f1c1524497777287cc2ac60c31b
[ "MIT" ]
null
null
null
exercicios/alinetattoo/index.html
jarbassouza/html-css
d104e1544c224f1c1524497777287cc2ac60c31b
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Aline Tattoo Studio</title> <link rel="shortcut icon" href="imagens/favicon.ico" type="image/x-icon" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> <link rel="stylesheet" href="estilo/style.css" /> <script src="scripts/script.js" defer ></script> </head> <body> <main> <header class="header" id="header"> <div class="btn"> <button id="btnDark"> <img src="imagens/darkmoon.png" alt="sol" /> </button> </div> <nav class="menu"> <a href="index.html" rel="next" target="_self">Home</a> <a href="dicas.html" rel="next" target="_self">Dicas</a> <a href="galeria.html" rel="next" target="_self">Galeria</a> <a href="politica.html" rel="next" target="_self">Politica</a> </nav> <picture> <source media="(max-width: 670px)" srcset="imagens/logo.png" /> <img src="imagens/logo.png" alt="Aline Tattoo" /> </picture> <p> Faça a sua tattoo com quem entende da arte e tem experiência. </p> </header> <div class="title-highlights"> <h1>Destaques</h1> </div> <section class="highlights"> <div class="container"> <div class="card"> <div class="item"> <img src="imagens/tattoo1.jpg" alt="Tattoo1" /> <span class="card-text" ><h3>A mulher com o caração na mão</h3></span> </div> </div> <div class="card"> <div class="item"> <img src="imagens/tattoo2.jpg" alt="Tattoo2" /> <span class="card-text" ><h3>A coruja que tudo ver</h3></span> </div> </div> <div class="card"> <div class="item"> <img src="imagens/tattoo3.jpg" alt="Tattoo3" /> <span class="card-text" ><h3>A vida imita a arte</h3></span> </div> </div> <div class="card"> <div class="item"> <img src="imagens/tattoo4.jpg" alt="Tattoo4" /> <span class="card-text" ><h3>O Elefante e o Escaravelho</h3></span> </div> </div> <div class="card"> <div class="item"> <img src="imagens/tattoo5.jpg" alt="Tattoo5" /> <span class="card-text" ><h3>O Rei Leão</h3></span> </div> </div> <div class="card"> <div class="item"> <img src="imagens/tattoo6.jpg" alt="Tattoo6" /> <span class="card-text" ><h3>A Lenda de Toy Story</h3></span> </div> </div> </div> </section> <!--A Tatuadora--> <div class="title-highlights"> <h1>Sobre Aline</h1> </div> <div class="tattoo-artist"> <div class="photo-aline"> <picture> <source media="(max-width: 480px)" srcset="imagens/alinetattoo1.png" /> <img src="imagens/alinetattoo.png" alt="Aline Tattoo" /> </picture> </div> <div class="aline-bio"> <p> Aline Souza é uma tatuadora capixaba erradicada em São Paulo a 5 anos, e ativa no universo da tatuagem a 7, Aline pertence a nova safra de tatuadoras que possuem uma ideia diferenciada sobre como ser e atuar neste universo, adota os grandes mestres como seus mentores e torna-se discípula destes mestres, a disciplina e o olhar clínico fazem com que as obras criadas por esses mestres torne-se referência para a criação de seus trabalhos cotidianos. </p> <p> Sua paixão é a arte Oriental, mas encontrou na cultura Polinésia uma forma de expandir seus conhecimentos e mostrar a precisão e criatividade de seus traços fortes e precisos. </p> </div> </div> <!--Como Chegar--> <div class="title-highlights"> <h1>Como Chegar</h1> </div> <div class="howtoget"> <div class="howtoget-map"> <iframe class="googlemap" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3744.130889669483!2d-40.27716628508086!3d-20.211881286446513!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xb81f0d749e671b%3A0x7f9ede2020da8b01!2sAline%20Tattoo!5e0!3m2!1spt-BR!2sbr!4v1645135598027!5m2!1spt-BR!2sbr" width="900" height="400" style="border: 1px" allowfullscreen="" loading="lazy" ></iframe> </div> </div> <!--Rodape--> <footer> <div class="contact-links"> <div class="contact-social"> <a href="https://www.facebook.com/Alinetattoo1" target="_blank"> <img src="imagens/face.png" alt="Facebook" /></a> <a href="https://api.whatsapp.com/send?phone=5527993126531" target="_blank" > <img src="imagens/whatsapp.png" alt="”Whatsapp”" /> </a> <a href="https://www.instagram.com/aline.tattoo/" target="_blank"> <img src="imagens/instagram.png" alt="Instagram" /></a> </div> </div> <p>© Aline Tattoo - Todos os direitos reservados</p> </footer> <button class="btnup"> <a href="#header"><i class="material-icons">expand_less</i></a> </button> </main> <div class="modal-promo"> <div class="modal"> <div class="button-modal">x</div> <div class="img-modal"> <img src="imagens/img-modal.png" alt="Imagem do Modal"> </div> <div class="title-modal"> <h2>Promoção !!!</h2> </div> <div class="announcement"> <h3>Faça duas tatuagens de 5cm²</h3> <h3>Pelo Preço de uma de 10cm²</h3> <p>*promoção valida até 01-03-2022</p> </div> </div> </div> </body> </html>
28.221106
285
0.593127
9fc7127cc24eff1ca31d6acf45d80c67d2cd652d
9,078
lua
Lua
filehandler.lua
okhowang/wireshark-emmylua
ea2a2e2175a8a0c9f7f47d32c7306c9d19eed304
[ "MIT" ]
1
2021-11-02T09:21:51.000Z
2021-11-02T09:21:51.000Z
filehandler.lua
okhowang/wireshark-emmylua
ea2a2e2175a8a0c9f7f47d32c7306c9d19eed304
[ "MIT" ]
null
null
null
filehandler.lua
okhowang/wireshark-emmylua
ea2a2e2175a8a0c9f7f47d32c7306c9d19eed304
[ "MIT" ]
null
null
null
---@class FileHandler ---A FileHandler object, created by a call to FileHandler.new(arg1, arg2, …​). The FileHandler object lets you create a file-format reader, or writer, or both, by setting your own read_open/read or write_open/write functions. --- ---Since: 1.11.3 ---@field read_open function Mode: Assign only. The Lua function to be called when Wireshark opens a file for reading. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfo object The purpose of the Lua function set to this read_open field is to check if the file Wireshark is opening is of its type, for example by checking for magic numbers or trying to parse records in the file, etc. The more can be verified the better, because Wireshark tries all file readers until it finds one that accepts the file, so accepting an incorrect file prevents other file readers from reading their files. The called Lua function should return true if the file is its type (it accepts it), false if not. The Lua function must also set the File offset position (using file:seek()) to where it wants it to be for its first read() call. ---@field read function Mode: Assign only. The Lua function to be called when Wireshark wants to read a packet from the file. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfo object A FrameInfo object The purpose of the Lua function set to this read field is to read the next packet from the file, and setting the parsed/read packet into the frame buffer using FrameInfo.data = foo or FrameInfo:read_data(file, frame.captured_length). The called Lua function should return the file offset/position number where the packet begins, or false if it hit an error. The file offset will be saved by Wireshark and passed into the set seek_read() Lua function later. ---@field seek_read function Mode: Assign only. The Lua function to be called when Wireshark wants to read a packet from the file at the given offset. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfo object A FrameInfo object The file offset number previously set by the read() function call The called Lua function should return true if the read was successful, or false if it hit an error. Since 2.4.0, a number is also acceptable to signal success, this allows for reuse of FileHandler:read: local function fh_read(file, capture, frame) ... end myfilehandler.read = fh_read function myfilehandler.seek_read(file, capture, frame, offset) if not file:seek("set", offset) then -- Seeking failed, return failure return false end -- Now try to read one frame return fh_read(file, capture, frame) end ---@field read_close function Mode: Assign only. The Lua function to be called when Wireshark wants to close the read file completely. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfo object It is not necessary to set this field to a Lua function - FileHandler can be registered without doing so - it is available in case there is memory/state to clear in your script when the file is closed. ---@field seq_read_close function Mode: Assign only. The Lua function to be called when Wireshark wants to close the sequentially-read file. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfo object It is not necessary to set this field to a Lua function - FileHandler can be registered without doing so - it is available in case there is memory/state to clear in your script when the file is closed for the sequential reading portion. After this point, there will be no more calls to read(), only seek_read(). ---@field can_write_encap function Mode: Assign only. The Lua function to be called when Wireshark wants to write a file, by checking if this file writer can handle the wtap packet encapsulation(s). When later called by Wireshark, the Lua function will be given a Lua number, which matches one of the encapsulations in the Lua wtap_encaps table. This might be the wtap_encap.PER_PACKET number, meaning the capture contains multiple encapsulation types, and the file reader should only return true if it can handle multiple encap types in one file. The function will then be called again, once for each encap type in the file, to make sure it can write each one. If the Lua file writer can write the given type of encapsulation into a file, then it returns the boolean true, else false. ---@field write_open function Mode: Assign only. The Lua function to be called when Wireshark opens a file for writing. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfoConst object The purpose of the Lua function set to this write_open field is similar to the read_open callback function: to initialize things necessary for writing the capture to a file. For example, if the output file format has a file header, then the file header should be written within this write_open function. The called Lua function should return true on success, or false if it hit an error. Also make sure to set the FileHandler.write (and potentially FileHandler.write_finish) functions before returning true from this function. ---@field write function Mode: Assign only. The Lua function to be called when Wireshark wants to write a packet to the file. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfoConst object A FrameInfoConst object of the current frame/packet to be written The purpose of the Lua function set to this write field is to write the next packet to the file. The called Lua function should return true on success, or false if it hit an error. ---@field write_finish function Mode: Assign only. The Lua function to be called when Wireshark wants to close the written file. When later called by Wireshark, the Lua function will be given: A File object A CaptureInfoConst object It is not necessary to set this field to a Lua function - FileHandler can be registered without doing so - it is available in case there is memory/state to clear in your script when the file is closed. ---@field type any Mode: Retrieve only. The internal file type. This is automatically set with a new number when the FileHandler is registered. ---@field extensions any Mode: Retrieve or assign. One or more semicolon-separated file extensions that this file type usually uses. For readers using heuristics to determine file type, Wireshark will try the readers of the file’s extension first, before trying other readers. But ultimately Wireshark tries all file readers for any file extension, until it finds one that accepts the file. (Since 2.6) For writers, the first extension is used to suggest the default file extension. ---@field writing_must_seek boolean Mode: Retrieve or assign. True if the ability to seek is required when writing this file format, else false. This will be checked by Wireshark when writing out to compressed file formats, because seeking is not possible with compressed files. Usually a file writer only needs to be able to seek if it needs to go back in the file to change something, such as a block or file length value earlier in the file. ---@field writes_name_resolution boolean Mode: Retrieve or assign. True if the file format supports name resolution records, else false. ---@field supported_comment_types any Mode: Retrieve or assign. Set to the bit-wise OR’ed number representing the type of comments the file writer supports writing, based on the numbers in the wtap_comments table. FileHandler = {} ---Creates a new FileHandler ---@param name string The name of the file type, for display purposes only. E.g., "Wireshark - pcapng" ---@param shortname string The file type short name, used as a shortcut in various places. E.g., "pcapng". Note: The name cannot already be in use. ---@param description string Descriptive text about this file format, for display purposes only ---@param type string The type of FileHandler, "r"/"w"/"rw" for reader/writer/both, include "m" for magic, "s" for strong heuristic ---@return FileHandler The newly created FileHandler object function FileHandler.new(name, shortname, description, type) end ---Generates a string of debug info for the FileHandler ---@return string String of debug information. function FileHandler:__tostring() end ---Register the FileHandler into Wireshark/tshark, so they can read/write this new format. All functions and settings must be complete before calling this registration function. This function cannot be called inside the reading/writing callback functions. ---@param filehandler FileHandler The FileHandler object to be registered ---@return number the new type number for this file reader/write function register_filehandler(filehandler) end ---Deregister the FileHandler from Wireshark/tshark, so it no longer gets used for reading/writing/display. This function cannot be called inside the reading/writing callback functions. ---@param filehandler FileHandler The FileHandler object to be deregistered function deregister_filehandler(filehandler) end
201.733333
858
0.794668
4ef6c1cc8fe7e1ad66f5b16d8df5e027f92b8655
1,203
sql
SQL
coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/current/5.0/tables/KC_TBL_IACUC_PROTOCOL_SUBMISSION.sql
smith750/kc
e411ed1a4f538a600e04f964a2ba347f5695837e
[ "ECL-2.0" ]
null
null
null
coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/current/5.0/tables/KC_TBL_IACUC_PROTOCOL_SUBMISSION.sql
smith750/kc
e411ed1a4f538a600e04f964a2ba347f5695837e
[ "ECL-2.0" ]
null
null
null
coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/current/5.0/tables/KC_TBL_IACUC_PROTOCOL_SUBMISSION.sql
smith750/kc
e411ed1a4f538a600e04f964a2ba347f5695837e
[ "ECL-2.0" ]
null
null
null
CREATE TABLE IACUC_PROTOCOL_SUBMISSION ( IACUC_PROTOCOL_SUBMISSION_ID NUMBER(12,0) NOT NULL, PROTOCOL_NUMBER VARCHAR2(20) NOT NULL, SEQUENCE_NUMBER NUMBER(4,0) NOT NULL, VERSION_NUMBER NUMBER(4,0), SUBMISSION_NUMBER NUMBER(4,0) NOT NULL, SCHEDULE_ID VARCHAR2(10), COMMITTEE_ID VARCHAR2(15), PROTOCOL_ID DECIMAL(12) NOT NULL, SCHEDULE_ID_FK DECIMAL(12), COMMITTEE_ID_FK DECIMAL(12), SUBMISSION_TYPE_CODE VARCHAR2(3) NOT NULL, SUBMISSION_TYPE_QUAL_CODE NUMBER(3,0), PROTOCOL_REVIEW_TYPE_CODE NUMBER(3,0) NOT NULL, SUBMISSION_STATUS_CODE NUMBER(3,0) NOT NULL, SUBMISSION_DATE DATE NOT NULL, COMMENTS VARCHAR2(2000), YES_VOTE_COUNT NUMBER(3,0), NO_VOTE_COUNT NUMBER(3,0), ABSTAINER_COUNT NUMBER(3,0), VOTING_COMMENTS VARCHAR2(2000), RECUSED_COUNT NUMBER(3,0), IS_BILLABLE VARCHAR2(1) DEFAULT 'N' NOT NULL, COMM_DECISION_MOTION_TYPE_CODE VARCHAR2(3), UPDATE_TIMESTAMP DATE, UPDATE_USER VARCHAR2(60), VER_NBR NUMBER(8,0) DEFAULT 1 NOT NULL, OBJ_ID VARCHAR2(36) NOT NULL) / ALTER TABLE IACUC_PROTOCOL_SUBMISSION ADD CONSTRAINT PK_IACUC_PROTOCOL_SUBMISSION PRIMARY KEY (IACUC_PROTOCOL_SUBMISSION_ID) /
34.371429
55
0.748961
d2527c44302db5d57f2980c3ec013038898e526a
1,730
php
PHP
views/compras/_form.php
guillez/escuela
d12a923968d6d161f4a0c2a5fa61a7ec36d04528
[ "BSD-3-Clause" ]
null
null
null
views/compras/_form.php
guillez/escuela
d12a923968d6d161f4a0c2a5fa61a7ec36d04528
[ "BSD-3-Clause" ]
null
null
null
views/compras/_form.php
guillez/escuela
d12a923968d6d161f4a0c2a5fa61a7ec36d04528
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use app\models\Proveedores; use yii\jui\DatePicker; /* @var $this yii\web\View */ /* @var $model app\models\Compras */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="compras-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'idproveedor')->dropDownList( ArrayHelper::map(Proveedores::find()->all(),'id','identificacion' ) ) ?> <?= $form->field($model, 'descripcion')->textInput(['maxlength' => true]) ?> <?php echo $form->field($model,'fecha_factura')-> widget(DatePicker::className(),[ 'dateFormat' => 'yyyy-MM-dd', 'clientOptions' => [ 'yearRange' => '-1:+1', 'changeYear' => true], 'options' => ['class' => 'form-control', 'style' => 'width:25%'] ]) ?> <?= $form->field($model, 'importe')->textInput() ?> <?php echo $form->field($model,'fecha_recepcion')-> widget(DatePicker::className(),[ 'dateFormat' => 'yyyy-MM-dd', 'clientOptions' => [ 'yearRange' => '-1:+1', 'changeYear' => true], 'options' => ['class' => 'form-control', 'style' => 'width:25%'] ]) ?> <?= $form->field($model, 'imputacion_compra')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'comprobante')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'pagado')->textInput() ?> <?= $form->field($model, 'modo_pago')->textInput(['maxlength' => true]) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
26.615385
150
0.569942
404a44c6c553040fb2341d0d30e0c24af6a57839
3,344
py
Python
devil/devil/utils/reset_usb.py
tingshao/catapult
a8fe19e0c492472a8ed5710be9077e24cc517c5c
[ "BSD-3-Clause" ]
138
2020-12-09T07:08:43.000Z
2022-03-30T22:32:09.000Z
devil/devil/utils/reset_usb.py
tingshao/catapult
a8fe19e0c492472a8ed5710be9077e24cc517c5c
[ "BSD-3-Clause" ]
20
2020-04-08T13:50:39.000Z
2022-03-31T01:01:54.000Z
devil/devil/utils/reset_usb.py
tingshao/catapult
a8fe19e0c492472a8ed5710be9077e24cc517c5c
[ "BSD-3-Clause" ]
43
2020-12-11T09:43:14.000Z
2022-03-08T12:56:30.000Z
#!/usr/bin/env python # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys if sys.platform == 'win32': raise ImportError('devil.utils.reset_usb only supported on unix systems.') import argparse import fcntl import logging import os import re if __name__ == '__main__': sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) from devil.android import device_errors from devil.utils import lsusb from devil.utils import run_tests_helper logger = logging.getLogger(__name__) _INDENTATION_RE = re.compile(r'^( *)') _LSUSB_BUS_DEVICE_RE = re.compile(r'^Bus (\d{3}) Device (\d{3}):') _LSUSB_ENTRY_RE = re.compile(r'^ *([^ ]+) +([^ ]+) *([^ ].*)?$') _LSUSB_GROUP_RE = re.compile(r'^ *([^ ]+.*):$') _USBDEVFS_RESET = ord('U') << 8 | 20 def reset_usb(bus, device): """Reset the USB device with the given bus and device.""" usb_file_path = '/dev/bus/usb/%03d/%03d' % (bus, device) with open(usb_file_path, 'w') as usb_file: logger.debug('fcntl.ioctl(%s, %d)', usb_file_path, _USBDEVFS_RESET) fcntl.ioctl(usb_file, _USBDEVFS_RESET) def reset_android_usb(serial): """Reset the USB device for the given Android device.""" lsusb_info = lsusb.lsusb() bus = None device = None for device_info in lsusb_info: device_serial = lsusb.get_lsusb_serial(device_info) if device_serial == serial: bus = int(device_info.get('bus')) device = int(device_info.get('device')) if bus and device: reset_usb(bus, device) else: raise device_errors.DeviceUnreachableError( 'Unable to determine bus(%s) or device(%s) for device %s' % (bus, device, serial)) def reset_all_android_devices(): """Reset all USB devices that look like an Android device.""" _reset_all_matching(lambda i: bool(lsusb.get_lsusb_serial(i))) def _reset_all_matching(condition): lsusb_info = lsusb.lsusb() for device_info in lsusb_info: if int(device_info.get('device')) != 1 and condition(device_info): bus = int(device_info.get('bus')) device = int(device_info.get('device')) try: reset_usb(bus, device) serial = lsusb.get_lsusb_serial(device_info) if serial: logger.info( 'Reset USB device (bus: %03d, device: %03d, serial: %s)', bus, device, serial) else: logger.info( 'Reset USB device (bus: %03d, device: %03d)', bus, device) except IOError: logger.error( 'Failed to reset USB device (bus: %03d, device: %03d)', bus, device) def main(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='count') parser.add_argument('-s', '--serial') parser.add_argument('--bus', type=int) parser.add_argument('--device', type=int) args = parser.parse_args() run_tests_helper.SetLogLevel(args.verbose) if args.serial: reset_android_usb(args.serial) elif args.bus and args.device: reset_usb(args.bus, args.device) else: parser.error('Unable to determine target. ' 'Specify --serial or BOTH --bus and --device.') return 0 if __name__ == '__main__': sys.exit(main())
29.078261
76
0.651316
40a911e135a96c2e48eec35fcfeabe73d915e8fe
78,217
html
HTML
docs/docsets/RbSwift.docset/Contents/Resources/Documents/Classes/Dir.html
liamnichols/RbSwift
522a1211258379df045cfdac1486c9bed2ee78bd
[ "MIT" ]
312
2017-03-30T15:48:25.000Z
2018-11-11T03:40:15.000Z
docs/docsets/RbSwift.docset/Contents/Resources/Documents/Classes/Dir.html
liamnichols/RbSwift
522a1211258379df045cfdac1486c9bed2ee78bd
[ "MIT" ]
3
2018-12-26T16:33:56.000Z
2019-06-08T22:53:19.000Z
docs/docsets/RbSwift.docset/Contents/Resources/Documents/Classes/Dir.html
liamnichols/RbSwift
522a1211258379df045cfdac1486c9bed2ee78bd
[ "MIT" ]
23
2017-05-14T06:31:42.000Z
2018-09-06T06:38:07.000Z
<!DOCTYPE html> <html lang="en"> <head> <title>Dir Class Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/swift/Class/Dir" class="dashAnchor"></a> <a title="Dir Class Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html">RbSwift Docs</a> (73% documented)</p> <p class="header-right"><a href="https://github.com/Draveness/RbSwift"><img src="../img/gh.png"/>View on GitHub</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html">RbSwift Reference</a> <img id="carat" src="../img/carat.png" /> Dir Class Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Classes/Dir.html">Dir</a> </li> <li class="nav-group-task"> <a href="../Classes/Dir/HomeDirectory.html">– HomeDirectory</a> </li> <li class="nav-group-task"> <a href="../Classes/Dir/RemoveDirectoryError.html">– RemoveDirectoryError</a> </li> <li class="nav-group-task"> <a href="../Classes/File.html">File</a> </li> <li class="nav-group-task"> <a href="../Classes/FileUtils.html">FileUtils</a> </li> <li class="nav-group-task"> <a href="../Classes/IO.html">IO</a> </li> <li class="nav-group-task"> <a href="../Classes/IO/SeekPosition.html">– SeekPosition</a> </li> <li class="nav-group-task"> <a href="../Classes/Stat.html">Stat</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Extensions/Array.html">Array</a> </li> <li class="nav-group-task"> <a href="../Extensions/Calendar.html">Calendar</a> </li> <li class="nav-group-task"> <a href="../Extensions/Character.html">Character</a> </li> <li class="nav-group-task"> <a href="../Extensions/Data.html">Data</a> </li> <li class="nav-group-task"> <a href="../Extensions/Date.html">Date</a> </li> <li class="nav-group-task"> <a href="../Extensions/Date/Period.html">– Period</a> </li> <li class="nav-group-task"> <a href="../Extensions/Double.html">Double</a> </li> <li class="nav-group-task"> <a href="../Extensions/Error.html">Error</a> </li> <li class="nav-group-task"> <a href="../Extensions/Float.html">Float</a> </li> <li class="nav-group-task"> <a href="../Extensions/Hash.html">Hash</a> </li> <li class="nav-group-task"> <a href="../Extensions/IndexPath.html">IndexPath</a> </li> <li class="nav-group-task"> <a href="../Extensions/IndexSet.html">IndexSet</a> </li> <li class="nav-group-task"> <a href="../Extensions/Int.html">Int</a> </li> <li class="nav-group-task"> <a href="../Extensions/Int16.html">Int16</a> </li> <li class="nav-group-task"> <a href="../Extensions/Int32.html">Int32</a> </li> <li class="nav-group-task"> <a href="../Extensions/Int64.html">Int64</a> </li> <li class="nav-group-task"> <a href="../Extensions/Integer.html">Integer</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSCalendar.html">NSCalendar</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSData.html">NSData</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSDate.html">NSDate</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSError.html">NSError</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSIndexPath.html">NSIndexPath</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSIndexSet.html">NSIndexSet</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSRange.html">NSRange</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSString.html">NSString</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSTimeZone.html">NSTimeZone</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSURL.html">NSURL</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSURLComponents.html">NSURLComponents</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSURLRequest.html">NSURLRequest</a> </li> <li class="nav-group-task"> <a href="../Extensions/Sequence.html">Sequence</a> </li> <li class="nav-group-task"> <a href="../Extensions/String.html">String</a> </li> <li class="nav-group-task"> <a href="../Extensions/String/LetterCase.html">– LetterCase</a> </li> <li class="nav-group-task"> <a href="../Extensions/TimeZone.html">TimeZone</a> </li> <li class="nav-group-task"> <a href="../Extensions/UInt.html">UInt</a> </li> <li class="nav-group-task"> <a href="../Extensions/UInt16.html">UInt16</a> </li> <li class="nav-group-task"> <a href="../Extensions/UInt32.html">UInt32</a> </li> <li class="nav-group-task"> <a href="../Extensions/UInt64.html">UInt64</a> </li> <li class="nav-group-task"> <a href="../Extensions/URL.html">URL</a> </li> <li class="nav-group-task"> <a href="../Extensions/URLComponents.html">URLComponents</a> </li> <li class="nav-group-task"> <a href="../Extensions/URLRequest.html">URLRequest</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Functions.html">Functions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1auRxs9EquatablerFTGSax_GSax__GSax_">&amp;(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1mFTSSSi_SS">*(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1mFTSiSS_SS">*(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1murFTGSax_SS_SS">*(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1murFTGSax_Si_GSax_">*(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi2mmFTSdSd_Sd">**(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi2mmFTSiSi_Si">**(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1pFTSSVS_8Pathname_S0_">+(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1pFTVS_8PathnameS0__S0_">+(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1pFTVS_8PathnameSS_S0_">+(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions/+(_:_:).html">+(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi1suRxs9EquatablerFTGSax_GSax__GSax_">-(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi2llFTSSSS_SS">&lt;&lt;(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi2eeuRxs9EquatablerFTGSaGSax__GSaGSax___Sb">==(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi2etFTSSPS_16RegexConvertible__Sb">=~(_:_:)</a> </li> <li class="nav-group-task"> <a href="../Functions.html#/s:F7RbSwiftoi2etFTVs9CharacterPS_16RegexConvertible__Sb">=~(_:_:)</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Protocols/OptionalType.html">OptionalType</a> </li> <li class="nav-group-task"> <a href="../Protocols/RegexConvertible.html">RegexConvertible</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Structs.html">Structs</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Structs/DateFormat.html">DateFormat</a> </li> <li class="nav-group-task"> <a href="../Structs/Duration.html">Duration</a> </li> <li class="nav-group-task"> <a href="../Structs/MatchData.html">MatchData</a> </li> <li class="nav-group-task"> <a href="../Structs/Pathname.html">Pathname</a> </li> <li class="nav-group-task"> <a href="../Structs/Regex.html">Regex</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Typealiases.html">Typealiases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Typealiases.html#/s:7RbSwift4Hash">Hash</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>Dir</h1> <p>Undocumented</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir4pathSS"></a> <a name="//apple_ref/swift/Property/path" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir4pathSS">path</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the path parameter passed to dir’s constructor.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">let</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L15">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir6filenoSi"></a> <a name="//apple_ref/swift/Property/fileno" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir6filenoSi">fileno</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the file descriptor used in dir. This method uses <code>dirfd()</code> function defined by POSIX 2008.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">fileno</span><span class="p">:</span> <span class="kt">Int</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L19-L21">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir3posSi"></a> <a name="//apple_ref/swift/Property/pos" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir3posSi">pos</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the current position in dir. See also <code>Dir#seek(pos:)</code>.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">pos</span><span class="p">:</span> <span class="kt">Int</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L24-L31">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir4tellSi"></a> <a name="//apple_ref/swift/Property/tell" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir4tellSi">tell</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the current position in dir.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">tell</span><span class="p">:</span> <span class="kt">Int</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L34-L36">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir7to_pathSS"></a> <a name="//apple_ref/swift/Property/to_path" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir7to_pathSS">to_path</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the path parameter passed to dir’s constructor.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">to_path</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L39-L41">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir7inspectSS"></a> <a name="//apple_ref/swift/Property/inspect" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir7inspectSS">inspect</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Return a string describing this Dir object.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">inspect</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L44-L46">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:vC7RbSwift3Dir11descriptionSS"></a> <a name="//apple_ref/swift/Property/description" class="dashAnchor"></a> <a class="token" href="#/s:vC7RbSwift3Dir11descriptionSS">description</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Return a string describing this Dir object.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="k">var</span> <span class="nv">description</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L49-L51">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:FC7RbSwift3DircFSSGSqS0__"></a> <a name="//apple_ref/swift/Method/init(_:)" class="dashAnchor"></a> <a class="token" href="#/s:FC7RbSwift3DircFSSGSqS0__">init(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns a new directory object for the named directory.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">?(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L54-L58">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir3newFSSGSqS0__"></a> <a name="//apple_ref/swift/Method/new(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir3newFSSGSqS0__">new(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns a new directory object for the named directory.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">new</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Dir</span><span class="p">?</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A new <code>Dir</code> object or nil.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L64-L66">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir4openFSSGSqS0__"></a> <a name="//apple_ref/swift/Method/open(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir4openFSSGSqS0__">open(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns a new directory object for the named directory.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">open</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Dir</span><span class="p">?</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A new <code>Dir</code> object or nil.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L72-L74">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZvC7RbSwift3Dir5getwdSS"></a> <a name="//apple_ref/swift/Variable/getwd" class="dashAnchor"></a> <a class="token" href="#/s:ZvC7RbSwift3Dir5getwdSS">getwd</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the path to the current working directory of this process as a string.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">var</span> <span class="nv">getwd</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L77-L79">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZvC7RbSwift3Dir3pwdSS"></a> <a name="//apple_ref/swift/Variable/pwd" class="dashAnchor"></a> <a class="token" href="#/s:ZvC7RbSwift3Dir3pwdSS">pwd</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the path to the current working directory of this process as a string. An alias to <code>Dir#getwd</code> var.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">var</span> <span class="nv">pwd</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L83-L85">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZvC7RbSwift3Dir4homeSS"></a> <a name="//apple_ref/swift/Variable/home" class="dashAnchor"></a> <a class="token" href="#/s:ZvC7RbSwift3Dir4homeSS">home</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the home directory of the current user or the named user if given.</p> <pre class="highlight plaintext"><code>Dir.home #=&gt; "/Users/username" </code></pre> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">var</span> <span class="nv">home</span><span class="p">:</span> <span class="kt">String</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L95-L97">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:OC7RbSwift3Dir13HomeDirectory"></a> <a name="//apple_ref/swift/Enum/HomeDirectory" class="dashAnchor"></a> <a class="token" href="#/s:OC7RbSwift3Dir13HomeDirectory">HomeDirectory</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Error throws when user doesn&rsquo;t exists.</p> <ul> <li>notExists: User doesn&rsquo;t exists</li> </ul> <a href="../Classes/Dir/HomeDirectory.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">HomeDirectory</span><span class="p">:</span> <span class="kt">Error</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L102-L104">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir4homeFzGSqSS_SS"></a> <a name="//apple_ref/swift/Method/home(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir4homeFzGSqSS_SS">home(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns the home directory of the current user or the named user if given.</p> <pre class="highlight plaintext"><code>Dir.home() #=&gt; "/Users/username" Dir.home("user") #=&gt; "/user" </code></pre> <div class="aside aside-throws"> <p class="aside-title">Throws</p> HomeDirectory.notExists if user doesn&rsquo;t exist. </div> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">home</span><span class="p">(</span><span class="n">_</span> <span class="nv">user</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span><span class="p">)</span> <span class="k">throws</span> <span class="o">-&gt;</span> <span class="kt">String</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>The name of user.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>Home directory.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L114-L117">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir5chdirFSSSb"></a> <a name="//apple_ref/swift/Method/chdir(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir5chdirFSSSb">chdir(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Changes the current working directory of the process to the given string.</p> <pre class="highlight plaintext"><code>Dir.chdir("/var/spool/mail") Dir.pwd #=&gt; "/var/spool/mail" </code></pre> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">chdir</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span> <span class="o">=</span> <span class="s">"~"</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A new current working directory.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A bool indicates the result of <code>Dir#chdir(path:)</code></p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L127-L129">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir6chrootFSSSb"></a> <a name="//apple_ref/swift/Method/chroot(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir6chrootFSSSb">chroot(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Changes this process’s idea of the file system root.</p> <div class="aside aside-see-also"> <p class="aside-title">See also</p> <code>Darwin.chroot</code>. </div> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">chroot</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A bool value indicates the result of <code>Darwin.chroot</code></p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L137-L139">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir5chdirurFTSS7closureFT_x_x"></a> <a name="//apple_ref/swift/Method/chdir(_:closure:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir5chdirurFTSS7closureFT_x_x">chdir(_:closure:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Changes the current working directory of the process to the given string. Block is passed the name of the new current directory, and the block is executed with that as the current directory. The original working directory is restored when the block exits. The return value of chdir is the value of the block.</p> <pre class="highlight plaintext"><code>Dir.pwd #=&gt; "/work" let value = Dir.chdir("/var") { Dir.pwd #=&gt; "/var" return 1 } Dir.pwd #=&gt; "/work" value #=&gt; 1 </code></pre> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="n">chdir</span><span class="o">&lt;</span><span class="kt">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span> <span class="o">=</span> <span class="s">"~"</span><span class="p">,</span> <span class="nv">closure</span><span class="p">:</span> <span class="p">((</span><span class="kt">Void</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">T</span><span class="p">))</span> <span class="o">-&gt;</span> <span class="kt">T</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A new current working directory.</p> </div> </td> </tr> <tr> <td> <code> <em>closure</em> </code> </td> <td> <div> <p>A block executed in target directory.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>The value of the closure.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L159-L165">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir5mkdirFzTSS9recursiveSbGSqSi__T_"></a> <a name="//apple_ref/swift/Method/mkdir(_:recursive:_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir5mkdirFzTSS9recursiveSbGSqSi__T_">mkdir(_:recursive:_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Makes a new directory named by string, with permissions specified by the optional parameter anInteger.</p> <pre class="highlight plaintext"><code>try Dir.mkdir("draveness") try! Dir.mkdir("draveness/spool/mail", recursive: true) </code></pre> <div class="aside aside-throws"> <p class="aside-title">Throws</p> When <code>FileManager#createDirectory(atPath:withIntermediateDirectories:attributes:)</code> throws. </div> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">mkdir</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">recursive</span><span class="p">:</span> <span class="kt">Bool</span> <span class="o">=</span> <span class="kc">false</span><span class="p">,</span> <span class="n">_</span> <span class="nv">permissions</span><span class="p">:</span> <span class="kt">Int</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A new directory path.</p> </div> </td> </tr> <tr> <td> <code> <em>recursive</em> </code> </td> <td> <div> <p>Whether creats intermeidate directories.</p> </div> </td> </tr> <tr> <td> <code> <em>permissions</em> </code> </td> <td> <div> <p>An integer represents the posix permission.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L177-L183">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:OC7RbSwift3Dir20RemoveDirectoryError"></a> <a name="//apple_ref/swift/Enum/RemoveDirectoryError" class="dashAnchor"></a> <a class="token" href="#/s:OC7RbSwift3Dir20RemoveDirectoryError">RemoveDirectoryError</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Error throws when called <code>Dir#rmdir(path:)</code> method.</p> <ul> <li>notEmpty: Directory is not empty.</li> <li>notExists: Directory is not exists.</li> </ul> <a href="../Classes/Dir/RemoveDirectoryError.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">RemoveDirectoryError</span><span class="p">:</span> <span class="kt">Error</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L189-L192">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir5rmdirFzSST_"></a> <a name="//apple_ref/swift/Method/rmdir(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir5rmdirFzSST_">rmdir(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Deletes the named directory.</p> <pre class="highlight plaintext"><code>try Dir.rmdir("/a/folder/path") </code></pre> <div class="aside aside-throws"> <p class="aside-title">Throws</p> <code><a href="../Classes/Dir/RemoveDirectoryError.html">RemoveDirectoryError</a></code> if the directory isn’t empty. </div> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">rmdir</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L200-L209">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir6unlinkFzSST_"></a> <a name="//apple_ref/swift/Method/unlink(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir6unlinkFzSST_">unlink(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Deletes the named directory. An alias to <code>Dir.rmdir(path:)</code>.</p> <pre class="highlight plaintext"><code>try Dir.unlink("/a/folder/path") </code></pre> <div class="aside aside-throws"> <p class="aside-title">Throws</p> <code><a href="../Classes/Dir/RemoveDirectoryError.html">RemoveDirectoryError</a></code> if the directory isn’t empty. </div> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">unlink</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L217-L219">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir7isExistFSSSb"></a> <a name="//apple_ref/swift/Method/isExist(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir7isExistFSSSb">isExist(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns true if the named file is a directory, false otherwise.</p> <pre class="highlight plaintext"><code>Dir.isExist("/a/folder/path/not/exists") #=&gt; false Dir.isExist("/a/folder/path/exists") #=&gt; true </code></pre> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">isExist</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A file path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A bool value indicates whether there is a directory in given path.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L228-L232">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir7isEmptyFSSSb"></a> <a name="//apple_ref/swift/Method/isEmpty(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir7isEmptyFSSSb">isEmpty(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns true if the named file is an empty directory, false if it is not a directory or non-empty.</p> <pre class="highlight plaintext"><code>Dir.isEmpty("/a/empty/folder") #=&gt; true Dir.isEmpty("/a/folder/not/exists") #=&gt; true Dir.isEmpty("/a/folder/with/files") #=&gt; false </code></pre> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">isEmpty</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A bool value indicates the directory is not exists or is empty.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L243-L248">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir7entriesFSSGSaSS_"></a> <a name="//apple_ref/swift/Method/entries(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir7entriesFSSGSaSS_">entries(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Returns an array containing all of the filenames in the given directory. Will return an empty array if the named directory doesn’t exist.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">entries</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="kt">String</span><span class="p">]</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>An array of all filenames in the given directory.</p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L255-L262">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir7foreachFTSS7closureFSST__T_"></a> <a name="//apple_ref/swift/Method/foreach(_:closure:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir7foreachFTSS7closureFSST__T_">foreach(_:closure:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">foreach</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">closure</span><span class="p">:</span> <span class="p">(</span><span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">())</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> <tr> <td> <code> <em>closure</em> </code> </td> <td> <div> <p>A closure accepts all the entries in current directory.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L270-L272">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:ZFC7RbSwift3Dir6deleteFSSSb"></a> <a name="//apple_ref/swift/Method/delete(_:)" class="dashAnchor"></a> <a class="token" href="#/s:ZFC7RbSwift3Dir6deleteFSSSb">delete(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Deletes the named directory.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="nf">delete</span><span class="p">(</span><span class="n">_</span> <span class="nv">path</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>path</em> </code> </td> <td> <div> <p>A directory path.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>A bool value indicates the result of <code>Dir.delete(path:)</code></p> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L279-L281">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:FC7RbSwift3Dir4seekFSiT_"></a> <a name="//apple_ref/swift/Method/seek(_:)" class="dashAnchor"></a> <a class="token" href="#/s:FC7RbSwift3Dir4seekFSiT_">seek(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Seeks to a particular location in dir.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">seek</span><span class="p">(</span><span class="n">_</span> <span class="nv">pos</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>pos</em> </code> </td> <td> <div> <p>A particular location.</p> </div> </td> </tr> </tbody> </table> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L286-L288">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:FC7RbSwift3Dir6rewindFT_T_"></a> <a name="//apple_ref/swift/Method/rewind()" class="dashAnchor"></a> <a class="token" href="#/s:FC7RbSwift3Dir6rewindFT_T_">rewind()</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Repositions dir to the first entry.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">rewind</span><span class="p">()</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/Draveness/RbSwift/tree/0.5.0/RbSwift/IO/Dir.swift#L291-L293">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2017 <a class="link" href="https://github.com/Draveness" target="_blank" rel="external">Draveness</a>. All rights reserved. (Last updated: 2017-05-15)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.8.2</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
48.311921
754
0.398072
2924b655490b9096315552522b6d93e5392cd480
976
py
Python
pypagai/experiments/core.py
gcouti/pypagAI
d08fac95361dcc036d890a88cb86ce090322a612
[ "Apache-2.0" ]
1
2018-07-24T18:53:26.000Z
2018-07-24T18:53:26.000Z
pypagai/experiments/core.py
gcouti/pypagAI
d08fac95361dcc036d890a88cb86ce090322a612
[ "Apache-2.0" ]
7
2020-01-28T21:45:14.000Z
2022-03-11T23:20:53.000Z
pypagai/experiments/core.py
gcouti/pypagAI
d08fac95361dcc036d890a88cb86ce090322a612
[ "Apache-2.0" ]
null
null
null
# aux pkg imports import pandas as pd # scikit imports from pypagai.experiments.evaluation import make_result_frame from sklearn.cross_validation import train_test_split from sklearn.utils import safe_indexing from sklearn.model_selection import KFold, StratifiedKFold, RepeatedStratifiedKFold, TimeSeriesSplit # sacred imports from sacred import Ingredient cv_ingredient = Ingredient('cv') cvs = { 'kf': KFold, 'skf': StratifiedKFold, 'rskf': RepeatedStratifiedKFold, 'ts': TimeSeriesSplit } def get_params(cv): cv = cvs.get(cv, None) if cv is None: return {} # return get_default_vars(cv.__init__) return {} @cv_ingredient.config def tcfg(): # data splitter name (options: kf, skf, rskf, ts, None). name = None # data splitter parameters params = get_params(name) @cv_ingredient.capture def get_cv(name, params): cv = cvs.get(name, None) if cv is None: return None return cv(**params)
19.918367
100
0.710041
e21bab548ebefbb6012daedf3ebdfcb24f4437d7
3,443
swift
Swift
FellowBloggerV2/Controllers/SearchViewController.swift
AaronCab/FellowBloggerV2
ad6ed7cb7ff4fcddba45ac030d5b83dca35b7038
[ "MIT" ]
1
2019-05-29T21:12:24.000Z
2019-05-29T21:12:24.000Z
FellowBloggerV2/Controllers/SearchViewController.swift
AaronCab/FellowBloggerV2
ad6ed7cb7ff4fcddba45ac030d5b83dca35b7038
[ "MIT" ]
null
null
null
FellowBloggerV2/Controllers/SearchViewController.swift
AaronCab/FellowBloggerV2
ad6ed7cb7ff4fcddba45ac030d5b83dca35b7038
[ "MIT" ]
null
null
null
// // SearchViewController.swift // FellowBloggerV2 // // Created by Aaron Cabreja on 3/20/19. // Copyright © 2019 Pursuit. All rights reserved. // import UIKit import Kingfisher import Firebase class SearchViewController: UIViewController { @IBOutlet weak var userTableView: UITableView! @IBOutlet weak var blogSearchBar: UISearchBar! private var listener: ListenerRegistration! private var authservice = AppDelegate.authservice private var blogger = [Blogger](){ didSet { DispatchQueue.main.async { self.userTableView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() userTableView.dataSource = self userTableView.delegate = self blogSearchBar.delegate = self hideKeyboardWhenTappedAround() navigationItem.title = "FellowBloggerV2" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Show Profile" { guard let selectedIndexPath = userTableView.indexPathForSelectedRow, let blogDVC = segue.destination as? BloggerProfileViewController else { fatalError("cannot segue to blogDVC") } let aBlogger1 = blogger[selectedIndexPath.row] blogDVC.blogger = aBlogger1 } else if segue.identifier == "Add Blog" { } } } extension SearchViewController: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return blogger.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as? ProfileTableViewCell else { return UITableViewCell()} let aBlogger = blogger[indexPath.row] cell.nameLabel?.text = aBlogger.displayName cell.emailLabel?.text = aBlogger.email cell.profileImage?.kf.setImage(with: URL(string: aBlogger.photoURL ?? "no image found"), placeholder: #imageLiteral(resourceName: "icons8-check_male")) return cell } } extension SearchViewController: UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } } extension SearchViewController: UISearchBarDelegate{ func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { blogger = [Blogger]() if searchText == ""{ return } else { listener = DBService.firestoreDB .collection(BloggersCollectionKeys.CollectionKey).addSnapshotListener { [weak self] (snapshot, error) in if let error = error { print("failed to fetch Blogs with error: \(error.localizedDescription)") } else if let snapshot = snapshot { self?.blogger = snapshot.documents.map { Blogger(dict: $0.data()) } .filter { $0.displayName.contains(searchText.lowercased()) || $0.displayName.contains(searchText.uppercased()) || ($0.firstName?.contains(searchText.lowercased()))! || ($0.lastName?.contains(searchText.uppercased()))! || $0.email.contains(searchText.lowercased())} } } } } }
38.255556
292
0.643625
e8d217405b251431417604627895b89587d826ed
11,794
asm
Assembly
Source/Apps/Timer.asm
vipoo/RomWBW
e463959fee431da2de3da962bd70cb0c556ffaed
[ "DOC", "MIT" ]
1
2021-11-10T12:31:51.000Z
2021-11-10T12:31:51.000Z
Source/Apps/Timer.asm
vipoo/RomWBW
e463959fee431da2de3da962bd70cb0c556ffaed
[ "DOC", "MIT" ]
1
2018-08-03T10:46:18.000Z
2018-08-03T10:46:18.000Z
Source/Apps/Timer.asm
vipoo/RomWBW
e463959fee431da2de3da962bd70cb0c556ffaed
[ "DOC", "MIT" ]
null
null
null
;=============================================================================== ; TIMER - Display system timer value ; ;=============================================================================== ; ; Author: Wayne Warthen (wwarthen@gmail.com) ;_______________________________________________________________________________ ; ; Usage: ; TIMER [/C] [/?] ; ex: TIMER (display current timer value) ; TIMER /? (display version and usage) ; TIMER /C (display timer value continuously) ; ; Operation: ; Reads and displays system timer value. ;_______________________________________________________________________________ ; ; Change Log: ; 2018-01-14 [WBW] Initial release ; 2018-01-17 [WBW] Add HBIOS check ; 2019-11-08 [WBW] Add seconds support ;_______________________________________________________________________________ ; ; ToDo: ;_______________________________________________________________________________ ; ;=============================================================================== ; Definitions ;=============================================================================== ; stksiz .equ $40 ; Working stack size ; restart .equ $0000 ; CP/M restart vector bdos .equ $0005 ; BDOS invocation vector ; ident .equ $FFFE ; loc of RomWBW HBIOS ident ptr ; rmj .equ 3 ; intended CBIOS version - major rmn .equ 1 ; intended CBIOS version - minor ; bf_sysver .equ $F1 ; BIOS: VER function bf_sysget .equ $F8 ; HBIOS: SYSGET function bf_sysset .equ $F9 ; HBIOS: SYSGET function bf_sysgettimer .equ $D0 ; TIMER subfunction bf_syssettimer .equ $D0 ; TIMER subfunction bf_sysgetsecs .equ $D1 ; SECONDS subfunction bf_syssetsecs .equ $D1 ; SECONDS subfunction ; ;=============================================================================== ; Code Section ;=============================================================================== ; .org $100 ; ; setup stack (save old value) ld (stksav),sp ; save stack ld sp,stack ; set new stack ; ; initialization call init ; initialize jr nz,exit ; abort if init fails ; ; process call process ; do main processing jr nz,exit ; abort on error ; exit: ; clean up and return to command processor call crlf ; formatting ld sp,(stksav) ; restore stack ;jp restart ; return to CP/M via restart ret ; return to CP/M w/o restart ; ; Initialization ; init: call crlf ; formatting ld de,msgban ; point to version message part 1 call prtstr ; print it ; call idbio ; identify active BIOS cp 1 ; check for HBIOS jp nz,errbio ; handle BIOS error ; ld a,rmj << 4 | rmn ; expected HBIOS ver cp d ; compare with result above jp nz,errbio ; handle BIOS error ; initx ; initialization complete xor a ; signal success ret ; return ; ; Process ; process: ; look for start of parms ld hl,$81 ; point to start of parm area (past len byte) ; process00: call nonblank ; skip to next non-blank char jp z,process0 ; no more parms, go to display ; ; check for option, introduced by a "/" cp '/' ; start of options? jp nz,usage ; yes, handle option call option ; do option processing ret nz ; done if non-zero return jr process00 ; continue looking for options ; process0: ; ; Test of API function to set seconds value ;ld b,bf_sysset ; HBIOS SYSGET function ;ld c,bf_syssetsecs ; SECONDS subfunction ;ld de,0 ; set seconds value ;ld hl,1000 ; ... to 1000 ;rst 08 ; call HBIOS, DE:HL := seconds value ; ; get and print seconds value call crlf2 ; formatting ; process1: ld b,bf_sysget ; HBIOS SYSGET function ld c,bf_sysgettimer ; TIMER subfunction rst 08 ; call HBIOS, DE:HL := timer value ld a,(first) or a ld a,0 ld (first),a jr nz,process1a ; test for new value ld a,(last) ; last LSB value to A cp l ; compare to current LSB jr z,process2 ; if equal, bypass display process1a: ; save and print new value ld a,l ; new LSB value to A ld (last),a ; save as last value call prtcr ; back to start of line ;call nz,prthex32 ; display it call prthex32 ; display it ld de,strtick ; tag call prtstr ; display it ; get and print seconds value ld b,bf_sysget ; HBIOS SYSGET function ld c,bf_sysgetsecs ; SECONDS subfunction rst 08 ; call HBIOS, DE:HL := seconds value call prthex32 ; display it ld a,'.' ; fraction separator call prtchr ; print it ld a,c ; get fractional component call prthex ; print it ld de,strsec ; tag call prtstr ; display it ; process2: ld a,(cont) ; continuous display? or a ; test for true/false jr z,process3 ; if false, get out ; ld c,6 ; BDOS: direct console I/O ld e,$FF ; input char call bdos ; call BDOS, A := char or a ; test for zero jr z,process1 ; loop until char pressed ; process3: xor a ; signal success ret ; ; Handle special options ; option: ; inc hl ; next char ld a,(hl) ; get it or a ; zero terminator? ret z ; done if so cp ' ' ; blank? ret z ; done if so cp '?' ; is it a '?'? jp z,usage ; yes, display usage cp 'C' ; is it a 'C', continuous? jp z,setcont ; yes, set continuous display jp errprm ; anything else is an error ; usage: ; jp erruse ; display usage and get out ; setcont: ; or $FF ; set A to true ld (cont),a ; and set continuous flag jr option ; check for more option letters ; ; Identify active BIOS. RomWBW HBIOS=1, UNA UBIOS=2, else 0 ; idbio: ; ; Check for UNA (UBIOS) ld a,($FFFD) ; fixed location of UNA API vector cp $C3 ; jp instruction? jr nz,idbio1 ; if not, not UNA ld hl,($FFFE) ; get jp address ld a,(hl) ; get byte at target address cp $FD ; first byte of UNA push ix instruction jr nz,idbio1 ; if not, not UNA inc hl ; point to next byte ld a,(hl) ; get next byte cp $E5 ; second byte of UNA push ix instruction jr nz,idbio1 ; if not, not UNA, check others ; ld bc,$04FA ; UNA: get BIOS date and version rst 08 ; DE := ver, HL := date ; ld a,2 ; UNA BIOS id = 2 ret ; and done ; idbio1: ; Check for RomWBW (HBIOS) ld hl,($FFFE) ; HL := HBIOS ident location ld a,'W' ; First byte of ident cp (hl) ; Compare jr nz,idbio2 ; Not HBIOS inc hl ; Next byte of ident ld a,~'W' ; Second byte of ident cp (hl) ; Compare jr nz,idbio2 ; Not HBIOS ; ld b,bf_sysver ; HBIOS: VER function ld c,0 ; required reserved value rst 08 ; DE := version, L := platform id ; ld a,1 ; HBIOS BIOS id = 1 ret ; and done ; idbio2: ; No idea what this is xor a ; Setup return value of 0 ret ; and done ; ; Print character in A without destroying any registers ; prtchr: push bc ; save registers push de push hl ld e,a ; character to print in E ld c,$02 ; BDOS function to output a character call bdos ; do it pop hl ; restore registers pop de pop bc ret ; prtdot: ; ; shortcut to print a dot preserving all regs push af ; save af ld a,'.' ; load dot char call prtchr ; print it pop af ; restore af ret ; done ; prtcr: ; ; shortcut to print a dot preserving all regs push af ; save af ld a,13 ; load CR value call prtchr ; print it pop af ; restore af ret ; done ; ; Print a zero terminated string at (DE) without destroying any registers ; prtstr: push de ; prtstr1: ld a,(de) ; get next char or a jr z,prtstr2 call prtchr inc de jr prtstr1 ; prtstr2: pop de ; restore registers ret ; ; Print the value in A in hex without destroying any registers ; prthex: push af ; save AF push de ; save DE call hexascii ; convert value in A to hex chars in DE ld a,d ; get the high order hex char call prtchr ; print it ld a,e ; get the low order hex char call prtchr ; print it pop de ; restore DE pop af ; restore AF ret ; done ; ; print the hex word value in bc ; prthexword: push af ld a,b call prthex ld a,c call prthex pop af ret ; ; print the hex dword value in de:hl ; prthex32: push bc push de pop bc call prthexword push hl pop bc call prthexword pop bc ret ; ; Convert binary value in A to ascii hex characters in DE ; hexascii: ld d,a ; save A in D call hexconv ; convert low nibble of A to hex ld e,a ; save it in E ld a,d ; get original value back rlca ; rotate high order nibble to low bits rlca rlca rlca call hexconv ; convert nibble ld d,a ; save it in D ret ; done ; ; Convert low nibble of A to ascii hex ; hexconv: and $0F ; low nibble only add a,$90 daa adc a,$40 daa ret ; ; Print value of A or HL in decimal with leading zero suppression ; Use prtdecb for A or prtdecw for HL ; prtdecb: push hl ld h,0 ld l,a call prtdecw ; print it pop hl ret ; prtdecw: push af push bc push de push hl call prtdec0 pop hl pop de pop bc pop af ret ; prtdec0: ld e,'0' ld bc,-10000 call prtdec1 ld bc,-1000 call prtdec1 ld bc,-100 call prtdec1 ld c,-10 call prtdec1 ld e,0 ld c,-1 prtdec1: ld a,'0' - 1 prtdec2: inc a add hl,bc jr c,prtdec2 sbc hl,bc cp e ret z ld e,0 call prtchr ret ; ; Start a new line ; crlf2: call crlf ; two of them crlf: push af ; preserve AF ld a,13 ; <CR> call prtchr ; print it ld a,10 ; <LF> call prtchr ; print it pop af ; restore AF ret ; ; Get the next non-blank character from (HL). ; nonblank: ld a,(hl) ; load next character or a ; string ends with a null ret z ; if null, return pointing to null cp ' ' ; check for blank ret nz ; return if not blank inc hl ; if blank, increment character pointer jr nonblank ; and loop ; ; Convert character in A to uppercase ; ucase: cp 'a' ; if below 'a' ret c ; ... do nothing and return cp 'z' + 1 ; if above 'z' ret nc ; ... do nothing and return res 5,a ; clear bit 5 to make lower case -> upper case ret ; and return ; ; Add the value in A to HL (HL := HL + A) ; addhl: add a,l ; A := A + L ld l,a ; Put result back in L ret nc ; if no carry, we are done inc h ; if carry, increment H ret ; and return ; ; Jump indirect to address in HL ; jphl: jp (hl) ; ; Errors ; erruse: ; command usage error (syntax) ld de,msguse jr err ; errprm: ; command parameter error (syntax) ld de,msgprm jr err ; errbio: ; invalid BIOS or version ld de,msgbio jr err ; err: ; print error string and return error signal call crlf2 ; print newline ; err1: ; without the leading crlf call prtstr ; print error string ; err2: ; without the string ; call crlf ; print newline or $FF ; signal error ret ; done ; ;=============================================================================== ; Storage Section ;=============================================================================== ; last .db 0 ; last LSB of timer value cont .db 0 ; non-zero indicates continuous display first .db $FF ; first pass flag (true at start) ; stksav .dw 0 ; stack pointer saved at start .fill stksiz,0 ; stack stack .equ $ ; stack top ; ; Messages ; msgban .db "TIMER v1.1, 10-Nov-2019",13,10 .db "Copyright (C) 2019, Wayne Warthen, GNU GPL v3",0 msguse .db "Usage: TIMER [/C] [/?]",13,10 .db " ex. TIMER (display current timer value)",13,10 .db " TIMER /? (display version and usage)",13,10 .db " TIMER /C (display timer value continuously)",0 msgprm .db "Parameter error (TIMER /? for usage)",0 msgbio .db "Incompatible BIOS or version, " .db "HBIOS v", '0' + rmj, ".", '0' + rmn, " required",0 strtick .db " Ticks, ",0 strsec .db " Seconds",0 ; .end
23.216535
81
0.608445
81cee25e6c6b01ee99800a210b1f553fceb75e5b
2,532
html
HTML
Class/Form.html
RogerRandomDev/WebTest
bb8537b1354417b833ec6c5f5e558da8bf64e9ec
[ "MIT" ]
null
null
null
Class/Form.html
RogerRandomDev/WebTest
bb8537b1354417b833ec6c5f5e558da8bf64e9ec
[ "MIT" ]
null
null
null
Class/Form.html
RogerRandomDev/WebTest
bb8537b1354417b833ec6c5f5e558da8bf64e9ec
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Author" content="Roger T. Grange"> <meta name="description" content="Form"> <meta property="og:image" content=""> <meta property="og:title" content=""> <meta property="og:description" content=""> <style>.textArea{resize: none;}</style> <title>Doc</title> </head> <body style="width: 100%; height: 100%;"> <form style="width: 33%; position:absolute; left: 50%; top: 50%; margin-left:-16.5%; margin-top: -12.5%;"> <fieldset> <legend>USER JOIN</legend> <label for="User">PilotID:</label> <input placeholder="Player" type="text" id="User" name="user.id" hid> <br> <label for="Password">Sector Access Code:</label> <input placeholder="0000" type="text" id="Password" name="user.password.id"> <br> <label for="ship"></label> <fieldset id="ship"> <legend>Ship</legend> <input type="radio" name="ship" id="ship0" name="HDP-001"> <label for="ship0">HDP-001</label> <input type="radio" name="ship" id="ship1" name="HSM-052"> <input type="radio" name="ship" id="ship2" name="EX-001"> </fieldset> <br> <label for="jointext">Join Message:</label> <br> <label for="test">Image</label> <input id="test" type="file" accept="image/jpg, image/jpeg"> <br> <textarea class="textArea" id="jointext" cols="15" rows="2" style="resize:none;" placeholder="has joined" name="join.message" readonly maxlength="32"></textarea> <br> <button type="reset">RESET</button> <button type="Submit">Enter Sector</button> <br> <fieldset id="symptoms"> <legend>SYMPTOMS</legend> <input type="checkbox" name="symp0" id="symptoms"> <label for="symp0">Runny Nose</label> <input type="checkbox" name="symp1" id="symptoms"> <label for="symp1">Coughing</label> <input type="checkbox" name="symp2" id="symptoms"> <label for="symp2">Restlessness</label> <input type="checkbox" name="symp3" id="symptoms"> <label for="symp3">Vomiting</label> </fieldset> </fieldset> </form> </body> </html>
41.508197
173
0.522117
9d0c47c7e88854da384552f066ce90166e3fa77d
970
kt
Kotlin
src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/smartvalues/SmartMetadata.kt
slatekit/slatek
f8ae048bc7d19704a2558e1d02374e98782e7b47
[ "Apache-2.0" ]
105
2016-10-06T08:56:10.000Z
2020-12-30T01:33:27.000Z
src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/smartvalues/SmartMetadata.kt
slatekit/slatek
f8ae048bc7d19704a2558e1d02374e98782e7b47
[ "Apache-2.0" ]
70
2017-08-18T14:51:07.000Z
2021-01-12T05:25:20.000Z
src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/smartvalues/SmartMetadata.kt
slatekit/slatek
f8ae048bc7d19704a2558e1d02374e98782e7b47
[ "Apache-2.0" ]
11
2016-11-21T07:20:13.000Z
2020-01-10T16:56:19.000Z
package slatekit.utils.smartvalues /** * @param name : Name for the smart string e.g. "PhoneUS" * @param desc : Description of the smart string e.g. "United States Phone number format" * @param required : Description of the smart string e.g. "United States Phone number format" * @param minLength : Minimum length required * @param maxLength : Maximum length required * @param examples : Examples of smart string e.g. [ "1234567890", "123-456-7890" ] * @param formats : Examples of the formats e.g. [ "xxxxxxxxxx", "xxx-xxx-xxxx" ] */ data class SmartMetadata( val name: String, val desc: String, val required: Boolean, val minLength: Long, // To accommodate longs val maxLength: Long, // To accommodate longs val examples: List<String>, val expressions:List<String>, val formats: List<String> ) { val example:String = examples.first() val format:String = formats.first() }
37.307692
94
0.662887
d9e36f59ae1cb4330409c2bd19837d2013ac8458
13,462
rs
Rust
src/schema/term.rs
StyMaar/tantivy
458ed29a31d4a8929193ba4f41b83cd69eaac5f9
[ "MIT" ]
1
2020-09-02T17:49:27.000Z
2020-09-02T17:49:27.000Z
src/schema/term.rs
StyMaar/tantivy
458ed29a31d4a8929193ba4f41b83cd69eaac5f9
[ "MIT" ]
null
null
null
src/schema/term.rs
StyMaar/tantivy
458ed29a31d4a8929193ba4f41b83cd69eaac5f9
[ "MIT" ]
1
2022-03-31T01:21:13.000Z
2022-03-31T01:21:13.000Z
use std::convert::TryInto; use std::hash::{Hash, Hasher}; use std::{fmt, str}; use super::Field; use crate::fastfield::FastValue; use crate::schema::{Facet, Type}; use crate::DateTime; /// Size (in bytes) of the buffer of a fast value (u64, i64, f64, or date) term. /// <field> + <type byte> + <value len> /// /// - <field> is a big endian encoded u32 field id /// - <type_byte>'s most significant bit expresses whether the term is a json term or not /// The remaining 7 bits are used to encode the type of the value. /// If this is a JSON term, the type is the type of the leaf of the json. /// /// - <value> is, if this is not the json term, a binary representation specific to the type. /// If it is a JSON Term, then it is preprended with the path that leads to this leaf value. const FAST_VALUE_TERM_LEN: usize = 4 + 1 + 8; /// Separates the different segments of /// the json path. pub const JSON_PATH_SEGMENT_SEP: u8 = 1u8; pub const JSON_PATH_SEGMENT_SEP_STR: &str = unsafe { std::str::from_utf8_unchecked(&[JSON_PATH_SEGMENT_SEP]) }; /// Separates the json path and the value in /// a JSON term binary representation. pub const JSON_END_OF_PATH: u8 = 0u8; /// Term represents the value that the token can take. /// /// It actually wraps a `Vec<u8>`. #[derive(Clone)] pub struct Term<B = Vec<u8>>(B) where B: AsRef<[u8]>; impl AsMut<Vec<u8>> for Term { fn as_mut(&mut self) -> &mut Vec<u8> { &mut self.0 } } impl Term { pub(crate) fn new() -> Term { Term(Vec::with_capacity(100)) } fn from_fast_value<T: FastValue>(field: Field, val: &T) -> Term { let mut term = Term(vec![0u8; FAST_VALUE_TERM_LEN]); term.set_field(T::to_type(), field); term.set_u64(val.to_u64()); term } /// Builds a term given a field, and a u64-value pub fn from_field_u64(field: Field, val: u64) -> Term { Term::from_fast_value(field, &val) } /// Builds a term given a field, and a i64-value pub fn from_field_i64(field: Field, val: i64) -> Term { Term::from_fast_value(field, &val) } /// Builds a term given a field, and a f64-value pub fn from_field_f64(field: Field, val: f64) -> Term { Term::from_fast_value(field, &val) } /// Builds a term given a field, and a DateTime value pub fn from_field_date(field: Field, val: &DateTime) -> Term { Term::from_fast_value(field, val) } /// Creates a `Term` given a facet. pub fn from_facet(field: Field, facet: &Facet) -> Term { let facet_encoded_str = facet.encoded_str(); Term::create_bytes_term(Type::Facet, field, facet_encoded_str.as_bytes()) } /// Builds a term given a field, and a string value pub fn from_field_text(field: Field, text: &str) -> Term { Term::create_bytes_term(Type::Str, field, text.as_bytes()) } fn create_bytes_term(typ: Type, field: Field, bytes: &[u8]) -> Term { let mut term = Term(vec![0u8; 5 + bytes.len()]); term.set_field(typ, field); term.0.extend_from_slice(bytes); term } /// Builds a term bytes. pub fn from_field_bytes(field: Field, bytes: &[u8]) -> Term { Term::create_bytes_term(Type::Bytes, field, bytes) } pub(crate) fn set_field(&mut self, typ: Type, field: Field) { self.0.clear(); self.0 .extend_from_slice(field.field_id().to_be_bytes().as_ref()); self.0.push(typ.to_code()); } /// Sets a u64 value in the term. /// /// U64 are serialized using (8-byte) BigEndian /// representation. /// The use of BigEndian has the benefit of preserving /// the natural order of the values. pub fn set_u64(&mut self, val: u64) { self.set_fast_value(val); self.set_bytes(val.to_be_bytes().as_ref()); } fn set_fast_value<T: FastValue>(&mut self, val: T) { self.0.resize(FAST_VALUE_TERM_LEN, 0u8); self.set_bytes(val.to_u64().to_be_bytes().as_ref()); } /// Sets a `i64` value in the term. pub fn set_i64(&mut self, val: i64) { self.set_fast_value(val); } /// Sets a `i64` value in the term. pub fn set_date(&mut self, date: crate::DateTime) { self.set_fast_value(date); } /// Sets a `f64` value in the term. pub fn set_f64(&mut self, val: f64) { self.set_fast_value(val); } /// Sets the value of a `Bytes` field. pub fn set_bytes(&mut self, bytes: &[u8]) { self.0.resize(5, 0u8); self.0.extend(bytes); } /// Set the texts only, keeping the field untouched. pub fn set_text(&mut self, text: &str) { self.set_bytes(text.as_bytes()); } /// Removes the value_bytes and set the type code. pub fn clear_with_type(&mut self, typ: Type) { self.truncate(5); self.0[4] = typ.to_code(); } /// Truncate the term right after the field and the type code. pub fn truncate(&mut self, len: usize) { self.0.truncate(len); } /// Truncate the term right after the field and the type code. pub fn append_bytes(&mut self, bytes: &[u8]) { self.0.extend_from_slice(bytes); } } impl<B> Ord for Term<B> where B: AsRef<[u8]> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.as_slice().cmp(other.as_slice()) } } impl<B> PartialOrd for Term<B> where B: AsRef<[u8]> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl<B> PartialEq for Term<B> where B: AsRef<[u8]> { fn eq(&self, other: &Self) -> bool { self.as_slice() == other.as_slice() } } impl<B> Eq for Term<B> where B: AsRef<[u8]> {} impl<B> Hash for Term<B> where B: AsRef<[u8]> { fn hash<H: Hasher>(&self, state: &mut H) { self.0.as_ref().hash(state) } } impl<B> Term<B> where B: AsRef<[u8]> { /// Wraps a object holding bytes pub fn wrap(data: B) -> Term<B> { Term(data) } fn typ_code(&self) -> u8 { *self .as_slice() .get(4) .expect("the byte representation is too short") } /// Return the type of the term. pub fn typ(&self) -> Type { Type::from_code(self.typ_code()).expect("The term has an invalid type code") } /// Returns the field. pub fn field(&self) -> Field { let mut field_id_bytes = [0u8; 4]; field_id_bytes.copy_from_slice(&self.0.as_ref()[..4]); Field::from_field_id(u32::from_be_bytes(field_id_bytes)) } /// Returns the `u64` value stored in a term. /// /// Returns None if the term is not of the u64 type, or if the term byte representation /// is invalid. pub fn as_u64(&self) -> Option<u64> { self.get_fast_type::<u64>() } fn get_fast_type<T: FastValue>(&self) -> Option<T> { if self.typ() != T::to_type() { return None; } let mut value_bytes = [0u8; 8]; let bytes = self.value_bytes(); if bytes.len() != 8 { return None; } value_bytes.copy_from_slice(self.value_bytes()); let value_u64 = u64::from_be_bytes(value_bytes); Some(FastValue::from_u64(value_u64)) } /// Returns the `i64` value stored in a term. /// /// Returns None if the term is not of the i64 type, or if the term byte representation /// is invalid. pub fn as_i64(&self) -> Option<i64> { self.get_fast_type::<i64>() } /// Returns the `f64` value stored in a term. /// /// Returns None if the term is not of the f64 type, or if the term byte representation /// is invalid. pub fn as_f64(&self) -> Option<f64> { self.get_fast_type::<f64>() } /// Returns the `Date` value stored in a term. /// /// Returns None if the term is not of the Date type, or if the term byte representation /// is invalid. pub fn as_date(&self) -> Option<crate::DateTime> { self.get_fast_type::<crate::DateTime>() } /// Returns the text associated with the term. /// /// Returns None if the field is not of string type /// or if the bytes are not valid utf-8. pub fn as_str(&self) -> Option<&str> { if self.as_slice().len() < 5 { return None; } if self.typ() != Type::Str { return None; } str::from_utf8(self.value_bytes()).ok() } /// Returns the facet associated with the term. /// /// Returns None if the field is not of facet type /// or if the bytes are not valid utf-8. pub fn as_facet(&self) -> Option<Facet> { if self.as_slice().len() < 5 { return None; } if self.typ() != Type::Facet { return None; } let facet_encode_str = str::from_utf8(self.value_bytes()).ok()?; Some(Facet::from_encoded_string(facet_encode_str.to_string())) } /// Returns the bytes associated with the term. /// /// Returns None if the field is not of bytes type. pub fn as_bytes(&self) -> Option<&[u8]> { if self.as_slice().len() < 5 { return None; } if self.typ() != Type::Bytes { return None; } Some(self.value_bytes()) } /// Returns the serialized value of the term. /// (this does not include the field.) /// /// If the term is a string, its value is utf-8 encoded. /// If the term is a u64, its value is encoded according /// to `byteorder::LittleEndian`. pub fn value_bytes(&self) -> &[u8] { &self.0.as_ref()[5..] } /// Returns the underlying `&[u8]`. /// /// Do NOT rely on this byte representation in the index. /// This value is likely to change in the future. pub(crate) fn as_slice(&self) -> &[u8] { self.0.as_ref() } } fn write_opt<T: std::fmt::Debug>(f: &mut fmt::Formatter, val_opt: Option<T>) -> fmt::Result { if let Some(val) = val_opt { write!(f, "{:?}", val)?; } Ok(()) } fn as_str(value_bytes: &[u8]) -> Option<&str> { std::str::from_utf8(value_bytes).ok() } fn get_fast_type<T: FastValue>(bytes: &[u8]) -> Option<T> { let value_u64 = u64::from_be_bytes(bytes.try_into().ok()?); Some(FastValue::from_u64(value_u64)) } /// Returns the json path (without non-human friendly separators, the type of the value, and the /// value bytes). Returns None if the value is not JSON or is not valid. pub(crate) fn as_json_path_type_value_bytes(bytes: &[u8]) -> Option<(&str, Type, &[u8])> { let pos = bytes.iter().cloned().position(|b| b == JSON_END_OF_PATH)?; let json_path = str::from_utf8(&bytes[..pos]).ok()?; let type_code = *bytes.get(pos + 1)?; let typ = Type::from_code(type_code)?; Some((json_path, typ, &bytes[pos + 2..])) } fn debug_value_bytes(typ: Type, bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result { match typ { Type::Str => { let s = as_str(bytes); write_opt(f, s)?; } Type::U64 => { write_opt(f, get_fast_type::<u64>(bytes))?; } Type::I64 => { write_opt(f, get_fast_type::<i64>(bytes))?; } Type::F64 => { write_opt(f, get_fast_type::<f64>(bytes))?; } // TODO pretty print these types too. Type::Date => { write_opt(f, get_fast_type::<crate::DateTime>(bytes))?; } Type::Facet => { let facet_str = str::from_utf8(bytes) .ok() .map(ToString::to_string) .map(Facet::from_encoded_string) .map(|facet| facet.to_path_string()); write_opt(f, facet_str)?; } Type::Bytes => { write_opt(f, Some(bytes))?; } Type::Json => { if let Some((path, typ, bytes)) = as_json_path_type_value_bytes(bytes) { let path_pretty = path.replace(JSON_PATH_SEGMENT_SEP_STR, "."); write!(f, "path={path_pretty}, vtype={typ:?}, ")?; debug_value_bytes(typ, bytes, f)?; } } } Ok(()) } impl<B> fmt::Debug for Term<B> where B: AsRef<[u8]> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let field_id = self.field().field_id(); let typ = self.typ(); write!(f, "Term(type={typ:?}, field={field_id}, ")?; debug_value_bytes(typ, self.value_bytes(), f)?; write!(f, ")",)?; Ok(()) } } #[cfg(test)] mod tests { use crate::schema::*; #[test] pub fn test_term_str() { let mut schema_builder = Schema::builder(); schema_builder.add_text_field("text", STRING); let title_field = schema_builder.add_text_field("title", STRING); let term = Term::from_field_text(title_field, "test"); assert_eq!(term.field(), title_field); assert_eq!(term.typ(), Type::Str); assert_eq!(term.as_str(), Some("test")) } #[test] pub fn test_term_u64() { let mut schema_builder = Schema::builder(); let count_field = schema_builder.add_u64_field("count", INDEXED); let term = Term::from_field_u64(count_field, 983u64); assert_eq!(term.field(), count_field); assert_eq!(term.typ(), Type::U64); assert_eq!(term.as_slice().len(), super::FAST_VALUE_TERM_LEN); assert_eq!(term.as_u64(), Some(983u64)) } }
30.526077
96
0.581414
40ba28b5c14d871f05695843c26809af6ff3d471
29,652
py
Python
pyp.py
hauntsaninja/pyp
6e82bd90f1a39f0431f8b1cc059e91b61e2e9986
[ "MIT" ]
1,194
2020-05-04T23:39:37.000Z
2022-03-31T14:16:52.000Z
pyp.py
hauntsaninja/pyp
6e82bd90f1a39f0431f8b1cc059e91b61e2e9986
[ "MIT" ]
25
2020-05-09T21:52:26.000Z
2022-03-06T23:36:51.000Z
pyp.py
hauntsaninja/pyp
6e82bd90f1a39f0431f8b1cc059e91b61e2e9986
[ "MIT" ]
35
2020-05-09T20:48:50.000Z
2021-12-14T07:07:20.000Z
#!/usr/bin/env python3 import argparse import ast import importlib import inspect import itertools import os import sys import textwrap import traceback from collections import defaultdict from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, cast __all__ = ["pypprint"] __version__ = "0.3.4" def pypprint(*args, **kwargs): # type: ignore """Replacement for ``print`` that special-cases dicts and iterables. - Dictionaries are printed one line per key-value pair, with key and value colon-separated. - Iterables (excluding strings) are printed one line per item - Everything else is delegated to ``print`` """ from typing import Iterable if len(args) != 1: print(*args, **kwargs) return x = args[0] if isinstance(x, dict): for k, v in x.items(): print(f"{k}:", v, **kwargs) elif isinstance(x, Iterable) and not isinstance(x, str): for i in x: print(i, **kwargs) else: print(x, **kwargs) class NameFinder(ast.NodeVisitor): """Finds undefined names, top-level defined names and wildcard imports in the given AST. A top-level defined name is any name that is stored to in the top-level scopes of ``trees``. An undefined name is any name that is loaded before it is defined (in any scope). Notes: a) we ignore deletes, b) used builtins will appear in undefined names, c) this logic doesn't fully support comprehension / nonlocal / global / late-binding scopes. """ def __init__(self, *trees: ast.AST) -> None: self._scopes: List[Set[str]] = [set()] self._comprehension_scopes: List[int] = [] self.undefined: Set[str] = set() self.wildcard_imports: List[str] = [] for tree in trees: self.visit(tree) assert len(self._scopes) == 1 @property def top_level_defined(self) -> Set[str]: return self._scopes[0] def flexible_visit(self, value: Any) -> None: if isinstance(value, list): for item in value: if isinstance(item, ast.AST): self.visit(item) elif isinstance(value, ast.AST): self.visit(value) def generic_visit(self, node: ast.AST) -> None: def order(f_v: Tuple[str, Any]) -> int: # This ordering fixes comprehensions, dict comps, loops, assignments return {"generators": -3, "iter": -3, "key": -2, "value": -1}.get(f_v[0], 0) # Adapted from ast.NodeVisitor.generic_visit, but re-orders traversal a little for _, value in sorted(ast.iter_fields(node), key=order): self.flexible_visit(value) def visit_Name(self, node: ast.Name) -> None: if isinstance(node.ctx, ast.Load): if all(node.id not in d for d in self._scopes): self.undefined.add(node.id) elif isinstance(node.ctx, ast.Store): self._scopes[-1].add(node.id) # Ignore deletes, see docstring self.generic_visit(node) def visit_Global(self, node: ast.Global) -> None: self._scopes[-1] |= self._scopes[0] & set(node.names) def visit_Nonlocal(self, node: ast.Nonlocal) -> None: if len(self._scopes) >= 2: self._scopes[-1] |= self._scopes[-2] & set(node.names) def visit_AugAssign(self, node: ast.AugAssign) -> None: if isinstance(node.target, ast.Name): # TODO: think about global, nonlocal if node.target.id not in self._scopes[-1]: self.undefined.add(node.target.id) self.generic_visit(node) def visit_NamedExpr(self, node: Any) -> None: self.visit(node.value) # PEP 572 has weird scoping rules assert isinstance(node.target, ast.Name) assert isinstance(node.target.ctx, ast.Store) scope_index = len(self._scopes) - 1 comp_index = len(self._comprehension_scopes) - 1 while comp_index >= 0 and scope_index == self._comprehension_scopes[comp_index]: scope_index -= 1 comp_index -= 1 self._scopes[scope_index].add(node.target.id) def visit_alias(self, node: ast.alias) -> None: if node.name != "*": self._scopes[-1].add(node.asname if node.asname is not None else node.name) def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if node.module is not None and "*" in (a.name for a in node.names): self.wildcard_imports.append(node.module) self.generic_visit(node) def visit_ClassDef(self, node: ast.ClassDef) -> None: self.flexible_visit(node.decorator_list) self.flexible_visit(node.bases) self.flexible_visit(node.keywords) self._scopes.append(set()) self.flexible_visit(node.body) self._scopes.pop() # Classes are not okay with self-reference, so define ``name`` afterwards self._scopes[-1].add(node.name) def visit_function_helper(self, node: Any, name: Optional[str] = None) -> None: # Functions are okay with recursion, but not self-reference while defining default values self.flexible_visit(node.args) if name is not None: self._scopes[-1].add(name) self._scopes.append(set()) for arg_node in ast.iter_child_nodes(node.args): if isinstance(arg_node, ast.arg): self._scopes[-1].add(arg_node.arg) self.flexible_visit(node.body) self._scopes.pop() def visit_FunctionDef(self, node: ast.FunctionDef) -> None: self.flexible_visit(node.decorator_list) self.visit_function_helper(node, node.name) def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: self.flexible_visit(node.decorator_list) self.visit_function_helper(node, node.name) def visit_Lambda(self, node: ast.Lambda) -> None: self.visit_function_helper(node) def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: # ExceptHandler's name is scoped to the handler. If name exists and the name is not already # defined, we'll define then undefine it to mimic the scope. if not node.name or node.name in self._scopes[-1]: self.generic_visit(node) return self.flexible_visit(node.type) assert node.name is not None self._scopes[-1].add(node.name) self.flexible_visit(node.body) self._scopes[-1].remove(node.name) def visit_comprehension_helper(self, node: Any) -> None: self._comprehension_scopes.append(len(self._scopes)) self._scopes.append(set()) self.generic_visit(node) self._scopes.pop() self._comprehension_scopes.pop() visit_ListComp = visit_comprehension_helper visit_SetComp = visit_comprehension_helper visit_GeneratorExp = visit_comprehension_helper visit_DictComp = visit_comprehension_helper def dfs_walk(node: ast.AST) -> Iterator[ast.AST]: """Helper to iterate over an AST depth-first.""" stack = [node] while stack: node = stack.pop() stack.extend(reversed(list(ast.iter_child_nodes(node)))) yield node MAGIC_VARS = { "index": {"i", "idx", "index"}, "loop": {"line", "x", "l"}, "input": {"lines", "stdin"}, } def is_magic_var(name: str) -> bool: return any(name in vars for vars in MAGIC_VARS.values()) class PypError(Exception): pass def get_config_contents() -> str: """Returns the empty string if no config file is specified.""" config_file = os.environ.get("PYP_CONFIG_PATH") if config_file is None: return "" try: with open(config_file, "r") as f: return f.read() except FileNotFoundError as e: raise PypError(f"Config file not found at PYP_CONFIG_PATH={config_file}") from e class PypConfig: """PypConfig is responsible for handling user configuration. We allow users to configure pyp with a config file that is very Python-like. Rather than executing the config file as Python unconditionally, we treat it as a source of definitions. We keep track of what each top-level stmt in the AST of the config file defines, and if we need that definition in our program, use it. A wrinkle here is that definitions in the config file may depend on other definitions within the config file; this is handled by build_missing_config. Another wrinkle is wildcard imports; these are kept track of and added to the list of special cased wildcard imports in build_missing_imports. """ def __init__(self) -> None: config_contents = get_config_contents() try: config_ast = ast.parse(config_contents) except SyntaxError as e: error = f": {e.text!r}" if e.text else "" raise PypError(f"Config has invalid syntax{error}") from e # List of config parts self.parts: List[ast.stmt] = config_ast.body # Maps from a name to index of config part that defines it self.name_to_def: Dict[str, int] = {} self.def_to_names: Dict[int, List[str]] = defaultdict(list) # Maps from index of config part to undefined names it needs self.requires: Dict[int, Set[str]] = defaultdict(set) # Modules from which automatic imports work without qualification, ordered by AST encounter self.wildcard_imports: List[str] = [] self.shebang: str = "#!/usr/bin/env python3" if config_contents.startswith("#!"): self.shebang = "\n".join( itertools.takewhile(lambda l: l.startswith("#"), config_contents.splitlines()) ) top_level: Tuple[Any, ...] = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) top_level += (ast.Import, ast.ImportFrom, ast.Assign, ast.AnnAssign, ast.If, ast.Try) for index, part in enumerate(self.parts): if not isinstance(part, top_level): node_type = type( part.value if isinstance(part, ast.Expr) else part ).__name__.lower() raise PypError( "Config only supports a subset of Python at top level; " f"unsupported construct ({node_type}) on line {part.lineno}" ) f = NameFinder(part) for name in f.top_level_defined: if self.name_to_def.get(name, index) != index: raise PypError(f"Config has multiple definitions of {repr(name)}") if is_magic_var(name): raise PypError(f"Config cannot redefine built-in magic variable {repr(name)}") self.name_to_def[name] = index self.def_to_names[index].append(name) self.requires[index] = f.undefined self.wildcard_imports.extend(f.wildcard_imports) class PypTransform: """PypTransform is responsible for transforming all input code. A lot of pyp's magic comes from it making decisions based on defined and undefined names in the input. This class helps keep track of that state as things change based on transformations. In general, the logic in here is very sensitive to reordering; there are various implicit assumptions about what transformations have happened and what names have been defined. But the code is pretty small and the tests are good, so you should be okay! """ def __init__( self, before: List[str], code: List[str], after: List[str], define_pypprint: bool, config: PypConfig, ) -> None: def parse_input(code: List[str]) -> ast.Module: try: return ast.parse(textwrap.dedent("\n".join(code).strip())) except SyntaxError as e: message = traceback.format_exception_only(type(e), e) message[0] = "Invalid input\n\n" raise PypError("".join(message).strip()) from e self.before_tree = parse_input(before) self.tree = parse_input(code) self.after_tree = parse_input(after) f = NameFinder(self.before_tree, self.tree, self.after_tree) self.defined: Set[str] = f.top_level_defined self.undefined: Set[str] = f.undefined self.wildcard_imports: List[str] = f.wildcard_imports # We'll always use sys in ``build_input``, so add it to undefined. # This lets config define it or lets us automatically import it later # (If before defines it, we'll just let it override the import...) self.undefined.add("sys") self.define_pypprint = define_pypprint self.config = config # The print statement ``build_output`` will add, if it determines it needs to. self.implicit_print: Optional[ast.Call] = None def build_missing_config(self) -> None: """Modifies the AST to define undefined names defined in config.""" config_definitions: Set[str] = set() attempt_to_define = set(self.undefined) while attempt_to_define: can_define = attempt_to_define & set(self.config.name_to_def) # The things we can define might in turn require some definitions, so update the things # we need to attempt to define and loop attempt_to_define = set() for name in can_define: config_definitions.update(self.config.def_to_names[self.config.name_to_def[name]]) attempt_to_define.update(self.config.requires[self.config.name_to_def[name]]) # We don't need to attempt to define things we've already decided we need to define attempt_to_define -= config_definitions config_indices = {self.config.name_to_def[name] for name in config_definitions} # Run basically the same thing in reverse to see which dependencies stem from magic vars before_config_indices = set(config_indices) derived_magic_indices = { i for i in config_indices if any(map(is_magic_var, self.config.requires[i])) } derived_magic_names = set() while derived_magic_indices: before_config_indices -= derived_magic_indices derived_magic_names |= { name for i in derived_magic_indices for name in self.config.def_to_names[i] } derived_magic_indices = { i for i in before_config_indices if self.config.requires[i] & derived_magic_names } magic_config_indices = config_indices - before_config_indices before_config_defs = [self.config.parts[i] for i in sorted(before_config_indices)] magic_config_defs = [self.config.parts[i] for i in sorted(magic_config_indices)] self.before_tree.body = before_config_defs + self.before_tree.body self.tree.body = magic_config_defs + self.tree.body for i in config_indices: self.undefined.update(self.config.requires[i]) self.defined |= config_definitions self.undefined -= config_definitions def define(self, name: str) -> None: """Defines a name.""" self.defined.add(name) self.undefined.discard(name) def get_valid_name_in_top_scope(self, name: str) -> str: """Return a name related to ``name`` that does not conflict with existing definitions.""" while name in self.defined or name in self.undefined: name += "_" return name def build_output(self) -> None: """Ensures that the AST prints something. This is done by either a) checking whether we load a thing that prints, or b) if the last thing in the tree is an expression, modifying the tree to print it. """ if self.undefined & {"print", "pprint", "pp", "pypprint"}: # has an explicit print return def inner(body: List[ast.stmt], use_pypprint: bool = False) -> bool: if not body: return False if isinstance(body[-1], ast.Pass): del body[-1] return True if not isinstance(body[-1], ast.Expr): if ( # If the last thing in the tree is a statement that has a body hasattr(body[-1], "body") # and doesn't have an orelse, since users could expect the print in that branch and not getattr(body[-1], "orelse", []) # and doesn't enter a new scope and not isinstance( body[-1], (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef) ) ): # ...then recursively look for a standalone expression return inner(body[-1].body, use_pypprint) # type: ignore return False if isinstance(body[-1].value, ast.Name): output = body[-1].value.id body.pop() else: output = self.get_valid_name_in_top_scope("output") self.define(output) body[-1] = ast.Assign( targets=[ast.Name(id=output, ctx=ast.Store())], value=body[-1].value ) print_fn = "print" if use_pypprint: print_fn = "pypprint" self.undefined.add("pypprint") if_print = ast.parse(f"if {output} is not None: {print_fn}({output})").body[0] body.append(if_print) self.implicit_print = if_print.body[0].value # type: ignore return True # First attempt to add a print to self.after_tree, then to self.tree # We use pypprint in self.after_tree and print in self.tree, although the latter is # subject to change later on if we call ``use_pypprint_for_implicit_print``. This logic # could be a little simpler if we refactored so that we know what transformations we will # do before we do them. success = inner(self.after_tree.body, True) or inner(self.tree.body) if not success: raise PypError( "Code doesn't generate any output; either explicitly print something, end with " "an expression that pyp can print, or explicitly end with `pass`." ) def use_pypprint_for_implicit_print(self) -> None: """If we implicitly print, use pypprint instead of print.""" if self.implicit_print is not None: self.implicit_print.func.id = "pypprint" # type: ignore # Make sure we import it later self.undefined.add("pypprint") def build_input(self) -> None: """Modifies the AST to use input from stdin. How we do this depends on which magic variables are used. """ possible_vars = {typ: names & self.undefined for typ, names in MAGIC_VARS.items()} if (possible_vars["loop"] or possible_vars["index"]) and possible_vars["input"]: loop_names = ", ".join(possible_vars["loop"] or possible_vars["index"]) input_names = ", ".join(possible_vars["input"]) raise PypError( f"Candidates found for both loop variable ({loop_names}) and " f"input variable ({input_names})" ) for typ, names in possible_vars.items(): if len(names) > 1: names_str = ", ".join(names) raise PypError(f"Multiple candidates for {typ} variable: {names_str}") if possible_vars["loop"] or possible_vars["index"]: # We'll loop over stdin and define loop / index variables idx_var = possible_vars["index"].pop() if possible_vars["index"] else None loop_var = possible_vars["loop"].pop() if possible_vars["loop"] else None if loop_var: self.define(loop_var) if idx_var: self.define(idx_var) if loop_var is None: loop_var = "_" if idx_var: for_loop = f"for {idx_var}, {loop_var} in enumerate(sys.stdin): " else: for_loop = f"for {loop_var} in sys.stdin: " for_loop += f"{loop_var} = {loop_var}.rstrip('\\n')" loop: ast.For = ast.parse(for_loop).body[0] # type: ignore loop.body.extend(self.tree.body) self.tree.body = [loop] elif possible_vars["input"]: # We'll read from stdin and define the necessary input variable input_var = possible_vars["input"].pop() self.define(input_var) if input_var == "stdin": input_assign = ast.parse(f"{input_var} = sys.stdin") else: input_assign = ast.parse(f"{input_var} = [x.rstrip('\\n') for x in sys.stdin]") self.tree.body = input_assign.body + self.tree.body self.use_pypprint_for_implicit_print() else: no_pipe_assertion = ast.parse( "assert sys.stdin.isatty() or not sys.stdin.read(), " '''"The command doesn't process input, but input is present"''' ) self.tree.body = no_pipe_assertion.body + self.tree.body self.use_pypprint_for_implicit_print() def build_missing_imports(self) -> None: """Modifies the AST to import undefined names.""" self.undefined -= set(dir(__import__("builtins"))) # Optimisation: we will almost always define sys and pypprint. However, in order for us to # get to `import sys`, we'll need to examine our wildcard imports, which in the presence # of config, could be slow. if "pypprint" in self.undefined: pypprint_def = ( inspect.getsource(pypprint) if self.define_pypprint else "from pyp import pypprint" ) self.before_tree.body = ast.parse(pypprint_def).body + self.before_tree.body self.undefined.remove("pypprint") if "sys" in self.undefined: self.before_tree.body = ast.parse("import sys").body + self.before_tree.body self.undefined.remove("sys") # Now short circuit if we can if not self.undefined: return def get_names_in_module(module: str) -> Any: try: mod = importlib.import_module(module) except ImportError as e: raise PypError( f"Config contains wildcard import from {module}, but {module} failed to import" ) from e return getattr(mod, "__all__", (n for n in dir(mod) if not n.startswith("_"))) subimports = {"Path": "pathlib", "pp": "pprint"} wildcard_imports = ( ["itertools", "math", "collections"] + self.config.wildcard_imports + self.wildcard_imports ) subimports.update( {name: module for module in wildcard_imports for name in get_names_in_module(module)} ) def get_import_for_name(name: str) -> str: if name in subimports: return f"from {subimports[name]} import {name}" return f"import {name}" self.before_tree.body = [ ast.parse(stmt).body[0] for stmt in sorted(map(get_import_for_name, self.undefined)) ] + self.before_tree.body def build(self) -> ast.Module: """Returns a transformed AST.""" self.build_missing_config() self.build_output() self.build_input() self.build_missing_imports() ret = ast.parse("") ret.body = self.before_tree.body + self.tree.body + self.after_tree.body # Add fake line numbers to the nodes, so we can generate a traceback on error i = 0 for node in dfs_walk(ret): if isinstance(node, ast.stmt): i += 1 node.lineno = i return ast.fix_missing_locations(ret) def unparse(tree: ast.AST, short_fallback: bool = False) -> str: """Returns Python code equivalent to executing ``tree``.""" if sys.version_info >= (3, 9): return ast.unparse(tree) try: import astunparse # type: ignore return cast(str, astunparse.unparse(tree)) except ImportError: pass if short_fallback: return f"# {ast.dump(tree)} # --explain has instructions to make this readable" return f""" from ast import * tree = fix_missing_locations({ast.dump(tree)}) # To see this in human readable form, run pyp with Python 3.9 # Alternatively, install a third party ast unparser: `python3 -m pip install astunparse` # Once you've done that, simply re-run. # In the meantime, this script is fully functional, if not easily readable or modifiable... exec(compile(tree, filename="<ast>", mode="exec"), {{}}) """ def run_pyp(args: argparse.Namespace) -> None: config = PypConfig() tree = PypTransform(args.before, args.code, args.after, args.define_pypprint, config).build() if args.explain: print(config.shebang) print(unparse(tree)) return try: exec(compile(tree, filename="<pyp>", mode="exec"), {}) except Exception as e: try: line_to_node: Dict[int, ast.AST] = {} for node in dfs_walk(tree): line_to_node.setdefault(getattr(node, "lineno", -1), node) def code_for_line(lineno: int) -> str: node = line_to_node[lineno] # Don't unparse nested child statements. Note this destroys the tree. for _, value in ast.iter_fields(node): if isinstance(value, list) and value and isinstance(value[0], ast.stmt): value.clear() return unparse(node, short_fallback=True).strip() # Time to commit several sins against CPython implementation details tb_except = traceback.TracebackException( type(e), e, e.__traceback__.tb_next # type: ignore ) for fs in tb_except.stack: if fs.filename == "<pyp>": fs._line = code_for_line(fs.lineno) # type: ignore[attr-defined] fs.lineno = "PYP_REDACTED" # type: ignore[assignment] tb_format = tb_except.format() assert "Traceback (most recent call last)" in next(tb_format) message = "Possible reconstructed traceback (most recent call last):\n" message += "".join(tb_format).strip("\n") message = message.replace(", line PYP_REDACTED", "") except Exception: message = "".join(traceback.format_exception_only(type(e), e)).strip() if isinstance(e, ModuleNotFoundError): message += ( "\n\nNote pyp treats undefined names as modules to automatically import. " "Perhaps you forgot to define something or PYP_CONFIG_PATH is set incorrectly?" ) if args.before and isinstance(e, NameError): var = str(e) var = var[var.find("'") + 1 : var.rfind("'")] if var in ("lines", "stdin"): message += ( "\n\nNote code in `--before` runs before any magic variables are defined " "and should not process input. Your command should work by simply removing " "`--before`, so instead passing in multiple statements in the main section " "of your code." ) raise PypError( "Code raised the following exception, consider using --explain to investigate:\n\n" f"{message}" ) from e def parse_options(args: List[str]) -> argparse.Namespace: parser = argparse.ArgumentParser( prog="pyp", formatter_class=argparse.RawDescriptionHelpFormatter, description=( "Easily run Python at the shell!\n\n" "For help and examples, see https://github.com/hauntsaninja/pyp\n\n" "Cheatsheet:\n" "- Use `x`, `l` or `line` for a line in the input. Use `i`, `idx` or `index` " "for the index\n" "- Use `lines` to get a list of rstripped lines\n" "- Use `stdin` to get sys.stdin\n" "- Use print explicitly if you don't like when or how or what pyp's printing\n" "- If the magic is ever too mysterious, use --explain" ), ) parser.add_argument("code", nargs="+", help="Python you want to run") parser.add_argument( "--explain", "--script", action="store_true", help="Prints the Python that would get run, instead of running it", ) parser.add_argument( "-b", "--before", action="append", default=[], metavar="CODE", help="Python to run before processing input", ) parser.add_argument( "-a", "--after", action="append", default=[], metavar="CODE", help="Python to run after processing input", ) parser.add_argument( "--define-pypprint", action="store_true", help="Defines pypprint, if used, instead of importing it from pyp.", ) parser.add_argument("--version", action="version", version=f"pyp {__version__}") return parser.parse_args(args) def main() -> None: try: run_pyp(parse_options(sys.argv[1:])) except PypError as e: print(f"error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": main()
40.563611
100
0.608121
869dedddac43ac7db8ac54b1891e8c86e9bc6b16
141
sql
SQL
sql/_07_misc/_01_statistics/cases/1010.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
9
2016-03-24T09:51:52.000Z
2022-03-23T10:49:47.000Z
sql/_07_misc/_01_statistics/cases/1010.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
173
2016-04-13T01:16:54.000Z
2022-03-16T07:50:58.000Z
sql/_07_misc/_01_statistics/cases/1010.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
38
2016-03-24T17:10:31.000Z
2021-10-30T22:55:45.000Z
--[er]Optimizing class that don't exist using "update statistics" with "all" and "except" key UPDATE STATISTICS ON ALL DCL1 (EXCEPT DCL2);
35.25
94
0.744681
7d667a712dc062ad73d1619437f479a8c273df98
54
html
HTML
index.html
Pascaldel/web
8f1baa6359a6d661b8a5124811048fb5ed2ccf5a
[ "MIT" ]
null
null
null
index.html
Pascaldel/web
8f1baa6359a6d661b8a5124811048fb5ed2ccf5a
[ "MIT" ]
null
null
null
index.html
Pascaldel/web
8f1baa6359a6d661b8a5124811048fb5ed2ccf5a
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en" > Coming soon </html>
54
54
0.648148
e85d256e89cc882b2f6b5d1059df706359173943
94
sql
SQL
sql/dbTables.sql
XarisA/Code-Snippets
9fab7575b5a94682dfd9ce1e80a5034001f2c3a7
[ "MIT" ]
null
null
null
sql/dbTables.sql
XarisA/Code-Snippets
9fab7575b5a94682dfd9ce1e80a5034001f2c3a7
[ "MIT" ]
null
null
null
sql/dbTables.sql
XarisA/Code-Snippets
9fab7575b5a94682dfd9ce1e80a5034001f2c3a7
[ "MIT" ]
null
null
null
SELECT top 100 * FROM INFORMATION_SCHEMA.TABLES where substring(TABLE_NAME,1,6)='f6103b'
23.5
49
0.765957
359bb81a60834ae269097964df5e5c18d520c0c8
399
sql
SQL
airbyte-integrations/bases/base-normalization/dbt-project-template/macros/cross_db_utils/datatypes.sql
rajatariya21/airbyte
11e70a7a96e2682b479afbe6f709b9a5fe9c4a8d
[ "MIT" ]
3
2021-09-10T13:29:51.000Z
2021-11-17T10:44:43.000Z
airbyte-integrations/bases/base-normalization/dbt-project-template/macros/cross_db_utils/datatypes.sql
rajatariya21/airbyte
11e70a7a96e2682b479afbe6f709b9a5fe9c4a8d
[ "MIT" ]
4
2021-09-01T00:33:50.000Z
2022-02-27T16:13:46.000Z
airbyte-integrations/bases/base-normalization/dbt-project-template/macros/cross_db_utils/datatypes.sql
rajatariya21/airbyte
11e70a7a96e2682b479afbe6f709b9a5fe9c4a8d
[ "MIT" ]
1
2021-07-02T15:08:53.000Z
2021-07-02T15:08:53.000Z
{# json ------------------------------------------------- #} {%- macro type_json() -%} {{ adapter.dispatch('type_json')() }} {%- endmacro -%} {% macro default__type_json() %} string {% endmacro %} {%- macro redshift__type_json() -%} varchar {%- endmacro -%} {% macro postgres__type_json() %} jsonb {% endmacro %} {% macro snowflake__type_json() %} variant {% endmacro %}
18.136364
65
0.508772
175a6c68a9e731e76f7c66ad5dfd3bafd39427dc
1,422
htm
HTML
pa1-skeleton/pa1-data/8/www.stanford.edu_dept_legal_Worddocs_UMcourtdoc.htm
yzhong94/cs276-spring-2019
a4780a9f88b8c535146040fe11bb513c91c5693b
[ "MIT" ]
null
null
null
pa1-skeleton/pa1-data/8/www.stanford.edu_dept_legal_Worddocs_UMcourtdoc.htm
yzhong94/cs276-spring-2019
a4780a9f88b8c535146040fe11bb513c91c5693b
[ "MIT" ]
null
null
null
pa1-skeleton/pa1-data/8/www.stanford.edu_dept_legal_Worddocs_UMcourtdoc.htm
yzhong94/cs276-spring-2019
a4780a9f88b8c535146040fe11bb513c91c5693b
[ "MIT" ]
null
null
null
office of the general counsel about the office stanford legal facts frequently asked questions hospitals legal information stanford links external legal resources recent legal developments u michigan court documents university of michigan law school brief grutter v bollinger 02 241 posted 2 20 03 university of michigan brief undergraduate admissions gratz v bollinger 02 516 posted 2 19 03 amicus brief of harvard black law students association stanford black law students association and yale black law students association posted 2 20 03 amicus brief of harvard university brown university university of chicago dartmouth college duke university university of pennsylvania princeton university yale university is located at http www news harvard edu gazette daily 0302 17 amicus html amicus briefs filed in favor of the petitioners including the briefs filed by the government january 16 2003 http chronicle com indepth michigan documents documents htm a library of court documents from the appellate and district courts including petitions to the supreme court for certiorari http supreme lp findlaw com supreme_court docket 2002 april html university of michigan lawsuit admissions website http www umich edu urel admissions back to affirmative action home page 2002 2010 board of trustees leland stanford junior university all rights reserved disclaimer questions comments suggestions to director of legal services
711
1,421
0.851617
609eacc257099b1c3b29539920ee283b06709827
937
kt
Kotlin
Section 6/helper-files-v2/kotlin files/MainActivity.kt
PacktPublishing/-Hands-On-Android-Animations
66be15de2b9d6c411e28bf59039bc0f4c4555e84
[ "MIT" ]
8
2019-05-16T09:32:47.000Z
2021-11-08T13:10:44.000Z
Section 6/helper-files-v2/kotlin files/MainActivity.kt
PacktPublishing/-Hands-On-Android-Animations
66be15de2b9d6c411e28bf59039bc0f4c4555e84
[ "MIT" ]
null
null
null
Section 6/helper-files-v2/kotlin files/MainActivity.kt
PacktPublishing/-Hands-On-Android-Animations
66be15de2b9d6c411e28bf59039bc0f4c4555e84
[ "MIT" ]
4
2019-05-16T09:32:52.000Z
2022-03-02T20:32:09.000Z
package learn.animation.com.recyclerviewanimation import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setUpRecyclerView() } private fun setUpRecyclerView() { val adapter = RecyclerAdapter(this, Landscape.data) recyclerView.adapter = adapter val layoutManager = LinearLayoutManager(this) layoutManager.orientation = LinearLayoutManager.VERTICAL recyclerView.layoutManager = layoutManager recyclerView.itemAnimator = DefaultItemAnimator() } }
27.558824
59
0.827108
1214f15e454479c4ecfe5dc45da358e48e6ec389
3,107
kt
Kotlin
app/src/main/java/com/example/myapplication/MainActivity.kt
FIftekhar/SimpleToDo
880296ffbb8848da6fd2781e6820d64741c83caf
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/myapplication/MainActivity.kt
FIftekhar/SimpleToDo
880296ffbb8848da6fd2781e6820d64741c83caf
[ "Apache-2.0" ]
1
2022-01-03T11:59:25.000Z
2022-01-03T11:59:25.000Z
app/src/main/java/com/example/myapplication/MainActivity.kt
FIftekhar/SimpleToDo
880296ffbb8848da6fd2781e6820d64741c83caf
[ "Apache-2.0" ]
null
null
null
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import org.apache.commons.io.FileUtils import android.util.Log import android.widget.Button import android.widget.EditText import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import java.io.File import java.io.IOException import java.nio.charset.Charset class MainActivity : AppCompatActivity() { var ListOfTasks = mutableListOf<String>() lateinit var adapter: TaskItemAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val onLongClickListener = object : TaskItemAdapter.OnLongClickListener { override fun onItemLongClicked(position: Int) { // Remove item from list ListOfTasks.removeAt(position) // Notify adapter that data set has changed adapter.notifyDataSetChanged() // Save the tasks list saveItems() } } loadItems() // Look up recyclerView in layout val recyclerView = findViewById<RecyclerView>(R.id.recyclerView) // Create adapter passing in the sample user data adapter = TaskItemAdapter(ListOfTasks, onLongClickListener) // Attach the adapter to the recyclerview to populate items recyclerView.adapter = adapter // Set layout manager to position the items recyclerView.layoutManager = LinearLayoutManager(this) // Set up the button and input field so tasks can be added to the list val inputTextField = findViewById<EditText>(R.id.addTaskField) // Get a reference to the button and then set an onClickListener findViewById<Button>(R.id.button).setOnClickListener { // Retrieve text that user inputted val userInputtedTask = inputTextField.text.toString() // Add the text to the list ListOfTasks.add(userInputtedTask) // Notify the adapter that data has changed adapter.notifyItemInserted(ListOfTasks.size - 1) // Clear text field after item is added inputTextField.setText("") // Save tasks list to file saveItems() } } // Save the data the user inputted by reading and writing from and to a file // Get the file we need fun getDataFile() : File { return File(filesDir, "data.txt") } // Load items by reading from the file fun loadItems() { try { ListOfTasks = FileUtils.readLines(getDataFile(), Charset.defaultCharset()) } catch (ioException: IOException) { ioException.printStackTrace() } } // Save the items by writing to the file fun saveItems() { try { FileUtils.writeLines(getDataFile(), ListOfTasks) } catch (ioException: IOException) { ioException.printStackTrace() } } }
29.875
86
0.65272
9ad0c7bd1ce4b37c931ee8aa70510016c20fa065
8,777
swift
Swift
WZIM/Classes/ToolBbar/WZIMChatRecordView.swift
WZLYiOS/WZIM
4c6c93f42e7ae73b527434f7dffc3d951cacb48a
[ "MIT" ]
2
2021-06-25T05:10:32.000Z
2021-06-25T18:21:19.000Z
WZIM/Classes/ToolBbar/WZIMChatRecordView.swift
WZLYiOS/WZIM
4c6c93f42e7ae73b527434f7dffc3d951cacb48a
[ "MIT" ]
null
null
null
WZIM/Classes/ToolBbar/WZIMChatRecordView.swift
WZLYiOS/WZIM
4c6c93f42e7ae73b527434f7dffc3d951cacb48a
[ "MIT" ]
null
null
null
// // WZIMChatRecordView.swift // WZLY // // Created by qiuqixiang on 2020/8/28. // Copyright © 2020 我主良缘. All rights reserved. // import UIKit import SnapKit // MARK - 录音监听弹窗 public class WZIMChatRecordView: UIView { /// 代理 public weak var delegate: WZIMChatRecordViewDelegate? /// 最大时限 public var maxDuration: CGFloat = 59.0 /// public var recoderVioceTime: CGFloat = 10 * 60 /// 音量多张图片 public var voiceImageArray: [String] = ["ToolBbar.bundle/icon_volume1_pop", "ToolBbar.bundle/icon_volume2_pop", "ToolBbar.bundle/icon_volume3_pop", "ToolBbar.bundle/icon_volume4_pop", "ToolBbar.bundle/icon_volume5_pop", "ToolBbar.bundle/icon_volume6_pop"] /// 录音提示图标view private lazy var recordView: UIView = { $0.backgroundColor = UIColor.gray $0.layer.cornerRadius = 5 $0.layer.masksToBounds = true $0.alpha = 0.6 return $0 }(UIView()) /// 音量变化图标 public lazy var voiceChangeImage: UIImageView = { $0.contentMode = .scaleAspectFill return $0 }(UIImageView()) /// 取消文字提示 private lazy var voiceCancle: UILabel = { $0.textAlignment = .center $0.backgroundColor = UIColor.clear $0.text = "手指上滑,取消发送" $0.font = UIFont.systemFont(ofSize: 14) $0.textColor = WZIMToolAppearance.hexadecimal(rgb: "0xdfdfdf") $0.layer.cornerRadius = 5 $0.layer.borderColor = UIColor.red.withAlphaComponent(0.5).cgColor return $0 }(UILabel()) /// 语音录制时间 private var timer: Timer? /// 是否点击到按键外部 private var buttonDragOutside: Bool = false /// 10秒倒计时 private lazy var timerOutSoon: UILabel = { $0.textAlignment = .center $0.backgroundColor = UIColor.clear $0.font = UIFont.systemFont(ofSize: 80) $0.textColor = WZIMToolAppearance.hexadecimal(rgb: "0xdfdfdf") return $0 }(UILabel()) /// 执行的时间长度 private var timeSum: CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear self.isHidden = true configView() configViewLocation() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func configView() { self.addSubview(recordView) recordView.addSubview(voiceChangeImage) recordView.addSubview(timerOutSoon) recordView.addSubview(voiceCancle) } public func configViewLocation() { recordView.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.centerX.equalToSuperview() make.width.equalTo(150) make.height.equalTo(150) } voiceChangeImage.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(10) make.leading.equalTo(20) make.right.equalTo(-20) make.bottom.equalToSuperview().offset(-60) } timerOutSoon.snp.makeConstraints { (make) in make.edges.equalTo(voiceChangeImage) } voiceCancle.snp.makeConstraints { (make) in make.leading.equalTo(15) make.right.equalToSuperview().offset(-15) make.bottom.equalToSuperview().offset(-15) make.height.equalTo(25) } } public func show() { UIApplication.shared.keyWindow?.addSubview(self) self.frame = UIApplication.shared.keyWindow?.bounds ?? CGRect.zero } } /// MARK - 扩展 extension WZIMChatRecordView { /// 录音按钮按下 public func recordButtonTouchDown() { self.isHidden = false timeSum = 0.0 buttonDragOutside = false timerOutSoon.text = "" voiceChangeImage.isHidden = false timerOutSoon.isHidden = true // 需要根据声音大小切换recordView动画 voiceCancle.text = "手指上滑,取消发送"; voiceCancle.backgroundColor = UIColor.clear timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) } @objc private func timerAction() { setVoiceImage() } // 手指在录音按钮内部时离开 public func recordButtonTouchUpInside() { self.isHidden = true timeSum = 0 buttonDragOutside = false timer?.invalidate() timer = nil } // 手指在录音按钮外部时离开 public func recordButtonTouchUpOutside() { self.isHidden = true timeSum = 0 buttonDragOutside = false timer?.invalidate() timer = nil } // 手指移动到录音按钮内部 public func recordButtonDragInside() { buttonDragOutside = false voiceCancle.text = "手指上滑,取消发送" voiceCancle.backgroundColor = UIColor.clear voiceChangeImage.image = voiceImageArray.count == 0 ? nil : UIImage(named: voiceImageArray.first!) } // 手指移动到录音按钮外部 public func recordButtonDragOutside() { voiceChangeImage.isHidden = false timerOutSoon.isHidden = true buttonDragOutside = true voiceCancle.text = "松开手指,取消发送" voiceCancle.backgroundColor = WZIMToolAppearance.hexadecimal(rgb: "0x9d3836") } /// 图片效果 private func setVoiceImage(){ timeSum += 0.05 if buttonDragOutside || timeSum > maxDuration { if timeSum > maxDuration { /// 时间超时 timeOut() timeSum = 0.0 buttonDragOutside = false timer?.invalidate() timer = nil } return } if timeSum >= recoderVioceTime - 10 { voiceChangeImage.isHidden = true timerOutSoon.isHidden = false if timeSum > recoderVioceTime { /// 时间超时 timeOut() timeSum = 0.0 buttonDragOutside = false timer?.invalidate() timer = nil }else if (timeSum > recoderVioceTime - 1) { timerOutSoon.text = "1"; } else if (timeSum > recoderVioceTime - 2) { timerOutSoon.text = "2"; } else if (timeSum > recoderVioceTime - 3) { timerOutSoon.text = "3"; } else if (timeSum > recoderVioceTime - 4) { timerOutSoon.text = "4"; } else if (timeSum > recoderVioceTime - 5) { timerOutSoon.text = "5"; } else if (timeSum > recoderVioceTime - 6) { timerOutSoon.text = "6"; } else if (timeSum > recoderVioceTime - 7) { timerOutSoon.text = "7"; } else if (timeSum > recoderVioceTime - 8) { timerOutSoon.text = "8"; } else if (timeSum > recoderVioceTime - 9) { timerOutSoon.text = "9"; } else if (timeSum >= recoderVioceTime - 10) { timerOutSoon.text = "10"; } return } voiceChangeImage.image = voiceImageArray.count == 0 ? nil : UIImage(named: voiceImageArray.first!) let voiceSound: CGFloat = delegate?.getEmPeekRecorderVoiceMeter(view: self) ?? 0.0 let index: Int = Int(floor(voiceSound*CGFloat(voiceImageArray.count))) if index >= voiceImageArray.count { voiceChangeImage.image = UIImage(named: voiceImageArray.last!) }else{ voiceChangeImage.image = UIImage(named: voiceImageArray[index]) } } private func timeOut() { timerOutSoon.isHidden = true voiceChangeImage.isHidden = false voiceChangeImage.image = UIImage(named: "ToolBbar.bundle/icon_warning_pop") voiceCancle.backgroundColor = UIColor.clear voiceCancle.text = "说话时间太长" delegate?.chatRecordView(view: self, recordTimeOut: timeSum) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3) { self.isHidden = true } } } // MARK - WZIMChatRecordViewDelegate public protocol WZIMChatRecordViewDelegate: class { /// 超时退出 func chatRecordView(view: WZIMChatRecordView, recordTimeOut: CGFloat) /// 获取音量大小 func getEmPeekRecorderVoiceMeter(view: WZIMChatRecordView) -> CGFloat }
30.796491
134
0.5601
f0351c577a324e005d0a9c1acdf54fc0b4f28867
2,003
py
Python
bin/varipack.py
angrydill/ItsyBitser
bf9689136748bef3d022aa7529b4529e610abbf7
[ "MIT" ]
null
null
null
bin/varipack.py
angrydill/ItsyBitser
bf9689136748bef3d022aa7529b4529e610abbf7
[ "MIT" ]
1
2021-04-26T15:31:50.000Z
2021-04-26T15:31:50.000Z
bin/varipack.py
angrydill/ItsyBitser
bf9689136748bef3d022aa7529b4529e610abbf7
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Packs/unpacks Hextream content to/from the Varipacker format """ import sys import argparse from itsybitser import hextream, varipacker def main(): """ Program entry point """ parser = argparse.ArgumentParser( description="Packs/unpacks Hextream content to/from the Varipacker format" ) commands = parser.add_mutually_exclusive_group(required=True) commands.add_argument("-p", "--pack", action="store_true", help="Pack Hextream content into Varipacker format") commands.add_argument("-u", "--unpack", action="store_true", help="Unpack Varipacker content into Hextream format") parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding="UTF-8"), help="Name of file with content to be packed/unpacked", default=sys.stdin) parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding="UTF-8"), help="Name of file in which to write packed/unpacked content", default=sys.stdout) parser.add_argument("-c", "--comment", type=str, help="Prepend the output with specified comment string") parser.add_argument("-n", "--omit-newline", action="store_true", help="The ending newline character(s) will be omitted from the output") args = parser.parse_args() source_content = args.infile.read() if args.pack: binary_content = hextream.decode(source_content) output_content = varipacker.encode(binary_content) else: binary_content = varipacker.decode(varipacker.distill(source_content)) output_content = hextream.encode(binary_content) if args.comment: args.outfile.write("# {}\n".format(args.comment)) args.outfile.write(output_content) if not args.omit_newline: args.outfile.write("\n") if __name__ == "__main__": main()
41.729167
95
0.642536
65185342728b8ea46c26ce2b78a8072737b087c9
2,102
py
Python
example/py/CHSHInequality/chsh_inequality.py
samn33/qlazy
b215febfec0a3b8192e57a20ec85f14576745a89
[ "Apache-2.0" ]
15
2019-04-09T13:02:58.000Z
2022-01-13T12:57:08.000Z
example/py/CHSHInequality/chsh_inequality.py
samn33/qlazy
b215febfec0a3b8192e57a20ec85f14576745a89
[ "Apache-2.0" ]
3
2020-02-26T16:21:18.000Z
2022-03-31T00:46:53.000Z
example/py/CHSHInequality/chsh_inequality.py
samn33/qlazy
b215febfec0a3b8192e57a20ec85f14576745a89
[ "Apache-2.0" ]
3
2021-01-28T05:38:55.000Z
2021-10-30T12:19:19.000Z
import random from qlazy import QState def classical_strategy(trials=1000): win_cnt = 0 for _ in range(trials): # random bits by Charlie (x,y) x = random.randint(0,1) y = random.randint(0,1) # response by Alice (a) a = 0 # response by Bob (b) b = 0 # count up if win if (x and y) == (a+b)%2: win_cnt += 1 print("== result of classical strategy (trials:{0:d}) ==".format(trials)) print("* win prob. = ", win_cnt/trials) def quantum_strategy(trials=1000): win_cnt = 0 for _ in range(trials): # random bits by Charlie (x,y) x = random.randint(0,1) y = random.randint(0,1) # make entangled 2 qubits (one for Alice and another for Bob) qs = QState(2).h(0).cx(0,1) # response by Alice (a) if x == 0: # measurement of Z-basis (= Ry(0.0)-basis) sa = qs.m([0], shots=1, angle=0.0, phase=0.0).lst if sa == 0: a = 0 else: a = 1 else: # measurement of X-basis (or Ry(0.5*PI)-basis) sa = qs.mx([0], shots=1).lst # sa = qs.m([0], shots=1, angle=0.5, phase=0.0).lst if sa == 0: a = 0 else: a = 1 # response by Bob (b) if y == 0: # measurement of Ry(0.25*PI)-basis sb = qs.m([1], shots=1, angle=0.25, phase=0.0).lst if sb == 0: b = 0 else: b = 1 else: # measurement of Ry(-0.25*PI)-basis sb = qs.m([1], shots=1, angle=-0.25, phase=0.0).lst if sb == 0: b = 0 else: b = 1 # count up if win if (x and y) == (a+b)%2: win_cnt += 1 print("== result of quantum strategy (trials:{0:d}) ==".format(trials)) print("* win prob. = ", win_cnt/trials) if __name__ == '__main__': classical_strategy() quantum_strategy()
25.634146
77
0.450523
07f0af8ca772bd39200c40adcbc93e82c30e6381
1,949
c
C
engine/color.c
Akalu/phy-engine
6dfc7467675b7de6607cf05cd06923479811ad93
[ "MIT" ]
1
2021-07-19T04:37:24.000Z
2021-07-19T04:37:24.000Z
engine/color.c
akalu/phy-engine
6dfc7467675b7de6607cf05cd06923479811ad93
[ "MIT" ]
null
null
null
engine/color.c
akalu/phy-engine
6dfc7467675b7de6607cf05cd06923479811ad93
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> #include "vector.h" #include "color.h" #include "cie.h" #include "extmath.h" #include "tonemapping.h" #include "render.h" RGB NullRGB = {0.0, 0.0, 0.0}, Black = {0.0, 0.0, 0.0}, Red = {1.0, 0.0, 0.0}, Yellow = {1.0, 1.0, 0.0}, Green = {0.0, 1.0, 0.0}, Turquoise = {0.0, 1.0, 1.0}, Blue = {0.0, 0.0, 1.0}, Magenta = {1.0, 0.0, 1.0}, White = {1.0, 1.0, 1.0}; COLOR *RescaleRadiance(COLOR in, COLOR *out) { COLORSCALE(tmopts.pow_bright_adjust, in, in); *out = TonemapScaleForDisplay(in); return out; } RGB *ColorToRGB(COLOR col, RGB *rgb) { #ifdef RGBCOLORS RGBSET(*rgb, col.spec[0], col.spec[1], col.spec[2]); #else xyz_rgb(col.spec, (float *)rgb); #endif return rgb; } COLOR *RGBToColor(RGB rgb, COLOR *col) { #ifdef RGBCOLORS COLORSET(*col, rgb.r, rgb.g, rgb.b); #else rgb_xyz((float *)&rgb, col->spec); #endif return col; } LUV *ColorToLUV(COLOR col, LUV *luv) { #ifdef RGBCOLORS { float xyz[3]; rgb_xyz(col.spec, xyz); xyz_luv(xyz, (float *)luv, CIE_WHITE_Y); } #else xyz_luv(col.spec, (float *)luv, CIE_WHITE_Y); #endif return luv; } COLOR *LUVToColor(LUV luv, COLOR *col) { #ifdef RGBCOLORS { float xyz[3]; luv_xyz((float *)&luv, xyz, CIE_WHITE_Y); xyz_rgb(xyz, col->spec); } #else luv_xyz((float *)&luv, col->spec, CIE_WHITE_Y); #endif return col; } LUV *ColorToDisplayLUV(COLOR col, LUV *luv) { RGB rgb; float xyz[3]; RadianceToRGB(col, &rgb); rgb_xyz((float*)&rgb, xyz); xyz_luv(xyz, (float*)luv, CIE_DISPLAY_WHITE_Y); return luv; } static void RGBClipProp(RGB *rgb) { float s = RGBMAXCOMPONENT(*rgb); if (s > 1.) { rgb->r /= s; rgb->g /= s; rgb->b /= s; } } RGB *RadianceToRGB(COLOR color, RGB *rgb) { RescaleRadiance(color, &color); ColorToRGB(color, rgb); RGBCLIP(*rgb); return rgb; }
17.247788
54
0.584402
d271372118f7ed00b7fe6242cb25284577aa09ad
483
php
PHP
src/Geometry/Extents/BoundingBoxOnly/Extent1662.php
dvdoug/PHPCoord
a64be84d5f6410287bad74de423aae4c43a6f315
[ "MIT" ]
81
2015-03-17T13:03:51.000Z
2021-12-10T19:59:58.000Z
src/Geometry/Extents/BoundingBoxOnly/Extent1662.php
dvdoug/PHPCoord
a64be84d5f6410287bad74de423aae4c43a6f315
[ "MIT" ]
29
2015-10-21T10:35:23.000Z
2022-01-29T19:21:04.000Z
src/Geometry/Extents/BoundingBoxOnly/Extent1662.php
dvdoug/PHPCoord
a64be84d5f6410287bad74de423aae4c43a6f315
[ "MIT" ]
13
2015-12-17T12:51:10.000Z
2022-03-16T05:43:21.000Z
<?php /** * PHPCoord. * * @author Doug Wright */ declare(strict_types=1); namespace PHPCoord\Geometry\Extents\BoundingBoxOnly; /** * Asia-ExFSU/Indonesia - 132°E to 138°E, S hemisphere. * @internal */ class Extent1662 { public function __invoke(): array { return [ [ [ [138, 0], [132, 0], [132, -10.055179481487], [138, -10.055179481487], [138, 0], ], ], ]; } }
16.655172
99
0.486542
df0b5216bd4289851153c34327b115dc8524fc45
12,708
lua
Lua
RemoteDISK/NetServer/rmdsrv.lua
Bs0Dd/OpenCompSoft
18cf66297bdc7c6f152e7fa77c28eb457e175f8e
[ "Apache-2.0" ]
8
2020-10-28T05:55:20.000Z
2021-10-17T20:26:44.000Z
RemoteDISK/NetServer/rmdsrv.lua
Bs0Dd/OpenCompSoft
18cf66297bdc7c6f152e7fa77c28eb457e175f8e
[ "Apache-2.0" ]
null
null
null
RemoteDISK/NetServer/rmdsrv.lua
Bs0Dd/OpenCompSoft
18cf66297bdc7c6f152e7fa77c28eb457e175f8e
[ "Apache-2.0" ]
2
2022-02-13T20:30:22.000Z
2022-02-13T20:32:51.000Z
--[[ RemoteDISK NetServer v1.03. Server program for make NetClient Network disks. Client connecting by port, hostname, login and password Uses settings from "/etc/rc.cfg" Author: Bs()Dd ]] local component = require("component") local computer = require("computer") local fs = require("filesystem") local event = require("event") local seriz = require("serialization") function request(_, _, opp, _, _, call, one, two, thr, four) event.ignore("modem_message", request) logfil, why = fs.open("/etc/rdwork.log", "a") if call == "RDCL" then if args.log then logfil:write("[" .. os.date("%T") .. "] " .. "[CONNECT]: " .. opp .. " is connected\n") end if one == args.hostname then card.send(opp, port, "RDAN") _, _, opp, _, _, call, one, two = event.pull("modem_message") if call == "RDLG" and one == args.login and two == args.password then if online.n == maxonline then card.send(opp, port, "RDAU", "RDFULL") if args.log then logfil:write( "[" .. os.date("%T") .. "] " .. "[LOGIN]: " .. opp .. " tried to login to full server\n" ) end logfil:close() event.listen("modem_message", request) return end card.send(opp, port, "RDAU", "OK", rfs.address) if online[opp] == nil then online[opp] = true online.n = online.n + 1 ofdesc[opp] = {n = 0} end if args.log then logfil:write("[" .. os.date("%T") .. "] " .. "[LOGIN]: " .. opp .. " is logged in\n") end elseif call == "RDLG" then card.send(opp, port, "RDAU", "FAIL") if args.log then logfil:write("[" .. os.date("%T") .. "] " .. "[LOGIN]: " .. opp .. " is failed to log in\n") end end end logfil:close() event.listen("modem_message", request) return end if online[opp] == nil then card.send(opp, port, "RDNAUT") if args.log then logfil:write( "[" .. os.date("%T") .. "] " .. "[LOGIN]: " .. opp .. " tried to get access without authorization\n" ) end logfil:close() event.listen("modem_message", request) return end if call == "RDISDIR" then card.send(opp, port, "RDISDIRA", rfs.isDirectory(one)) if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called isDirectory("' .. one .. '")\n' ) end elseif call == "RDLMOD" then card.send(opp, port, "RDLMODA", rfs.lastModified(one)) if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called lastModified("' .. one .. '")\n' ) end elseif call == "RDLIST" then lst, err = rfs.list(one) if err ~= nil then card.send(opp, port, "RDLISTA", nil, err) end if lst ~= nil then card.send(opp, port, "RDLISTA", seriz.serialize(lst)) else card.send(opp, port, "RDLISTA", nil, nil) end if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called list("' .. one .. '")\n') end elseif call == "RDTOTL" then card.send(opp, port, "RDTOTLA", rfs.spaceTotal()) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called spaceTotal()\n") end elseif call == "RDOPEN" then if ofdesc[opp].n == maxdescr then card.send(opp, port, "RDOPENA", nil, "too many open handles") logfil:close() event.listen("modem_message", request) return else fdes, err = rfs.open(one, two) if err ~= nil then card.send(opp, port, "RDOPENA", nil, err) else ofdesc[opp][tonumber(tostring(fdes))] = fdes ofdesc[opp].n = ofdesc[opp].n + 1 card.send(opp, port, "RDOPENA", tonumber(tostring(fdes))) end if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called open("' .. one .. '", "' .. two .. '")\n' ) end end elseif call == "RDRM" then card.send(opp, port, "RDRMA", rfs.remove(one)) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called remove("' .. one .. '")\n') end elseif call == "RDRN" then card.send(opp, port, "RDRNA", rfs.rename(one, two)) if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called rename("' .. one .. '", "' .. two .. '")\n' ) end elseif call == "RDREAD" then if ofdesc[opp][one] ~= nil then sended = 0 remain = two if two > maxpackspace then bread = maxpackspace else bread = two end while sended < two do rdd = rfs.read(ofdesc[opp][one], bread) card.send(opp, port, "RDREADA", rdd) sended = sended + maxpackspace remain = remain - maxpackspace if remain < maxpackspace then bread = remain end end else card.send(opp, port, "RDREADA", nil, "bad file descriptor") end if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called read(" .. one .. ', "' .. two .. '")\n' ) end elseif call == "RDCLS" then if ofdesc[opp][one] == "closed" then card.send(opp, port, "RDCLSA") elseif ofdesc[opp][one] ~= nil then card.send(opp, port, "RDCLSA", rfs.close(ofdesc[opp][one])) ofdesc[opp][one] = "closed" ofdesc[opp].n = ofdesc[opp].n - 1 else card.send(opp, port, "RDCLSA", nil, "bad file descriptor") end if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called close(" .. one .. ")\n") end elseif call == "RDGLAB" then card.send(opp, port, "RDGLABA", rfs.getLabel()) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called getLabel()\n") end elseif call == "RDSEEK" then card.send(opp, port, "RDSEEKA", rfs.seek(one, two, thr)) if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called seek(" .. one .. ', "' .. two .. '", ' .. thr .. ")\n" ) end elseif call == "RDFSIZ" then card.send(opp, port, "RDFSIZA", rfs.size(one)) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called size("' .. one .. '")\n') end elseif call == "RDISRO" then card.send(opp, port, "RDISROA", rfs.isReadOnly()) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called isReadOnly()\n") end elseif call == "RDSLAB" then card.send(opp, port, "RDSLABA", rfs.setLabel(one)) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called setLabel("' .. one .. '")\n') end elseif call == "RDMKDR" then card.send(opp, port, "RDMKDRA", rfs.makeDirectory(one)) if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called makeDirectory("' .. one .. '")\n' ) end elseif call == "RDISEX" then card.send(opp, port, "RDISEXA", rfs.exists(one)) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. ' called exists("' .. one .. '")\n') end elseif call == "RDFREE" then card.send(opp, port, "RDFREEA", rfs.spaceUsed()) if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called spaceUsed()\n") end elseif call == "RDWRT" then oneb = one if ofdesc[opp][one] ~= nil then fhand = ofdesc[opp][one] card.send(opp, port, "RDWRTA") readed = 0 rdata = "" while readed < two do while true do _, _, ropp, _, _, call, one = event.pull("modem_message") if ropp == opp then break end end if one ~= nil then rdata = rdata .. one end readed = readed + #one end stat, err = rfs.write(fhand, rdata) card.send(opp, port, "RDWRTPA", stat, err) else card.send(opp, port, "RDWRTA", nil, "bad file descriptor") end if args.log == 2 then logfil:write( "[" .. os.date("%T") .. "] " .. "[VERBOSE]: " .. opp .. " called write(" .. oneb .. ", data len: " .. #rdata .. ")\n" ) end elseif call == "RDBYE" then online[opp] = nil online.n = online.n - 1 for _, dcl in pairs(ofdesc[opp]) do if dcl ~= "closed" then rfs.close(dcl) end end ofdesc[opp] = nil card.send(opp, port, "RDBYEA", "user logged off") if args.log == 2 then logfil:write("[" .. os.date("%T") .. "] " .. "[CONNECT]: " .. opp .. " disconnected\n") end end logfil:close() event.listen("modem_message", request) end function start() if work == nil then if component.list("modem")() == nil then io.stderr:write("No Network Card is detected.") return end card = component.proxy(component.list("modem")()) work = true print("RemoteDISK NetServer v1.03\n") if args == nil then io.stderr:write("FATAL ERROR! No settings found!") return end port = args.port card.open(port) maxpackspace = card.maxPacketSize() - 20 rfs = component.proxy(args.hddaddress) if rfs == nil then io.stderr:write("FATAL ERROR! Hard drive insn't exists!") return else print("Hard drive " .. rfs.address .. " is selected") print('Server "' .. args.hostname .. '", port ' .. port) end if args.mode == 1 then maxonline = 14 maxdescr = 1 elseif args.mode == 2 then maxonline = 7 maxdescr = 2 else print("FATAL ERROR! Incorrect mode.") return end if args.log then logfil, why = io.open("/etc/rdwork.log", "w") if logfil == nil then print("FATAL ERROR! Can't open logging file: " .. why) return end print("Logging started!") logfil:write("[" .. os.date("%T") .. "] " .. "[STATUS]: Server started\n") logfil:close() end online = {n = 0} ofdesc = {} work = true event.listen("modem_message", request) else io.stderr:write("Server already started!\n") end end function stop() if work == true then work = nil event.ignore("modem_message", request) card.close(port) if args.log then logfil = io.open("/etc/rdwork.log", "a") logfil:write("[" .. os.date("%T") .. "] " .. "[STATUS]: Server stopped\n") logfil:close() end print("Server stopped.") else io.stderr:write("Server isn't working now!\n") end end
37.266862
120
0.449559