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
bd1a894899684122677347581275d5045a909477
586
rb
Ruby
app/models/snapshot.rb
batterseapower/boardlog
2830f7abe2cd6c0bd908f7a493ad24707588577a
[ "BSD-3-Clause" ]
1
2016-05-08T16:02:17.000Z
2016-05-08T16:02:17.000Z
app/models/snapshot.rb
batterseapower/boardlog
2830f7abe2cd6c0bd908f7a493ad24707588577a
[ "BSD-3-Clause" ]
null
null
null
app/models/snapshot.rb
batterseapower/boardlog
2830f7abe2cd6c0bd908f7a493ad24707588577a
[ "BSD-3-Clause" ]
null
null
null
class Snapshot include DataMapper::Resource belongs_to :whiteboard has 1, :image property :id, Serial property :taken_at, DateTime, :nullable => false property :body, Text, :nullable => false property :public, Boolean, :nullable => false, :default => true def previous whiteboard.snapshots.first(:taken_at.lt => taken_at) end def next whiteboard.snapshots.first(:taken_at.gt => taken_at) end def body_html # We don't bother caching this in the database or even in memory.. for now Boardlog::Sanitize.sanitize_markdown(body) end end
22.538462
78
0.704778
00baee391aeadad518f1d2468772211178acf737
309
swift
Swift
Sources/Swift-Travis-Sonarcloud-CI/Swift_Travis_Sonarcloud_CI.swift
ladislas/Swift-Travis-Sonarcloud-CI
dcb8211e7c13beba728b2c3f6d3f6c2f248cd6c7
[ "MIT" ]
null
null
null
Sources/Swift-Travis-Sonarcloud-CI/Swift_Travis_Sonarcloud_CI.swift
ladislas/Swift-Travis-Sonarcloud-CI
dcb8211e7c13beba728b2c3f6d3f6c2f248cd6c7
[ "MIT" ]
null
null
null
Sources/Swift-Travis-Sonarcloud-CI/Swift_Travis_Sonarcloud_CI.swift
ladislas/Swift-Travis-Sonarcloud-CI
dcb8211e7c13beba728b2c3f6d3f6c2f248cd6c7
[ "MIT" ]
2
2019-07-18T10:47:21.000Z
2020-11-20T18:42:32.000Z
struct Swift_Travis_Sonarcloud_CI { var text = "Hello, World!" } class MyClass { let v1: String let v2: Int public init(v1: String, v2: Int) { self.v1 = v1 self.v2 = v2 } public func say() -> String { print(v1) return v1 } public func count() -> Int { print(v2) return v2 } }
10.655172
35
0.601942
dc572f8bee3b6233d5cb6758eb9adad085d57b82
2,185
ts
TypeScript
src/simplesite/parse-datestamp.ts
meyfa/ka-mensa-fetch
0521a9adf0f06cfe5dbe0911320d81d024bb8e2e
[ "MIT" ]
1
2021-01-04T02:43:16.000Z
2021-01-04T02:43:16.000Z
src/simplesite/parse-datestamp.ts
meyfa/ka-mensa-fetch
0521a9adf0f06cfe5dbe0911320d81d024bb8e2e
[ "MIT" ]
18
2020-09-09T10:28:23.000Z
2022-02-16T14:15:12.000Z
src/simplesite/parse-datestamp.ts
meyfa/ka-mensa-fetch
0521a9adf0f06cfe5dbe0911320d81d024bb8e2e
[ "MIT" ]
null
null
null
import { DateSpec } from '../types/date-spec' // CONSTANTS /** * RegExp for parsing date strings of the following form: "Mo 02.12.". * First group: day (1..31), second group: month (1..12). */ const DATE_REGEXP = /^\s*(?:Mo|Di|Mi|Do|Fr|Sa|So)\s*(\d+)\.(\d+)\.\s*$/ // METHODS /** * Guess year information from a reference date and the month alone. * * @param refYear The reference year (i.e. data acquisition date). * @param refMonth The reference month. * @param month The month for which year should be guessed. * @returns The most likely year. */ function guessYear (refYear: number, refMonth: number, month: number): number { // split the reference year into 3 sections and check whether the given month // lies reasonably close to the reference third; // if it does, year is probably the reference year; // otherwise, it is the previous or the next year, depending on the section. if (refMonth <= 3) { // 0 .. 3; in range: 0 .. 7 return month < 8 ? refYear : refYear - 1 } else if (refMonth <= 7) { // 4 .. 7; in range: 0 .. 11 return refYear } else { // 8 .. 11; in range: 4 .. 11 return month < 4 ? refYear + 1 : refYear } } // MAIN EXPORT /** * Parse a datestamp string of the form "Mo 02.12." with respect to a reference * date. * * The returned object has keys `day` (1..31), `month` (0..11), `year` (...). * If invalid input was given, undefined is returned. * * @param str String to be parsed. * @param reference The reference date for year guessing. * @returns An object containing integers: day, month, year. */ export function parseDatestamp (str: string, reference: Date): DateSpec | undefined { const match = str.match(DATE_REGEXP) if (match == null) { return undefined } const day = parseInt(match[1], 10) const month = parseInt(match[2], 10) - 1 // plausibility check if (day < 1 || day > 31 || month < 0 || month > 11) { return undefined } const refYear = reference.getFullYear() const refMonth = reference.getMonth() const year = guessYear(refYear, refMonth, month) // JS Date has month run from 0 to 11, inclusive return { day, month, year } }
28.376623
85
0.646224
e71d82b9508cda6f617c760685eb1d7178f9f2ed
1,499
php
PHP
views/drug-opd/_form.php
foyplvowlp/med-cup
5d3ea7b86347aa580ec2ad718c8c6ed7d65f4951
[ "BSD-3-Clause" ]
null
null
null
views/drug-opd/_form.php
foyplvowlp/med-cup
5d3ea7b86347aa580ec2ad718c8c6ed7d65f4951
[ "BSD-3-Clause" ]
null
null
null
views/drug-opd/_form.php
foyplvowlp/med-cup
5d3ea7b86347aa580ec2ad718c8c6ed7d65f4951
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\DrugOpd */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="drug-opd-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'HOSPCODE')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'PID')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'SEQ')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DATE_SERV')->textInput() ?> <?= $form->field($model, 'CLINIC')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DIDSTD')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DNAME')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'AMOUNT')->textInput() ?> <?= $form->field($model, 'UNIT')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'UNIT_PACKING')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DRUGPRICE')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DRUGCOST')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'PROVIDER')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'D_UPDATE')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
29.98
150
0.561708
6b093a0f6b057a30ccedeccfe642acd8fc9d604b
53
js
JavaScript
index.js
CatOstrovsky/website-parser
229da144447462226ac655d01e250a2b10d77714
[ "Apache-2.0" ]
null
null
null
index.js
CatOstrovsky/website-parser
229da144447462226ac655d01e250a2b10d77714
[ "Apache-2.0" ]
1
2019-02-25T10:48:59.000Z
2019-02-25T10:48:59.000Z
index.js
CatOstrovsky/website-parser
229da144447462226ac655d01e250a2b10d77714
[ "Apache-2.0" ]
null
null
null
const Scraper = require("./scraper"); Scraper.run();
17.666667
37
0.679245
01c35d1e93c1a2d28c1bd05e0691f5fcf460711a
25,011
c
C
tests/csmith/small_arrays/csmith_143.c
talsewell/cerberus
c8c6d25f0cb8d4cd2672ffd0790fb0de3f2a51e3
[ "BSD-2-Clause" ]
12
2020-09-03T09:57:26.000Z
2022-01-28T04:28:00.000Z
tests/csmith/small_arrays/csmith_143.c
talsewell/cerberus
c8c6d25f0cb8d4cd2672ffd0790fb0de3f2a51e3
[ "BSD-2-Clause" ]
182
2021-02-26T23:07:40.000Z
2022-02-10T12:33:45.000Z
tests/csmith/small_arrays/csmith_143.c
talsewell/cerberus
c8c6d25f0cb8d4cd2672ffd0790fb0de3f2a51e3
[ "BSD-2-Clause" ]
4
2020-09-02T11:54:39.000Z
2022-03-16T23:23:11.000Z
// Options: --no-pointers --no-structs --no-unions --argc --no-bitfields --checksum --comma-operators --compound-assignment --concise --consts --divs --embedded-assigns --pre-incr-operator --pre-decr-operator --post-incr-operator --post-decr-operator --unary-plus-operator --jumps --longlong --int8 --uint8 --no-float --main --math64 --muls --safe-math --no-packed-struct --no-paranoid --no-volatiles --no-volatile-pointers --const-pointers --no-builtins --max-array-dim 1 --max-array-len-per-dim 4 --max-block-depth 1 --max-block-size 10 --max-expr-complexity 4 --max-funcs 10 --max-pointer-depth 2 --max-struct-fields 2 --max-union-fields 2 -o csmith_143.c #include "csmith.h" static long __undefined; static uint32_t g_2 = 4294967288UL; static uint16_t g_12 = 9UL; static int64_t g_32 = 0xA0C0E0752570E81DLL; static int8_t g_89 = (-8L); static uint64_t g_95 = 0x622B46159332C321LL; static uint32_t g_122 = 0x848B2A49L; static int32_t g_128 = (-1L); static int8_t g_129[2] = {0x13L,0x13L}; static uint32_t g_130 = 0x995F5642L; static uint64_t g_183 = 0UL; static uint64_t g_188[3] = {0x092C45C1CA509578LL,0x092C45C1CA509578LL,0x092C45C1CA509578LL}; static int16_t g_191 = 0x4318L; static uint32_t g_192 = 0xFC300F03L; static int64_t g_197 = (-1L); static uint32_t g_216 = 0x36F7AE06L; static uint32_t g_223 = 18446744073709551615UL; static uint8_t g_224 = 0xECL; static int64_t g_225 = 0x898853A53F0CD3A6LL; static uint32_t g_226[2] = {0x6CA6B16CL,0x6CA6B16CL}; static int32_t g_233 = 0xB7F1185DL; static int64_t g_274[1] = {0x3A405008DB593B29LL}; static int64_t g_278[3] = {0xF3A4FFD7926D94D4LL,0xF3A4FFD7926D94D4LL,0xF3A4FFD7926D94D4LL}; static int8_t g_284[1] = {0x92L}; static int64_t g_285[2] = {6L,6L}; static int16_t g_286 = 0xF6C5L; static int32_t g_287 = (-9L); static uint64_t g_289 = 18446744073709551615UL; static int8_t g_321 = 1L; static int8_t g_322[2] = {0x43L,0x43L}; static uint32_t g_339 = 4294967287UL; static uint64_t g_342 = 0x5211CC2D51F966EFLL; static uint32_t g_343[1] = {0UL}; static int8_t g_346 = 1L; static int32_t g_359 = 1L; static uint32_t g_375 = 0x6918CF42L; static int32_t g_380 = 0x4A929C1EL; static int32_t g_382 = 0x2BC67A94L; static uint32_t g_383 = 0x74E5CEEDL; static int32_t g_418 = 0x6434FF4CL; static uint32_t g_427 = 2UL; static int16_t g_469 = (-1L); static int32_t g_476 = 8L; static uint32_t g_478 = 1UL; static uint64_t g_485 = 0UL; static int32_t g_494 = 8L; static int32_t func_1(void); static int32_t func_17(const uint8_t p_18); static int8_t func_23(int8_t p_24, uint32_t p_25, const uint16_t p_26); static int32_t func_33(int32_t p_34, uint8_t p_35, int32_t p_36, int8_t p_37); static int64_t func_39(uint8_t p_40, int16_t p_41, int8_t p_42, const int8_t p_43, int32_t p_44); static int16_t func_45(const uint8_t p_46, const uint64_t p_47, uint8_t p_48, int8_t p_49, uint8_t p_50); static int16_t func_53(int32_t p_54, int8_t p_55, uint32_t p_56, uint16_t p_57, int16_t p_58); static int32_t func_66(int32_t p_67, int32_t p_68, const int32_t p_69); static uint16_t func_75(int64_t p_76); static int32_t func_107(int64_t p_108, uint32_t p_109, uint8_t p_110); static int32_t func_1(void) { int16_t l_31[4] = {0x6C71L,0x6C71L,0x6C71L,0x6C71L}; int32_t l_492 = 0xD9618E89L; uint8_t l_508 = 0x07L; int i; lbl_507: --g_2; for (g_2 = 0; (g_2 >= 14); g_2 = safe_add_func_int64_t_s_s(g_2, 2)) { uint32_t l_9[3]; uint8_t l_432 = 0x52L; uint8_t l_493[1]; int32_t l_495 = 0L; int i; for (i = 0; i < 3; i++) l_9[i] = 3UL; for (i = 0; i < 1; i++) l_493[i] = 0x62L; l_495 = (safe_div_func_uint32_t_u_u((l_9[2] && (((safe_lshift_func_uint8_t_u_s(((g_494 = (l_9[0] , ((g_12--) & ((safe_mul_func_int8_t_s_s(((((func_17(((safe_mul_func_uint16_t_u_u((safe_add_func_uint32_t_u_u((func_23(((g_32 = ((safe_add_func_uint16_t_u_u(((safe_div_func_int64_t_s_s(6L, l_31[1])) >= 1L), (-2L))) || g_2)) , l_9[1]), g_2, l_31[1]) < g_2), g_284[0])), g_382)) ^ l_432)) <= l_492) , l_9[2]) || g_226[0]) != g_322[1]), l_493[0])) ^ g_382)))) != 0x469AL), 3)) | l_493[0]) | 0x2147A898L)), g_382)); } g_494 = ((safe_add_func_int16_t_s_s(g_346, ((safe_lshift_func_uint8_t_u_s((l_31[1] < (((safe_lshift_func_uint8_t_u_s((((((((safe_div_func_uint16_t_u_u(l_31[3], g_216)) , l_31[0]) < 0x03L) | 255UL) , l_31[3]) ^ g_128) == g_128), g_469)) < 0L) | 0x33L)), g_418)) == 0x61L))) != l_31[3]); for (g_224 = (-24); (g_224 != 36); g_224 = safe_add_func_int16_t_s_s(g_224, 5)) { int16_t l_506 = 0x27D4L; uint64_t l_525[3]; int32_t l_526 = 0x767460E2L; int32_t l_529[4]; int32_t l_530 = 0x4D76D018L; int i; for (i = 0; i < 3; i++) l_525[i] = 0UL; for (i = 0; i < 4; i++) l_529[i] = 1L; if (l_506) break; if (g_32) goto lbl_507; l_508 |= l_492; if (g_12) break; g_494 = (safe_rshift_func_int8_t_s_s((safe_sub_func_uint16_t_u_u((l_530 = (((safe_add_func_int32_t_s_s((safe_mod_func_int16_t_s_s((safe_sub_func_uint8_t_u_u((l_529[0] = (safe_mul_func_uint8_t_u_u((g_278[1] > (((safe_mod_func_int8_t_s_s(((safe_mul_func_uint16_t_u_u(((((l_526 = l_525[0]) ^ (safe_div_func_uint32_t_u_u(1UL, 0x4F1BE709L))) || 0x42964D2C5A1C4B35LL) ^ (-1L)), l_508)) , g_224), l_31[0])) , g_274[0]) , 0xF4F576CC4F3EBBF6LL)), 0xD9L))), l_506)), g_322[1])), g_223)) , (-1L)) , g_469)), l_31[1])), 3)); } return l_508; } static int32_t func_17(const uint8_t p_18) { uint32_t l_441 = 0UL; int8_t l_444 = 1L; int32_t l_445 = 0L; int32_t l_446[1]; int32_t l_470 = 1L; int i; for (i = 0; i < 1; i++) l_446[i] = 0xAEC62697L; g_418 |= (safe_mod_func_int64_t_s_s(4L, (l_446[0] = (l_445 = (safe_mul_func_uint16_t_u_u((((safe_mul_func_int8_t_s_s(((safe_rshift_func_uint8_t_u_s((((((g_284[0] = ((l_441 ^ (safe_mul_func_uint16_t_u_u(((l_441 | g_191) && g_278[1]), l_444))) , g_122)) || p_18) >= 4L) & l_444) >= g_128), l_441)) != 0xC092L), 1UL)) , p_18) && p_18), g_346)))))); if (l_445) { int32_t l_453 = 0x813186D7L; int32_t l_457 = (-1L); g_359 = ((((safe_mod_func_uint16_t_u_u(0x9062L, (safe_mul_func_uint8_t_u_u((g_224--), (p_18 , l_441))))) | l_453) > 0x94AFL) && g_322[1]); l_457 = (safe_sub_func_int32_t_s_s((safe_unary_minus_func_int64_t_s(1L)), 0x04539A42L)); } else { uint64_t l_466 = 0x25829FC07342370ALL; int32_t l_477[1]; int i; for (i = 0; i < 1; i++) l_477[i] = 0x997B7948L; l_446[0] = (((safe_lshift_func_uint16_t_u_u(((l_445 ^= ((safe_sub_func_uint8_t_u_u((g_224 ^= (g_343[0] , (((safe_mul_func_uint8_t_u_u((p_18 | ((safe_mul_func_uint16_t_u_u(g_223, l_466)) , p_18)), 0x84L)) < l_466) , p_18))), 0x5DL)) , l_446[0])) > g_284[0]), 6)) <= 0L) && p_18); l_470 = ((g_285[0] |= (safe_add_func_int8_t_s_s((l_446[0] = ((g_274[0] != 0x74BA25DFF6FBC400LL) >= (l_445 = (g_469 = g_382)))), 0xD6L))) < 18446744073709551613UL); l_446[0] = ((!(safe_mul_func_uint16_t_u_u((safe_div_func_uint16_t_u_u((g_478++), ((g_278[2] = (safe_sub_func_int8_t_s_s((g_284[0] = 5L), g_216))) | (safe_rshift_func_int16_t_s_u(((l_477[0] = (-2L)) != g_285[0]), 4))))), p_18))) > l_466); l_477[0] &= 9L; g_485++; l_477[0] = ((((safe_rshift_func_int8_t_s_s((safe_sub_func_uint8_t_u_u(l_470, ((0xC578233632720136LL & g_183) ^ g_469))), p_18)) < l_444) , 4UL) && p_18); return l_446[0]; } return g_225; } static int8_t func_23(int8_t p_24, uint32_t p_25, const uint16_t p_26) { int16_t l_38[3]; int32_t l_254 = 1L; int32_t l_430 = 0x0C3684FAL; int i; for (i = 0; i < 3; i++) l_38[i] = (-10L); l_430 = func_33(((l_38[1] , (func_39(l_38[1], func_45((l_254 = (safe_add_func_int16_t_s_s((((func_53(p_24, p_26, l_38[2], p_24, l_38[1]) == l_38[2]) && l_38[2]) ^ g_2), p_25))), p_26, p_24, g_225, p_24), g_286, p_24, g_2) | p_24)) , (-10L)), p_25, g_322[0], p_24); l_430 &= (!g_285[1]); l_254 = l_38[1]; return l_430; } static int32_t func_33(int32_t p_34, uint8_t p_35, int32_t p_36, int8_t p_37) { int16_t l_374 = 0x99D4L; int32_t l_377 = 0x2DBB7FF9L; int32_t l_378[2]; int32_t l_379 = 7L; const uint32_t l_390 = 1UL; uint64_t l_401 = 7UL; int64_t l_422 = 0xAC402F94EE3061FALL; uint8_t l_423 = 0x56L; int32_t l_426 = 0x8F051323L; int i; for (i = 0; i < 2; i++) l_378[i] = 1L; if ((safe_mod_func_int32_t_s_s((p_34 && ((safe_rshift_func_int16_t_s_s(0x7E27L, 8)) == g_95)), p_35))) { int16_t l_376[4]; int32_t l_381[3]; int32_t l_406 = 0xEBF98C91L; int i; for (i = 0; i < 4; i++) l_376[i] = 0x9853L; for (i = 0; i < 3; i++) l_381[i] = (-8L); l_374 = (safe_mod_func_int16_t_s_s(((safe_sub_func_int32_t_s_s((safe_sub_func_int8_t_s_s((safe_rshift_func_uint8_t_u_s(((safe_rshift_func_uint8_t_u_s(g_285[1], (0x8A4D542AL <= 0xA297C537L))) & p_34), g_225)), p_36)), p_36)) || p_36), p_37)); g_359 &= 0xE04016B2L; l_379 = (0x7FD6D6BBC8EBB682LL <= ((p_35 & ((l_378[1] = (p_37 = (l_377 = ((g_375 = (g_359 = 7L)) == l_376[0])))) ^ p_34)) || 6L)); ++g_383; l_381[0] = ((safe_mod_func_int32_t_s_s((((safe_mul_func_uint16_t_u_u((l_390 , (246UL <= (safe_add_func_int64_t_s_s(1L, 18446744073709551615UL)))), l_381[0])) || 3UL) & 8L), l_379)) & p_36); g_359 = (safe_mul_func_uint8_t_u_u(p_35, (safe_mod_func_int32_t_s_s((safe_sub_func_uint16_t_u_u(g_188[0], (5L < l_381[0]))), g_197)))); l_381[0] = (((l_378[1] = l_376[2]) > ((safe_mod_func_int8_t_s_s((l_401 , (p_36 ^ 18446744073709551609UL)), 0x12L)) | 0x36L)) >= 0x53L); l_406 = ((safe_div_func_uint8_t_u_u(((l_381[0] ^= l_379) , p_36), (g_129[0] |= (safe_mul_func_int16_t_s_s((l_376[0] > 0L), 0xC62FL))))) ^ p_34); return g_339; } else { uint32_t l_412 = 0x4D033237L; int32_t l_413 = 0x18410EFEL; l_413 ^= (l_379 = ((g_191 |= (p_36 || ((l_378[1] = (g_224 = (((safe_rshift_func_int16_t_s_s((+((safe_add_func_uint64_t_u_u(((4294967295UL >= 0xD5835A90L) == l_412), p_34)) | l_390)), l_390)) || g_343[0]) && g_32))) <= p_37))) >= 0x7C41L)); l_423 = (g_359 = ((safe_mul_func_int8_t_s_s((safe_rshift_func_uint16_t_u_u(g_418, (((l_377 <= (safe_lshift_func_uint8_t_u_u(((safe_unary_minus_func_uint16_t_u(l_390)) , l_413), 3))) , l_422) == g_359))), p_34)) != p_34)); l_379 = (+((p_36 , g_285[1]) | (p_35 ^ l_379))); g_359 |= ((safe_unary_minus_func_uint16_t_u((l_378[1] < g_285[1]))) != (-8L)); } l_378[1] = ((((((l_426 = l_379) < 0xC6L) | (0xB9EFL || g_287)) != g_32) > g_380) > 0x8F55981EL); g_427--; return g_2; } static int64_t func_39(uint8_t p_40, int16_t p_41, int8_t p_42, const int8_t p_43, int32_t p_44) { int32_t l_295 = 0x1F41A29CL; int32_t l_296 = (-1L); uint64_t l_305 = 0x4861A75924AF79D1LL; int32_t l_315 = 0xF2773CD8L; if (((((-1L) ^ ((((l_295 |= 0x6F06CA2D36F85CD4LL) , (g_192 , p_44)) | p_41) , l_295)) & l_296) , p_44)) { uint16_t l_300 = 1UL; int32_t l_323[4]; uint64_t l_324 = 4UL; int i; for (i = 0; i < 4; i++) l_323[i] = 7L; p_44 &= (~(((g_226[0] || (g_188[0] = ((safe_mul_func_uint16_t_u_u(l_300, ((safe_mod_func_uint16_t_u_u(((safe_mul_func_int16_t_s_s(0x0C79L, (-5L))) >= l_305), p_43)) >= 0x21L))) != p_42))) , 0x124FL) && l_296)); p_44 = (((safe_mod_func_uint8_t_u_u((safe_mod_func_int32_t_s_s((safe_unary_minus_func_uint64_t_u(l_295)), l_305)), (0x49FBD7E930A53C3CLL | 0x60EA1D606A619FA6LL))) != 0x3AAD8979L) , 0xDC543C91L); l_296 |= (((l_305 >= ((((safe_mul_func_uint8_t_u_u((g_226[0] >= ((g_192 ^= (safe_mod_func_uint64_t_u_u((g_285[1] >= l_295), 0xECA2208B1A2417E7LL))) , l_315)), g_2)) != p_43) > 0UL) ^ p_44)) != (-1L)) < 0xB67E5E51F4D32C97LL); l_296 = (safe_sub_func_int16_t_s_s((g_32 > (!g_191)), ((p_40 && p_43) && g_284[0]))); g_321 |= (safe_div_func_int32_t_s_s(g_192, (l_296 & g_285[1]))); l_324--; p_44 = 0L; } else { int64_t l_337 = 0x299CB9E567AA4D16LL; int32_t l_338[1]; uint32_t l_357 = 0x9F1F9AA6L; int32_t l_358 = 5L; int i; for (i = 0; i < 1; i++) l_338[i] = 0x8C8D9B6EL; g_339 = (((safe_mul_func_int8_t_s_s(g_285[1], (((safe_add_func_int32_t_s_s((0x5C160B9AC8691DADLL <= (l_338[0] = (safe_mod_func_int32_t_s_s((safe_mul_func_int8_t_s_s(((safe_div_func_int8_t_s_s(l_337, 0xDBL)) >= g_285[1]), 0UL)), p_44)))), p_43)) || p_42) == 9L))) != 9L) > 1UL); p_44 &= p_41; g_343[0] = ((((((safe_mod_func_int8_t_s_s((l_295 ^= ((g_89 = ((g_342 = p_44) <= p_40)) != (l_338[0] <= 9UL))), g_274[0])) == l_315) , l_296) == g_226[0]) <= 18446744073709551609UL) || g_339); g_346 = (safe_mod_func_uint8_t_u_u((g_224 |= l_315), (-1L))); g_359 = (l_358 = (((safe_add_func_int16_t_s_s((safe_sub_func_uint16_t_u_u((((safe_add_func_int16_t_s_s(((safe_rshift_func_int8_t_s_u((safe_mul_func_int16_t_s_s((p_40 & (p_42 <= (l_315 , g_225))), 65535UL)), 3)) < l_338[0]), l_338[0])) >= l_357) >= g_216), g_287)), l_296)) == p_42) && g_128)); } return g_226[0]; } static int16_t func_45(const uint8_t p_46, const uint64_t p_47, uint8_t p_48, int8_t p_49, uint8_t p_50) { uint8_t l_255 = 5UL; int32_t l_267 = (-3L); int32_t l_283 = 1L; int32_t l_288 = (-4L); --l_255; for (p_49 = 0; (p_49 >= (-2)); p_49 = safe_sub_func_int32_t_s_s(p_49, 8)) { int32_t l_266 = 0L; l_267 &= ((safe_rshift_func_int8_t_s_u(((g_226[0] , l_255) , (l_266 = (safe_rshift_func_uint8_t_u_u((safe_add_func_uint8_t_u_u((5L != g_188[0]), l_255)), p_47)))), 6)) >= l_255); l_267 = ((safe_div_func_int64_t_s_s((p_48 >= (--g_130)), g_225)) & ((+(((g_197 , p_50) , p_46) > g_2)) >= 255UL)); g_274[0] = ((p_50 = ((+(p_49 , (p_46 <= l_267))) >= (-5L))) , 0L); g_278[1] ^= (((((((safe_mul_func_uint16_t_u_u(p_48, (g_188[0] , ((!g_183) ^ l_267)))) ^ p_50) != g_32) > p_50) ^ g_188[0]) > g_130) , 1L); } if ((l_283 = (safe_rshift_func_uint16_t_u_u((l_267 = l_267), (safe_rshift_func_int16_t_s_u(0L, 7)))))) { return g_188[2]; } else { uint64_t l_292 = 18446744073709551615UL; g_289--; l_292++; return p_48; } } static int16_t func_53(int32_t p_54, int8_t p_55, uint32_t p_56, uint16_t p_57, int16_t p_58) { int8_t l_61[4]; int32_t l_83 = (-7L); int64_t l_193 = 0L; uint16_t l_244[1]; int i; for (i = 0; i < 4; i++) l_61[i] = 0x87L; for (i = 0; i < 1; i++) l_244[i] = 0x51DFL; if ((safe_sub_func_int16_t_s_s(l_61[1], (safe_rshift_func_uint16_t_u_s((g_2 > (safe_mul_func_int16_t_s_s(0x3D38L, 0x5845L))), 2))))) { int8_t l_70 = 0x18L; p_54 = func_66(l_61[3], (l_70 , ((p_54 >= l_70) || 0x6845D487L)), p_56); } else { uint32_t l_84 = 0x237EEBDCL; int32_t l_173 = 1L; int16_t l_186 = 0x9EA8L; uint32_t l_187 = 0xFC704608L; l_173 &= func_66(g_2, ((safe_rshift_func_uint16_t_u_u((func_75((((func_66((l_83 &= (safe_mod_func_uint64_t_u_u((((safe_sub_func_uint32_t_u_u(0xD2E653D3L, (safe_sub_func_uint8_t_u_u((g_32 || p_56), g_2)))) >= l_61[1]) , 0UL), g_2))), l_84, g_2) & g_32) == 0xF0F592B025F3D189LL) && p_56)) > p_55), g_2)) , l_83), l_84); l_83 = (+(g_95 = ((!(~(252UL && (((0UL != ((safe_mul_func_int8_t_s_s((safe_rshift_func_int16_t_s_s((safe_sub_func_uint64_t_u_u(0xFE60FC580C8C66A0LL, g_32)), g_89)), g_95)) & (-10L))) , l_61[0]) > g_32)))) ^ l_84))); g_183++; g_188[0] = (l_186 & l_187); return g_122; } for (l_83 = 0; l_83 < 3; l_83 += 1) { g_188[l_83] = 0UL; } g_191 |= (safe_mod_func_uint32_t_u_u(l_61[1], ((-3L) || g_128))); lbl_245: g_192 &= p_55; l_83 = l_193; for (p_56 = 8; (p_56 != 53); p_56 = safe_add_func_uint32_t_u_u(p_56, 3)) { uint16_t l_196 = 4UL; return l_196; } g_197 = (-10L); for (p_58 = (-15); (p_58 <= (-8)); p_58 = safe_add_func_int8_t_s_s(p_58, 8)) { int8_t l_200 = 1L; uint8_t l_211 = 0x31L; int32_t l_212 = 0x66F017B8L; int32_t l_238[3]; int i; for (i = 0; i < 3; i++) l_238[i] = 0x52FCFA09L; l_200 = 1L; l_211 = (safe_sub_func_uint32_t_u_u(0x4CBD725CL, (((p_55 = 0x1BL) ^ (safe_mod_func_int32_t_s_s((safe_div_func_int8_t_s_s(((safe_sub_func_uint16_t_u_u((safe_mul_func_uint8_t_u_u(g_95, 1UL)), 65535UL)) ^ l_200), l_200)), p_57))) < p_57))); l_83 &= (g_224 = ((g_188[2] > ((l_212 ^= p_54) ^ (g_223 = (safe_add_func_uint8_t_u_u((safe_unary_minus_func_uint8_t_u((g_216--))), (safe_add_func_uint8_t_u_u((safe_mod_func_uint32_t_u_u((p_58 ^ g_32), p_56)), p_57))))))) < l_61[1])); --g_226[0]; g_233 |= (g_2 , (!(((g_226[0] == (safe_lshift_func_int8_t_s_u(((((safe_unary_minus_func_int16_t_s((l_83 = g_216))) , p_55) , l_83) < g_191), 3))) & 0x91L) , 18446744073709551614UL))); l_238[2] ^= (safe_mul_func_uint8_t_u_u((((l_212 = (((safe_div_func_int64_t_s_s((l_61[2] < l_61[1]), (l_211 , 0x3FC95AA9AF56AD3ALL))) == 65535UL) == 0UL)) == p_57) , p_56), g_226[0])); l_83 = (safe_mul_func_uint8_t_u_u(254UL, (safe_rshift_func_uint8_t_u_s((g_128 , (!(((l_83 || (-6L)) , g_128) <= p_54))), l_244[0])))); if (g_183) goto lbl_245; } l_83 &= (((safe_mod_func_uint32_t_u_u(4294967286UL, (safe_mod_func_int16_t_s_s(((((safe_rshift_func_uint16_t_u_s(l_244[0], 14)) < (safe_div_func_int8_t_s_s((((g_188[0] = ((l_61[1] != l_193) | 0xDAC16468L)) == g_2) ^ p_58), 0x92L))) == g_192) == 0xA0L), 0x9D84L)))) != p_55) == g_89); return l_244[0]; } static int32_t func_66(int32_t p_67, int32_t p_68, const int32_t p_69) { const uint32_t l_71 = 0x54A037A7L; int32_t l_72 = (-1L); l_72 = (((p_67 , (p_67 != (p_68 == g_2))) < p_67) && l_71); l_72 = g_32; return l_72; } static uint16_t func_75(int64_t p_76) { int8_t l_90 = 0xD3L; int32_t l_92 = (-1L); int32_t l_93 = 0L; uint64_t l_105 = 0x7F2E326E24E13FEALL; int32_t l_131 = (-4L); int32_t l_171 = 0x95C9911EL; int32_t l_172 = (-1L); lbl_106: for (p_76 = 10; (p_76 <= 18); ++p_76) { int8_t l_87[2]; int32_t l_88 = 0x477CAF8BL; int32_t l_91 = 0L; int32_t l_94 = 7L; int i; for (i = 0; i < 2; i++) l_87[i] = (-1L); g_95++; if (l_87[1]) continue; } for (g_32 = (-29); (g_32 < (-25)); g_32 = safe_add_func_uint32_t_u_u(g_32, 6)) { int64_t l_100[2]; int32_t l_101 = 0x2DEFE8EBL; uint32_t l_104 = 0xF7123672L; int32_t l_123 = (-1L); int i; for (i = 0; i < 2; i++) l_100[i] = 7L; if (g_32) break; l_92 = p_76; l_101 = l_100[1]; l_104 = (safe_lshift_func_uint16_t_u_u(0x1959L, 13)); l_105 = p_76; l_92 = 0L; if (g_32) goto lbl_106; l_123 &= func_66(func_107((safe_sub_func_int32_t_s_s(p_76, ((safe_mod_func_int16_t_s_s(((l_93 = ((((safe_div_func_int32_t_s_s((safe_mul_func_int16_t_s_s(l_92, (safe_mul_func_int16_t_s_s(7L, g_32)))), g_89)) , 65527UL) > p_76) || 0xFD2B101DL)) != 0x2CC6L), g_89)) > l_100[1]))), l_101, g_2), g_89, g_32); if (l_105) continue; l_131 ^= (p_76 >= ((g_130 = (l_90 && ((((g_129[0] = (((((safe_div_func_int8_t_s_s((l_101 = ((safe_rshift_func_uint8_t_u_u((g_128 = ((0L ^ 0L) | 6UL)), l_100[1])) , (-1L))), g_89)) & 1UL) , 0x5C44L) && p_76) == 0UL)) || l_93) != g_95) ^ 0xCFL))) > l_92)); } l_93 = (((safe_div_func_uint32_t_u_u((safe_mul_func_uint8_t_u_u(((safe_mul_func_int16_t_s_s((0L < ((safe_lshift_func_int8_t_s_u((safe_rshift_func_int8_t_s_s((g_129[0] = g_2), 1)), 4)) & (!(((safe_rshift_func_int8_t_s_s(p_76, 4)) >= 0x36L) & 0L)))), g_95)) == 0x2D9A1771DC5CD976LL), l_93)), l_105)) == 0UL) ^ 9L); l_172 ^= (((safe_mod_func_int64_t_s_s((p_76 = (((~(safe_div_func_int64_t_s_s(((safe_add_func_int32_t_s_s((safe_mul_func_uint8_t_u_u((safe_unary_minus_func_uint16_t_u((safe_lshift_func_int8_t_s_s((safe_mod_func_uint64_t_u_u((safe_div_func_int64_t_s_s((safe_mod_func_int8_t_s_s(((((safe_mod_func_int8_t_s_s(((g_32 , (((l_171 |= (l_93 = ((g_128 < ((safe_sub_func_uint32_t_u_u((((safe_mod_func_int64_t_s_s((safe_mod_func_int32_t_s_s(((l_92 = ((g_130 && p_76) | l_92)) || 0xF262EB4CL), l_131)), p_76)) >= g_129[1]) ^ g_129[0]), l_131)) && l_90)) , 1L))) , (-1L)) , l_90)) <= 3L), l_105)) <= 0x75AA4048L) >= g_122) != p_76), l_105)), l_131)), 1L)), 6)))), p_76)), 0x05672CF6L)) & 8UL), p_76))) , g_128) <= 0xCB42A3456A020803LL)), 8UL)) & l_90) < g_32); return g_129[0]; } static int32_t func_107(int64_t p_108, uint32_t p_109, uint8_t p_110) { uint32_t l_121 = 9UL; g_122 = ((p_109 , p_110) != (((p_109 > l_121) == g_89) >= 1L)); return p_109; } int main (int argc, char* argv[]) { int i; int print_hash_value = 0; if (argc == 2 && strcmp(argv[1], "1") == 0) print_hash_value = 1; platform_main_begin(); crc32_gentab(); func_1(); transparent_crc(g_2, "g_2", print_hash_value); transparent_crc(g_12, "g_12", print_hash_value); transparent_crc(g_32, "g_32", print_hash_value); transparent_crc(g_89, "g_89", print_hash_value); transparent_crc(g_95, "g_95", print_hash_value); transparent_crc(g_122, "g_122", print_hash_value); transparent_crc(g_128, "g_128", print_hash_value); for (i = 0; i < 2; i++) { transparent_crc(g_129[i], "g_129[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_130, "g_130", print_hash_value); transparent_crc(g_183, "g_183", print_hash_value); for (i = 0; i < 3; i++) { transparent_crc(g_188[i], "g_188[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_191, "g_191", print_hash_value); transparent_crc(g_192, "g_192", print_hash_value); transparent_crc(g_197, "g_197", print_hash_value); transparent_crc(g_216, "g_216", print_hash_value); transparent_crc(g_223, "g_223", print_hash_value); transparent_crc(g_224, "g_224", print_hash_value); transparent_crc(g_225, "g_225", print_hash_value); for (i = 0; i < 2; i++) { transparent_crc(g_226[i], "g_226[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_233, "g_233", print_hash_value); for (i = 0; i < 1; i++) { transparent_crc(g_274[i], "g_274[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } for (i = 0; i < 3; i++) { transparent_crc(g_278[i], "g_278[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } for (i = 0; i < 1; i++) { transparent_crc(g_284[i], "g_284[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } for (i = 0; i < 2; i++) { transparent_crc(g_285[i], "g_285[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_286, "g_286", print_hash_value); transparent_crc(g_287, "g_287", print_hash_value); transparent_crc(g_289, "g_289", print_hash_value); transparent_crc(g_321, "g_321", print_hash_value); for (i = 0; i < 2; i++) { transparent_crc(g_322[i], "g_322[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_339, "g_339", print_hash_value); transparent_crc(g_342, "g_342", print_hash_value); for (i = 0; i < 1; i++) { transparent_crc(g_343[i], "g_343[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_346, "g_346", print_hash_value); transparent_crc(g_359, "g_359", print_hash_value); transparent_crc(g_375, "g_375", print_hash_value); transparent_crc(g_380, "g_380", print_hash_value); transparent_crc(g_382, "g_382", print_hash_value); transparent_crc(g_383, "g_383", print_hash_value); transparent_crc(g_418, "g_418", print_hash_value); transparent_crc(g_427, "g_427", print_hash_value); transparent_crc(g_469, "g_469", print_hash_value); transparent_crc(g_476, "g_476", print_hash_value); transparent_crc(g_478, "g_478", print_hash_value); transparent_crc(g_485, "g_485", print_hash_value); transparent_crc(g_494, "g_494", print_hash_value); platform_main_end(crc32_context ^ 0xFFFFFFFFUL, print_hash_value); return 0; }
46.488848
750
0.621886
0a51b18122704c75e3283301e1f7c00e02d14170
2,298
cs
C#
LCUTool/API/Models/Summoner.cs
spiderbuddy411/AutoAccept-Skin-Booster-ARAM
f80ae78a4d53bdf6dc2387ead91044438ddbb629
[ "MIT" ]
4
2021-04-06T01:20:00.000Z
2022-03-23T18:43:36.000Z
LCUTool/API/Models/Summoner.cs
spiderbuddy411/AutoAccept-Skin-Booster-ARAM
f80ae78a4d53bdf6dc2387ead91044438ddbb629
[ "MIT" ]
1
2021-09-13T03:32:54.000Z
2021-09-13T03:32:54.000Z
LCUTool/API/Models/Summoner.cs
spiderbuddy411/AutoAccept-Skin-Booster-ARAM
f80ae78a4d53bdf6dc2387ead91044438ddbb629
[ "MIT" ]
1
2022-03-23T18:43:37.000Z
2022-03-23T18:43:37.000Z
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LCUAPI.API.Models { class SummonerObject { public class RerollPoints { [JsonProperty("currentPoints")] public int CurrentPoints { get; set; } [JsonProperty("maxRolls")] public int MaxRolls { get; set; } [JsonProperty("numberOfRolls")] public int NumberOfRolls { get; set; } [JsonProperty("pointsCostToRoll")] public int PointsCostToRoll { get; set; } [JsonProperty("pointsToReroll")] public int PointsToReroll { get; set; } } public class Summoner { [JsonProperty("accountId")] public long AccountId { get; set; } [JsonProperty("displayName")] public string DisplayName { get; set; } [JsonProperty("internalName")] public string InternalName { get; set; } [JsonProperty("nameChangeFlag")] public bool NameChangeFlag { get; set; } [JsonProperty("percentCompleteForNextLevel")] public int PercentCompleteForNextLevel { get; set; } [JsonProperty("profileIconId")] public int ProfileIconId { get; set; } [JsonProperty("puuid")] public string Puuid { get; set; } [JsonProperty("rerollPoints")] public RerollPoints RerollPoints { get; set; } /* [JsonProperty("summonerId")] public int SummonerId { get; set; }*/ // eror id summoner search [JsonProperty("summonerLevel")] public int SummonerLevel { get; set; } [JsonProperty("unnamed")] public bool Unnamed { get; set; } [JsonProperty("xpSinceLastLevel")] public int XpSinceLastLevel { get; set; } [JsonProperty("xpUntilNextLevel")] public int XpUntilNextLevel { get; set; } } } class SummonerProfile { [JsonProperty("backgroundSkinId")] public int BackgroundSkinId { get; set; } [JsonProperty("regalia")] public string Regalia { get; set; } } }
27.035294
77
0.568755
c37a26d75c25cf636fc3be282f50aa2ec7b20ab4
6,296
cs
C#
tests/Prism.Plugin.Logging.Tests/Tests/Registration/GraylogRegistrationTests.cs
mdartu/Prism.Plugin.Logging
d4c17288aa0f13816d2cd2854e2d1e3a67a2eb81
[ "MIT" ]
75
2017-11-10T18:34:07.000Z
2022-03-30T06:20:42.000Z
tests/Prism.Plugin.Logging.Tests/Tests/Registration/GraylogRegistrationTests.cs
mdartu/Prism.Plugin.Logging
d4c17288aa0f13816d2cd2854e2d1e3a67a2eb81
[ "MIT" ]
83
2017-08-05T02:48:15.000Z
2022-02-07T13:13:48.000Z
tests/Prism.Plugin.Logging.Tests/Tests/Registration/GraylogRegistrationTests.cs
mdartu/Prism.Plugin.Logging
d4c17288aa0f13816d2cd2854e2d1e3a67a2eb81
[ "MIT" ]
19
2017-10-23T07:48:40.000Z
2022-03-20T09:58:41.000Z
using System; using System.Collections.Generic; using Moq; using Prism.Ioc; using Prism.Logging; using Prism.Logging.Graylog; using Xunit; namespace Prism.Plugin.Logging.Tests.Registration { public class GraylogRegistrationTests { [Fact] public void RegistersGelfLoggerWithUri() { var mockContainer = new Mock<IContainerExtension>(); mockContainer.Object.RegisterGraylogLogger(new Uri("http://127.0.0.1:8080")); mockContainer.Verify(c => c.RegisterInstance(typeof(IGelfOptions), It.IsAny<GelfOptions>())); mockContainer.Verify(c => c.RegisterManySingleton(typeof(GelfLogger), typeof(IAnalyticsService), typeof(ICrashesService), typeof(ILogger), typeof(IAggregableLogger))); } [Fact] public void RegistersGelfLoggerWithDelegateConfiguration() { var mockContainer = new Mock<IContainerExtension>(); mockContainer.Object.RegisterGraylogLogger(o => { o.Host = new Uri("https://127.0.0.1:8080"); }); mockContainer.Verify(c => c.RegisterInstance(typeof(IGelfOptions), It.IsAny<GelfOptions>())); mockContainer.Verify(c => c.RegisterManySingleton(typeof(GelfLogger), typeof(IAnalyticsService), typeof(ICrashesService), typeof(ILogger), typeof(IAggregableLogger))); } [Fact] public void GelfLoggerRegisteredWithAggregateLogger() { var mockContainer = new Mock<IContainerExtension>(); mockContainer.Setup(c => c.RegisterManySingleton(It.IsAny<Type>(), It.IsAny<Type[]>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.RegisterSingleton(It.IsAny<Type>(), It.IsAny<Func<IContainerProvider, object>>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.RegisterSingleton(It.IsAny<Type>(), It.IsAny<Type>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.Register(It.IsAny<Type>(), It.IsAny<Func<IContainerProvider, object>>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.Resolve(typeof(IEnumerable<IAggregableLogger>))) .Returns(Array.Empty<IAggregableLogger>()); mockContainer.Setup(c => c.Resolve(typeof(AggregateLogger))) .Returns(new AggregateLogger()); mockContainer.Setup(c => c.IsRegistered(typeof(ILogger))) .Returns(false); mockContainer.Setup(c => c.IsRegistered(typeof(IAggregateLogger))) .Returns(true); mockContainer.Object.UseAggregateLogger(); mockContainer.Object.RegisterGraylogLogger(new Uri("http://127.0.0.1:8080")); mockContainer.Verify(c => c.RegisterInstance(typeof(IGelfOptions), It.IsAny<GelfOptions>()), Times.Once); mockContainer.Verify(c => c.RegisterSingleton(typeof(IGelfLogger), typeof(GelfLogger)), Times.Once); mockContainer.Verify(c => c.Register(typeof(IAggregableLogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.RegisterSingleton(typeof(AggregateLogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(ILogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(IAnalyticsService), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(ICrashesService), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(IAggregateLogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); } [Fact] public void AggregateLoggerReplacesGelfLogger() { var mockContainer = new Mock<IContainerExtension>(); mockContainer.Setup(c => c.RegisterManySingleton(It.IsAny<Type>(), It.IsAny<Type[]>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.RegisterSingleton(It.IsAny<Type>(), It.IsAny<Func<IContainerProvider, object>>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.Register(It.IsAny<Type>(), It.IsAny<Func<IContainerProvider, object>>())) .Returns(mockContainer.Object); mockContainer.Setup(c => c.Resolve(typeof(IEnumerable<IAggregableLogger>))) .Returns(Array.Empty<IAggregableLogger>()); mockContainer.As<IContainerProvider>().Setup(c => c.Resolve(typeof(AggregateLogger))) .Returns(new AggregateLogger()); mockContainer.Setup(c => c.IsRegistered(typeof(ILogger))) .Returns(true); mockContainer.Setup(c => c.IsRegistered(typeof(IAggregateLogger))) .Returns(false); mockContainer.Object.RegisterGraylogLogger(new Uri("http://127.0.0.1:8080")); mockContainer.Object.UseAggregateLogger(); mockContainer.Verify(c => c.RegisterInstance(typeof(IGelfOptions), It.IsAny<GelfOptions>()), Times.Once); mockContainer.Verify(c => c.RegisterManySingleton(typeof(GelfLogger), typeof(IAnalyticsService), typeof(ICrashesService), typeof(ILogger), typeof(IAggregableLogger))); mockContainer.Verify(c => c.RegisterSingleton(typeof(AggregateLogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(ILogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(IAnalyticsService), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(ICrashesService), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); mockContainer.Verify(c => c.Register(typeof(IAggregateLogger), It.IsAny<Func<IContainerProvider, object>>()), Times.Once); } } }
53.355932
142
0.636436
c6fce16f78a55d0c18e5272bb437deb8828d33bb
34,305
rs
Rust
src/lib.rs
dignifiedquire/blake2s_simd
a2053c18912493c1d9497d25bcdc8464099a9a5b
[ "MIT" ]
2
2019-05-27T02:19:46.000Z
2019-05-29T01:23:45.000Z
src/lib.rs
dignifiedquire/blake2s_simd
a2053c18912493c1d9497d25bcdc8464099a9a5b
[ "MIT" ]
1
2019-03-08T13:55:25.000Z
2019-06-23T18:40:57.000Z
src/lib.rs
dignifiedquire/blake2s_simd
a2053c18912493c1d9497d25bcdc8464099a9a5b
[ "MIT" ]
2
2018-12-02T20:35:32.000Z
2019-04-16T20:45:45.000Z
//! EXPERIMENTAL implementation of BLAKE2s #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate core; #[macro_use] extern crate arrayref; extern crate arrayvec; extern crate byteorder; extern crate constant_time_eq; use byteorder::{ByteOrder, LittleEndian}; use core::cmp; use core::fmt; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod avx2; mod portable; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod sse41; pub mod blake2sp; #[cfg(test)] mod test; /// The max hash length. pub const OUTBYTES: usize = 32; /// The max key length. pub const KEYBYTES: usize = 32; /// The max salt length. pub const SALTBYTES: usize = 8; /// The max personalization length. pub const PERSONALBYTES: usize = 8; /// The number input bytes passed to each call to the compression function. Small benchmarks need /// to use an even multiple of `BLOCKBYTES`, or else their apparent throughput will be low. pub const BLOCKBYTES: usize = 64; const IV: [u32; 8] = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ]; const SIGMA: [[u8; 16]; 12] = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], ]; // Safety note: The compression interface is unsafe in general, even though the portable // implementation is safe, because calling the AVX2 implementation on a platform that doesn't // support AVX2 is undefined behavior. type CompressFn = unsafe fn(&mut StateWords, &Block, count: u64, lastblock: u32, lastnode: u32); type Compress8Fn = unsafe fn( state0: &mut StateWords, state1: &mut StateWords, state2: &mut StateWords, state3: &mut StateWords, state4: &mut StateWords, state5: &mut StateWords, state6: &mut StateWords, state7: &mut StateWords, block0: &Block, block1: &Block, block2: &Block, block3: &Block, block4: &Block, block5: &Block, block6: &Block, block7: &Block, count0: u64, count1: u64, count2: u64, count3: u64, count4: u64, count5: u64, count6: u64, count7: u64, lastblock0: u32, lastblock1: u32, lastblock2: u32, lastblock3: u32, lastblock4: u32, lastblock5: u32, lastblock6: u32, lastblock7: u32, lastnode0: u32, lastnode1: u32, lastnode2: u32, lastnode3: u32, lastnode4: u32, lastnode5: u32, lastnode6: u32, lastnode7: u32, ); type Hash4ExactFn = unsafe fn(params: &Params, input0: &[u8], input1: &[u8], input2: &[u8], input3: &[u8]) -> [Hash; 4]; type Hash8ExactFn = unsafe fn( params: &Params, input0: &[u8], input1: &[u8], input2: &[u8], input3: &[u8], input4: &[u8], input5: &[u8], input6: &[u8], input7: &[u8], ) -> [Hash; 8]; type Vectorize8Fn = unsafe fn(words: &mut [AlignedWords8; 8]); type Compress8VectorizedFn = unsafe fn( vectorized_words: &mut [AlignedWords8; 8], block0: &Block, block1: &Block, block2: &Block, block3: &Block, block4: &Block, block5: &Block, block6: &Block, block7: &Block, count_low: &AlignedWords8, count_high: &AlignedWords8, lastblock: &AlignedWords8, lastnode: &AlignedWords8, ); type StateWords = [u32; 8]; type Block = [u8; BLOCKBYTES]; type HexString = arrayvec::ArrayString<[u8; 2 * OUTBYTES]>; #[derive(Copy, Clone)] #[repr(C, align(32))] pub struct AlignedWords8(pub [u32; 8]); impl core::ops::Deref for AlignedWords8 { type Target = [u32; 8]; fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for AlignedWords8 { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub fn blake2s(input: &[u8]) -> Hash { State::new().update(input).finalize() } #[derive(Clone)] pub struct Params { hash_length: u8, key_length: u8, key: [u8; KEYBYTES], salt: [u8; SALTBYTES], personal: [u8; PERSONALBYTES], fanout: u8, max_depth: u8, max_leaf_length: u32, node_offset: u64, node_depth: u8, inner_hash_length: u8, last_node: bool, } impl Params { pub fn new() -> Self { Self::default() } fn make_words(&self) -> StateWords { let (salt_left, salt_right) = array_refs!(&self.salt, 4, 4); let (personal_left, personal_right) = array_refs!(&self.personal, 4, 4); [ IV[0] ^ self.hash_length as u32 ^ (self.key_length as u32) << 8 ^ (self.fanout as u32) << 16 ^ (self.max_depth as u32) << 24, IV[1] ^ (self.max_leaf_length as u32), IV[2] ^ (self.node_offset as u32), IV[3] ^ (self.node_offset >> 32) as u32 ^ (self.node_depth as u32) << 16 ^ (self.inner_hash_length as u32) << 24, IV[4] ^ LittleEndian::read_u32(salt_left), IV[5] ^ LittleEndian::read_u32(salt_right), IV[6] ^ LittleEndian::read_u32(personal_left), IV[7] ^ LittleEndian::read_u32(personal_right), ] } pub fn to_state(&self) -> State { State::with_params(self) } pub fn hash_length(&mut self, length: usize) -> &mut Self { assert!( 1 <= length && length <= OUTBYTES, "Bad hash length: {}", length ); self.hash_length = length as u8; self } pub fn key(&mut self, key: &[u8]) -> &mut Self { assert!(key.len() <= KEYBYTES, "Bad key length: {}", key.len()); self.key_length = key.len() as u8; self.key = [0; KEYBYTES]; self.key[..key.len()].copy_from_slice(key); self } pub fn salt(&mut self, salt: &[u8]) -> &mut Self { assert!(salt.len() <= SALTBYTES, "Bad salt length: {}", salt.len()); self.salt = [0; SALTBYTES]; self.salt[..salt.len()].copy_from_slice(salt); self } pub fn personal(&mut self, personalization: &[u8]) -> &mut Self { assert!( personalization.len() <= PERSONALBYTES, "Bad personalization length: {}", personalization.len() ); self.personal = [0; PERSONALBYTES]; self.personal[..personalization.len()].copy_from_slice(personalization); self } pub fn fanout(&mut self, fanout: u8) -> &mut Self { self.fanout = fanout; self } pub fn max_depth(&mut self, depth: u8) -> &mut Self { assert!(depth != 0, "Bad max depth: {}", depth); self.max_depth = depth; self } pub fn max_leaf_length(&mut self, length: u32) -> &mut Self { self.max_leaf_length = length; self } pub fn node_offset(&mut self, offset: u64) -> &mut Self { assert!(offset < (1 << 48), "Bad node offset: {}", offset); self.node_offset = offset; self } pub fn node_depth(&mut self, depth: u8) -> &mut Self { self.node_depth = depth; self } pub fn inner_hash_length(&mut self, length: usize) -> &mut Self { assert!(length <= OUTBYTES, "Bad inner hash length: {}", length); self.inner_hash_length = length as u8; self } pub fn last_node(&mut self, last_node: bool) -> &mut Self { self.last_node = last_node; self } } impl Default for Params { fn default() -> Self { Self { hash_length: OUTBYTES as u8, key_length: 0, key: [0; KEYBYTES], salt: [0; SALTBYTES], personal: [0; PERSONALBYTES], // NOTE: fanout and max_depth don't default to zero! fanout: 1, max_depth: 1, max_leaf_length: 0, node_offset: 0, node_depth: 0, inner_hash_length: 0, last_node: false, } } } #[derive(Clone)] pub struct State { h: StateWords, buf: Block, buflen: u8, count: u64, compress_fn: CompressFn, last_node: bool, hash_length: u8, } impl State { pub fn new() -> Self { Self::with_params(&Params::default()) } fn with_params(params: &Params) -> Self { let mut state = Self { h: params.make_words(), compress_fn: default_compress_impl().0, buf: [0; BLOCKBYTES], buflen: 0, count: 0, last_node: params.last_node, hash_length: params.hash_length, }; if params.key_length > 0 { let mut key_block = [0; BLOCKBYTES]; key_block[..KEYBYTES].copy_from_slice(&params.key); state.update(&key_block); } state } fn fill_buf(&mut self, input: &mut &[u8]) { let take = cmp::min(BLOCKBYTES - self.buflen as usize, input.len()); self.buf[self.buflen as usize..self.buflen as usize + take].copy_from_slice(&input[..take]); self.buflen += take as u8; self.count += take as u64; *input = &input[take..]; } // If the state already has some input in its buffer, try to fill the buffer and perform a // compression. However, only do the compression if there's more input coming, otherwise it // will give the wrong hash it the caller finalizes immediately after. fn compress_buffer_if_possible(&mut self, input: &mut &[u8]) { if self.buflen > 0 { self.fill_buf(input); if !input.is_empty() { unsafe { (self.compress_fn)(&mut self.h, &self.buf, self.count, 0, 0); } self.buflen = 0; } } } /// Add input to the hash. You can call `update` any number of times. pub fn update(&mut self, mut input: &[u8]) -> &mut Self { // If we have a partial buffer, try to complete it. self.compress_buffer_if_possible(&mut input); // While there's more than a block of input left (which also means we cleared the buffer // above), compress blocks directly without copying. while input.len() > BLOCKBYTES { self.count += BLOCKBYTES as u64; let block = array_ref!(input, 0, BLOCKBYTES); unsafe { (self.compress_fn)(&mut self.h, block, self.count, 0, 0); } input = &input[BLOCKBYTES..]; } // Buffer any remaining input, to be either compressed or finalized in a subsequent call. // Note that this represents some copying overhead, which in theory we could avoid in // all-at-once setting. A function hardcoded for exactly BLOCKSIZE input bytes is about 10% // faster than using this implementation for the same input. But non-multiple sizes still // require copying, and the savings disappear into the noise for any larger multiple. Any // caller so concerned with performance that they're shaping their hash inputs down to the // single byte, should just call the compression function directly. self.fill_buf(&mut input); self } /// Finalize the state and return a `Hash`. This method is idempotent, and calling it multiple /// times will give the same result. It's also possible to `update` with more input in between. pub fn finalize(&mut self) -> Hash { for i in self.buflen as usize..BLOCKBYTES { self.buf[i] = 0; } let last_node = if self.last_node { !0 } else { 0 }; let mut h_copy = self.h; unsafe { (self.compress_fn)(&mut h_copy, &self.buf, self.count, !0, last_node); } Hash { bytes: state_words_to_bytes(&h_copy), len: self.hash_length, } } /// Set a flag indicating that this is the last node of its level in a tree hash. This is /// equivalent to [`Params::last_node`], except that it can be set at any time before calling /// `finalize`. That allows callers to begin hashing a node without knowing ahead of time /// whether it's the last in its level. For more details about the intended use of this flag /// [the BLAKE2 spec]. /// /// [`Params::last_node`]: struct.Params.html#method.last_node /// [the BLAKE2 spec]: https://blake2.net/blake2.pdf pub fn set_last_node(&mut self, last_node: bool) -> &mut Self { self.last_node = last_node; self } /// Return the total number of bytes input so far. pub fn count(&self) -> u64 { self.count } } fn state_words_to_bytes(state_words: &StateWords) -> [u8; OUTBYTES] { let mut bytes = [0; OUTBYTES]; { let refs = mut_array_refs!(&mut bytes, 4, 4, 4, 4, 4, 4, 4, 4); LittleEndian::write_u32(refs.0, state_words[0]); LittleEndian::write_u32(refs.1, state_words[1]); LittleEndian::write_u32(refs.2, state_words[2]); LittleEndian::write_u32(refs.3, state_words[3]); LittleEndian::write_u32(refs.4, state_words[4]); LittleEndian::write_u32(refs.5, state_words[5]); LittleEndian::write_u32(refs.6, state_words[6]); LittleEndian::write_u32(refs.7, state_words[7]); } bytes } #[cfg(feature = "std")] impl std::io::Write for State { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.update(buf); Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } impl fmt::Debug for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // NB: Don't print the words. Leaking them would allow length extension. write!( f, "State {{ count: {}, hash_length: {}, last_node: {} }}", self.count, self.hash_length, self.last_node, ) } } impl Default for State { fn default() -> Self { Self::with_params(&Params::default()) } } /// A finalized BLAKE2 hash, with constant-time equality. #[derive(Clone, Copy)] pub struct Hash { bytes: [u8; OUTBYTES], len: u8, } impl Hash { pub fn as_bytes(&self) -> &[u8] { &self.bytes[..self.len as usize] } pub fn to_hex(&self) -> HexString { bytes_to_hex(self.as_bytes()) } } fn bytes_to_hex(bytes: &[u8]) -> HexString { let mut s = arrayvec::ArrayString::new(); let table = b"0123456789abcdef"; for &b in bytes { s.push(table[(b >> 4) as usize] as char); s.push(table[(b & 0xf) as usize] as char); } s } /// This implementation is constant time, if the two hashes are the same length. impl PartialEq for Hash { fn eq(&self, other: &Hash) -> bool { constant_time_eq::constant_time_eq(&self.as_bytes(), &other.as_bytes()) } } /// This implementation is constant time, if the slice is the same length as the hash. impl PartialEq<[u8]> for Hash { fn eq(&self, other: &[u8]) -> bool { constant_time_eq::constant_time_eq(&self.as_bytes(), other) } } impl Eq for Hash {} impl AsRef<[u8]> for Hash { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl fmt::Debug for Hash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Hash(0x{})", self.to_hex()) } } pub fn update8( state0: &mut State, state1: &mut State, state2: &mut State, state3: &mut State, state4: &mut State, state5: &mut State, state6: &mut State, state7: &mut State, mut input0: &[u8], mut input1: &[u8], mut input2: &[u8], mut input3: &[u8], mut input4: &[u8], mut input5: &[u8], mut input6: &[u8], mut input7: &[u8], ) { // First we need to make sure all the buffers are clear. state0.compress_buffer_if_possible(&mut input0); state1.compress_buffer_if_possible(&mut input1); state2.compress_buffer_if_possible(&mut input2); state3.compress_buffer_if_possible(&mut input3); state4.compress_buffer_if_possible(&mut input4); state5.compress_buffer_if_possible(&mut input5); state6.compress_buffer_if_possible(&mut input6); state7.compress_buffer_if_possible(&mut input7); // Now, as long as all of the states have more than a block of input coming (so that we know we // don't need to finalize any of them), compress in parallel directly into their state words. let compress8_fn = default_compress_impl().1; while input0.len() > BLOCKBYTES && input1.len() > BLOCKBYTES && input2.len() > BLOCKBYTES && input3.len() > BLOCKBYTES && input4.len() > BLOCKBYTES && input5.len() > BLOCKBYTES && input6.len() > BLOCKBYTES && input7.len() > BLOCKBYTES { state0.count += BLOCKBYTES as u64; state1.count += BLOCKBYTES as u64; state2.count += BLOCKBYTES as u64; state3.count += BLOCKBYTES as u64; state4.count += BLOCKBYTES as u64; state5.count += BLOCKBYTES as u64; state6.count += BLOCKBYTES as u64; state7.count += BLOCKBYTES as u64; unsafe { compress8_fn( &mut state0.h, &mut state1.h, &mut state2.h, &mut state3.h, &mut state4.h, &mut state5.h, &mut state6.h, &mut state7.h, array_ref!(input0, 0, BLOCKBYTES), array_ref!(input1, 0, BLOCKBYTES), array_ref!(input2, 0, BLOCKBYTES), array_ref!(input3, 0, BLOCKBYTES), array_ref!(input4, 0, BLOCKBYTES), array_ref!(input5, 0, BLOCKBYTES), array_ref!(input6, 0, BLOCKBYTES), array_ref!(input7, 0, BLOCKBYTES), state0.count, state1.count, state2.count, state3.count, state4.count, state5.count, state6.count, state7.count, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ); } input0 = &input0[BLOCKBYTES..]; input1 = &input1[BLOCKBYTES..]; input2 = &input2[BLOCKBYTES..]; input3 = &input3[BLOCKBYTES..]; input4 = &input4[BLOCKBYTES..]; input5 = &input5[BLOCKBYTES..]; input6 = &input6[BLOCKBYTES..]; input7 = &input7[BLOCKBYTES..]; } // Finally, if there's any remaining input, add it into the state the usual way. Note that if // one of the inputs is short, this could actually be more work than the loop above. The caller // should hopefully arrange for that not to happen. state0.update(input0); state1.update(input1); state2.update(input2); state3.update(input3); state4.update(input4); state5.update(input5); state6.update(input6); state7.update(input7); } pub fn finalize8( state0: &mut State, state1: &mut State, state2: &mut State, state3: &mut State, state4: &mut State, state5: &mut State, state6: &mut State, state7: &mut State, ) -> [Hash; 8] { // Zero out the buffer tails, which might contain bytes from previous blocks. for i in state0.buflen as usize..BLOCKBYTES { state0.buf[i] = 0; } for i in state1.buflen as usize..BLOCKBYTES { state1.buf[i] = 0; } for i in state2.buflen as usize..BLOCKBYTES { state2.buf[i] = 0; } for i in state3.buflen as usize..BLOCKBYTES { state3.buf[i] = 0; } for i in state4.buflen as usize..BLOCKBYTES { state4.buf[i] = 0; } for i in state5.buflen as usize..BLOCKBYTES { state5.buf[i] = 0; } for i in state6.buflen as usize..BLOCKBYTES { state6.buf[i] = 0; } for i in state7.buflen as usize..BLOCKBYTES { state7.buf[i] = 0; } // Translate the last node flag of each state into the u64 that BLAKE2 uses. let last_node0: u32 = if state0.last_node { !0 } else { 0 }; let last_node1: u32 = if state1.last_node { !0 } else { 0 }; let last_node2: u32 = if state2.last_node { !0 } else { 0 }; let last_node3: u32 = if state3.last_node { !0 } else { 0 }; let last_node4: u32 = if state4.last_node { !0 } else { 0 }; let last_node5: u32 = if state5.last_node { !0 } else { 0 }; let last_node6: u32 = if state6.last_node { !0 } else { 0 }; let last_node7: u32 = if state7.last_node { !0 } else { 0 }; // Make copies of all the state words. This step is what makes finalize idempotent. let mut h_copy0 = state0.h; let mut h_copy1 = state1.h; let mut h_copy2 = state2.h; let mut h_copy3 = state3.h; let mut h_copy4 = state4.h; let mut h_copy5 = state5.h; let mut h_copy6 = state6.h; let mut h_copy7 = state7.h; // Do the final parallel compression step. let compress8_fn = default_compress_impl().1; unsafe { compress8_fn( &mut h_copy0, &mut h_copy1, &mut h_copy2, &mut h_copy3, &mut h_copy4, &mut h_copy5, &mut h_copy6, &mut h_copy7, &state0.buf, &state1.buf, &state2.buf, &state3.buf, &state4.buf, &state5.buf, &state6.buf, &state7.buf, state0.count, state1.count, state2.count, state3.count, state4.count, state5.count, state6.count, state7.count, !0, !0, !0, !0, !0, !0, !0, !0, last_node0, last_node1, last_node2, last_node3, last_node4, last_node5, last_node6, last_node7, ); } // Extract the resulting hashes. [ Hash { bytes: state_words_to_bytes(&h_copy0), len: state0.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy1), len: state1.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy2), len: state2.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy3), len: state3.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy4), len: state4.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy5), len: state5.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy6), len: state6.hash_length, }, Hash { bytes: state_words_to_bytes(&h_copy7), len: state7.hash_length, }, ] } pub fn hash4_exact( // TODO: Separate params for each input. params: &Params, input0: &[u8], input1: &[u8], input2: &[u8], input3: &[u8], ) -> [Hash; 4] { // These asserts are safety invariants for the AVX2 implementation. let len = input0.len(); let same_length = (input1.len() == len) && (input2.len() == len) && (input3.len() == len); let even_length = len % BLOCKBYTES == 0; let nonempty = len != 0; assert!( same_length && even_length && nonempty, "invalid hash8_exact inputs" ); let hash4_exact_fn = default_compress_impl().3; unsafe { hash4_exact_fn(params, input0, input1, input2, input3) } } pub fn hash8_exact( // TODO: Separate params for each input. params: &Params, input0: &[u8], input1: &[u8], input2: &[u8], input3: &[u8], input4: &[u8], input5: &[u8], input6: &[u8], input7: &[u8], ) -> [Hash; 8] { // These asserts are safety invariants for the AVX2 implementation. let len = input0.len(); let same_length = (input1.len() == len) && (input2.len() == len) && (input3.len() == len) && (input4.len() == len) && (input5.len() == len) && (input6.len() == len) && (input7.len() == len); let even_length = len % BLOCKBYTES == 0; let nonempty = len != 0; assert!( same_length && even_length && nonempty, "invalid hash8_exact inputs" ); let hash8_exact_fn = default_compress_impl().2; unsafe { hash8_exact_fn( params, input0, input1, input2, input3, input4, input5, input6, input7, ) } } pub fn hash8( params0: &Params, params1: &Params, params2: &Params, params3: &Params, params4: &Params, params5: &Params, params6: &Params, params7: &Params, input0: &[u8], input1: &[u8], input2: &[u8], input3: &[u8], input4: &[u8], input5: &[u8], input6: &[u8], input7: &[u8], ) -> [Hash; 8] { // Keying isn't supported yet. assert_eq!(0, params0.key_length); assert_eq!(0, params1.key_length); assert_eq!(0, params2.key_length); assert_eq!(0, params3.key_length); assert_eq!(0, params4.key_length); assert_eq!(0, params5.key_length); assert_eq!(0, params6.key_length); assert_eq!(0, params7.key_length); let fns = default_compress_impl(); let compress_fn = fns.0; let vectorize8_fn = fns.4; let compress8_vectorized_fn = fns.5; let mut state_words8 = [ AlignedWords8(params0.make_words()), AlignedWords8(params1.make_words()), AlignedWords8(params2.make_words()), AlignedWords8(params3.make_words()), AlignedWords8(params4.make_words()), AlignedWords8(params5.make_words()), AlignedWords8(params6.make_words()), AlignedWords8(params7.make_words()), ]; unsafe { vectorize8_fn(&mut state_words8); } let mut count = 0; loop { let update_all = input0.len() - count > BLOCKBYTES && input1.len() - count > BLOCKBYTES && input2.len() - count > BLOCKBYTES && input3.len() - count > BLOCKBYTES && input4.len() - count > BLOCKBYTES && input5.len() - count > BLOCKBYTES && input6.len() - count > BLOCKBYTES && input7.len() - count > BLOCKBYTES; let finalize_all = input0.len() - count == BLOCKBYTES && input1.len() - count == BLOCKBYTES && input2.len() - count == BLOCKBYTES && input3.len() - count == BLOCKBYTES && input4.len() - count == BLOCKBYTES && input5.len() - count == BLOCKBYTES && input6.len() - count == BLOCKBYTES && input7.len() - count == BLOCKBYTES; if !update_all && !finalize_all { // If all the inputs can't be compressed in tandem, break out of // the efficient loop and split the states apart. break; } let block0 = array_ref!(input0, count, BLOCKBYTES); let block1 = array_ref!(input1, count, BLOCKBYTES); let block2 = array_ref!(input2, count, BLOCKBYTES); let block3 = array_ref!(input3, count, BLOCKBYTES); let block4 = array_ref!(input4, count, BLOCKBYTES); let block5 = array_ref!(input5, count, BLOCKBYTES); let block6 = array_ref!(input6, count, BLOCKBYTES); let block7 = array_ref!(input7, count, BLOCKBYTES); count += BLOCKBYTES; let count_low = count as u32; let count_high = ((count as u64) >> 32) as u32; let lastblock; let lastnode; if finalize_all { lastblock = AlignedWords8([!0; 8]); lastnode = AlignedWords8([ if params0.last_node { !0 } else { 0 }, if params1.last_node { !0 } else { 0 }, if params2.last_node { !0 } else { 0 }, if params3.last_node { !0 } else { 0 }, if params4.last_node { !0 } else { 0 }, if params5.last_node { !0 } else { 0 }, if params6.last_node { !0 } else { 0 }, if params7.last_node { !0 } else { 0 }, ]); } else { lastblock = AlignedWords8([0; 8]); lastnode = AlignedWords8([0; 8]); } unsafe { compress8_vectorized_fn( &mut state_words8, block0, block1, block2, block3, block4, block5, block6, block7, &AlignedWords8([count_low; 8]), &AlignedWords8([count_high; 8]), &lastblock, &lastnode, ); } if finalize_all { unsafe { vectorize8_fn(&mut state_words8); } return [ Hash { bytes: state_words_to_bytes(&state_words8[0]), len: params0.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[1]), len: params1.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[2]), len: params2.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[3]), len: params3.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[4]), len: params4.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[5]), len: params5.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[6]), len: params6.hash_length, }, Hash { bytes: state_words_to_bytes(&state_words8[7]), len: params7.hash_length, }, ]; } } // Unvectorize the state. Note that vectorize is its own inverse. In the // SIMD implementation it's a matrix transposition, and in the portable // implementation it's actually a no-op. unsafe { vectorize8_fn(&mut state_words8); } // Individually finish each input. let finish = |params: &Params, words: &StateWords, input: &[u8]| -> Hash { let mut state = State { h: *words, buf: [0; BLOCKBYTES], buflen: 0, count: count as u64, compress_fn: compress_fn, last_node: params.last_node, hash_length: params.hash_length, }; state.update(&input[count..]); state.finalize() }; [ finish(params0, &state_words8[0], input0), finish(params1, &state_words8[1], input1), finish(params2, &state_words8[2], input2), finish(params3, &state_words8[3], input3), finish(params4, &state_words8[4], input4), finish(params5, &state_words8[5], input5), finish(params6, &state_words8[6], input6), finish(params7, &state_words8[7], input7), ] } // Safety: The unsafe blocks above rely on this function to never return avx2::compress except on // platforms where it's safe to call. #[allow(unreachable_code)] fn default_compress_impl() -> ( CompressFn, Compress8Fn, Hash8ExactFn, Hash4ExactFn, Vectorize8Fn, Compress8VectorizedFn, ) { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { #[cfg(feature = "std")] { if is_x86_feature_detected!("avx2") { return ( sse41::compress, avx2::compress8, avx2::hash8_exact, sse41::hash4_exact, avx2::vectorize_words8, avx2::compress8_vectorized, ); } } } // On other platforms (non-x86 or pre-AVX2) use the portable implementation. ( portable::compress, portable::compress8, portable::hash8_exact, portable::hash4_exact, portable::vectorize_words8, portable::compress8_vectorized, ) } // This module is pub for internal benchmarks only. Please don't use it. #[doc(hidden)] pub mod benchmarks { pub use crate::portable::compress as compress_portable; pub use crate::portable::compress8 as compress8_portable; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use crate::sse41::compress as compress_sse41; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use crate::sse41::compress4_transposed as compress4_transposed_sse41; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use crate::avx2::compress8 as compress8_avx2; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use crate::avx2::compress8_transposed_all as compress8_transposed_all_avx2; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use crate::avx2::compress8_vectorized as compress8_vectorized_avx2; // Safety: The portable implementation should be safe to call on any platform. pub fn force_portable(state: &mut crate::State) { state.compress_fn = compress_portable; } pub fn force_portable_blake2sp(state: &mut crate::blake2sp::State) { crate::blake2sp::force_portable(state); } }
31.617512
100
0.554817
df825717a793a41cdbb70f7f382d13dc67c1498c
240
cs
C#
src/HttpMessage/Models/Schemas/ExtractedWord.cs
bbSkygazer/IotWebServer
9040f346e9992116fb4678da54ceb077b1680f62
[ "MIT" ]
136
2015-07-28T06:28:17.000Z
2022-01-07T09:28:40.000Z
src/HttpMessage/Models/Schemas/ExtractedWord.cs
bbSkygazer/IotWebServer
9040f346e9992116fb4678da54ceb077b1680f62
[ "MIT" ]
135
2015-08-17T08:11:32.000Z
2020-07-30T16:01:07.000Z
src/HttpMessage/Models/Schemas/ExtractedWord.cs
bbSkygazer/IotWebServer
9040f346e9992116fb4678da54ceb077b1680f62
[ "MIT" ]
66
2015-07-29T09:57:48.000Z
2020-10-26T22:14:05.000Z
namespace Restup.HttpMessage.Models.Schemas { internal struct ExtractedWord { public string Word { get; set; } public byte[] RemainingBytes { get; set; } public bool WordFound { get; set; } } }
24
51
0.595833
f1c196f9b4f584095ee1ff8705d64257700f94c1
104
rb
Ruby
lib/lab42/open_object/hash_like.rb
RobertDober/lab42_open_object
ad413e46b6b6de5151687ee47babfe41246c81a3
[ "Apache-2.0" ]
null
null
null
lib/lab42/open_object/hash_like.rb
RobertDober/lab42_open_object
ad413e46b6b6de5151687ee47babfe41246c81a3
[ "Apache-2.0" ]
null
null
null
lib/lab42/open_object/hash_like.rb
RobertDober/lab42_open_object
ad413e46b6b6de5151687ee47babfe41246c81a3
[ "Apache-2.0" ]
null
null
null
module Lab42::OpenObject::HashLike def merge with self.class.new to_hash.merge(with) end end
14.857143
38
0.721154
02b6fd676b8055976f0aff9d4ac0daf6de01459b
16,979
cpp
C++
DocCluster/src/DCController.cpp
McGill-DMaS/FIHC
6928f6fdf62f0e0de004623a8f956e4ca3b3afa1
[ "Apache-2.0" ]
null
null
null
DocCluster/src/DCController.cpp
McGill-DMaS/FIHC
6928f6fdf62f0e0de004623a8f956e4ca3b3afa1
[ "Apache-2.0" ]
null
null
null
DocCluster/src/DCController.cpp
McGill-DMaS/FIHC
6928f6fdf62f0e0de004623a8f956e4ca3b3afa1
[ "Apache-2.0" ]
null
null
null
// DCController.cpp: implementation of the CDCController class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #if !defined(DCCONTROLLER_H) #include "DCController.h" #endif #if !defined(DCKMEANSMGR_H) #include "DCKMeansMgr.h" #endif #if !defined(DCCLUTOMGR_H) #include "DCClutoMgr.h" #endif #if !defined(BFFILEHELPER_H) #include "BFFileHelper.h" #endif char runningChars [] = {'-', '\\', '|', '/'}; CDCDebug* debugObject = new CDCDebug(); ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDCController::CDCController() { } CDCController::~CDCController() { cleanup(); } BOOL CDCController::initialize(TDCAlgoMode algoMode) { if (!m_treeBuilder.initialize(&m_clusterMgr)) return FALSE; if (!m_evalMgr.initialize(algoMode, &m_docMgr, &m_clusterMgr)) return FALSE; if (!m_outputMgr.initialize(algoMode, &m_docMgr, &m_clusterMgr, &m_clusterMgr2)) return FALSE; return TRUE; } void CDCController::cleanup() { delete debugObject; debugObject = NULL; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- BOOL CDCController::runFreqItems(FLOAT globalSupport, FLOAT clusterSupport, int kClusters, LPCTSTR inputDir) { // Document Manager reads all the files CString docSetDirPath = inputDir; docSetDirPath += DC_DOCUMENTS_DIRECTORY; CString stopWordFilePath = inputDir; stopWordFilePath += DC_STOPWORDS_FILENAME; m_docMgr.setDocDirectory((LPCTSTR) docSetDirPath); m_docMgr.setStopWordFile(DC_STOPWORDS_FILENAME); m_docMgr.setMinSupport(globalSupport); m_docMgr.preProcess(); CDCDocuments* pAllDocs = NULL; m_docMgr.getAllDocs(pAllDocs); ASSERT(pAllDocs); CDCFreqItemsets * pF1 = NULL; m_docMgr.getF1Sets(pF1); ASSERT(pF1); DEBUGPrint(_T("********\n")); DEBUGPrint(_T("* FIHC *\n")); DEBUGPrint(_T("********\n")); CDCDebug::printTime(); // Frequent Item Manager mines the frequent itemset (Apriori) m_freqItemMgr.setMinGlobalSupport(globalSupport); if (!m_freqItemMgr.mineGlobalFreqItemsets(pAllDocs, pF1)) { ASSERT(FALSE); return FALSE; } CDCFreqItemsets* pGlobalFreqItemsets = NULL; m_freqItemMgr.getGlobalFreqItemsets(pGlobalFreqItemsets); ASSERT(pGlobalFreqItemsets); #ifdef _DEBUG_PRT_INFO DEBUGPrint("Global frequent itemsets\n"); debugObject->printFreqItemsets(*pGlobalFreqItemsets); #endif // Cluster Manager builds the clusters of documents CDCDebug::printTime(); if (TRUE) { // tree based clustering if (!m_clusterMgr.makeClusters(pAllDocs, pGlobalFreqItemsets, clusterSupport)) { ASSERT(FALSE); return FALSE; } } else { // linear clustering m_clusterMgr2.setAllDocs(pAllDocs); m_clusterMgr2.setClusterSupport(clusterSupport); TDCClusterOrderType orderType = ORDER_TYPE_GLOBAL_SUP; BOOL descOrAsc = TRUE; if(!m_clusterMgr2.produceClusters(pGlobalFreqItemsets, orderType, descOrAsc)) { ASSERT(FALSE); return FALSE; } } // Tree Builder constructs the topical tree CDCDebug::printTime(); if (!m_treeBuilder.buildTree()) { ASSERT(FALSE); return FALSE; } // Remove empty clusters CDCDebug::printTime(); if (!m_treeBuilder.removeEmptyClusters(FALSE)) { ASSERT(FALSE); return FALSE; } /* // Pruning clusters from tree if (!m_treeBuilder.pruneTree()) { ASSERT(FALSE); return FALSE; } */ if (TRUE) { // prune children based on inter-cluster similarity with parent if (!m_treeBuilder.pruneChildren()) { ASSERT(FALSE); return FALSE; } /* // Remove empty clusters if (!m_treeBuilder.removeEmptyClusters(TRUE)) { ASSERT(FALSE); return FALSE; } */ // inter-cluster similarity based pruning if (!m_treeBuilder.interSimPrune(kClusters)) { ASSERT(FALSE); return FALSE; } /* // similarity based pruning if (!m_treeBuilder.simBasedPrune(kClusters)) { ASSERT(FALSE); return FALSE; } */ // score based pruning if (!m_treeBuilder.interSimOverPrune(kClusters)) { ASSERT(FALSE); return FALSE; } } else { // score based pruning if (!m_treeBuilder.interSimOverPrune(kClusters)) { ASSERT(FALSE); return FALSE; } } // Evaluate clusters using overall similairty CDCDebug::printTime(); CDCClusterWH* pClusterWH = NULL; m_clusterMgr.getClusterWH(pClusterWH); CDCCluster* pRoot = NULL; if (!pClusterWH->getTreeRoot(pRoot)) { ASSERT(FALSE); return FALSE; } // Evaluate clusters using FMeasure FLOAT fMeasure = 0.0f; if (!m_evalMgr.evalFMeasure(pRoot, fMeasure)) { ASSERT(FALSE); return FALSE; } DEBUGPrint(_T("F-Measure = %f\n"), fMeasure); // Evaluate overall similarity FLOAT overallSim = 0.0f; if (!m_evalMgr.evalOverallSimilarity(pRoot, overallSim)) { ASSERT(FALSE); return FALSE; } //DEBUGPrint(_T("Overall similarity = %f\n"), overallSim); // Evaluate clusters using entropy FLOAT entropyH = 0.0f; if (!m_evalMgr.evalEntropyHierarchical(pRoot, entropyH)) { ASSERT(FALSE); return FALSE; } //DEBUGPrint(_T("Entropy (Hierarchical) = %f\n"), entropyH); FLOAT entropyF = 0.0f; if (!m_evalMgr.evalEntropyFlat(pRoot, entropyF)) { ASSERT(FALSE); return FALSE; } DEBUGPrint(_T("Entropy (Flat) = %f\n"), entropyF); // Output Manager organizes and displays the results to user CString inputDirStr = inputDir; CString prefixStr; int slashPos = inputDirStr.ReverseFind(TCHAR('\\')); if (slashPos == -1) prefixStr = DC_XML_FREQITEM_FILENAME; else prefixStr = inputDirStr.Mid(slashPos + 1); CString outFilePath = makeOutFilePath(_T(".."), (LPCTSTR) prefixStr, globalSupport, clusterSupport, kClusters, fMeasure, entropyF); if (!m_outputMgr.produceOutput((LPCTSTR) outFilePath, fMeasure, overallSim, entropyH, entropyF)) { ASSERT(FALSE); return FALSE; } DEBUGPrint(_T("Output file: %s\n"), outFilePath); CDCDebug::printTime(); return TRUE; } //--------------------------------------------------------------------------- // Run the K-Means algorithm //--------------------------------------------------------------------------- BOOL CDCController::runKMeans(int kClusters, LPCTSTR inputDir) { // Document Manager reads all the files CString docSetDirPath = inputDir; docSetDirPath += DC_DOCUMENTS_DIRECTORY; CString stopWordFilePath = inputDir; stopWordFilePath += DC_STOPWORDS_FILENAME; m_docMgr.setDocDirectory((LPCTSTR) docSetDirPath); m_docMgr.setStopWordFile(DC_STOPWORDS_FILENAME); m_docMgr.setMinSupport(0.0f); m_docMgr.preProcess(); CDCDocuments* pAllDocs = NULL; m_docMgr.getAllDocs(pAllDocs); ASSERT(pAllDocs); #ifdef DC_DOCVECTOR_CONVERTOR if (!writeVectorsFile(pAllDocs)) { ASSERT(FALSE); return FALSE; } return TRUE; #endif // Run the K-Means algorithm DEBUGPrint("***********\n"); DEBUGPrint("* K-Means *\n"); DEBUGPrint("***********\n"); CDCDebug::printTime(); CDCKMeansMgr kMeansMgr; if (!kMeansMgr.makeClusters(kClusters, pAllDocs)) { ASSERT(FALSE); return FALSE; } CDCDebug::printTime(); CDCCluster* pRoot = NULL; kMeansMgr.getRoot(pRoot); CDCClusters* pChildren = NULL; pRoot->getTreeChildren(pChildren); // Evaluate clusters using FMeasure FLOAT fMeasure = 0.0f; if (!m_evalMgr.evalFMeasure(pRoot, fMeasure)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("F-Measure = %f\n"), fMeasure); // Evaluate clusters using overall similairty FLOAT overallSim = 0.0f; if (!m_evalMgr.evalOverallSimilarity(pRoot, overallSim)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } //DEBUGPrint(_T("Overall similarity = %f\n"), overallSim); // Evaluate clusters using entropy FLOAT entropyH = 0.0f; if (!m_evalMgr.evalEntropyHierarchical(pRoot, entropyH)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("Entropy (Hierarchical) = %f\n"), entropyH); FLOAT entropyF = 0.0f; if (!m_evalMgr.evalEntropyFlat(pRoot, entropyF)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("Entropy (Flat) = %f\n"), entropyF); // Output Manager organizes and displays the results to user CString inputDirStr = inputDir; CString prefixStr = DC_XML_KMEANS_FILENAME; int slashPos = inputDirStr.ReverseFind(TCHAR('\\')); if (slashPos != -1) prefixStr += inputDirStr.Mid(slashPos + 1); CString outFilePath = makeOutFilePath(_T(".."), (LPCTSTR) prefixStr, 0.0f, 0.0f, kClusters, fMeasure, entropyF); if (!m_outputMgr.produceOutput((LPCTSTR) outFilePath, pRoot, fMeasure, overallSim, entropyH, entropyF)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("Output file: %s\n"), outFilePath); CDCDebug::printTime(); pChildren->cleanup(); return TRUE; } //--------------------------------------------------------------------------- // Run the Cluto evaluator //--------------------------------------------------------------------------- BOOL CDCController::runCluto(LPCTSTR solFile, LPCTSTR classFile) { DEBUGPrint("*******************\n"); DEBUGPrint("* Cluto Evaluator *\n"); DEBUGPrint("*******************\n"); CDCClutoMgr clutoMgr; if (!clutoMgr.makeClusters(solFile, classFile)) { ASSERT(FALSE); return FALSE; } CDCCluster* pRoot = NULL; clutoMgr.getRoot(pRoot); CDCClusters* pChildren = NULL; pRoot->getTreeChildren(pChildren); // Evaluate clusters using FMeasure FLOAT fMeasure = 0.0f; if (!m_evalMgr.evalFMeasure(pRoot, fMeasure)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("F-Measure = %f\n"), fMeasure); // Evaluate clusters using overall similairty FLOAT overallSim = 0.0f; if (!m_evalMgr.evalOverallSimilarity(pRoot, overallSim)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } //DEBUGPrint(_T("Overall similarity = %f\n"), overallSim); // Evaluate clusters using entropy FLOAT entropyH = 0.0f; if (!m_evalMgr.evalEntropyHierarchical(pRoot, entropyH)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("Entropy (Hierarchical) = %f\n"), entropyH); FLOAT entropyF = 0.0f; if (!m_evalMgr.evalEntropyFlat(pRoot, entropyF)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("Entropy (Flat) = %f\n"), entropyF); // get number of clusters CString drive, dir, fname, ext; CBFFileHelper::splitPath(solFile, drive, dir, fname, ext); ext = ext.Mid(1); int kClusters = StrToInt((LPCTSTR) ext); // Output Manager organizes and displays the results to user CString outFilePath = makeOutFilePath(drive + dir, DC_XML_CLUTO_FILENAME, 0.0f, 0.0f, kClusters, fMeasure, entropyF); if (!m_outputMgr.produceOutput((LPCTSTR) outFilePath, pRoot, fMeasure, overallSim, entropyH, entropyF)) { ASSERT(FALSE); pChildren->cleanup(); return FALSE; } DEBUGPrint(_T("Output file: %s\n"), outFilePath); pChildren->cleanup(); return TRUE; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- CString CDCController::makeOutFilePath(LPCTSTR dir, LPCTSTR fileNamePrefix, FLOAT globalSupport, FLOAT clusterSupport, int kClusters, FLOAT fm, FLOAT entropyF) { time_t ltime; time(&ltime); CString outFilePath = dir; if (outFilePath.Right(1) != _T("\\") && outFilePath.Right(1) != _T("/")) outFilePath += _T("\\"); outFilePath += fileNamePrefix; CString gsStr; int gsSupport = (int) (globalSupport * 100.5f); if (gsSupport >= 100) gsStr.Format(_T("%d"), gsSupport); else if (gsSupport >= 10) gsStr.Format(_T("0%d"), gsSupport); else gsStr.Format(_T("00%d"), gsSupport); gsStr = gsStr.Left(3); CString csStr; int csSupport = (int) (clusterSupport * 100.5f); if (csSupport >= 100) csStr.Format(_T("%d"), csSupport); else if (csSupport >= 10) csStr.Format(_T("0%d"), csSupport); else csStr.Format(_T("00%d"), csSupport); csStr = csStr.Left(3); CString kcStr; if (kClusters >= 100) kcStr.Format(_T("%d"), kClusters); else if (kClusters >= 10) kcStr.Format(_T("0%d"), kClusters); else kcStr.Format(_T("00%d"), kClusters); kcStr = kcStr.Left(3); CString fmStr; fmStr.Format(_T("_%f"), fm); CString entropyFStr; entropyFStr.Format(_T("_%f"), entropyF); CString timeStr; timeStr.Format(_T("_%ld"), ltime); outFilePath += gsStr + csStr + kcStr + fmStr + entropyFStr + DC_XML_EXT; return outFilePath; } //--------------------------------------------------------------------------- // Write vectors to the file //--------------------------------------------------------------------------- BOOL CDCController::writeVectorsFile(CDCDocuments* pAllDocs) { int nDocs = pAllDocs->GetSize(); if (nDocs == 0) return TRUE; CString vectorFileName = _T("vectors.mat"); CString classFileName = _T("vectors.mat.rclass"); CString labelFileName = _T("vectors.mat.clabel"); CStdioFile vectorFile, classFile, labelFile; if (!vectorFile.Open(vectorFileName, CFile::modeCreate | CFile::modeWrite)) { ASSERT(FALSE); return FALSE; } if (!classFile.Open(classFileName, CFile::modeCreate | CFile::modeWrite)) { ASSERT(FALSE); vectorFile.Close(); return FALSE; } // get number of nonzero entries int nonZeroEntry = 0; CDCDocument* pDoc = NULL; CDCDocVector* pDocVector = NULL; for (int i = 0; i < nDocs; ++i) { DEBUGPrint(_T("%d\r"), i); pDoc = pAllDocs->GetAt(i); pDoc->getDocVector(pDocVector); int vectorSize = pDocVector->GetSize(); for (int v = 0; v < vectorSize; ++v) { if ((*pDocVector)[v] > 0) { ++nonZeroEntry; } } } // # of docs, # of distinct words, # of nonzero entries CString outStr; ((CDCDocument*) pAllDocs->GetAt(0))->getDocVector(pDocVector); int vectorSize = pDocVector->GetSize(); outStr.Format(_T("%d %d %d\n"), nDocs, vectorSize, nonZeroEntry); vectorFile.WriteString(outStr); for (i = 0; i < nDocs; ++i) { DEBUGPrint(_T("%d\r"), i); pDoc = pAllDocs->GetAt(i); pDoc->getDocVector(pDocVector); vectorSize = pDocVector->GetSize(); outStr.Empty(); for (int v = 0; v < vectorSize; ++v) { if ((*pDocVector)[v] > 0) { CString temp; temp.Format(_T(" %d %d"), v + 1, (*pDocVector)[v]); outStr += temp; } } vectorFile.WriteString(outStr + _T("\n")); classFile.WriteString(pDoc->getClassName() + _T("\n")); } classFile.Close(); vectorFile.Close(); // write label file if (!labelFile.Open(labelFileName, CFile::modeCreate | CFile::modeWrite)) { ASSERT(FALSE); return FALSE; } CString labelStr; for (int v = 0; v < vectorSize; ++v) { if (!m_docMgr.getFreqTermFromID(v, labelStr)) { ASSERT(FALSE); return FALSE; } labelFile.WriteString(labelStr + _T("\n")); } labelFile.Close(); return TRUE; }
30.428315
160
0.566464
c4e625a98b552cf6e92bf5fc7f2d46aed001c7a0
520
cpp
C++
source/ItemShotgun.cpp
fgrehm/pucrs-doom2d
edea7d5d762f427a5a8c944d36819009eb514429
[ "MIT" ]
1
2016-08-15T16:11:40.000Z
2016-08-15T16:11:40.000Z
source/ItemShotgun.cpp
fgrehm/pucrs-doom2d
edea7d5d762f427a5a8c944d36819009eb514429
[ "MIT" ]
null
null
null
source/ItemShotgun.cpp
fgrehm/pucrs-doom2d
edea7d5d762f427a5a8c944d36819009eb514429
[ "MIT" ]
null
null
null
#include "ItemShotgun.h" ItemShotgun::ItemShotgun(int _x, int _y): x(_x), y(_y) { sprite = new cgf::Sprite(); sprite->load("data/img/shotgun.png"); sprite->scale(1.2, 1.2); sf::Vector2f vpos = sf::Vector2f(); vpos.x = x; vpos.y = y; sprite->setPosition(vpos); } ItemShotgun::~ItemShotgun(){ if (sprite){ delete sprite; } } void ItemShotgun::visit(Inventory *iv) { iv->addShotgun(); } void ItemShotgun::draw(cgf::Game* game){ game->getScreen()->draw(*sprite); }
16.25
41
0.6
f75d69dc23ef389fd961186177cc173f3e87d50d
24
rb
Ruby
maps/gsiv/string_procs/wayto/25390_25391.rb
elanthia-online/cartograph
d496f275be828b4227d62ccfd409b64021a88fc7
[ "MIT" ]
3
2020-12-15T15:09:08.000Z
2021-08-21T18:50:28.000Z
maps/gsiv/string_procs/wayto/25390_25391.rb
elanthia-online/cartograph
d496f275be828b4227d62ccfd409b64021a88fc7
[ "MIT" ]
3
2020-10-11T15:33:29.000Z
2020-12-19T04:44:46.000Z
maps/gsiv/string_procs/wayto/25390_25391.rb
elanthia-online/cartograph
d496f275be828b4227d62ccfd409b64021a88fc7
[ "MIT" ]
null
null
null
fput 'stand' fput 'out'
12
12
0.666667
438851270daf4e9d4a626989f4de5d3db86710bb
4,952
cpp
C++
applications/shell/Eval.cpp
jfpowell/skift
2ebbfc82206c17c044cc49ae07633bad8eb9f984
[ "MIT" ]
null
null
null
applications/shell/Eval.cpp
jfpowell/skift
2ebbfc82206c17c044cc49ae07633bad8eb9f984
[ "MIT" ]
null
null
null
applications/shell/Eval.cpp
jfpowell/skift
2ebbfc82206c17c044cc49ae07633bad8eb9f984
[ "MIT" ]
null
null
null
#include <libsystem/Assert.h> #include <libsystem/Result.h> #include <libsystem/core/CString.h> #include <libsystem/io/File.h> #include <libsystem/io/Filesystem.h> #include <libsystem/io/Pipe.h> #include <libsystem/io/Stream.h> #include <libsystem/process/Launchpad.h> #include <libsystem/process/Process.h> #include "shell/Shell.h" static const char *PATH[] = { "/System/Binaries", "/System/Posix/bin", "/Applications", }; static bool find_command_path(char *buffer, const char *command) { if (command[0] == '/' || command[0] == '.') { snprintf(buffer, PATH_LENGTH, "%s", command); return file_exist(buffer); } else { snprintf(buffer, PATH_LENGTH, "/Applications/%s/%s", command, command); if (file_exist(buffer)) { return true; } for (size_t i = 0; i < __array_length(PATH); i++) { snprintf(buffer, PATH_LENGTH, "%s/%s", PATH[i], command); if (file_exist(buffer)) { return true; } } } return false; } Result shell_exec(ShellCommand *command, Stream *stdin, Stream *stdout, int *pid) { char executable[PATH_LENGTH]; if (!find_command_path(executable, command->command)) { *pid = -1; return ERR_NO_SUCH_FILE_OR_DIRECTORY; } Launchpad *launchpad = launchpad_create(command->command, executable); list_foreach(char, arg, command->arguments) { launchpad_argument(launchpad, arg); } launchpad_handle(launchpad, HANDLE(stdin), 0); launchpad_handle(launchpad, HANDLE(stdout), 1); Result result = launchpad_launch(launchpad, pid); if (result != SUCCESS) { printf("%s: Command not found! \e[90m%s\e[m\n", command->command, result_to_string(result)); } return result; } int shell_eval(ShellNode *node, Stream *stdin, Stream *stdout) { switch (node->type) { case SHELL_NODE_COMMAND: { ShellCommand *command = (ShellCommand *)node; ShellBuiltinCallback builtin = shell_get_builtin(command->command); if (builtin) { // list_count(command->arguments) + 1 for argv[0] which is the command name. char **argv = (char **)calloc(command->arguments->count() + 1, sizeof(argv)); argv[0] = command->command; int argc = 1; list_foreach(char, arg, command->arguments) { argv[argc] = arg; argc++; } int result = builtin(argc, (const char **)argv); free(argv); return result; } int pid; Result result = shell_exec(command, stdin, stdout, &pid); if (result == SUCCESS) { int command_result = -1; process_wait(pid, &command_result); return command_result; } } break; case SHELL_NODE_PIPELINE: { ShellPipeline *pipeline = (ShellPipeline *)node; List *pipes = list_create(); for (int i = 0; i < pipeline->commands->count() - 1; i++) { list_pushback(pipes, pipe_create()); } int *processes = (int *)calloc(pipeline->commands->count(), sizeof(int)); for (int i = 0; i < pipeline->commands->count(); i++) { ShellCommand *command = nullptr; list_peekat(pipeline->commands, i, (void **)&command); assert(command); Stream *command_stdin = stdin; Stream *command_stdout = stdout; if (i > 0) { Pipe *input_pipe; assert(list_peekat(pipes, i - 1, (void **)&input_pipe)); command_stdin = input_pipe->out; } if (i < pipeline->commands->count() - 1) { Pipe *output_pipe; assert(list_peekat(pipes, i, (void **)&output_pipe)); command_stdout = output_pipe->in; } shell_exec(command, command_stdin, command_stdout, &processes[i]); } list_destroy_with_callback(pipes, (ListDestroyElementCallback)pipe_destroy); for (int i = 0; i < pipeline->commands->count(); i++) { int exit_value; process_wait(processes[i], &exit_value); } free(processes); return 0; } break; case SHELL_NODE_REDIRECT: { ShellRedirect *redirect = (ShellRedirect *)node; __cleanup(stream_cleanup) Stream *stream = stream_open(redirect->destination, OPEN_WRITE | OPEN_CREATE); if (handle_has_error(stream)) { handle_printf_error(stream, "Failed to open '%s'", redirect->destination); return -1; } return shell_eval(redirect->command, stdin, stream); } break; default: break; } return -1; }
25.394872
112
0.557351
ff59b00d20c33151f9f2dd25610a80e8b73fe9b2
12,098
py
Python
lib/models/decode.py
shachargluska/centerpose
01c2c8bfa9d3ee91807f2ffdcc48728d104265bd
[ "MIT" ]
245
2019-11-29T02:55:25.000Z
2022-03-30T07:30:18.000Z
lib/models/decode.py
shachargluska/centerpose
01c2c8bfa9d3ee91807f2ffdcc48728d104265bd
[ "MIT" ]
24
2019-11-29T10:05:00.000Z
2022-03-30T07:16:06.000Z
lib/models/decode.py
FishLiuabc/centerpose
555d753cd82693476f91f78c53aa4147f5a83015
[ "MIT" ]
45
2019-11-29T05:12:02.000Z
2022-03-21T02:20:36.000Z
from __future__ import absolute_import, division, print_function import torch import torch.nn as nn import torch.nn.functional as F from .utils import _gather_feat, _transpose_and_gather_feat def _nms(heat, kernel=3): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep def _left_aggregate(heat): ''' heat: batchsize x channels x h x w ''' shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(1, heat.shape[0]): inds = (heat[i] >= heat[i - 1]) ret[i] += ret[i - 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape) def _right_aggregate(heat): ''' heat: batchsize x channels x h x w ''' shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(heat.shape[0] - 2, -1, -1): inds = (heat[i] >= heat[i +1]) ret[i] += ret[i + 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape) def _top_aggregate(heat): ''' heat: batchsize x channels x h x w ''' heat = heat.transpose(3, 2) shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(1, heat.shape[0]): inds = (heat[i] >= heat[i - 1]) ret[i] += ret[i - 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape).transpose(3, 2) def _bottom_aggregate(heat): ''' heat: batchsize x channels x h x w ''' heat = heat.transpose(3, 2) shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(heat.shape[0] - 2, -1, -1): inds = (heat[i] >= heat[i + 1]) ret[i] += ret[i + 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape).transpose(3, 2) def _h_aggregate(heat, aggr_weight=0.1): return aggr_weight * _left_aggregate(heat) + \ aggr_weight * _right_aggregate(heat) + heat def _v_aggregate(heat, aggr_weight=0.1): return aggr_weight * _top_aggregate(heat) + \ aggr_weight * _bottom_aggregate(heat) + heat def _topk_channel(scores, K=40): batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() return topk_scores, topk_inds, topk_ys, topk_xs def _topk(scores, K=40): batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), K) topk_clses = (topk_ind / K).int() topk_inds = _gather_feat( topk_inds.view(batch, -1, 1), topk_ind).view(batch, K) topk_ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K) topk_xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, K) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def ctdet_decode(heat, wh, reg=None, cat_spec_wh=False, K=100): batch, cat, height, width = heat.size() # heat = torch.sigmoid(heat) # perform nms on heatmaps heat = _nms(heat) scores, inds, clses, ys, xs = _topk(heat, K=K) if reg is not None: reg = _transpose_and_gather_feat(reg, inds) reg = reg.view(batch, K, 2) xs = xs.view(batch, K, 1) + reg[:, :, 0:1] ys = ys.view(batch, K, 1) + reg[:, :, 1:2] else: xs = xs.view(batch, K, 1) + 0.5 ys = ys.view(batch, K, 1) + 0.5 wh = _transpose_and_gather_feat(wh, inds) if cat_spec_wh: wh = wh.view(batch, K, cat, 2) clses_ind = clses.view(batch, K, 1, 1).expand(batch, K, 1, 2).long() wh = wh.gather(2, clses_ind).view(batch, K, 2) else: wh = wh.view(batch, K, 2) clses = clses.view(batch, K, 1).float() scores = scores.view(batch, K, 1) bboxes = torch.cat([xs - wh[..., 0:1] / 2, ys - wh[..., 1:2] / 2, xs + wh[..., 0:1] / 2, ys + wh[..., 1:2] / 2], dim=2) detections = torch.cat([bboxes, scores, clses], dim=2) return detections def whole_body_decode( heat, wh, kps, seg_feat=None, seg=None, reg=None, hm_hp=None, hp_offset=None, K=100): batch, cat, height, width = heat.size() num_joints = kps.shape[1] // 2 # perform nms on heatmaps heat = _nms(heat) scores, inds, clses, ys, xs = _topk(heat, K=K) kps = _transpose_and_gather_feat(kps, inds) kps = kps.view(batch, K, num_joints * 2) kps[..., ::2] += xs.view(batch, K, 1).expand(batch, K, num_joints) kps[..., 1::2] += ys.view(batch, K, 1).expand(batch, K, num_joints) if reg is not None: reg = _transpose_and_gather_feat(reg, inds) reg = reg.view(batch, K, 2) xs = xs.view(batch, K, 1) + reg[:, :, 0:1] ys = ys.view(batch, K, 1) + reg[:, :, 1:2] else: xs = xs.view(batch, K, 1) + 0.5 ys = ys.view(batch, K, 1) + 0.5 wh = _transpose_and_gather_feat(wh, inds) wh = wh.view(batch, K, 2) weight = _transpose_and_gather_feat(seg, inds) ## you can write (if weight.size(1)!=seg_feat.size(1): 3x3conv else 1x1conv ) here to select seg conv. ## for 3x3 weight = weight.view([weight.size(1), -1, 3, 3]) pred_seg = F.conv2d(seg_feat, weight, stride=1, padding=1) clses = clses.view(batch, K, 1).float() scores = scores.view(batch, K, 1) bboxes = torch.cat([xs - wh[..., 0:1] / 2, ys - wh[..., 1:2] / 2, xs + wh[..., 0:1] / 2, ys + wh[..., 1:2] / 2], dim=2) if hm_hp is not None: hm_hp = _nms(hm_hp) thresh = 0.1 kps = kps.view(batch, K, num_joints, 2).permute( 0, 2, 1, 3).contiguous() # b x J x K x 2 reg_kps = kps.unsqueeze(3).expand(batch, num_joints, K, K, 2) hm_score, hm_inds, hm_ys, hm_xs = _topk_channel(hm_hp, K=K) # b x J x K if hp_offset is not None: hp_offset = _transpose_and_gather_feat( hp_offset, hm_inds.view(batch, -1)) hp_offset = hp_offset.view(batch, num_joints, K, 2) hm_xs = hm_xs + hp_offset[:, :, :, 0] hm_ys = hm_ys + hp_offset[:, :, :, 1] else: hm_xs = hm_xs + 0.5 hm_ys = hm_ys + 0.5 mask = (hm_score > thresh).float() hm_score = (1 - mask) * -1 + mask * hm_score hm_ys = (1 - mask) * (-10000) + mask * hm_ys hm_xs = (1 - mask) * (-10000) + mask * hm_xs hm_kps = torch.stack([hm_xs, hm_ys], dim=-1).unsqueeze( 2).expand(batch, num_joints, K, K, 2) dist = (((reg_kps - hm_kps) ** 2).sum(dim=4) ** 0.5) min_dist, min_ind = dist.min(dim=3) # b x J x K hm_score = hm_score.gather(2, min_ind).unsqueeze(-1) # b x J x K x 1 min_dist = min_dist.unsqueeze(-1) min_ind = min_ind.view(batch, num_joints, K, 1, 1).expand( batch, num_joints, K, 1, 2) hm_kps = hm_kps.gather(3, min_ind) hm_kps = hm_kps.view(batch, num_joints, K, 2) l = bboxes[:, :, 0].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) t = bboxes[:, :, 1].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) r = bboxes[:, :, 2].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) b = bboxes[:, :, 3].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) mask = (hm_kps[..., 0:1] < l) + (hm_kps[..., 0:1] > r) + \ (hm_kps[..., 1:2] < t) + (hm_kps[..., 1:2] > b) + \ (hm_score < thresh) + (min_dist > (torch.max(b - t, r - l) * 0.3)) mask = (mask > 0).float().expand(batch, num_joints, K, 2) kps = (1 - mask) * hm_kps + mask * kps kps = kps.permute(0, 2, 1, 3).contiguous().view( batch, K, num_joints * 2) detections = torch.cat([bboxes, scores, kps, torch.transpose(hm_score.squeeze(dim=3), 1, 2)], dim=2) return detections, pred_seg def multi_pose_decode( heat, wh, kps, reg=None, hm_hp=None, hp_offset=None, K=100): batch, cat, height, width = heat.size() num_joints = kps.shape[1] // 2 # heat = torch.sigmoid(heat) # perform nms on heatmaps heat = _nms(heat) scores, inds, clses, ys, xs = _topk(heat, K=K) kps = _transpose_and_gather_feat(kps, inds) kps = kps.view(batch, K, num_joints * 2) kps[..., ::2] += xs.view(batch, K, 1).expand(batch, K, num_joints) kps[..., 1::2] += ys.view(batch, K, 1).expand(batch, K, num_joints) if reg is not None: reg = _transpose_and_gather_feat(reg, inds) reg = reg.view(batch, K, 2) xs = xs.view(batch, K, 1) + reg[:, :, 0:1] ys = ys.view(batch, K, 1) + reg[:, :, 1:2] else: xs = xs.view(batch, K, 1) + 0.5 ys = ys.view(batch, K, 1) + 0.5 wh = _transpose_and_gather_feat(wh, inds) wh = wh.view(batch, K, 2) clses = clses.view(batch, K, 1).float() scores = scores.view(batch, K, 1) bboxes = torch.cat([xs - wh[..., 0:1] / 2, ys - wh[..., 1:2] / 2, xs + wh[..., 0:1] / 2, ys + wh[..., 1:2] / 2], dim=2) if hm_hp is not None: hm_hp = _nms(hm_hp) thresh = 0.1 kps = kps.view(batch, K, num_joints, 2).permute( 0, 2, 1, 3).contiguous() # b x J x K x 2 reg_kps = kps.unsqueeze(3).expand(batch, num_joints, K, K, 2) hm_score, hm_inds, hm_ys, hm_xs = _topk_channel(hm_hp, K=K) # b x J x K if hp_offset is not None: hp_offset = _transpose_and_gather_feat( hp_offset, hm_inds.view(batch, -1)) hp_offset = hp_offset.view(batch, num_joints, K, 2) hm_xs = hm_xs + hp_offset[:, :, :, 0] hm_ys = hm_ys + hp_offset[:, :, :, 1] else: hm_xs = hm_xs + 0.5 hm_ys = hm_ys + 0.5 mask = (hm_score > thresh).float() hm_score = (1 - mask) * -1 + mask * hm_score hm_ys = (1 - mask) * (-10000) + mask * hm_ys hm_xs = (1 - mask) * (-10000) + mask * hm_xs hm_kps = torch.stack([hm_xs, hm_ys], dim=-1).unsqueeze( 2).expand(batch, num_joints, K, K, 2) dist = (((reg_kps - hm_kps) ** 2).sum(dim=4) ** 0.5) min_dist, min_ind = dist.min(dim=3) # b x J x K hm_score = hm_score.gather(2, min_ind).unsqueeze(-1) # b x J x K x 1 min_dist = min_dist.unsqueeze(-1) min_ind = min_ind.view(batch, num_joints, K, 1, 1).expand( batch, num_joints, K, 1, 2) hm_kps = hm_kps.gather(3, min_ind) hm_kps = hm_kps.view(batch, num_joints, K, 2) l = bboxes[:, :, 0].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) t = bboxes[:, :, 1].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) r = bboxes[:, :, 2].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) b = bboxes[:, :, 3].view(batch, 1, K, 1).expand(batch, num_joints, K, 1) mask = (hm_kps[..., 0:1] < l) + (hm_kps[..., 0:1] > r) + \ (hm_kps[..., 1:2] < t) + (hm_kps[..., 1:2] > b) + \ (hm_score < thresh) + (min_dist > (torch.max(b - t, r - l) * 0.3)) mask = (mask > 0).float().expand(batch, num_joints, K, 2) kps = (1 - mask) * hm_kps + mask * kps kps = kps.permute(0, 2, 1, 3).contiguous().view( batch, K, num_joints * 2) detections = torch.cat([bboxes, scores, kps, torch.transpose(hm_score.squeeze(dim=3), 1, 2)], dim=2) return detections
39.152104
108
0.54943
b52e414e01256ce1d8a15c85f50f7924731dffd9
1,633
lua
Lua
doc/examples/geterr.lua
julthomas/luasnmp
51a24968c8216e2bded70fcb7561adc668e71b55
[ "MIT" ]
6
2017-03-13T14:28:09.000Z
2022-01-25T21:19:12.000Z
doc/examples/geterr.lua
julthomas/luasnmp
51a24968c8216e2bded70fcb7561adc668e71b55
[ "MIT" ]
4
2020-08-27T12:28:07.000Z
2021-05-07T07:38:33.000Z
doc/examples/geterr.lua
julthomas/luasnmp
51a24968c8216e2bded70fcb7561adc668e71b55
[ "MIT" ]
9
2015-09-06T07:29:38.000Z
2021-04-18T19:55:36.000Z
require "snmp" local done = 2 function default_cb(vb, status, index, reqid, session, magic) if magic == "local" then print("Callback: REQUEST SPECIFIC") else print("Callback: SESSION DEFAULT") end print(string.format(" status='%s' index=%d reqid=%d magic='%s'", status or "nil", index or 0, reqid, magic or "nil")) if vb then print(string.format(" OID=%s type=%s value=%s", vb.oid, vb.type, vb.value)) end done = done - 1 session:close() end -- -- Trap callback function. -- local function trap_cb(vlist, ip, host, session) end -- -- Open session. -- hub1, err = snmp.open{ peer = "obelix", community = "private", trap = trap_cb, callback = default_cb, } assert(hub1, err) -- -- Clone a session -- hub2 = assert(snmp.open{peer = "10.0.0.1", trap = trap_cb, callback = default_cb}) -- -- Synchronous request -- local vlist, err, index = snmp.get(hub1, {"sysName.0","sysContact.0"}) if not err then print(string.format("Contact for %s : %s", vlist[1].value, vlist[2].value)) else if index then print(string.format("Error : %s in index %d", err, index)) else print(string.format("Error : %s", err)) end end -- -- Asynchronous request on hub1 -- reqid, err = snmp.asynch_get(hub1, "sysContact.0", default_cb, "local") assert(reqid, err) print(string.format("reqid = %d", reqid)) -- -- Asynchronous request on hub2 -- reqid, err = snmp.asynch_get(hub2, "sysName.0", nil, "default") assert(reqid, err) print(string.format("reqid = %d", reqid)) -- -- Loop for events and callback completion -- while done > 0 do snmp.event() end
20.4125
82
0.636252
23e6c74da972599836a440cfd6b123c2ece8c3eb
760
js
JavaScript
public/webviewer/lib/core/AzurePartRetriever.chunk.js
electrone901/education-connect-metis
f0b7998e01e07b46aa38662be380e465390ab2bf
[ "MIT" ]
6
2021-12-12T12:40:23.000Z
2022-01-12T02:33:32.000Z
public/webviewer/lib/core/AzurePartRetriever.chunk.js
electrone901/education-connect-metis
f0b7998e01e07b46aa38662be380e465390ab2bf
[ "MIT" ]
1
2022-03-12T18:09:57.000Z
2022-03-24T08:04:35.000Z
public/webviewer/lib/core/AzurePartRetriever.chunk.js
electrone901/education-connect-metis
f0b7998e01e07b46aa38662be380e465390ab2bf
[ "MIT" ]
1
2022-02-12T00:33:56.000Z
2022-02-12T00:33:56.000Z
/** Notice * This file contains works from many authors under various (but compatible) licenses. Please see core.txt for more information. **/ (function(){(window.wpCoreControlsBundle=window.wpCoreControlsBundle||[]).push([[5],{368:function(ha,ea,f){f.r(ea);var ba=f(2),z=f(124);ha=f(363);f=f(318);ha=function(f){function da(z,y,x,w){return f.call(this,z,y,x,w)||this}Object(ba.c)(da,f);da.prototype.zP=function(){return{start:this.SO-z.a,stop:this.SO}};da.prototype.Er=function(z){var y=this;this.Qm(this.url,{start:0,stop:1},function(x,w,e){if(x)return z(x);x=e.request.getResponseHeader("Content-Range");y.SO=x.split("/")[1];f.prototype.Er.call(y,z)})}; return da}(ha["default"]);Object(f.a)(ha);Object(f.b)(ha);ea["default"]=ha}}]);}).call(this || window)
190
513
0.698684
97f0c9af6fd2060f02cb307ed200d3cb80a2c3a6
4,119
dart
Dart
lib/constant/style.dart
Vellutia/currency_converter
aca104702bd41377a4f8c2c931e3492a213ed5f2
[ "Apache-2.0" ]
3
2020-03-26T12:01:16.000Z
2020-04-20T11:54:57.000Z
lib/constant/style.dart
Vellutia/Currency-Converter
aca104702bd41377a4f8c2c931e3492a213ed5f2
[ "Apache-2.0" ]
null
null
null
lib/constant/style.dart
Vellutia/Currency-Converter
aca104702bd41377a4f8c2c931e3492a213ed5f2
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/material.dart'; const Color primaryColor = Color(0xff2196f3); const Color accentColor = Color(0xfffafafa); const TextTheme primaryTextTheme = TextTheme( bodyText1: TextStyle( color: accentColor, ), bodyText2: TextStyle( color: accentColor, ), button: TextStyle( color: accentColor, ), caption: TextStyle( color: accentColor, ), headline1: TextStyle( color: accentColor, ), headline2: TextStyle( color: accentColor, ), headline3: TextStyle( color: accentColor, ), headline4: TextStyle( color: accentColor, ), headline5: TextStyle( color: accentColor, ), headline6: TextStyle( color: accentColor, ), subtitle1: TextStyle( color: accentColor, ), subtitle2: TextStyle( color: accentColor, ), ); const TextTheme accentTextTheme = TextTheme( bodyText1: TextStyle( color: primaryColor, ), bodyText2: TextStyle( color: primaryColor, ), button: TextStyle( color: primaryColor, ), caption: TextStyle( color: primaryColor, ), headline1: TextStyle( color: primaryColor, ), headline2: TextStyle( color: primaryColor, ), headline3: TextStyle( color: primaryColor, ), headline4: TextStyle( color: primaryColor, ), headline5: TextStyle( color: primaryColor, ), headline6: TextStyle( color: primaryColor, ), subtitle1: TextStyle( color: primaryColor, ), subtitle2: TextStyle( color: primaryColor, ), ); const AppBarTheme primaryAppBarTheme = AppBarTheme( color: primaryColor, actionsIconTheme: primaryIconTheme, iconTheme: primaryIconTheme, textTheme: accentTextTheme, ); const IconThemeData primaryIconTheme = IconThemeData( color: accentColor, ); const IconThemeData accentIconTheme = IconThemeData( color: primaryColor, ); const FloatingActionButtonThemeData floatingTheme = FloatingActionButtonThemeData( foregroundColor: accentColor, backgroundColor: primaryColor, ); const Color darkPrimaryColor = Color(0xff64ffda); const Color darkAccentColor = Color(0xff212121); const TextTheme darkPrimaryTextTheme = TextTheme( bodyText1: TextStyle( color: darkAccentColor, ), bodyText2: TextStyle( color: darkAccentColor, ), button: TextStyle( color: darkAccentColor, ), caption: TextStyle( color: darkAccentColor, ), headline1: TextStyle( color: darkAccentColor, ), headline2: TextStyle( color: darkAccentColor, ), headline3: TextStyle( color: darkAccentColor, ), headline4: TextStyle( color: darkAccentColor, ), headline5: TextStyle( color: darkAccentColor, ), headline6: TextStyle( color: darkAccentColor, ), subtitle1: TextStyle( color: darkAccentColor, ), subtitle2: TextStyle( color: darkAccentColor, ), ); const TextTheme darkAccentTextTheme = TextTheme( bodyText1: TextStyle( color: darkPrimaryColor, ), bodyText2: TextStyle( color: darkPrimaryColor, ), button: TextStyle( color: darkPrimaryColor, ), caption: TextStyle( color: darkPrimaryColor, ), headline1: TextStyle( color: darkPrimaryColor, ), headline2: TextStyle( color: darkPrimaryColor, ), headline3: TextStyle( color: darkPrimaryColor, ), headline4: TextStyle( color: darkPrimaryColor, ), headline5: TextStyle( color: darkPrimaryColor, ), headline6: TextStyle( color: darkPrimaryColor, ), subtitle1: TextStyle( color: darkPrimaryColor, ), subtitle2: TextStyle( color: darkPrimaryColor, ), ); const AppBarTheme darkPrimaryAppBarTheme = AppBarTheme( color: darkPrimaryColor, actionsIconTheme: darkPrimaryIconTheme, iconTheme: darkPrimaryIconTheme, textTheme: darkPrimaryTextTheme, ); const IconThemeData darkPrimaryIconTheme = IconThemeData( color: darkAccentColor, ); const IconThemeData darkAccentIconTheme = IconThemeData( color: darkPrimaryColor, ); const FloatingActionButtonThemeData darkFloatingTheme = FloatingActionButtonThemeData( foregroundColor: darkAccentColor, backgroundColor: darkPrimaryColor, );
19.995146
57
0.710124
33cf4121acd54e21e077732957affc5053903a6b
6,323
h
C
shared/include/crypto_api/cc_rnd_common.h
ARM-software/Cryptocell-713-TEE-Lib
bc0aca96f9769bba1a5927aa2bc6b82ceee94dea
[ "BSD-3-Clause" ]
2
2021-06-14T17:29:27.000Z
2021-07-04T00:13:39.000Z
shared/include/crypto_api/cc_rnd_common.h
QPC-database/Cryptocell-713-TEE-Lib
bc0aca96f9769bba1a5927aa2bc6b82ceee94dea
[ "BSD-3-Clause" ]
null
null
null
shared/include/crypto_api/cc_rnd_common.h
QPC-database/Cryptocell-713-TEE-Lib
bc0aca96f9769bba1a5927aa2bc6b82ceee94dea
[ "BSD-3-Clause" ]
5
2021-01-24T11:06:38.000Z
2021-07-04T00:13:40.000Z
/* * Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause OR Arm's non-OSI source license * */ /*! @file @brief This file contains the CryptoCell random-number generation APIs. The random-number generation module implements <em>NIST Special Publication 800-90A: Recommendation for Random Number Generation Using Deterministic Random Bit Generators.</em> */ /*! @addtogroup cc_rnd @{ */ #ifndef _CC_RND_COMMON_H #define _CC_RND_COMMON_H #include "cc_error.h" #include "cc_aes_defs.h" #include "cc_rnd_common_trng.h" #ifdef __cplusplus extern "C" { #endif /************************ Defines ******************************/ /* RND seed and additional input sizes */ /*! The maximal size of the random seed in words. */ #define CC_RND_SEED_MAX_SIZE_WORDS 12 #ifndef CC_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS /*! The maximal size of the additional input-data in words. */ #define CC_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS CC_RND_SEED_MAX_SIZE_WORDS #endif /* Maximal requested size counter (12 bits active) - maximal count of generated random 128 bit blocks allowed per one request of Generate function according NIST 800-90 it is (2^12 - 1) = 0x3FFFF */ /* Maximal size for one RNG generation (in bits) = max_num_of_bits_per_request = 2^19 (FIPS 800-90 Tab.3) */ /*! The maximal size of the generated vector in bits. */ #define CC_RND_MAX_GEN_VECTOR_SIZE_BITS 0x7FFFF /*! The maximal size of the generated random vector in Bytes. */ #define CC_RND_MAX_GEN_VECTOR_SIZE_BYTES 0xFFFF /*! The maximal size of the generated vector in Bytes. */ #define CC_RND_REQUESTED_SIZE_COUNTER 0x3FFFF /************************ Structs *****************************/ /*! @brief The structure for the RND state. This includes internal data that must be saved by the user between boots. */ typedef struct { /* Seed buffer, consists from concatenated Key||V: max size 12 words */ /*! The random-seed buffer. */ uint32_t Seed[CC_RND_SEED_MAX_SIZE_WORDS]; /* Previous value for continuous test */ /*! The previous random data, used for continuous test. */ uint32_t PreviousRandValue[CC_AES_CRYPTO_BLOCK_SIZE_IN_WORDS]; /*! The previous additional-input buffer. */ /* AdditionalInput buffer max size = seed max size words + 4w for padding*/ uint32_t PreviousAdditionalInput[CC_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS+3]; /*! The additional-input buffer. */ uint32_t AdditionalInput[CC_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS+4]; /*! The size of the additional input in words. */ uint32_t AddInputSizeWords; /*! The Reseed counter (32-bit active). Indicates the number of requests for entropy. since instantiation or reseeding. */ uint32_t ReseedCounter; /*! The key size according to security strength:<ul><li>128 bits: 4 words.</li><li>256 bits: 8 words.</li></ul> */ uint32_t KeySizeWords; /* State flag (see definition of StateFlag above), containing bit-fields, defining: - b'0: instantiation steps: 0 - not done, 1 - done; - 2b'9,8: working or testing mode: 0 - working, 1 - KAT DRBG test, 2 - KAT TRNG test; b'16: flag defining is Previous random valid or not: 0 - not valid, 1 - valid */ /*! The state flag used internally in the code. */ uint32_t StateFlag; /*! The validation tag used internally in the code. */ uint32_t ValidTag; CCTrngState_t trngState; /*!< TRNG state */ } CCRndState_t; /*! The RND vector-generation function pointer. */ typedef CCError_t (*CCRndGenerateVectWorkFunc_t)( \ void *rndState_ptr, /*!< A pointer to the RND-state context. */ \ unsigned char *out_ptr, /*!< A pointer to the output buffer. */ \ size_t outSizeBytes /*!< The size of the output in Bytes. */ ); /*****************************************************************************/ /********************** Public Functions *************************/ /*****************************************************************************/ /**********************************************************************************************************/ /*! @brief Generates a random vector with specific limitations by testing candidates (described and used in FIPS Publication 186-4: Digital Signature Standard (DSS): for example: B.1.2 or B.4.2). This function draws a random vector, compare it to the range limits, and if within range - return it in rndVect_ptr. If outside the range, the function continues retrying until a conforming vector is found, or the maximal retries limit is exceeded. If maxVect_ptr is provided, rndSizeInBits specifies its size, and the output vector must conform to the range [1 < rndVect < maxVect_ptr]. If maxVect_ptr is NULL, rndSizeInBits specifies the exact required vector size, and the output vector must be the exact same bit size (with its most significant bit = 1). \note The RND module must be instantiated prior to invocation of this API. @return \c CC_OK on success. @return A non-zero value from cc_rnd_error.h on failure. */ CIMPORT_C CCError_t CC_RndGenerateVectorInRange( CCRndGenerateVectWorkFunc_t f_rng, /*!< [in] Pointer to DRBG function*/ void *p_rng, /*!< [in/out] Pointer to the random context - the input to f_rng. */ size_t rndSizeInBits, /*!< [in] The size in bits of the random vector required. The allowed size in range 2 <= rndSizeInBits < 2^19-1, bits. */ uint8_t *maxVect_ptr, /*!< [in] Pointer to the vector defining the upper limit for the random vector output, Given as little-endian byte array. If not NULL, its actual size is treated as [(rndSizeInBits+7)/8] bytes. */ uint8_t *rndVect_ptr /*!< [in/out] Pointer to the output buffer for the random vector. Must be at least [(rndSizeInBits+7)/8] bytes. Treated as little-endian byte array. */ ); #ifdef __cplusplus } #endif /*! @} */ #endif /* #ifndef _CC_RND_COMMON_H */
42.153333
183
0.632769
da1416d05440a2c81459012c1fdb621fb93fd997
1,525
php
PHP
application/views/user/edit.php
cobblepotz/ci_sample
da66dc1abb891a57a36c6c11b0ff724a63da4cd5
[ "MIT" ]
null
null
null
application/views/user/edit.php
cobblepotz/ci_sample
da66dc1abb891a57a36c6c11b0ff724a63da4cd5
[ "MIT" ]
null
null
null
application/views/user/edit.php
cobblepotz/ci_sample
da66dc1abb891a57a36c6c11b0ff724a63da4cd5
[ "MIT" ]
null
null
null
<div class="row"> <div class="col-md-12"> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">User Edit</h3> </div> <?php echo form_open('user/edit/'.$user['id']); ?> <div class="box-body"> <div class="row clearfix"> <div class="col-md-6"> <label for="nama" class="control-label">Nama</label> <div class="form-group"> <input type="text" name="nama" value="<?php echo ($this->input->post('nama') ? $this->input->post('nama') : $user['nama']); ?>" class="form-control" id="nama" /> </div> </div> <div class="col-md-6"> <label for="pekerjaan" class="control-label">Pekerjaan</label> <div class="form-group"> <input type="text" name="pekerjaan" value="<?php echo ($this->input->post('pekerjaan') ? $this->input->post('pekerjaan') : $user['pekerjaan']); ?>" class="form-control" id="pekerjaan" /> </div> </div> <div class="col-md-6"> <label for="alamat" class="control-label">Alamat</label> <div class="form-group"> <textarea name="alamat" class="form-control" id="alamat"><?php echo ($this->input->post('alamat') ? $this->input->post('alamat') : $user['alamat']); ?></textarea> </div> </div> </div> </div> <div class="box-footer"> <button type="submit" class="btn btn-success"> <i class="fa fa-check"></i> Save </button> </div> <?php echo form_close(); ?> </div> </div> </div>
40.131579
193
0.549508
3897a05cd60d5015f59765cde5b7785154cd7220
943
php
PHP
vendor/docker-php/docker-php-api/src/Model/ContainersCreatePostBodyNetworkingConfig.php
linuxserver/heimdall-docker-manager
6b28d48a228c0605e41fea708032770cf3c9e9a7
[ "MIT" ]
5
2019-10-19T12:00:58.000Z
2022-01-13T07:50:47.000Z
vendor/docker-php/docker-php-api/src/Model/ContainersCreatePostBodyNetworkingConfig.php
linuxserver/heimdall-docker-manager
6b28d48a228c0605e41fea708032770cf3c9e9a7
[ "MIT" ]
1
2020-06-18T01:18:24.000Z
2020-06-18T01:18:24.000Z
vendor/docker-php/docker-php-api/src/Model/ContainersCreatePostBodyNetworkingConfig.php
linuxserver/heimdall-docker-manager
6b28d48a228c0605e41fea708032770cf3c9e9a7
[ "MIT" ]
1
2021-07-16T01:34:06.000Z
2021-07-16T01:34:06.000Z
<?php declare(strict_types=1); /* * This file has been auto generated by Jane, * * Do no edit it directly. */ namespace Docker\API\Model; class ContainersCreatePostBodyNetworkingConfig { /** * A mapping of network name to endpoint configuration for that network. * * @var EndpointSettings[] */ protected $endpointsConfig; /** * A mapping of network name to endpoint configuration for that network. * * @return EndpointSettings[] */ public function getEndpointsConfig(): ?\ArrayObject { return $this->endpointsConfig; } /** * A mapping of network name to endpoint configuration for that network. * * @param EndpointSettings[] $endpointsConfig * * @return self */ public function setEndpointsConfig(?\ArrayObject $endpointsConfig): self { $this->endpointsConfig = $endpointsConfig; return $this; } }
20.5
76
0.638388
96760f0db06332e35ffa5de8034fb8c48afe59cf
1,042
rb
Ruby
test/support/model.rb
fnando/formatted_attributes
b50d959ecabec84408f4acf2a75530affb9fe11d
[ "MIT" ]
1
2015-10-21T14:19:01.000Z
2015-10-21T14:19:01.000Z
test/support/model.rb
fnando/formatted_attributes
b50d959ecabec84408f4acf2a75530affb9fe11d
[ "MIT" ]
null
null
null
test/support/model.rb
fnando/formatted_attributes
b50d959ecabec84408f4acf2a75530affb9fe11d
[ "MIT" ]
null
null
null
# frozen_string_literal: true class Product < ActiveRecord::Base include ActionView::Helpers::NumberHelper include FormattedAttributes formatted :price, :shipping, with: :number_format validates_numericality_of :price, :shipping, only_integer: true # Receives a formatted value and converts it into an integer value. private def convert_with_number_format(number) number = BigDecimal(number.to_s) / 100 number_to_currency(number, unit: "", separator: ",", delimiter: "") end # Receives a integer value and converts into a formatted number string. private def convert_from_number_format(number) _, operator, number, precision = *number.to_s.match(/^([+-])?(\d+)(?:[,.](\d+))?$/) (BigDecimal("#{operator}#{number}.#{precision.to_i}") * 100).to_i end end class Post attr_accessor :text include FormattedAttributes formatted_attribute :text, with: :html def convert_with_html(text) %[<p>#{text}</p>] end def convert_from_html(text) text.to_s[%r{^<p>(.*?)</p>$}, 1] end end
26.717949
73
0.701536
455caa2f9bb99b93f487716d61aa12b12e031a40
2,092
py
Python
hathor/cli/openapi_json.py
mbnunes/hathor-core
e5e0d4a627341e2a37ee46db5c9354ddb7f8dfb8
[ "Apache-2.0" ]
51
2019-12-28T03:33:27.000Z
2022-03-10T14:03:03.000Z
hathor/cli/openapi_json.py
mbnunes/hathor-core
e5e0d4a627341e2a37ee46db5c9354ddb7f8dfb8
[ "Apache-2.0" ]
316
2019-09-10T09:20:05.000Z
2022-03-31T20:18:56.000Z
hathor/cli/openapi_json.py
jansegre/hathor-core
22b3de6be2518e7a0797edbf0e4f6eb1cf28d6fd
[ "Apache-2.0" ]
19
2020-01-04T00:13:18.000Z
2022-02-08T21:18:46.000Z
# Copyright 2021 Hathor Labs # # 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 json import os from typing import Any, Dict from hathor.cli.openapi_files.register import get_registered_resources BASE_PATH = os.path.join(os.path.dirname(__file__), 'openapi_files') DEFAULT_OUTPUT_PATH = os.path.join(BASE_PATH, 'openapi.json') def get_base() -> Dict[str, Any]: """ Returns the base configuration from OpenAPI json """ with open(os.path.join(BASE_PATH, 'openapi_base.json'), 'r') as f: return json.load(f) def get_components() -> Dict[str, Any]: """ Returns the components from OpenAPI json """ with open(os.path.join(BASE_PATH, 'openapi_components.json'), 'r') as f: return json.load(f) def get_openapi_dict() -> Dict[str, Any]: """ Returns the generated OpenAPI dict """ openapi = get_base() components = get_components() openapi['components'] = components['components'] for resource in get_registered_resources(): openapi['paths'].update(resource.openapi) return openapi def main(): import argparse from hathor.cli.util import create_parser parser = create_parser() parser.add_argument('--indent', type=int, default=None, help='Number of spaces to use for indentation') parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'), default=DEFAULT_OUTPUT_PATH, nargs='?', help='Output file where OpenSPI json will be written') args = parser.parse_args() openapi = get_openapi_dict() json.dump(openapi, args.out, indent=args.indent)
33.206349
117
0.708891
58a2fa796538d177b2df6a3d56271ab7f0684269
4,915
swift
Swift
iVaultTests/QRCode/MoneroUriParserTest.swift
scala-network/ScalaiVault
13d3acacf38e791abf942090bd5af0755d754b84
[ "MIT" ]
1
2021-08-04T12:08:33.000Z
2021-08-04T12:08:33.000Z
iVaultTests/QRCode/MoneroUriParserTest.swift
scala-network/iVault
13d3acacf38e791abf942090bd5af0755d754b84
[ "MIT" ]
null
null
null
iVaultTests/QRCode/MoneroUriParserTest.swift
scala-network/iVault
13d3acacf38e791abf942090bd5af0755d754b84
[ "MIT" ]
null
null
null
// // QRCScannerTest.swift // XWalletTests // // Created by loj on 10.06.18. // import XCTest import iVault class MoneroUriParserTest: XCTestCase { private var testee: MoneroUriParser! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. self.testee = MoneroUriParser() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } public func test_ValidateWalletAddressWithoutPrefix() { let uriWithoutPrefix = self.generateFullUri(withPrefix: false, walletAddress: validWalletAddress, paymentId: nil, amount: nil, description: nil) let result = self.testee.process(uriWithoutPrefix) // XCTAssertEqual(.ok, result.parseResult) XCTAssertEqual(validWalletAddress, result.payment.walletAddress) } public func test_ValidateWalletAddressWithPrefix() { let uriWithoutPrefix = self.generateFullUri(withPrefix: true, walletAddress: validWalletAddress, paymentId: nil, amount: nil, description: nil) let result = self.testee.process(uriWithoutPrefix) // XCTAssertEqual(.ok, result.parseResult) XCTAssertEqual(validWalletAddress, result.payment.walletAddress) } public func test_ValidateWalletAddressFormat() { let uriWithoutPrefix = self.generateFullUri(withPrefix: true, walletAddress: invalidWalletAddress, paymentId: nil, amount: nil, description: nil) let result = self.testee.process(uriWithoutPrefix) // XCTAssertEqual(.invalidWalletAddress, result.parseResult) XCTAssertNil(result.payment.walletAddress) } public func test_ValidatePaymentID() { let uriWithValidPaymentId = self.generateFullUri(withPrefix: true, walletAddress: validWalletAddress, paymentId: validPaymentId, amount: validAmount, description: validDescription) let resultForValidPaymentId = self.testee.process(uriWithValidPaymentId) // XCTAssertEqual(.ok, resultForValidPaymentId.parseResult) XCTAssertEqual(validPaymentId, resultForValidPaymentId.payment.paymentId) let uriWithInvalidPaymentId = self.generateFullUri(withPrefix: true, walletAddress: validWalletAddress, paymentId: invalidPaymentId, amount: validAmount, description: validDescription) let resultForInvalidPaymentId = self.testee.process(uriWithInvalidPaymentId) // XCTAssertEqual(.invalidPaymentId, resultForInvalidPaymentId.parseResult) XCTAssertNil(resultForInvalidPaymentId.payment.paymentId) } public func test_ValidateAmount() { } private func generateFullUri(withPrefix: Bool, walletAddress: String, paymentId: String?, amount: String?, description: String?) -> String { var parameters = [String]() var addressPart = "" if withPrefix { addressPart = "monero:\(walletAddress)" } else { addressPart = walletAddress } if let paymentId = paymentId { parameters.append("tx_payment_id=\(paymentId)") } if let amount = amount { parameters.append("tx_amount=\(amount)") } if let description = description { parameters.append("tx_description=\(description)") } return "\(addressPart)?\(parameters.joined(separator: "&"))" } private let validWalletAddress = "45J9JcnvugpQNQ34PyxtNANrtAkBe18rvd7kKPs7UsGqVmUGsgh5P1HX17D17d6Yyf8XRW9imLabq486M9264gA1PZd4G7f" private let validPaymentId = "657c5df1563fd943" private let validAmount = "22.08" private let validDescription = "validdescription" private let invalidWalletAddress = "45J9JcnvugpQNQ34PyxtNANrtAkBe18rvd7kKPs7UsGqVmUGsgh5P1HX17D17d6Yyf8XRW9imLabq486M9264gA" private let invalidPaymentId = "657c5df1563fd943X" private let invalidAmount = "22.08.2018" }
40.286885
134
0.58413
6b740582536776df33e8e8aeef6ab5317b875e04
7,342
js
JavaScript
client/src/Components/network/lessonPlans.js
IgniteSTEM/web-app
c1d38c79f5815236fb7b29848b50bfc78a84a861
[ "MIT" ]
null
null
null
client/src/Components/network/lessonPlans.js
IgniteSTEM/web-app
c1d38c79f5815236fb7b29848b50bfc78a84a861
[ "MIT" ]
null
null
null
client/src/Components/network/lessonPlans.js
IgniteSTEM/web-app
c1d38c79f5815236fb7b29848b50bfc78a84a861
[ "MIT" ]
null
null
null
export default [ { id: 1, title: "Game Theory: A Class on Strategy", subtitle: "This lesson will investigate game theory and its various principles and application in the real world.", author: "Project BEST ", description: "Game theory is a field (a branch of mathematics, logic, and psychology) that aims to discern certain principles in interactions. This lesson will investigate game theory and its various principles and application in the real world.", link: "https://lessons.hackinabox.tech/files/Game_Theory.pdf", image: "https://lessons.hackinabox.tech/img/gametheory.png", grade: "6-12", subject: "Math", }, { id: 2, title: "Illusions: Vision and Perception", subtitle: "Optical illusions can be used to help us understand the inner workings of perception", author: "Project BEST ", description: "Vision and perception are very complicated processes, and optical illusions can be used to help understand the inner workings of perception. In this lesson, students will engage with various optical illusions and dissect them to understand the fundamental happenings in each.", link: "https://lessons.hackinabox.tech/files/Illusions.pdf", image: "https://lessons.hackinabox.tech/img/illusionAndPerception.png", grade: "4-8", subject: "Math", }, { id: 3, title: "Popsicle Structures", subtitle: "Using the basics of architecture, students work together in small team to build the tallest structure", author: "Project BEST ", description: "Students will learn how to create sound structures with using the basics of architecture. Students work together in small team to build the tallest structure. Students should use triangles as well as cross beams and should draw out a basic plan before starting to build", link: "https://lessons.hackinabox.tech/files/Popsicle_Structures.pdf", image: "https://lessons.hackinabox.tech/img/popsicleStructures.png", grade: "6-12", subject: "Science", }, { id: 4, title: "Art in Public Spaces", subtitle: "Public art and the use of context and content", author: "Stanford Design for America Team", description: "The use of content and context in public art, getting students to view the ordinary with an artist’s eye", link: "https://lessons.hackinabox.tech/files/Art_Public.pdf", image: "https://lessons.hackinabox.tech/img/ArtinPublicSpaces.png", grade: "8-9", subject: "Art, Architecture, Social Studies, History", }, { id: 5, title: "Remix- Computer Science", subtitle: "A look into the use of remixing, an important concept in Computer Science. Fits into the hour of code. ", author: "Jennifer Latimer, Code.org Teacher of the Month", description: "This lesson provides students with an application of remixing, an important concept in computer science.", image: "https://lessons.hackinabox.tech/img/remix.png", grade: "5", subject: "CS - Hour of Code", }, { id: 6, title: "Rights Constructor ", subtitle: "Interactive activity with the Bill of Rights and its modern day implications", author: "Stanford Design for America Team", description: "This lesson teaches the bill of rights as well as the historical reasons and context behind it. It also covers the modern connotations of these amendments.", link: "https://lessons.hackinabox.tech/files/Rights_Constructor.pdf", image: "https://lessons.hackinabox.tech/img/rights.png", grade: "8-9", subject: "American History, Government, Constitutional Law", }, { id: 7, title: "Rube Goldberg Machine: How a Bill Becomes a Law", subtitle: "A fun, interactive visualization of how a bill becomes a law", author: "Stanford Design for America Team", description: "This lesson creates a fun, innovative environment for students to learn about the process of passing a bill. The abstract and creative thinking skills in their choice of material and mechanism help them tie facts and ideas to visuals.", link: "https://lessons.hackinabox.tech/files/Rude_Goldberg.pdf", grade: "8-9", subject: "American History, Government, Constitutional Law", }, { id: 8, title: "Shakespeare in Modern Day", subtitle: "A glimpse into Shakespeare's style and wordplay", author: "Stanford Design for America Team", description: "This lesson gives student both an increased retention and understanding of Shakespearean phrasing as well as an insight into the work of translators. Hopefully this plan will help students gain an appreciation for Shakespeare’s style and wordplay.", image: "https://lessons.hackinabox.tech/img/Shakespeare.png", grade: "8-9", subject: "English, Literature", }, { id: 9, title: "Understanding War: The Battle Plan", subtitle: "A reenactment of one of the most tumultuous, defining times in national history...enacted via water balloons!", description: "Stanford Design for America Team", link: "This lesson will help students gain an understanding of the most tumultuous, defining time in national history. It will focus on the geography and physicality of the American Revolution and its major battles, and also on the social dynamics of war — relationships between soldiers and generals, reporters and the public", grade: "8-9", subject: "American History, Government, Constitutional Law", }, { id: 10, title: "Ruby Says Robot Game", subtitle: "A basic challenge to get students thinking about simple instructions and sequences, or in coding terms, creating algorithms.", author: "Piper EDU", description: "This lesson is an intro to computational thinking, and students will create quick basic commands for real world problems then link them to coding concepts.", link: "https://docs.google.com/document/d/1dw6KJpZK79QFxwjAnmduvBzMUS8XwVo4k8BXSSJqtqw/edit#heading=h.w02bwl1lj1m", image: "https://cdn.shopify.com/s/files/1/0925/6256/t/54/assets/newkit-min.png?7946576747404267751", grade: "3-8,", subject: "CS", }, { id: 11, title: "Loops, Sequences, and Events, Oh My!", subtitle: "A dive into computational tinkering through the Piper Kit!", author: "Piper EDU", description: "The goal of this lesson is for students to refresh their learning of Piper hardware and electronic component and dive into computational tinkering! The first three projects challenge the students to practice keys electronic and programming skills, but extend understanding to solve problems by coding behaviors in the language of Piper Code including making lights blink, changing the sequence of the lights based on pivoting questions, and orchestrate cause and effect.", link: "https://docs.google.com/document/d/1dw6KJpZK79QFxwjAnmduvBzMUS8XwVo4k8BXSSJqtqw/edit#heading=h.95kdm12ecgob", image: "https://cdn.shopify.com/s/files/1/0925/6256/t/54/assets/newkit-min.png?7946576747404267751", grade: "3-8", subject: "CS", }, { id: 12, title: "Light and Sound Inventions", subtitle: "Adding on hardware and interactive functions ", author: "Piper EDU", description: "Students will build a random button controller for a custom made game with 4 different colored LED lights and a buzzer", link: "https://docs.google.com/document/d/1dw6KJpZK79QFxwjAnmduvBzMUS8XwVo4k8BXSSJqtqw/edit#heading=h.oyca6a37d1c1", image: "https://cdn.shopify.com/s/files/1/0925/6256/t/54/assets/newkit-min.png?7946576747404267751", grade: "3-8", subject: "CS", }, ];
56.476923
488
0.751703
da9d292dac27e498ace28fa17e420befeec102ff
1,744
php
PHP
src/Message/Entity/Text.php
guoyouworld/vbot
29128c3e467e8ec3977f8851290d7c2f3ba2eb81
[ "MIT" ]
3
2019-03-05T03:47:11.000Z
2019-09-27T07:16:42.000Z
src/Message/Entity/Text.php
guoyouworld/vbot
29128c3e467e8ec3977f8851290d7c2f3ba2eb81
[ "MIT" ]
null
null
null
src/Message/Entity/Text.php
guoyouworld/vbot
29128c3e467e8ec3977f8851290d7c2f3ba2eb81
[ "MIT" ]
2
2018-02-19T14:04:08.000Z
2022-03-22T14:35:10.000Z
<?php /** * Created by PhpStorm. * User: Hanson * Date: 2016/12/16 * Time: 18:33. */ namespace Hanson\Vbot\Message\Entity; use Hanson\Vbot\Message\MessageInterface; use Hanson\Vbot\Support\Console; class Text extends Message implements MessageInterface { public $isAt; public function __construct($msg) { parent::__construct($msg); $this->make(); } /** * 发送消息. * * @param $word string|Text 消息内容 * @param $username string 目标username * * @return bool */ public static function send($username, $word) { if (!$word || !$username) { return false; } $word = is_string($word) ? $word : $word->content; $random = strval(time() * 1000).'0'.strval(rand(100, 999)); $data = [ 'BaseRequest' => server()->baseRequest, 'Msg' => [ 'Type' => 1, 'Content' => $word, 'FromUserName' => myself()->username, 'ToUserName' => $username, 'LocalID' => $random, 'ClientMsgId' => $random, ], 'Scene' => 0, ]; $result = http()->post(server()->baseUri.'/webwxsendmsg?pass_ticket='.server()->passTicket, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), true ); if ($result['BaseResponse']['Ret'] != 0) { Console::log('发送消息失败 '.time(), Console::WARNING); return false; } return true; } public function make() { $this->content = $this->message; $this->isAt = str_contains($this->content, '@'.myself()->nickname); } }
23.253333
99
0.504587
cd0f43d39332f7d5fa2b22350124f6132f6bbbab
32,186
cs
C#
frm_Main.cs
xmikedanielsx/cSharp-Import-Delimited-Files
a38e6b9d6fb591abac5829859945c63f9d1c1090
[ "MIT" ]
null
null
null
frm_Main.cs
xmikedanielsx/cSharp-Import-Delimited-Files
a38e6b9d6fb591abac5829859945c63f9d1c1090
[ "MIT" ]
null
null
null
frm_Main.cs
xmikedanielsx/cSharp-Import-Delimited-Files
a38e6b9d6fb591abac5829859945c63f9d1c1090
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; using Microsoft.VisualBasic.FileIO; using System.Text.RegularExpressions; using System.Text.Json; namespace BulkImportDelimitedFlatFiles { public partial class frm_Main : Form { SqlConnection cnn = new SqlConnection(); int hasError = 0; FileInfo[] files; Dictionary<string, DataTable> filesToLoad = new Dictionary<string, DataTable>(); Dictionary<string, Dictionary<string, Dictionary<string,string>>> filesToLoadMapping = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); Boolean fileListLoaded = false; LocalConfig lconfig; public frm_Main() { InitializeComponent(); lbl_ExpandTopPanel.Visible = false; cmbox_delimiter.SelectedItem = "Tab"; txtbox_defaultDataLength.Text = "max"; dgv_FieldList.Enabled = false; this.setJsonObjectConfig(); btn_loadToSQL.Enabled = false; } private void setJsonObjectConfig() { var enviroment = System.Environment.CurrentDirectory; if (File.Exists(@"" + Directory.GetParent(enviroment).Parent.FullName.ToString().Replace(".dll", "") + @"\config.json")) { this.lconfig = JsonSerializer.Deserialize<LocalConfig>(File.ReadAllText(@"" + Directory.GetParent(enviroment).Parent.FullName.ToString().Replace(".dll", "") + @"\config.json")); } txtbox_FinalTableName.Text = this.lconfig.tableName.ToString(); txtbox_tablePrefix.Text = this.lconfig.tablePrefix.ToString(); } private void btn_testConnection_Click(object sender, EventArgs e) { string cnnString; string sqlServer; string sqlUser; string sqlPass; string sqlDatabase; // set sql variables sqlServer = txtbox_sqlServer.Text.ToString(); sqlUser = txtbox_sqlUser.Text.ToString(); sqlPass = txtbox_sqlPass.Text.ToString(); sqlDatabase = txtbox_sqlDatabase.Text.ToString(); if (chbox_windowsAuth.Checked == true) { if (txtbox_sqlServer.Text.ToString() == "" || txtbox_sqlDatabase.Text.ToString() == "") { MessageBox.Show("I am sorry, but you need to make sure you fill out ALL of the SQL Server Connection Info Boxes"); this.hasError = 1; return; } cnnString = "Data Source=" + sqlServer + ";Initial Catalog=\"" + sqlDatabase + "\";Integrated Security=true;"; } else { if (txtbox_sqlServer.Text.ToString() == "" || txtbox_sqlUser.Text.ToString() == "" || txtbox_sqlPass.Text.ToString() == "" || txtbox_sqlDatabase.Text.ToString() == "") { MessageBox.Show("I am sorry, but you need to make sure you fill out ALL of the SQL Server Connection Info Boxes"); this.hasError = 1; return; } cnnString = "Data Source=" + sqlServer + ";Initial Catalog=" + sqlDatabase + ";User ID=" + sqlUser + ";Password=" + sqlPass + ""; } if(this.cnn.State == ConnectionState.Open) { this.cnn.Close(); } this.cnn.ConnectionString = cnnString; lbl_testConnStatus.ForeColor = Color.Black; lbl_testConnStatus.Text = "Trying to Connect..."; try { this.cnn.Open(); lbl_testConnStatus.ForeColor = Color.Green; lbl_testConnStatus.Text = "Connection Successful"; this.cnn.Close(); } catch (Exception err) { lbl_testConnStatus.ForeColor = Color.Red; lbl_testConnStatus.Text = err.Message.ToString(); this.hasError = 1; return; } } private void btn_openFileDiag_Click(object sender, EventArgs e) { FolderBrowserDialog fd = new FolderBrowserDialog(); DialogResult dr = fd.ShowDialog(); if(dr == DialogResult.OK) { txtbox_pickUpPath.Text = fd.SelectedPath.ToString(); } } private void btn_loadFilesToList_Click(object sender, EventArgs e) { lv_fileList.Items.Clear(); dgv_FieldList.Rows.Clear(); //this.btn_testConnection_Click(sender, e); if (this.hasError == 1) { return; } if (txtbox_pickUpPath.Text.ToString() == "" || Directory.Exists(txtbox_pickUpPath.Text.ToString()) == false) { MessageBox.Show("I am sorry your folder path is either blank or does not exist"); this.hasError = 1; } if (this.hasError == 1) { return; } try { DirectoryInfo di = new DirectoryInfo(txtbox_pickUpPath.Text.ToString()); string[] extensions = new[] { ".txt", ".csv" }; if (this.files != null) { Array.Clear(this.files, 0, this.files.Length); } lv_fileList.Items.Clear(); this.files = di.EnumerateFiles() .Where(f => extensions.Contains(f.Extension.ToLower())) .ToArray(); if (this.filesToLoad != null) { this.filesToLoad.Clear(); } List<string> failedFiles = new List<string>(); foreach(FileInfo fl in this.files) { lv_fileList.Items.Add(fl.FullName.ToString()); DataTable dtfl = GetDataTableFromCSVFile(fl.FullName.ToString()); if(dtfl != null) { this.filesToLoad.Add(fl.FullName.ToString(), dtfl); } else { failedFiles.Add(fl.FullName); } } foreach(string fi in failedFiles) { lv_fileList.FindItemWithText(fi).ForeColor = Color.Red; } this.fileListLoaded = true; foreach (ListViewItem lv in lv_fileList.Items) { this.updateFileMapping(sender, e, lv.Index); lv_fileList.Items[lv.Index].Checked = true; } if (lv_fileList.Items[0] != null) { lv_fileList.Items[0].Selected = true; lv_fileList.Items[0].Focused = true; } dgv_FieldList.Enabled = true; lv_fileList.Enabled = true; btn_loadToSQL.Enabled = true; } catch { lv_fileList.Enabled = false; dgv_FieldList.Enabled = false; } } // TODO: Need to add Checks for Drop Table and for Create Unioned Table // TODO: Need to add more validation private void loadTablesToSQLServer() { if (txtbox_FinalTableName.Text.Trim() == "" && chbox_CreateAllTablesTable.Checked == true) { MessageBox.Show("Sorry you have chosen to create an all tables and left the final table name blank. Please fill something in."); return; } int fCount = this.lv_fileList.CheckedItems.Count; int fCnt = 1; if(fCount == 0) { MessageBox.Show("Sorry but you have not selected any files to Load. Please select the check box next to the files you wish to load."); return; } string lastTableName; int lastTableNumberOriginal = 1; int lastTableNumber = 1; string tablePrefix = ""; Boolean useTablePrefix = chbox_tablePrefix.Checked; decimal currentProg = (decimal)((double)fCnt/fCount*100); if (useTablePrefix) { tablePrefix = txtbox_tablePrefix.Text.ToString(); try { //string query = @"SELECT MAX(t.name) AS LastTable, RIGHT(MAX(T.name),3) AS LastTableNumber FROM sys.tables t WHERE name LIKE '%" + tablePrefix + @"[0-9]%'"; string query = @"SELECT * FROM (SELECT MAX(t.name) AS LastTable, RIGHT(MAX(T.name),3) AS LastTableNumber FROM sys.tables t WHERE name LIKE '"+tablePrefix+@"[0-9]%') a WHERE lastTable IS NOT null"; cnn.Open(); SqlCommand cmd = new SqlCommand(query, this.cnn); //MessageBox.Show("Connection Open ! "); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); if(ds.Tables.Count > 0) { if(ds.Tables[0].Rows.Count > 0) { lastTableName = ds.Tables[0].Rows[0]["LastTable"].ToString(); lastTableNumberOriginal = Int32.Parse(ds.Tables[0].Rows[0]["LastTableNumber"].ToString())+1; } else { lastTableName = txtbox_tablePrefix.Text.ToString(); lastTableNumberOriginal = Int32.Parse("000") + 1; } } else { lastTableName = txtbox_tablePrefix.Text.ToString(); lastTableNumberOriginal = Int32.Parse("000") + 1; } this.cnn.Close(); } catch (Exception ex) { if (this.cnn.State == ConnectionState.Open) { cnn.Close(); } MessageBox.Show(ex.Message.ToString()); return; } } lastTableNumber = lastTableNumberOriginal; frm_loadStatus ltDialog = new frm_loadStatus(txtbox_sqlServer.Text.ToString()); ltDialog.Show(); Boolean errorsHappened = false; foreach (ListViewItem lii in lv_fileList.CheckedItems) { lbl_loadFilesStatus.ForeColor = Color.Black; lbl_loadFilesStatus.Text = "Loading your files..."; DataTable dtToLoad; FileInfo fi = FileSystem.GetFileInfo(lii.Text.ToString()); string fName = fi.Name.ToString().Replace(".txt", "").Replace(".csv", ""); string tNameToInsert = useTablePrefix ? tablePrefix + lastTableNumber.ToString().PadLeft(3, '0') : fName; ltDialog.setLoadingText("Loading Table " + tNameToInsert); ltDialog.setLoadStatus(currentProg); try { dtToLoad = this.filesToLoad[lii.Text.ToString()]; if (chbox_DropTables.Checked == true) { string dropTable = "if exists(select 1 FROM sys.tables where name = '" + tNameToInsert + "') BEGIN DROP TABLE [" + tNameToInsert + "]; END"; SqlCommand cmdDT = new SqlCommand(dropTable, this.cnn); cmdDT.Connection.Open(); cmdDT.ExecuteNonQuery(); cmdDT.Connection.Close(); cmdDT.Dispose(); } string createTable = "CREATE TABLE [" + tNameToInsert + "] ("; Dictionary<string, Dictionary<string, string>> fd = this.filesToLoadMapping[fi.FullName.ToString()]; int cLength = dtToLoad.Columns.Count; for (int i = 0; i < cLength; i++) { Dictionary<string, string> dd = fd[dtToLoad.Columns[i].Ordinal.ToString()]; string dtstr = dd["dataType"].ToString() == "Text" ? "varchar" : dd["dataType"].ToString(); if (dd["dataType"].ToString() == "Text") { dtstr += "(" + dd["dtLength"].ToString() + ")"; } //this.filesToLoadMapping[dtToLoad.Columns[i].ToString()] if (i == cLength - 1) { createTable += "[" + dtToLoad.Columns[i].ToString() + "] " + dtstr; } else { createTable += "[" + dtToLoad.Columns[i].ToString() + "] " + dtstr + ","; } } createTable += ") "; System.Diagnostics.Debug.WriteLine(createTable); SqlCommand cmd2 = new SqlCommand(createTable, this.cnn); cmd2.Connection.Open(); cmd2.ExecuteNonQuery(); cmd2.Connection.Close(); cmd2.Dispose(); this.cnn.Open(); using (SqlBulkCopy s = new SqlBulkCopy(cnn)) { string abc = "dbo.[" + tNameToInsert + "]"; s.DestinationTableName = abc; s.BulkCopyTimeout = 0; s.WriteToServer(dtToLoad); } this.cnn.Close(); lbl_loadFilesStatus.ForeColor = Color.Green; lbl_loadFilesStatus.Text = "Your files have been loaded"; //InsertDataIntoSQLServerUsingSQLBulkCopy(dtToLoad, tToInsert, cnn); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); cnn.Close(); lbl_loadFilesStatus.ForeColor = Color.Red; lbl_loadFilesStatus.Text = ex.Message; errorsHappened = true; } fCnt++; lastTableNumber++; currentProg = (decimal)((double)fCnt / fCount * 100); } if (chbox_CreateAllTablesTable.Checked == false) { ltDialog.setLoadingText(errorsHappened ? @"We loaded the tables we could" : @"Your Tables have Been Loaded "); ltDialog.setLoadStatus(new decimal(100)); ltDialog.showOkButton(); btn_loadToSQL.Enabled = false; return; } lastTableNumber = lastTableNumberOriginal; //foreach (System.Collections.Generic.KeyValuePair<string, DataTable> fl in this.filesToLoad) { //} // end foreach if(chbox_CreateAllTablesTable.Checked == true) { string finalTable = txtbox_FinalTableName.Text.ToString(); try { decimal lstat = new decimal(90); ltDialog.setLoadStatus(lstat); ltDialog.setLoadingText("Trying to create your Unioned Table \"" + txtbox_FinalTableName.Text.ToString() + " \""); if(chbox_DropTables.Checked == true) { string dropTable = "if exists(select 1 FROM sys.tables where name = '" + finalTable + "') BEGIN DROP TABLE [" + finalTable + "]; END"; SqlCommand cmdDT = new SqlCommand(dropTable, this.cnn); cmdDT.Connection.Open(); cmdDT.ExecuteNonQuery(); cmdDT.Connection.Close(); cmdDT.Dispose(); } cnn.Open(); var enviroment = System.Environment.CurrentDirectory; string currentLocationOfExe = Directory.GetParent(enviroment).Parent.FullName; string script = File.ReadAllText(@"" + currentLocationOfExe.ToString().Replace(".dll", "") + @"\SQL Scripts\DropOriginalTableCustomFunctions.sql"); SqlCommand cmScripts = new SqlCommand(script, cnn); cmScripts.ExecuteNonQuery(); script = File.ReadAllText(@"" + currentLocationOfExe.ToString().Replace(".dll", "") + @"\SQL Scripts\OriginalTableList.sql"); cmScripts.CommandText = script; cmScripts.ExecuteNonQuery(); script = File.ReadAllText(@"" + currentLocationOfExe.ToString().Replace(".dll", "") + @"\SQL Scripts\get_originalUnion.sql"); cmScripts.CommandText = script; cmScripts.ExecuteNonQuery(); cnn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); cnn.Close(); return; } Dictionary<string, string> tListLoaded = new Dictionary<string, string>(); try { string qToUnion = @" DECLARE @tvalues OriginalTableList "; qToUnion += useTablePrefix ? @" INSERT INTO @tvalues (tbl, srcFile) VALUES " : @" INSERT INTO @tvalues(tbl) VALUES "; int itemsAddedCount = this.lv_fileList.CheckedItems.Count; int itemsAddedCounter = 1; foreach(ListViewItem lii in this.lv_fileList.CheckedItems) { FileInfo fl = FileSystem.GetFileInfo(lii.Text.ToString()); string fName = fl.Name.ToString().Replace(".txt", "").Replace(".csv", ""); string tName = useTablePrefix == true ? tablePrefix + lastTableNumber.ToString().PadLeft(3, '0') : fName; if (itemsAddedCounter != itemsAddedCount) { qToUnion += useTablePrefix ? @" ('" + tName + @"', '"+ fName +"'), " : @" ('" + fName + @"'), "; } else { qToUnion += useTablePrefix ? @" ('" + tName + @"', '" + fName + "') " : @" ('" + fName + @"') "; } if(useTablePrefix) { tListLoaded.Add(fl.FullName.ToString(), tName); } lastTableNumber++; itemsAddedCounter++; } qToUnion += Environment.NewLine; string nTName = finalTable; qToUnion += @"EXEC dbo.get_OriginalUnion @tvalues, '" + nTName + "'"; SqlCommand cmd3 = new SqlCommand(qToUnion, cnn); cmd3.Connection.Open(); cmd3.ExecuteNonQuery(); cmd3.Connection.Close(); cmd3.Dispose(); //string ChangeOriginalTableToFile = @"EXEC sp_rename 'dbo."+finalTable+".OriginalTable', 'OriginalFile', 'COLUMN'; "; //SqlCommand cmd4 = new SqlCommand(ChangeOriginalTableToFile, cnn); //cmd4.Connection.Open(); cmd4.ExecuteNonQuery(); cmd4.Connection.Close(); //cmd4.Dispose(); ltDialog.setLoadingText(@"You Now Have A New Table " + Environment.NewLine + nTName); ltDialog.setLoadStatus(new decimal(100)); ltDialog.showOkButton(); } catch (Exception em) { MessageBox.Show(em.Message.ToString()); ltDialog.showCancelButton(); } } // SETUP Scripts So that SQL Can be updated for union table and used to create Union Table btn_loadToSQL.Enabled = false; } private DataTable GetDataTableFromCSVFile(string csv_file_path) { DataTable csvData = new DataTable(); try { using (TextFieldParser csvReader = new TextFieldParser(csv_file_path)) { string[] dv; List<string> dl = new List<string>(); switch (cmbox_delimiter.Text.ToString()) { case "Tab": dl.Add("\t"); break; case "Comma": dl.Add(","); break; case "Semi-Colon": dl.Add(";"); break; case "Pipe": dl.Add("|"); break; default: dl.Add("\t"); break; } dv = dl.ToArray(); //MessageBox.Show(dv); csvReader.SetDelimiters( dv ); csvReader.HasFieldsEnclosedInQuotes = true; string[] colFields = csvReader.ReadFields(); foreach (string column in colFields) { DataColumn datecolumn = new DataColumn(column); datecolumn.AllowDBNull = true; csvData.Columns.Add(datecolumn); } while (!csvReader.EndOfData) { string[] fieldData = csvReader.ReadFields(); //Making empty value as null for (int i = 0; i < fieldData.Length; i++) { if (fieldData[i] == "") { fieldData[i] = null; } } csvData.Rows.Add(fieldData); } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); return null; } return csvData; } private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) { } private void lbl_CollapseTopPanel_Click(object sender, EventArgs e) { sc_Main.Panel1Collapsed = true; lbl_ExpandTopPanel.Visible = true; } private void lbl_ExpandTopPanel_Click(object sender, EventArgs e) { sc_Main.Panel1Collapsed = false; lbl_ExpandTopPanel.Visible = false; } private void tsm_exit_Click(object sender, EventArgs e) { Application.Exit(); } private void tsm_clearData_Click(object sender, EventArgs e) { string msg = "Are you sure you want to clear all the data on screen?"; var result = MessageBox.Show(msg, "Clear Data", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); // If the no button was pressed ... if (result == DialogResult.OK) { // clear the screens data this.clearTheScreen(); } } private void clearTheScreen() { // Clear SQL Server Stuff // CheckBoxes txtbox_sqlServer.Text = ""; txtbox_sqlUser.Text = ""; txtbox_sqlPass.Text = ""; txtbox_sqlDatabase.Text = ""; txtbox_pickUpPath.Text = ""; // Labels lbl_testConnStatus.Text = ""; // Clear bottom Checkboxes chbox_DropTables.Checked = false; chbox_CreateAllTablesTable.Checked = true; // Clear lists and tables lv_fileList.Items.Clear(); dgv_FieldList.Rows.Clear(); // Clear Other Labels lbl_LoadToSQLStatus.Text = ""; lbl_loadFilesStatus.Text = ""; } private void chbox_windowsAuth_CheckedChanged(object sender, EventArgs e) { if(this.chbox_windowsAuth.Checked == true) { txtbox_sqlUser.Enabled = false; txtbox_sqlPass.Enabled = false; } else { txtbox_sqlUser.Enabled = true; txtbox_sqlPass.Enabled = true; } } private void updateFileMapping (object sender, EventArgs e, int idx) { dgv_FieldList.Rows.Clear(); int ci = idx == -1 ? lv_fileList.SelectedIndex() : idx; FileInfo fl = this.files[ci]; if (!this.filesToLoad.ContainsKey(fl.FullName.ToString())) { return; } DataTable dt = this.filesToLoad[fl.FullName.ToString()]; Dictionary<string, Dictionary<string, string>> ftm = null; if (this.filesToLoadMapping.ContainsKey(fl.FullName.ToString())) { ftm = this.filesToLoadMapping[fl.FullName.ToString()]; } if (ftm == null) { // Mapping Doesn't exist prefil will generic mapping foreach (DataColumn col in dt.Columns) { dgv_FieldList.Rows.Add( col.Ordinal.ToString() , col.ColumnName.ToString() , "Text" , txtbox_defaultDataLength.Text.ToString() ); } this.dgv_FieldList_CellValueChanged_Call(sender, null, ci); } else { // Mapping Does Exist. Get Mapping and prefill with mapping foreach (System.Collections.Generic.KeyValuePair<string, Dictionary<string, string>> em in ftm) { dgv_FieldList.Rows.Add( em.Value["Ordinal"].ToString() , em.Value["fieldName"].ToString() , em.Value["dataType"] , em.Value["dtLength"] ); } } } private void cbl_fileList_SelectedIndexChanged(object sender, EventArgs e) { this.updateFileMapping(sender, e, -1); } private void dgv_FieldList_CellValueChanged(object sender, DataGridViewCellEventArgs e) { this.dgv_FieldList_CellValueChanged_Call(sender, e, -1); } private void updateMappingForFile (int idx) { if (this.files != null) { FileInfo fl = this.files[idx]; this.filesToLoadMapping.Remove(fl.FullName.ToString()); Dictionary<string, Dictionary<string, string>> ml = new Dictionary<string, Dictionary<string, string>>(); foreach (DataGridViewRow r in dgv_FieldList.Rows) { Dictionary<string, string> dmr = new Dictionary<string, string>(); dmr.Add("Ordinal", r.Cells["index"].Value.ToString()); dmr.Add("fieldName", r.Cells["fieldName"].Value.ToString()); dmr.Add("dataType", r.Cells["dataType"].Value.ToString()); dmr.Add("dtLength", r.Cells["dtLength"].Value.ToString()); ml.Add(r.Cells["index"].Value.ToString(), dmr); } this.filesToLoadMapping.Add(fl.FullName.ToString(), ml); } } private void dgv_FieldList_CellValueChanged_Call (object sender, DataGridViewCellEventArgs e, int ci) { int idx = ci == -1 ? lv_fileList.SelectedIndex() : ci; if (this.fileListLoaded) { if(e == null) { this.updateMappingForFile(idx); return; } if ( e.RowIndex != 0) { int ri = e.RowIndex; //MessageBox.Show(ri.ToString()); DataGridViewRow dgvr = dgv_FieldList.Rows[e.RowIndex]; string input = dgvr.Cells["dtLength"].Value.ToString(); string patt1 = @"\d+"; Match m1 = Regex.Match(input, patt1); Boolean mm1; if (m1.Length > 0) { mm1 = true; } else { mm1 = false; } if ( dgvr.Cells["dataType"].Value.ToString() == "Text" && input.ToUpper() != "MAX" && !mm1 ) { MessageBox.Show("Your Value is invalid for the data length"); dgvr.Cells["dtLength"].Value = "max"; } this.updateMappingForFile(idx); } } } private void btn_CheckStuff_Click(object sender, EventArgs e) { string opt = ""; foreach(System.Collections.Generic.KeyValuePair<string, System.Data.DataTable> fl in this.filesToLoad) { opt += fl.Key.ToString() + "\n"; Dictionary<string, Dictionary<string,string>> fm = this.filesToLoadMapping[fl.Key.ToString()]; foreach(System.Collections.Generic.KeyValuePair<string, Dictionary<string,string>> fmr in fm) { foreach(System.Collections.Generic.KeyValuePair<string,string> fmrv in fmr.Value) { opt += fmrv.Key.ToString() + " >>> " + fmrv.Value.ToString() + "\n"; } } } MessageBox.Show(opt); } private void btn_loadToSQL_Click(object sender, EventArgs e) { this.btn_testConnection_Click(sender, e); this.loadTablesToSQLServer(); } private void chbox_CreateAllTablesTable_CheckedChanged(object sender, EventArgs e) { if(this.chbox_CreateAllTablesTable.Checked) { txtbox_FinalTableName.Visible = true; } else { txtbox_FinalTableName.Visible = false; } } private void openExcelToCSv(object sender, EventArgs e) { frm_excelToCSV etc = new frm_excelToCSV(); etc.Show(); } private void chbox_tablePrefix_CheckedChanged(object sender, EventArgs e) { if(chbox_tablePrefix.Checked) { txtbox_tablePrefix.Visible = true; } else { txtbox_tablePrefix.Visible = false; } if(chbox_tablePrefix.Checked && chbox_DropTables.Checked) { lbl_warningIncremental.Text = "Drop Tables will be ignored w/create incremental checked"; lbl_warningIncremental.ForeColor = Color.Red; } else { lbl_warningIncremental.Text = ""; } } private void chbox_DropTables_CheckedChanged(object sender, EventArgs e) { if (chbox_tablePrefix.Checked && chbox_DropTables.Checked) { lbl_warningIncremental.Text = "Drop Tables will be ignored w/create incremental checked"; lbl_warningIncremental.ForeColor = Color.Red; } else { lbl_warningIncremental.Text = ""; } } } public static class Extension { public static int SelectedIndex(this ListView listView) { if (listView.SelectedIndices.Count > 0) return listView.SelectedIndices[0]; else return 0; } } public class LocalConfig { public string tableName { get; set; } public string tablePrefix { get; set; } } }
42.630464
216
0.494936
f1db519c8495ae166078904668db70f963ce85ce
1,922
rb
Ruby
app/models/tracker.rb
floXcoder/InRailsWeBlog
1a6e37c27050818c8f3fb92a0fe488f8ba39025e
[ "MIT" ]
5
2019-05-21T21:58:54.000Z
2020-11-25T10:40:15.000Z
app/models/tracker.rb
floXcoder/InRailsWeBlog
1a6e37c27050818c8f3fb92a0fe488f8ba39025e
[ "MIT" ]
null
null
null
app/models/tracker.rb
floXcoder/InRailsWeBlog
1a6e37c27050818c8f3fb92a0fe488f8ba39025e
[ "MIT" ]
2
2018-02-13T14:41:02.000Z
2019-02-21T13:11:23.000Z
# frozen_string_literal: true # == Schema Information # # Table name: trackers # # id :bigint not null, primary key # tracked_type :string not null # tracked_id :bigint not null # views_count :integer default(0), not null # queries_count :integer default(0), not null # searches_count :integer default(0), not null # clicks_count :integer default(0), not null # popularity :integer default(0), not null # rank :integer default(0), not null # home_page :boolean default(FALSE), not null # created_at :datetime not null # updated_at :datetime not null # visits_count :integer default(0), not null # class Tracker < ApplicationRecord # == Attributes =========================================================== # == Extensions =========================================================== # == Relationships ======================================================== belongs_to :tracked, polymorphic: true, touch: true belongs_to :article, class_name: 'Article', foreign_key: 'tracked_id', optional: true belongs_to :tag, class_name: 'Tag', foreign_key: 'tracked_id', optional: true belongs_to :topic, class_name: 'Topic', foreign_key: 'tracked_id', optional: true # == Validations ========================================================== # == Scopes =============================================================== # == Callbacks ============================================================ # == Class Methods ======================================================== # == Instance Methods ===================================================== end
33.719298
77
0.413632
ef44e12c63dceadd576424a104174b0e7d2b924d
5,535
c
C
src/xrt/ipc/client/ipc_client_hmd.c
SimulaVR/monado
b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21
[ "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause" ]
2
2021-11-08T05:17:12.000Z
2022-01-24T12:50:59.000Z
src/xrt/ipc/client/ipc_client_hmd.c
SimulaVR/monado
b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21
[ "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/xrt/ipc/client/ipc_client_hmd.c
SimulaVR/monado
b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21
[ "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
// Copyright 2020, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 /*! * @file * @brief IPC Client HMD device. * @author Jakob Bornecrantz <jakob@collabora.com> * @ingroup ipc_client */ #include <math.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "xrt/xrt_device.h" #include "os/os_time.h" #include "math/m_api.h" #include "util/u_var.h" #include "util/u_misc.h" #include "util/u_debug.h" #include "util/u_device.h" #include "util/u_distortion_mesh.h" #include "client/ipc_client.h" #include "ipc_client_generated.h" /* * * Structs and defines. * */ /*! * An IPC client proxy for an HMD @ref xrt_device. * @implements xrt_device */ struct ipc_client_hmd { struct xrt_device base; struct ipc_connection *ipc_c; uint32_t device_id; }; /* * * Functions * */ static inline struct ipc_client_hmd * ipc_client_hmd(struct xrt_device *xdev) { return (struct ipc_client_hmd *)xdev; } static void ipc_client_hmd_destroy(struct xrt_device *xdev) { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); // Remove the variable tracking. u_var_remove_root(ich); // We do not own these, so don't free them. ich->base.inputs = NULL; ich->base.outputs = NULL; // Free this device with the helper. u_device_free(&ich->base); } static void ipc_client_hmd_update_inputs(struct xrt_device *xdev) { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); xrt_result_t r = ipc_call_device_update_input(ich->ipc_c, ich->device_id); if (r != XRT_SUCCESS) { IPC_ERROR(ich->ipc_c, "Error calling input update!"); } } static void ipc_client_hmd_get_tracked_pose(struct xrt_device *xdev, enum xrt_input_name name, uint64_t at_timestamp_ns, struct xrt_space_relation *out_relation) { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); xrt_result_t r = ipc_call_device_get_tracked_pose(ich->ipc_c, ich->device_id, name, at_timestamp_ns, out_relation); if (r != XRT_SUCCESS) { IPC_ERROR(ich->ipc_c, "Error calling tracked pose!"); } } static void ipc_client_hmd_get_view_pose(struct xrt_device *xdev, const struct xrt_vec3 *eye_relation, uint32_t view_index, struct xrt_pose *out_pose) { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); xrt_result_t r = ipc_call_device_get_view_pose(ich->ipc_c, ich->device_id, eye_relation, view_index, out_pose); if (r != XRT_SUCCESS) { IPC_ERROR(ich->ipc_c, "Error calling view pose!"); } } /*! * @public @memberof ipc_client_hmd */ struct xrt_device * ipc_client_hmd_create(struct ipc_connection *ipc_c, struct xrt_tracking_origin *xtrack, uint32_t device_id) { struct ipc_shared_memory *ism = ipc_c->ism; struct ipc_shared_device *isdev = &ism->isdevs[device_id]; enum u_device_alloc_flags flags = (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD); struct ipc_client_hmd *ich = U_DEVICE_ALLOCATE(struct ipc_client_hmd, flags, 0, 0); ich->ipc_c = ipc_c; ich->device_id = device_id; ich->base.update_inputs = ipc_client_hmd_update_inputs; ich->base.get_tracked_pose = ipc_client_hmd_get_tracked_pose; ich->base.get_view_pose = ipc_client_hmd_get_view_pose; ich->base.destroy = ipc_client_hmd_destroy; // Start copying the information from the isdev. ich->base.tracking_origin = xtrack; ich->base.name = isdev->name; ich->device_id = device_id; // Print name. snprintf(ich->base.str, XRT_DEVICE_NAME_LEN, "%s", isdev->str); // Setup inputs, by pointing directly to the shared memory. assert(isdev->num_inputs > 0); ich->base.inputs = &ism->inputs[isdev->first_input_index]; ich->base.num_inputs = isdev->num_inputs; #if 0 // Setup info. struct u_device_simple_info info; info.display.w_pixels = 1920; info.display.h_pixels = 1080; info.display.w_meters = 0.13f; info.display.h_meters = 0.07f; info.lens_horizontal_separation_meters = 0.13f / 2.0f; info.lens_vertical_position_meters = 0.07f / 2.0f; info.views[0].fov = 85.0f * (M_PI / 180.0f); info.views[1].fov = 85.0f * (M_PI / 180.0f); if (!u_device_setup_split_side_by_side(&ich->base, &info)) { IPC_ERROR(ich->ipc_c, "Failed to setup basic device info"); ipc_client_hmd_destroy(&ich->base); return NULL; } #endif for (int i = 0; i < XRT_MAX_DEVICE_BLEND_MODES; i++) { ich->base.hmd->blend_modes[i] = ipc_c->ism->hmd.blend_modes[i]; } ich->base.hmd->num_blend_modes = ipc_c->ism->hmd.num_blend_modes; ich->base.hmd->views[0].display.w_pixels = ipc_c->ism->hmd.views[0].display.w_pixels; ich->base.hmd->views[0].display.h_pixels = ipc_c->ism->hmd.views[0].display.h_pixels; ich->base.hmd->views[0].fov = ipc_c->ism->hmd.views[0].fov; ich->base.hmd->views[1].display.w_pixels = ipc_c->ism->hmd.views[1].display.w_pixels; ich->base.hmd->views[1].display.h_pixels = ipc_c->ism->hmd.views[1].display.h_pixels; ich->base.hmd->views[1].fov = ipc_c->ism->hmd.views[1].fov; // Distortion information, fills in xdev->compute_distortion(). u_distortion_mesh_set_none(&ich->base); // Setup variable tracker. u_var_add_root(ich, ich->base.str, true); u_var_add_ro_u32(ich, &ich->device_id, "device_id"); ich->base.orientation_tracking_supported = isdev->orientation_tracking_supported; ich->base.position_tracking_supported = isdev->position_tracking_supported; ich->base.device_type = isdev->device_type; ich->base.hand_tracking_supported = isdev->hand_tracking_supported; return &ich->base; }
27.954545
112
0.715628
7fdb6a0f0efead710925b6e985d6322ca66fb667
822
swift
Swift
Examples/Example/Kit/Collection/CollectionCellViewModel.swift
MasterWatcher/RxDataSources
71a0839dc0bbdd33fe6c198f44d0f5f0ef071fb5
[ "MIT" ]
2
2020-01-05T07:09:50.000Z
2021-03-22T12:10:23.000Z
Examples/Example/Kit/Collection/CollectionCellViewModel.swift
MasterWatcher/RxDataSources
71a0839dc0bbdd33fe6c198f44d0f5f0ef071fb5
[ "MIT" ]
null
null
null
Examples/Example/Kit/Collection/CollectionCellViewModel.swift
MasterWatcher/RxDataSources
71a0839dc0bbdd33fe6c198f44d0f5f0ef071fb5
[ "MIT" ]
null
null
null
// // CollectionViewCellViewModel.swift // Example // // Created by Goncharov Anton on 04/01/2020. // Copyright © 2020 kzaher. All rights reserved. // import Foundation import UIKit protocol CollectionCellViewModel: CollectionItemType, Equatable { associatedtype CollectionCellType: ConfigurableCell & UICollectionViewCell where CollectionCellType.ViewModel == Self } extension CollectionCellViewModel { var collectionReuseIdentifier: String { String(describing: CollectionCellType.self) } //according to https://developer.apple.com/documentation/uikit/uicollectionviewflowlayout/1617711-itemsize var itemSize: CGSize { CGSize(width: 50, height: 50) } func configure(_ cell: UICollectionViewCell) { (cell as? CollectionCellType)?.configure(with: self) } }
26.516129
121
0.742092
339370fadbd447c996084cfb2d0092cbac74c5a8
96
psd1
PowerShell
ZP.Template/Activities/Activity.ZP.Template/en-US/Activity.ZP.Template.psd1
Zervicepoint/zervicepoint-starter-base
7669d0debf6804be0b1b71d31b0671f1303bdd55
[ "MIT" ]
2
2021-05-18T14:44:54.000Z
2021-05-19T07:33:50.000Z
ZP.Template/Activities/Activity.ZP.Template/en-US/Activity.ZP.Template.psd1
Zervicepoint/zervicepoint-starter-base
7669d0debf6804be0b1b71d31b0671f1303bdd55
[ "MIT" ]
null
null
null
ZP.Template/Activities/Activity.ZP.Template/en-US/Activity.ZP.Template.psd1
Zervicepoint/zervicepoint-starter-base
7669d0debf6804be0b1b71d31b0671f1303bdd55
[ "MIT" ]
null
null
null
ConvertFrom-StringData @' NewZPResource0 = Name was supplied. NewZPResource1 = Name was null. '@
24
35
0.78125
7a54717f400f74680f2c41e3d2ad81ed68ed447d
1,523
swift
Swift
Lesson01/Lesson01/Model/Game.swift
djestat/Design_Patterns
14562eef86ad6816a2be1204a335e29635c89bc8
[ "Unlicense" ]
1
2019-10-24T10:15:57.000Z
2019-10-24T10:15:57.000Z
Lesson01/Lesson01/Model/Game.swift
djestat/Design_Patterns
14562eef86ad6816a2be1204a335e29635c89bc8
[ "Unlicense" ]
null
null
null
Lesson01/Lesson01/Model/Game.swift
djestat/Design_Patterns
14562eef86ad6816a2be1204a335e29635c89bc8
[ "Unlicense" ]
null
null
null
// // Game.swift // Lesson01 // // Created by Igor on 22.10.2019. // Copyright © 2019 IgorLab. All rights reserved. // import Foundation final class Game { static let shared = Game() var gameSession: GameSession? private let scoreCaretaker = ScoreCaretaker() private(set) var results: [ScoreResult] { didSet { scoreCaretaker.save(scores: self.results) } } private init() { self.results = self.scoreCaretaker.retriveScoress() } func addResult() { let scoreResult = ScoreResult(rightAnswer: gameSession!.rightAnswer.value, numberOfQuestions: gameSession!.questionsCount, percentRightAnswers: (Double(gameSession!.rightAnswer.value) / Double(gameSession!.questionsCount)) * 100) self.results.append(scoreResult) } func clearGameSession() { gameSession = nil } // Startegy var difficulty: Difficulty = .inseries private lazy var questionsStrategy: QuestionsStrategy = { switch self.difficulty { case .inseries: let questions = InSeriesStrategy() return questions case .random: let questions = RandomStrategy() return questions } }() func getQuestions() -> [Question] { return questionsStrategy.orderOfQuestion() } } struct ScoreResult: Codable { var rightAnswer: Int var numberOfQuestions: Int var percentRightAnswers: Double }
23.796875
237
0.622456
cd2d024ffe1a7d490d8847f3e7609b93418577f4
598
cs
C#
Assets/_user/scripts/Libs/RESTful/BaseRequestResponse.cs
oswaldocarvalho/unity-restful-client
f64305d67b6fde95e4886ee3ca72be9216650524
[ "BSD-3-Clause" ]
8
2018-09-04T08:51:22.000Z
2022-01-28T19:30:00.000Z
Assets/_user/scripts/Libs/RESTful/BaseRequestResponse.cs
oswaldocarvalho/unity-restful-client
f64305d67b6fde95e4886ee3ca72be9216650524
[ "BSD-3-Clause" ]
1
2019-03-08T11:19:08.000Z
2020-09-21T22:24:59.000Z
Assets/_user/scripts/Libs/RESTful/BaseRequestResponse.cs
oswaldocarvalho/unity-restful-client
f64305d67b6fde95e4886ee3ca72be9216650524
[ "BSD-3-Clause" ]
null
null
null
using System; using System.Reflection; using UnityEngine.Networking; namespace RESTfull { [Serializable] public class BaseRequestResponse { public string GetQueryString() { FieldInfo[] fields = this.GetType().GetFields(); string queryString = "?"; foreach(FieldInfo field in fields) { queryString += (queryString.Length==1?"":"&") + $"{UnityWebRequest.EscapeURL(field.Name)}={UnityWebRequest.EscapeURL(field.GetValue(this).ToString())}"; } return queryString; } } }
24.916667
168
0.588629
df17e277f097e30ca98a4b55bc40bfdc16f3ceaf
947
rb
Ruby
spec/support/application_test_helper.rb
kvokka/zombie_check
e2010f9a6a896dc43a2da3317f3aa5a7f52689c2
[ "MIT" ]
null
null
null
spec/support/application_test_helper.rb
kvokka/zombie_check
e2010f9a6a896dc43a2da3317f3aa5a7f52689c2
[ "MIT" ]
null
null
null
spec/support/application_test_helper.rb
kvokka/zombie_check
e2010f9a6a896dc43a2da3317f3aa5a7f52689c2
[ "MIT" ]
null
null
null
# frozen_string_literal: true require "open3" require "fileutils" module ApplicationTestHelper def run_zombie_check(options = {}) Dir.chdir(root_path) do captured_stdout = "" ttl = options[:ttl] Open3.popen3("#{zombie_bin} #{options[:params]}") do |_stdin, stdout, _stderr, wait_thr| if ttl sleep ttl Process.kill("INT", wait_thr.pid) end captured_stdout = stdout.read end end end def create_fake_hosts_file(content) File.open(fake_hosts_path, "a") do |file| file.write(content.is_a?(Array) ? content.join("\n") : content) end end def remove_fake_hosts_file FileUtils.rm_rf(fake_hosts_path) end private def zombie_bin File.join(root_path, "bin", "zombie_check") end def root_path File.expand_path("../../../", __FILE__) end def fake_hosts_path File.join(root_path, "fake_hosts.txt") end end
22.023256
94
0.640971
da771009b6644a2c9f5f2081cad303dcb8bbe29b
79
ts
TypeScript
docs/src/pages/preset/index.ts
PrettyCoffee/react-startpage
732744f1f9d20a800ad66db5005882461badc4c9
[ "MIT" ]
32
2021-03-19T00:05:30.000Z
2022-03-09T08:03:06.000Z
docs/src/pages/preset/index.ts
PrettyCoffee/react-startpage
732744f1f9d20a800ad66db5005882461badc4c9
[ "MIT" ]
10
2021-03-21T00:21:04.000Z
2022-01-09T16:30:04.000Z
docs/src/pages/preset/index.ts
PrettyCoffee/react-startpage
732744f1f9d20a800ad66db5005882461badc4c9
[ "MIT" ]
4
2021-03-19T18:11:46.000Z
2022-01-17T19:14:54.000Z
// @ts-ignore import Docs from "./preset.mdx" export default Docs as React.FC
15.8
31
0.721519
ed0be547b7fd848c308fc563227d34e7630990b0
317
h
C
WVRProgram/WVRProgram/Classes/Live/Reserve/WVRLiveReservePresenter.h
portal-io/portal-ios-business
e8c3776b5a2e81c152c41fbf78fe33f48ed64d07
[ "MIT" ]
null
null
null
WVRProgram/WVRProgram/Classes/Live/Reserve/WVRLiveReservePresenter.h
portal-io/portal-ios-business
e8c3776b5a2e81c152c41fbf78fe33f48ed64d07
[ "MIT" ]
null
null
null
WVRProgram/WVRProgram/Classes/Live/Reserve/WVRLiveReservePresenter.h
portal-io/portal-ios-business
e8c3776b5a2e81c152c41fbf78fe33f48ed64d07
[ "MIT" ]
null
null
null
// // WVRReserveController.h // WhaleyVR // // Created by qbshen on 2016/12/7. // Copyright © 2016年 Snailvr. All rights reserved. // #import "SQBaseCollectionPresenter.h" @interface WVRLiveReservePresenter : SQBaseCollectionPresenter + (instancetype)createPresenter:(id)createArgs; - (UIView *)getView; @end
17.611111
62
0.741325
f2b1f236256fd1445ff5f8ed2a84b90428f65313
1,107
lua
Lua
SERVER-DATA/RESOURCES/[NOT]/esx_shops/config.lua
nimaisox/ESX-SERVER-FIVEM
a7d362c1f8d2508e5b8c12e1b5955f672fe4e266
[ "MIT" ]
1
2022-03-06T23:02:54.000Z
2022-03-06T23:02:54.000Z
SERVER-DATA/RESOURCES/[NOT]/esx_shops/config.lua
nimaisox/ESX-SERVER-FIVEM
a7d362c1f8d2508e5b8c12e1b5955f672fe4e266
[ "MIT" ]
null
null
null
SERVER-DATA/RESOURCES/[NOT]/esx_shops/config.lua
nimaisox/ESX-SERVER-FIVEM
a7d362c1f8d2508e5b8c12e1b5955f672fe4e266
[ "MIT" ]
null
null
null
Config = {} Config.DrawDistance = 100 Config.Size = {x = 1.5, y = 1.5, z = 1.5} Config.Color = {r = 0, g = 128, b = 255} Config.Type = 1 Config.Locale = 'en' Config.Zones = { TwentyFourSeven = { Items = {}, Pos = { vector3(373.8, 325.8, 102.5), vector3(2557.4, 382.2, 107.6), vector3(-3038.9, 585.9, 6.9), vector3(-3241.9, 1001.4, 11.8), vector3(547.4, 2671.7, 41.1), vector3(1961.4, 3740.6, 31.3), vector3(2678.9, 3280.6, 54.2), vector3(1729.2, 6414.1, 34.0) }}, RobsLiquor = { Items = {}, Pos = { vector3(1135.8, -982.2, 45.4), vector3(-1222.9, -906.9, 11.3), vector3(-1487.5, -379.1, 39.1), vector3(-2968.2, 390.9, 14.0), vector3(1166.0, 2708.9, 37.1), vector3(1392.5, 3604.6, 33.9), vector3(127.8, -1284.7, 28.2), --StripClub vector3(-1393.4, -606.6, 29.3), --Tequila la vector3(-559.9, 287.0, 81.1) --Bahamamas }}, LTDgasoline = { Items = {}, Pos = { vector3(-48.5, -1757.5, 28.4), vector3(1163.3, -323.8, 68.2), vector3(-707.5, -914.2, 18.2), vector3(-1820.5, 792.5, 137.1), vector3(1698.3, 4924.4, 41.0) }} }
23.553191
47
0.553749
b720f8b2868f3b8dffdeecb790853f558f2a23a7
1,075
cs
C#
StarWars/GameObjects/GameObject.cs
IllIgt/Asteroids_Game
9d19e15c5638ecab764c40b95ad5434245e58e7b
[ "Unlicense" ]
null
null
null
StarWars/GameObjects/GameObject.cs
IllIgt/Asteroids_Game
9d19e15c5638ecab764c40b95ad5434245e58e7b
[ "Unlicense" ]
null
null
null
StarWars/GameObjects/GameObject.cs
IllIgt/Asteroids_Game
9d19e15c5638ecab764c40b95ad5434245e58e7b
[ "Unlicense" ]
null
null
null
using System; using System.Drawing; using System.Windows.Forms; namespace StarWars { internal abstract class GameObject : ICollision { protected Point _Position; protected Point _Speed; protected Size _Size; public Rectangle Rect => new Rectangle(_Position, _Size); protected GameObject(Point Position, Point Speed, Size Size) { _Position = Position; _Speed = Speed; _Size = Size; } public bool Collision(ICollision obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); return Rect.IntersectsWith(obj.Rect); } public abstract void Draw(); public virtual void Update() { _Position.X += _Speed.X; _Position.Y += _Speed.Y; if (_Position.X < 0 || _Position.X > Game.Width - _Size.Width) _Speed.X *= -1; if (_Position.Y < 0 || _Position.Y > Game.Height - _Size.Height) _Speed.Y *= -1; } } }
25.595238
77
0.552558
5cfaac6919b1c6dc826a78c13bb10c7e44847948
1,032
php
PHP
routes/api.php
todashunta/word
d4075fcc8bca332013f891b58bda17e43b1bb191
[ "MIT" ]
null
null
null
routes/api.php
todashunta/word
d4075fcc8bca332013f891b58bda17e43b1bb191
[ "MIT" ]
null
null
null
routes/api.php
todashunta/word
d4075fcc8bca332013f891b58bda17e43b1bb191
[ "MIT" ]
null
null
null
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\ApiController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); Route::get('/index', [ApiController::class, 'index'])->name('api_index'); Route::get('/chapters/{word_book_id}', [ApiController::class, 'get_chapters']); Route::get('/words/{chapter_id}', [ApiController::class, 'get_words']); Route::get('/means/{word_id}', [ApiController::class, 'get_means']); Route::get('/all/{chapter_id}', [ApiController::class, 'get_all']); Route::post('/excel', [ApiController::class, 'excel']);
34.4
79
0.606589
1b7ec44e35a499b1d6034128849b6052fec987db
1,337
rb
Ruby
lib/flexible_config/overview.rb
brett-richardson/flexible-config
088a12ca3a317711accfcfae85efef05b18ea6a1
[ "MIT" ]
3
2016-03-22T21:06:02.000Z
2021-03-03T10:49:40.000Z
lib/flexible_config/overview.rb
brett-richardson/flexible-config
088a12ca3a317711accfcfae85efef05b18ea6a1
[ "MIT" ]
null
null
null
lib/flexible_config/overview.rb
brett-richardson/flexible-config
088a12ca3a317711accfcfae85efef05b18ea6a1
[ "MIT" ]
1
2017-08-31T11:34:56.000Z
2017-08-31T11:34:56.000Z
module FlexibleConfig class Overview def call available_files.reduce({}) do |memo, i| memo[i] = config_lines_for_file i memo end end def print call.each do |key, value| Kernel.puts "#===== #{key.upcase} (#{key}.yml) =====" value.each { |v| Kernel.puts v } Kernel.puts "\n" end end private def available_files WrappedYaml.config_data.keys end def config_lines_for_file(category) builder = FlexibleConfig::Builder.new category keys = [] WrappedYaml.config_data[category].values.each do |env| keys += flat_hash(env).keys end keys.uniq.sort.map do |keys| value = begin builder[keys.join '.'] rescue FlexibleConfig::NotFound => e "### NO VALUE ###" end combined_keys = [category] + keys dotted_key = keys.join '.' env_key = combined_keys.map(&:upcase).join '_' from_env = !WrappedEnv[env_key].nil? ? 'ENV OVERRIDE' : '' sprintf("%-40s|%-12s| %-45s = %s", dotted_key, from_env, env_key, value ) end end def flat_hash(h, f = [], g = {}) return g.update(f => h) unless h.is_a? Hash h.each { |k, r| flat_hash r, f+[k], g } g end end end
23.45614
71
0.538519
4d0e5e220f40a05275d7d7d5613e89112435a0ed
1,608
cs
C#
Client/src/IO.Swagger.Test/Model/GameTests.cs
KonH/LeaderboardService
077fa1946e7e0c1e49fab3603b1998612d242126
[ "MIT" ]
4
2017-05-06T11:31:27.000Z
2020-09-14T01:30:18.000Z
Client/src/IO.Swagger.Test/Model/GameTests.cs
KonH/LeaderboardService
077fa1946e7e0c1e49fab3603b1998612d242126
[ "MIT" ]
null
null
null
Client/src/IO.Swagger.Test/Model/GameTests.cs
KonH/LeaderboardService
077fa1946e7e0c1e49fab3603b1998612d242126
[ "MIT" ]
null
null
null
/* * API V1 * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using IO.Swagger.Api; using IO.Swagger.Model; using IO.Swagger.Client; using System.Reflection; namespace IO.Swagger.Test { /// <summary> /// Class for testing Game /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class GameTests { private Game instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { instance = new Game(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of Game /// </summary> [Test] public void GameInstanceTest() { Assert.IsInstanceOf<Game>(instance, "variable 'instance' is a Game"); } /// <summary> /// Test the property 'Name' /// </summary> [Test] public void NameTest() { var newName = "NewName"; instance.Name = newName; Assert.AreEqual(newName, instance.Name); } } }
20.615385
104
0.560323
551343fbcbf6b277166bd8fb2ac1c1799365500e
555
dart
Dart
lib/transform_completer.dart
yuan-kuan/dorker
eb5a3550c06a2067e65f7b22b4c394cdadaa3515
[ "BSD-2-Clause" ]
11
2018-12-17T03:07:02.000Z
2021-12-11T14:35:47.000Z
lib/transform_completer.dart
yuan-kuan/dorker
eb5a3550c06a2067e65f7b22b4c394cdadaa3515
[ "BSD-2-Clause" ]
2
2019-06-11T08:38:20.000Z
2019-06-17T14:43:53.000Z
lib/transform_completer.dart
yuan-kuan/dorker
eb5a3550c06a2067e65f7b22b4c394cdadaa3515
[ "BSD-2-Clause" ]
1
2019-06-11T08:15:16.000Z
2019-06-11T08:15:16.000Z
import 'dart:async' show Completer; typedef T Transform<T>(dynamic data); class TransformCompleter<T> { final _completer = Completer<T>(); final Transform<T> _transform; TransformCompleter([this._transform]); void complete([dynamic data]) { try { _completer.complete(_transform?.call(data)); } catch (e) { _completer.completeError(e); } } void completeError(dynamic error) { _completer.completeError(error); } bool get isCompleted => _completer.isCompleted; Future<T> get future => _completer.future; }
21.346154
50
0.69009
d00c7fed3dac7932915146b846c4fa172d4f7ba9
437
rb
Ruby
lib/acts_as_uuidable/acts_as_uuidable.rb
erebuseternal/inaturalist
fc8218f329abbb5462015e723a2756031d8834b1
[ "MIT" ]
466
2015-01-22T07:03:18.000Z
2022-03-28T12:02:45.000Z
lib/acts_as_uuidable/acts_as_uuidable.rb
erebuseternal/inaturalist
fc8218f329abbb5462015e723a2756031d8834b1
[ "MIT" ]
2,181
2015-01-01T03:21:02.000Z
2022-03-31T20:40:40.000Z
lib/acts_as_uuidable/acts_as_uuidable.rb
erebuseternal/inaturalist
fc8218f329abbb5462015e723a2756031d8834b1
[ "MIT" ]
164
2015-01-04T01:36:53.000Z
2022-03-14T19:37:45.000Z
module ActsAsUUIDable extend ActiveSupport::Concern included do validates_uniqueness_of :uuid before_validation :set_uuid def set_uuid self.uuid ||= SecureRandom.uuid self.uuid = uuid.downcase true end # If we seem to be assigning a UUID to the id column, ignore it def id=(new_id) return if new_id.to_s =~ BelongsToWithUuid::UUID_PATTERN super( new_id ) end end end
18.208333
67
0.675057
ddd4e0649a1fe6ade3f15033ec8d064da2d13f39
2,746
java
Java
faces-utils/src/main/java/org/qfast/omnifaces/util/Callback.java
amawaziny/utils
d6e59b53fd01cd8c4451592a5f42ce572da2f811
[ "Apache-2.0" ]
null
null
null
faces-utils/src/main/java/org/qfast/omnifaces/util/Callback.java
amawaziny/utils
d6e59b53fd01cd8c4451592a5f42ce572da2f811
[ "Apache-2.0" ]
null
null
null
faces-utils/src/main/java/org/qfast/omnifaces/util/Callback.java
amawaziny/utils
d6e59b53fd01cd8c4451592a5f42ce572da2f811
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012 OmniFaces. * * 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 org.qfast.omnifaces.util; /** * Collection of callback interfaces. Useful in (mini) visitor and strategy * patterns. * * @author Bauke Scholtz */ public final class Callback { // Constructors --------------------------------------------------------------------------------------------------- private Callback() { // Hide constructor. } // Interfaces ----------------------------------------------------------------------------------------------------- /** * Use this if you need a void callback. * * @author Bauke Scholtz */ public interface Void { /** * This method should be invoked by the method where you're passing this * callback instance to. */ void invoke(); } /** * Use this if you need a callback which returns a value. * * @author Bauke Scholtz * @param <R> The return type. */ public interface Returning<R> { /** * This method should be invoked by the method where you're passing this * callback instance to. * * @return The callback result. */ R invoke(); } /** * Use this if you need a callback which takes an argument. * * @author Bauke Scholtz * @param <A> The argument type. */ public interface WithArgument<A> { /** * This method should be invoked by the method where you're passing this * callback instance to. * * @param a The callback argument to work with. */ void invoke(A a); } /** * Use this if you need a callback which takes an argument and returns a * value. * * @author Bauke Scholtz * @param <R> The return type. * @param <A> The argument type. */ public interface ReturningWithArgument<R, A> { /** * This method should be invoked by the method where you're passing this * callback instance to. * * @param a The callback argument to work with. * @return The callback result. */ R invoke(A a); } }
28.604167
119
0.554261
c6a3fede4626bdc52e153a611c93135781fec00a
30,068
lua
Lua
config.lua
choi303/QBus-radialmenu
340cae5b91affc57ead5531c6731dc894545a170
[ "Apache-2.0" ]
7
2021-05-14T15:55:32.000Z
2022-01-11T17:59:59.000Z
config.lua
choi303/qb-radialmenu
340cae5b91affc57ead5531c6731dc894545a170
[ "Apache-2.0" ]
null
null
null
config.lua
choi303/qb-radialmenu
340cae5b91affc57ead5531c6731dc894545a170
[ "Apache-2.0" ]
null
null
null
Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, } Config = {} Config.MenuItems = { [1] = { id = 'citizen', title = 'Sivil', icon = '#citizen', items = { { id = 'givenum', title = 'Numara Ver', icon = '#nummer', type = 'client', event = 'qb-phone_new:client:GiveContactDetails', shouldClose = true, }, { id = 'getintrunk', title = 'Bagaja Gir', icon = '#vehiclekey', type = 'client', event = 'qb-trunk:client:GetIn', shouldClose = true, }, { id = 'cornerselling', title = 'Kose Satis', icon = '#cornerselling', type = 'client', event = 'qb-drugs:client:cornerselling', shouldClose = true, }, { id = 'togglehotdogsell', title = 'Hotdog Sat', icon = '#cornerselling', type = 'client', event = 'qb-hotdogjob:client:ToggleSell', shouldClose = true, }, { id = 'interactions', title = 'Etkilesimler', icon = '#illegal', items = { { id = 'handcuff', title = 'Kelepcele', icon = '#general', type = 'client', event = 'police:client:CuffPlayerSoft', shouldClose = true, }, { id = 'playerinvehicle', title = 'Araca koy', icon = '#general', type = 'client', event = 'police:client:PutPlayerInVehicle', shouldClose = true, }, { id = 'playeroutvehicle', title = 'Aractan Cikar', icon = '#general', type = 'client', event = 'police:client:SetPlayerOutVehicle', shouldClose = true, }, { id = 'stealplayer', title = 'Ara', icon = '#general', type = 'client', event = 'police:client:RobPlayer', shouldClose = true, }, { id = 'escort', title = 'Tasi', icon = '#general', type = 'client', event = 'police:client:KidnapPlayer', shouldClose = true, }, { id = 'escort2', title = 'Tasi2', icon = '#general', type = 'client', event = 'police:client:EscortPlayer', shouldClose = true, }, { id = 'escort554', title = 'Rehin al', icon = '#general', type = 'client', event = 'A5:Client:TakeHostage', shouldClose = true, }, } }, } }, [2] = { id = 'general', title = 'Genel', icon = '#general', items = { { id = 'house', title = 'Ev Etkilesimi', icon = '#house', items = { { id = 'givehousekey', title = 'Ev Anahtari Ver', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:giveHouseKey', shouldClose = true, items = {}, }, { id = 'removehousekey', title = 'Anahtar sil', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:removeHouseKey', shouldClose = true, items = {}, }, { id = 'togglelock', title = 'Kilit Ac/Kapa', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:toggleDoorlock', shouldClose = true, }, { id = 'decoratehouse', title = 'Evi Dekore et', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:decorate', shouldClose = true, }, { id = 'houseLocations', title = 'Ev Depo/dolap', icon = '#house', items = { { id = 'setstash', title = 'Depo', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:setLocation', shouldClose = true, }, { id = 'setoutift', title = 'Dolap', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:setLocation', shouldClose = true, }, { id = 'setlogout', title = 'Cikis', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:setLocation', shouldClose = true, }, } } } }, } }, [3] = { id = 'blips', title = 'Mekanlar', icon = '#mekan', items = { { id = 'tattoshop', title = 'Dövmeci Dükkanı', icon = '#dovme', type = 'client', event = 'qb-radialmenu:client:tattoShop', shouldClose = true, }, { id = 'barbershop', title = 'Berber Dükkanı', icon = '#kuafor', type = 'client', event = 'qb-radialmenu:client:barberShop', shouldClose = true, }, { id = 'garage', title = 'Garaj', icon = '#garaj', type = 'client', event = 'qb-radialmenu:client:garage', shouldClose = true, }, { id = 'gas', title = 'Benzin İstasyonu', icon = '#cam', type = 'client', event = 'qb-radialmenu:client:gas', shouldClose = true, }, { id = 'clothshop', title = 'Kıyafet Dükkanı', icon = '#kiyafet', type = 'client', event = 'qb-radialmenu:client:clothShop', shouldClose = true, }, { id = 'deleteblips', title = 'İşareti Kaldır', icon = '#iptal', type = 'client', event = 'qb-radialmenu:client:deleteblips', shouldClose = true, }, }, }, [4] = { id = 'jobinteractions', title = 'Meslek', icon = '#handshaking', items = {}, }, } Config.JobInteractions = { ["doctor"] = { { id = 'statuscheck', title = 'Kisiyi kontrol et', icon = '#general', type = 'client', event = 'hospital:client:CheckStatus', shouldClose = true, }, { id = 'treatwounds', title = 'Yaralari iyilestir', icon = '#general', type = 'client', event = 'hospital:client:TreatWounds', shouldClose = true, }, { id = 'reviveplayer', title = 'Yardim et', icon = '#general', type = 'client', event = 'hospital:client:RevivePlayer', shouldClose = true, }, { id = 'emergencybutton2', title = 'Acil Durum', icon = '#general', type = 'client', event = 'police:client:SendPoliceEmergencyAlert', shouldClose = true, }, { id = 'escort', title = 'Tasi', icon = '#general', type = 'client', event = 'police:client:EscortPlayer', shouldClose = true, }, { id = 'brancardoptions', title = 'Sedye', icon = '#vehicle', items = { { id = 'spawnbrancard', title = 'Sedye Cikart', icon = '#general', type = 'client', event = 'hospital:client:TakeBrancard', shouldClose = false, }, { id = 'despawnbrancard', title = 'Sedye Sok', icon = '#general', type = 'client', event = 'hospital:client:RemoveBrancard', shouldClose = false, }, }, }, }, ["ambulance"] = { { id = 'statuscheck', title = 'Kisiyi kontrol et', icon = '#general', type = 'client', event = 'hospital:client:CheckStatus', shouldClose = true, }, { id = 'treatwounds', title = 'Yaralari iyilestir', icon = '#general', type = 'client', event = 'hospital:client:TreatWounds', shouldClose = true, }, { id = 'emergencybutton2', title = 'Acil Yardim', icon = '#general', type = 'client', event = 'police:client:SendPoliceEmergencyAlert', shouldClose = true, }, { id = 'escort', title = 'Tasi', icon = '#general', type = 'client', event = 'police:client:EscortPlayer', shouldClose = true, }, { id = 'brancardoptions', title = 'Sedye', icon = '#vehicle', items = { { id = 'spawnbrancard', title = 'Sedye Cikart', icon = '#general', type = 'client', event = 'hospital:client:TakeBrancard', shouldClose = false, }, { id = 'despawnbrancard', title = 'Sedye Sok', icon = '#general', type = 'client', event = 'hospital:client:RemoveBrancard', shouldClose = false, }, }, }, }, ["taxi"] = { { id = 'togglemeter', title = 'Taksimetre Ac/Kapa', icon = '#general', type = 'client', event = 'qb-taxi:client:toggleMeter', shouldClose = false, }, { id = 'togglemouse', title = 'Taksimetre Calistir/Kapat', icon = '#general', type = 'client', event = 'qb-taxi:client:enableMeter', shouldClose = true, }, { id = 'npc_mission', title = 'NPC Görevi', icon = '#general', type = 'client', event = 'qb-taxi:client:DoTaxiNpc', shouldClose = true, }, }, ["tow"] = { { id = 'togglenpc', title = 'NPC Ac/kapa', icon = '#general', type = 'client', event = 'jobs:client:ToggleNpc', shouldClose = true, }, { id = 'towvehicle', title = 'Cekici arac', icon = '#vehicle', type = 'client', event = 'qb-tow:client:TowVehicle', shouldClose = true, }, }, ["police"] = { { id = 'emergencybutton', title = 'Acil Durum', icon = '#general', type = 'client', event = 'police:client:SendPoliceEmergencyAlert', shouldClose = true, }, { id = 'checkvehstatus', title = 'Arac Ayar Kontrolu', icon = '#vehiclekey', type = 'client', event = 'qb-tunerchip:server:TuneStatus', shouldClose = true, }, { id = 'resethouse', title = 'Ev kilidi resetle', icon = '#vehiclekey', type = 'client', event = 'qb-houses:client:ResetHouse', shouldClose = true, }, { id = 'takedriverlicense', title = 'Ehliyetini al', icon = '#vehicle', type = 'client', event = 'police:client:SeizeDriverLicense', shouldClose = true, }, { id = 'policeinteraction', title = 'Polis etkilesimleri', icon = '#house', items = { { id = 'statuscheck', title = 'Kisi kontrol', icon = '#general', type = 'client', event = 'hospital:client:CheckStatus', shouldClose = true, }, { id = 'checkstatus', title = 'Durum kontrol', icon = '#general', type = 'client', event = 'police:client:CheckStatus', shouldClose = true, }, { id = 'escort', title = 'Tasi', icon = '#general', type = 'client', event = 'police:client:EscortPlayer', shouldClose = true, }, { id = 'searchplayer', title = 'Ara', icon = '#general', type = 'client', event = 'police:client:SearchPlayer', shouldClose = true, }, { id = 'jailplayer', title = 'Hapis', icon = '#general', type = 'client', event = 'police:client:JailPlayer', shouldClose = true, }, } }, { id = 'policeobjects', title = 'Objeler', icon = '#house', items = { { id = 'spawnpion', title = 'Pion', icon = '#vehiclekey', type = 'client', event = 'police:client:spawnCone', shouldClose = false, }, { id = 'spawnhek', title = 'Cit', icon = '#vehiclekey', type = 'client', event = 'police:client:spawnBarier', shouldClose = false, }, { id = 'spawnschotten', title = 'Bariyer', icon = '#vehiclekey', type = 'client', event = 'police:client:spawnSchotten', shouldClose = false, }, { id = 'spawntent', title = 'Cadir', icon = '#vehiclekey', type = 'client', event = 'police:client:spawnTent', shouldClose = false, }, { id = 'spawnverlichting', title = 'Isik', icon = '#vehiclekey', type = 'client', event = 'police:client:spawnLight', shouldClose = false, }, { id = 'spikestrip', title = 'Yer teli', icon = '#vehiclekey', type = 'client', event = 'police:client:SpawnSpikeStrip', shouldClose = false, }, { id = 'deleteobject', title = 'Obje sil', icon = '#vehiclekey', type = 'client', event = 'police:client:deleteObject', shouldClose = false, }, } }, }, ["hotdog"] = { { id = 'togglesell', title = 'Satisi ac/kapa', icon = '#general', type = 'client', event = 'qb-hotdogjob:client:ToggleSell', shouldClose = true, }, }, -- ["taxi"] = { -- }, } Config.TrunkClasses = { [0] = { allowed = true, x = 0.0, y = -1.5, z = 0.0 }, --Coupes [1] = { allowed = true, x = 0.0, y = -2.0, z = 0.0 }, --Sedans [2] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --SUVs [3] = { allowed = true, x = 0.0, y = -1.5, z = 0.0 }, --Coupes [4] = { allowed = true, x = 0.0, y = -2.0, z = 0.0 }, --Muscle [5] = { allowed = true, x = 0.0, y = -2.0, z = 0.0 }, --Sports Classics [6] = { allowed = true, x = 0.0, y = -2.0, z = 0.0 }, --Sports [7] = { allowed = true, x = 0.0, y = -2.0, z = 0.0 }, --Super [8] = { allowed = false, x = 0.0, y = -1.0, z = 0.25 }, --Motorcycles [9] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Off-road [10] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Industrial [11] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Utility [12] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Vans [13] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Cycles [14] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Boats [15] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Helicopters [16] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Planes [17] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Service [18] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Emergency [19] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Military [20] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Commercial [21] = { allowed = true, x = 0.0, y = -1.0, z = 0.25 }, --Trains } Config.VehicleMenu = { [1] = { id = 'vehicle', title = 'Arac', icon = '#vehicle', items = { { id = 'vehicledoors', title = 'Arac kapilari', icon = '#vehicledoors', items = { { id = 'door0', title = 'On Sol', icon = '#leftdoor', type = 'client', event = 'qb-radialmenu:client:openDoor', shouldClose = false, }, { id = 'door4', title = 'Kaput', icon = '#idkaart', type = 'client', event = 'qb-radialmenu:client:openDoor', shouldClose = false, }, { id = 'door1', title = 'On sag', icon = '#rightdoor', type = 'client', event = 'qb-radialmenu:client:openDoor', shouldClose = false, }, { id = 'door3', title = 'Arka sag', icon = '#rightdoor', type = 'client', event = 'qb-radialmenu:client:openDoor', shouldClose = false, }, { id = 'door5', title = 'Bagaj', icon = '#idkaart', type = 'client', event = 'qb-radialmenu:client:openDoor', shouldClose = false, }, { id = 'door2', title = 'Sol Arka', icon = '#leftdoor', type = 'client', event = 'qb-radialmenu:client:openDoor', shouldClose = false, }, } }, { id = 'vehicleextras', title = 'Arac Ekstralari', icon = '#plus', items = { { id = 'extra1', title = 'Ekstra 1', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra2', title = 'Ekstra 2', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra3', title = 'Ekstra 3', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra4', title = 'Extra 4', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra5', title = 'Ekstra 5', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra6', title = 'Ekstra 6', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra7', title = 'Ekstra 7', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra8', title = 'Ekstra 8', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, { id = 'extra9', title = 'Ekstra 9', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:setExtra', shouldClose = false, }, } }, { id = 'vehicleseats', title = 'Arac koltuklari', icon = '#vehicledoors', items = { { id = 'door0', title = 'Surucu', icon = '#plus', type = 'client', event = 'qb-radialmenu:client:ChangeSeat', shouldClose = false, }, } }, }, }, [2] = { id = 'blips', title = 'Mekanlar', icon = '#mekan', items = { { id = 'tattoshop', title = 'Dövmeci Dükkanı', icon = '#dovme', type = 'client', event = 'qb-radialmenu:client:tattoShop', shouldClose = true, }, { id = 'barbershop', title = 'Berber Dükkanı', icon = '#kuafor', type = 'client', event = 'qb-radialmenu:client:barberShop', shouldClose = true, }, { id = 'garage', title = 'Garaj', icon = '#garaj', type = 'client', event = 'qb-radialmenu:client:garage', shouldClose = true, }, { id = 'gas', title = 'Benzin İstasyonu', icon = '#cam', type = 'client', event = 'qb-radialmenu:client:gas', shouldClose = true, }, { id = 'clothshop', title = 'Kıyafet Dükkanı', icon = '#kiyafet', type = 'client', event = 'qb-radialmenu:client:clothShop', shouldClose = true, }, { id = 'deleteblips', title = 'İşareti Kaldır', icon = '#iptal', type = 'client', event = 'qb-radialmenu:client:deleteblips', shouldClose = true, }, }, }, [3] = { id = 'jobinteractions', title = 'Meslek', icon = '#handshaking', items = {}, }, }
36.270205
179
0.311161
94c02279b87cca4bc40b396712978236a86270f6
4,341
kt
Kotlin
app/src/main/java/com/jx3box/ui/cms/AchievementAdapter.kt
JX3BOX/JX3BOX
6931ec7f5edc83595f6baeec3063fd9c18759c5f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jx3box/ui/cms/AchievementAdapter.kt
JX3BOX/JX3BOX
6931ec7f5edc83595f6baeec3063fd9c18759c5f
[ "Apache-2.0" ]
1
2020-09-20T08:14:35.000Z
2020-09-30T14:46:04.000Z
app/src/main/java/com/jx3box/ui/cms/AchievementAdapter.kt
JX3BOX/jx3box-android
6931ec7f5edc83595f6baeec3063fd9c18759c5f
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021. jx3box.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.jx3box.ui.cms import android.view.animation.DecelerateInterpolator import androidx.core.view.ViewCompat import androidx.recyclerview.widget.LinearLayoutManager import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder import com.jx3box.R import com.jx3box.data.net.model.AchievementEntity import com.jx3box.databinding.ItemAchievementBinding import com.jx3box.utils.gone import com.jx3box.utils.isVisible import com.jx3box.utils.visible /** * @author Carey * @date 2021/1/14 */ class AchievementAdapter : BaseQuickAdapter<AchievementEntity, BaseDataBindingHolder<ItemAchievementBinding>>( R.layout.item_achievement ) { override fun convert( holder: BaseDataBindingHolder<ItemAchievementBinding>, item: AchievementEntity ) { val dataBinding = holder.dataBinding dataBinding?.apply { data = item executePendingBindings() if (item.item != null) { rewardIcon.visible() } else { rewardIcon.gone() } if (item.postfixName.isNotBlank() || item.prefixName.isNotBlank()) { tvCJSubTitle.visible() } else { tvCJSubTitle.gone() } val seriesAchievementList = item.seriesAchievementList if (!seriesAchievementList.isNullOrEmpty()) { lineBottomLeft.visible() lineBottomRight.visible() imgPullMore.visible() val layoutManager = LinearLayoutManager(context) layoutManager.orientation = LinearLayoutManager.HORIZONTAL recyclerChild.layoutManager = layoutManager val seriesAdapter = SeriesAchievementAdapter() recyclerChild.adapter = seriesAdapter for (index in seriesAchievementList.indices) { seriesAchievementList[index].isChecked = false } seriesAchievementList[0].isChecked = true item.seriesId = null seriesAdapter.setList(seriesAchievementList) imgPullMore.rotation = 0f imgPullMore.setOnClickListener { if (recyclerChild.isVisible) { recyclerChild.gone() ViewCompat.animate(imgPullMore).setDuration(200) .setInterpolator(DecelerateInterpolator()) .rotation(0f) .start() } else { recyclerChild.visible() ViewCompat.animate(imgPullMore).setDuration(200) .setInterpolator(DecelerateInterpolator()) .rotation(180f) .start() } } seriesAdapter.setOnItemClickListener { _, _, position -> for (index in seriesAchievementList.indices) { seriesAchievementList[index].isChecked = false } seriesAchievementList[position].isChecked = true item.seriesId = position tvName.text = seriesAchievementList[position].name tvDesc.text = seriesAchievementList[position].shortDesc seriesAdapter.notifyDataSetChanged() } } else { recyclerChild.gone() lineBottomLeft.gone() lineBottomRight.gone() imgPullMore.gone() } } } }
39.825688
87
0.586501
b598c8703a1596b5f8e346470bf86597fbba4bb6
139
rb
Ruby
app/controllers/admins_controller.rb
jschnapper/forecasts
df7163edf8ce93e7793fe43966819f1ecf7feb5e
[ "MIT" ]
null
null
null
app/controllers/admins_controller.rb
jschnapper/forecasts
df7163edf8ce93e7793fe43966819f1ecf7feb5e
[ "MIT" ]
4
2021-10-01T03:37:41.000Z
2021-12-05T17:22:39.000Z
app/controllers/admins_controller.rb
jschnapper/forecasts
df7163edf8ce93e7793fe43966819f1ecf7feb5e
[ "MIT" ]
null
null
null
class AdminsController < ManagementController before_action -> { requires_at_least_role :admin } def index render :index end end
19.857143
52
0.76259
770f309f8bce4999886199fc8a31d2b76c38e79b
1,968
dart
Dart
lib/widgets/rate_widget.dart
wmfadel/Shelf
ad400035d52ff3a078934b5fef0be32d1cce6033
[ "Apache-2.0" ]
2
2021-11-25T10:52:38.000Z
2021-11-25T10:57:46.000Z
lib/widgets/rate_widget.dart
wmfadel/Shelf
ad400035d52ff3a078934b5fef0be32d1cce6033
[ "Apache-2.0" ]
null
null
null
lib/widgets/rate_widget.dart
wmfadel/Shelf
ad400035d52ff3a078934b5fef0be32d1cce6033
[ "Apache-2.0" ]
null
null
null
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; class RateWidget extends StatelessWidget { final bool isUp; final String userID; RateWidget({ required this.userID, required this.isUp, }); @override Widget build(BuildContext context) { return FutureBuilder<DocumentSnapshot>( future: FirebaseFirestore.instance.collection('users').doc(userID).get(), builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(); return RateBuild( snapshot.data?.get(isUp ? 'upVote' : 'downVote'), isUp, userID, ); }, ); } } // ignore: must_be_immutable class RateBuild extends StatefulWidget { int rate; final bool isUp; final String userID; RateBuild(this.rate, this.isUp, this.userID); @override _RateBuildState createState() => _RateBuildState(); } class _RateBuildState extends State<RateBuild> { @override Widget build(BuildContext context) { var children = [ Text( widget.rate.toString(), style: TextStyle( color: widget.isUp ? Colors.blueAccent : Colors.redAccent, fontSize: 25), ), SizedBox(height: 15), FloatingActionButton( heroTag: widget.isUp ? 'up' : 'down', onPressed: () async { FirebaseFirestore.instance .collection('users') .doc(widget.userID) .update({widget.isUp ? 'upVote' : 'downVote': (++widget.rate)}); setState(() {}); }, backgroundColor: widget.isUp ? Colors.blueAccent : Colors.redAccent, child: Icon(widget.isUp ? Icons.thumb_up : Icons.thumb_down), ), ]; return Column(children: [ if (widget.isUp) ...children, if (!widget.isUp) ...children.reversed ]); } }
27.71831
79
0.623984
7aa3c49612ee1104d3f5c9a02441205a29f119d5
2,234
cs
C#
examples/SimpleProducer/Program.cs
hsz-develop/confluent-kafka-dotnet--unity3d-uwp
45790d9af1fea47555f58ff611c103388a2d2d92
[ "Apache-2.0" ]
null
null
null
examples/SimpleProducer/Program.cs
hsz-develop/confluent-kafka-dotnet--unity3d-uwp
45790d9af1fea47555f58ff611c103388a2d2d92
[ "Apache-2.0" ]
null
null
null
examples/SimpleProducer/Program.cs
hsz-develop/confluent-kafka-dotnet--unity3d-uwp
45790d9af1fea47555f58ff611c103388a2d2d92
[ "Apache-2.0" ]
null
null
null
// Copyright 2016-2017 Confluent Inc., 2015-2016 Andreas Heider // // 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. // // Derived from: rdkafka-dotnet, licensed under the 2-clause BSD License. // // Refer to LICENSE for more information. using System; using System.Text; using System.Collections.Generic; using Confluent.Kafka.Serialization; namespace Confluent.Kafka.Examples.SimpleProducer { public class Program { public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: SimpleProducer brokerList topicName"); return; } string brokerList = args[0]; string topicName = args[1]; var config = new Dictionary<string, object> { { "bootstrap.servers", brokerList } }; using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8))) { Console.WriteLine($"{producer.Name} producing on {topicName}. q to exit."); string text; while ((text = Console.ReadLine()) != "q") { var deliveryReport = producer.ProduceAsync(topicName, null, text); deliveryReport.ContinueWith(task => { Console.WriteLine($"Partition: {task.Result.Partition}, Offset: {task.Result.Offset}"); }); } // Tasks are not waited on synchronously (ContinueWith is not synchronous), // so it's possible they may still in progress here. producer.Flush(TimeSpan.FromSeconds(10)); } } } }
35.460317
112
0.608774
58a4cc8bfade7bd9f434b74283683b26b36ec06b
1,870
go
Go
pkg/cli/context.go
fing-ir/fing-cli
2f85b36382217d0ca4f133908a32bc9c228b7a77
[ "Apache-2.0" ]
null
null
null
pkg/cli/context.go
fing-ir/fing-cli
2f85b36382217d0ca4f133908a32bc9c228b7a77
[ "Apache-2.0" ]
null
null
null
pkg/cli/context.go
fing-ir/fing-cli
2f85b36382217d0ca4f133908a32bc9c228b7a77
[ "Apache-2.0" ]
null
null
null
package cli import ( "fmt" "io" "github.com/fingcloud/cli/pkg/api" "github.com/fingcloud/cli/pkg/config/session" "github.com/fingcloud/cli/pkg/ui" "github.com/spf13/pflag" "github.com/thoas/go-funk" ) var ( Version = "v0.0.0-dev" BuildDate = "now" Commit = "commit" ) type Context struct { Stdout io.Writer Stderr io.Writer Client *api.Client APIServer string AccessToken string Auth string AskAuth bool Path string } func NewContext(out io.Writer, err io.Writer) *Context { return &Context{ Stdout: out, Stderr: err, } } func (c *Context) AddFlags(flags *pflag.FlagSet) { flags.StringVar(&c.AccessToken, "access-token", c.AccessToken, "access token for the API server authentication") flags.StringVar(&c.APIServer, "server", c.APIServer, "the address of the API server") flags.StringVar(&c.Auth, "auth", c.Auth, "specify auth account") flags.BoolVar(&c.AskAuth, "use-auth", c.AskAuth, "show logged in auth to use") } func stringptr(val string) *string { return &val } func (c *Context) SetupClient() error { var accessToken string if c.AskAuth { sessions, err := session.Read() if err != nil { return err } options := funk.Map(sessions, func(s *session.Session) string { return s.Email }).([]string) if err := ui.PromptSelect("select account", options, &c.Auth); err != nil { return err } } if c.Auth != "" { if err := session.UseSession(c.Auth); err != nil { return err } } sess, _ := session.CurrentSession() if sess != nil { accessToken = sess.Token } if c.AccessToken != "" { accessToken = c.AccessToken } opts := make([]api.Option, 0) opts = append(opts, api.WithUserAgent(fmt.Sprintf("fingcli/%s", Version))) if c.APIServer != "" { opts = append(opts, api.WithBaseURL(c.APIServer)) } c.Client = api.NewClient(accessToken, opts...) return nil }
20.549451
113
0.665775
cdc6c042887b1859a2c21fd507e5574e9a4cd689
2,374
cs
C#
mono-for-android/3.3.0.1/Pubnub-Messaging/Andr.Unit-master/Android.NUnitLite/AndrRunner/Elements/TestCaseElement.cs
goodybag/pubnub-api
7d37385f5dc58551c4e73674d35a26b0f239cc06
[ "MIT" ]
1
2017-01-18T07:05:38.000Z
2017-01-18T07:05:38.000Z
mono-for-android/3.3.0.1/Pubnub-Messaging/Andr.Unit-master/Android.NUnitLite/AndrRunner/Elements/TestCaseElement.cs
goodybag/pubnub-api
7d37385f5dc58551c4e73674d35a26b0f239cc06
[ "MIT" ]
null
null
null
mono-for-android/3.3.0.1/Pubnub-Messaging/Andr.Unit-master/Android.NUnitLite/AndrRunner/Elements/TestCaseElement.cs
goodybag/pubnub-api
7d37385f5dc58551c4e73674d35a26b0f239cc06
[ "MIT" ]
null
null
null
// // Copyright 2011-2012 Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using Android.App; using Android.Content; using Android.Views; using NUnitLite; namespace Android.NUnitLite.UI { class TestCaseElement : TestElement { public TestCaseElement (TestCase test) : base (test) { if (test.RunState == RunState.Runnable) Indicator = "..."; // hint there's more } protected override string GetCaption () { if (TestCase.RunState == RunState.Ignored) { return String.Format ("<b>{0}</b><br><font color='#FF7700'>{1}: {2}</font>", TestCase.Name, TestCase.RunState, TestCase.IgnoreReason); } else if (Result == null) { return String.Format ("<b>{0}</b><br><font color='grey'>{1}</font>", TestCase.Name, TestCase.RunState); } else if (Result.IsSuccess) { return String.Format ("<b>{0}</b><br><font color='green'>Success!</font>", TestCase.Name); } else { return String.Format ("<b>{0}</b><br><font color='red'>{1}</font>", TestCase.Name, Result.Message); } } public TestCase TestCase { get { return Test as TestCase; } } public override View GetView (Context context, View convertView, ViewGroup parent) { View view = base.GetView (context, convertView, parent); view.Click += delegate { if (TestCase.RunState != RunState.Runnable) return; AndroidRunner runner = AndroidRunner.Runner; if (!runner.OpenWriter ("Run " + TestCase.FullName, context)) return; try { TestCase.Run (runner); } finally { runner.CloseWriter (); } if (!Result.IsSuccess) { Intent intent = new Intent (context, typeof (TestResultActivity)); intent.PutExtra ("TestCase", Name); intent.AddFlags (ActivityFlags.NewTask); context.StartActivity (intent); } }; return view; } } }
29.308642
107
0.663437
0a6da40851c3673eee96717e630162b1804dc134
403
cs
C#
Gotcha/Models/WordWordset.cs
marcoduister/Gotcha-Casus
e0b2ff86ad0e52e83fa2a6d29670be48e5a3e551
[ "MIT" ]
null
null
null
Gotcha/Models/WordWordset.cs
marcoduister/Gotcha-Casus
e0b2ff86ad0e52e83fa2a6d29670be48e5a3e551
[ "MIT" ]
null
null
null
Gotcha/Models/WordWordset.cs
marcoduister/Gotcha-Casus
e0b2ff86ad0e52e83fa2a6d29670be48e5a3e551
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gotcha.Models { class WordWordset { //Atributte/property public Guid WordSet_Id { get; set; } public Guid Word_Id { get; set; } //Relations public Word Word { get; set; } public WordSet WordSet { get; set; } } }
18.318182
44
0.627792
8da3ad74392de3a86da3bda561ab6f21300af09d
108
js
JavaScript
lesson-001/ex001.js
MiguelMDSDP/learning-javascript
48d6ffa917d32d2aab27eef4bbda8b1868312663
[ "MIT" ]
null
null
null
lesson-001/ex001.js
MiguelMDSDP/learning-javascript
48d6ffa917d32d2aab27eef4bbda8b1868312663
[ "MIT" ]
null
null
null
lesson-001/ex001.js
MiguelMDSDP/learning-javascript
48d6ffa917d32d2aab27eef4bbda8b1868312663
[ "MIT" ]
null
null
null
window.alert("It's my first message"); window.confirm("Are you ready?"); window.prompt("What's your name?");
36
38
0.712963
387e5d2bf9d47c8a72c881b5285eb06997fceb37
1,818
php
PHP
src/Mapper/Plugin/ForceEntityReference/ForceEntityReferenceHandler.php
spaceonfire/cycle-bridge
aa5d7eed0b231c899c1b5bb4a541f1a1f21dcc14
[ "MIT" ]
null
null
null
src/Mapper/Plugin/ForceEntityReference/ForceEntityReferenceHandler.php
spaceonfire/cycle-bridge
aa5d7eed0b231c899c1b5bb4a541f1a1f21dcc14
[ "MIT" ]
null
null
null
src/Mapper/Plugin/ForceEntityReference/ForceEntityReferenceHandler.php
spaceonfire/cycle-bridge
aa5d7eed0b231c899c1b5bb4a541f1a1f21dcc14
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace spaceonfire\Bridge\Cycle\Mapper\Plugin\ForceEntityReference; use Cycle\ORM\ORMInterface; use Cycle\ORM\Relation; use Cycle\ORM\SchemaInterface; use spaceonfire\Bridge\Cycle\EntityReference; use spaceonfire\Bridge\Cycle\EntityReferenceFactory; use spaceonfire\Bridge\Cycle\Mapper\Plugin\HydrateBeforeEvent; final class ForceEntityReferenceHandler { private const TO_ONE_RELATIONS = [ Relation::EMBEDDED, Relation::HAS_ONE, Relation::BELONGS_TO, Relation::REFERS_TO, Relation::BELONGS_TO_MORPHED, Relation::MORPHED_HAS_ONE, ]; private ORMInterface $orm; public function __construct(ORMInterface $orm) { $this->orm = $orm; } public function onHydrate(HydrateBeforeEvent $event): void { $data = $event->getData(); $entity = $event->getEntity(); $role = $this->orm->resolveRole($entity); $referenceFactory = null; $relations = $this->orm->getSchema()->define($role, SchemaInterface::RELATIONS); /** * @phpstan-var string $relation * @phpstan-var array<int,mixed> $relationSchema */ foreach ($relations as $relation => $relationSchema) { if (!isset($data[$relation]) || !\is_object($data[$relation])) { continue; } if (!\in_array($relationSchema[Relation::TYPE], self::TO_ONE_RELATIONS, true)) { continue; } if ($data[$relation] instanceof EntityReference) { continue; } $referenceFactory ??= new EntityReferenceFactory(); $data[$relation] = $referenceFactory->promisize($this->orm, $data[$relation]); } $event->replaceData($data); } }
28.40625
92
0.617162
dd9b90430e431e3b662b1e8d30726e34412ac2bd
989
java
Java
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/TextCanvasElement.java
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
1
2016-08-23T10:29:44.000Z
2016-08-23T10:29:44.000Z
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/TextCanvasElement.java
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/TextCanvasElement.java
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
package org.glob3.mobile.generated; // // TextCanvasElement.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/12/13. // // // // TextCanvasElement.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/12/13. // // public class TextCanvasElement extends CanvasElement { private final String _text; private final GFont _font; private final Color _color ; public TextCanvasElement(String text, GFont font, Color color) { _text = text; _font = new GFont(font); _color = new Color(color); } public void dispose() { if (_font != null) _font.dispose(); super.dispose(); } public final Vector2F getExtent(ICanvas canvas) { canvas.setFont(_font); return canvas.textExtent(_text); } public final void drawAt(float left, float top, ICanvas canvas) { canvas.setFont(_font); canvas.setFillColor(_color); canvas.fillText(_text, left, top); } }
17.660714
66
0.624874
dab74a8be9b7da113868dd85ccc536ddbb0dbcae
2,940
php
PHP
app/UserAuth/Http/Middleware/AuthenticateSession.php
lsurma/laravel-auth-template
df3355fa62e4a2fda96d3b41c6434327879dff8f
[ "MIT" ]
1
2020-01-16T07:58:18.000Z
2020-01-16T07:58:18.000Z
app/UserAuth/Http/Middleware/AuthenticateSession.php
lsurma/laravel-auth-template
df3355fa62e4a2fda96d3b41c6434327879dff8f
[ "MIT" ]
null
null
null
app/UserAuth/Http/Middleware/AuthenticateSession.php
lsurma/laravel-auth-template
df3355fa62e4a2fda96d3b41c6434327879dff8f
[ "MIT" ]
null
null
null
<?php namespace App\UserAuth\Http\Middleware; use App\UserAuth\Common\Interfaces\HasSessionAuthInterface; use Closure; use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Factory as AuthFactory; /** * Based on Laravel middleware (\Illuminate\Session\Middleware\AuthenticateSession::class), but instead of password hash as our session identifier, * we will be using custom property called "session_auth_token" */ class AuthenticateSession { /** * The authentication factory implementation. * * @var \Illuminate\Auth\SessionGuard|\Illuminate\Contracts\Auth\Factory */ protected $auth; /** * Key under which session auth token will be stored * * @var string */ protected $sessionAttributeKey = 'session_auth_token'; /** * Create a new middleware instance. * * @param \Illuminate\Contracts\Auth\Factory $auth * @return void */ public function __construct(AuthFactory $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (! $request->hasSession() || ! $request->user()) { return $next($request); } if (! $request->session()->has($this->sessionAttributeKey)) { $this->storeSessionAuthToken($request); } if ($request->session()->get($this->sessionAttributeKey) !== $request->user()->getSessionAuthToken()) { $this->logout($request); } return tap($next($request), function () use ($request) { $this->storeSessionAuthToken($request); }); } /** * Store the user's current password hash in the session. * * @param \Illuminate\Http\Request $request * @return void */ protected function storeSessionAuthToken($request) { /** @var HasSessionAuthInterface $user */ $user = $request->user(); if (!$user) { return; } // Get user token, and check if its not falsey value // if it is, then regenerate token if(!$token = $user->getSessionAuthToken()) { $token = tap($user, function($user) { $user->regenerateSessionAuthToken(); })->getSessionAuthToken(); } $request->session()->put([ $this->sessionAttributeKey => $token, ]); } /** * Log the user out of the application. * * @param \Illuminate\Http\Request $request * @return void * * @throws \Illuminate\Auth\AuthenticationException */ protected function logout($request) { $this->auth->logoutCurrentDevice(); $request->session()->flush(); throw new AuthenticationException; } }
26.25
147
0.592177
ef5341b7fdebe0c984cddb1ad37e38cd66ded410
328
php
PHP
examples/edit_issue.php
danillofb/jira-api-restclient
3cc6dadd15d0ebc6873bf0158ce115b471142870
[ "MIT" ]
9
2015-12-27T19:00:15.000Z
2019-09-03T11:08:54.000Z
examples/edit_issue.php
danillofb/jira-api-restclient
3cc6dadd15d0ebc6873bf0158ce115b471142870
[ "MIT" ]
4
2016-01-04T14:44:06.000Z
2019-02-07T07:03:51.000Z
examples/edit_issue.php
danillofb/jira-api-restclient
3cc6dadd15d0ebc6873bf0158ce115b471142870
[ "MIT" ]
3
2015-12-29T18:01:06.000Z
2019-02-06T17:39:35.000Z
<?php require dirname(__FILE__) ."/common.php"; $api = getApiClient(); $updObj = new stdClass(); $updObj->customfield_10401 = [ ['set' => 'Value here'] ]; $r = $api->editIssue($key, [ "update" => $updObj ]); /* $api->editIssue($key, array( "fields" => array( "<FieldID>" => "Value" ), )); */
14.909091
41
0.52439
0a4c664b839df50823ee8452a1b2f537f2f7b47c
1,590
cs
C#
DragonSpark.Application/Entities/Queries/Composition/StartInput.cs
DragonSpark/Framework
6425e8178240bbabdcbecfe4288c977a29bf53ff
[ "MIT" ]
10
2017-03-08T07:38:44.000Z
2022-02-26T17:04:37.000Z
DragonSpark.Application/Entities/Queries/Composition/StartInput.cs
DragonSpark/Framework
6425e8178240bbabdcbecfe4288c977a29bf53ff
[ "MIT" ]
2
2017-11-04T09:26:33.000Z
2019-11-06T16:57:19.000Z
DragonSpark.Application/Entities/Queries/Composition/StartInput.cs
DragonSpark/Framework
6425e8178240bbabdcbecfe4288c977a29bf53ff
[ "MIT" ]
1
2017-10-21T12:58:29.000Z
2017-10-21T12:58:29.000Z
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Linq.Expressions; namespace DragonSpark.Application.Entities.Queries.Composition; public class StartInput<TIn, T> : StartInput<TIn, T, T> where T : class { protected StartInput(Expression<Func<DbContext, IQueryable<T>, IQueryable<T>>> instance) : base(instance) {} protected StartInput(Expression<Func<IQueryable<T>, IQueryable<T>>> instance) : base(instance) {} protected StartInput(Expression<Func<TIn, IQueryable<T>, IQueryable<T>>> instance) : base(instance) {} protected StartInput(Expression<Func<DbContext, TIn, IQueryable<T>>> previous, Expression<Func<DbContext, TIn, IQueryable<T>, IQueryable<T>>> instance) : base(previous, instance) {} } public class StartInput<TIn, T, TTo> : Combine<TIn, T, TTo> where T : class { protected StartInput(Expression<Func<DbContext, IQueryable<T>, IQueryable<TTo>>> instance) : base(Set<TIn, T>.Default, instance) {} protected StartInput(Expression<Func<IQueryable<T>, IQueryable<TTo>>> instance) : base(Set<TIn, T>.Default, instance) {} protected StartInput(Expression<Func<TIn, IQueryable<T>, IQueryable<TTo>>> instance) : base(Set<TIn, T>.Default, instance) {} protected StartInput(Expression<Func<DbContext, TIn, IQueryable<T>, IQueryable<TTo>>> instance) : base(Set<TIn, T>.Default, instance) {} protected StartInput(Expression<Func<DbContext, TIn, IQueryable<T>>> previous, Expression<Func<DbContext, TIn, IQueryable<T>, IQueryable<TTo>>> instance) : base(previous, instance) {} }
40.769231
103
0.725157
44591c961571bc4e7e09eba3facd17594e8b7ef7
298
py
Python
moe/bandit/bla/__init__.py
dstoeckel/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
[ "Apache-2.0" ]
966
2015-01-10T05:27:30.000Z
2022-03-26T21:04:36.000Z
moe/bandit/bla/__init__.py
dstoeckel/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
[ "Apache-2.0" ]
46
2015-01-16T22:33:08.000Z
2019-09-04T16:33:27.000Z
moe/bandit/bla/__init__.py
dstoeckel/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
[ "Apache-2.0" ]
143
2015-01-07T03:57:19.000Z
2022-02-28T01:10:45.000Z
# -*- coding: utf-8 -*- """Bandit directory containing multi-armed bandit implementations of BLA policies in python. **Files in this package** * :mod:`moe.bandit.bla.bla`: :class:`~moe.bandit.bla.bla.BLA` object for allocating bandit arms and choosing the winning arm based on BLA policy. """
29.8
92
0.721477
ef3700695d42b776b2c301b4d07dbf5233a78604
12,825
go
Go
lisp/parser/parser.go
nilium/skim
a54ad32948f2b3aa7876591031e7cd55fed00a04
[ "BSD-3-Clause" ]
null
null
null
lisp/parser/parser.go
nilium/skim
a54ad32948f2b3aa7876591031e7cd55fed00a04
[ "BSD-3-Clause" ]
4
2017-05-26T05:01:30.000Z
2017-06-19T02:08:40.000Z
lisp/parser/parser.go
nilium/skim
a54ad32948f2b3aa7876591031e7cd55fed00a04
[ "BSD-3-Clause" ]
1
2019-02-11T08:11:23.000Z
2019-02-11T08:11:23.000Z
package parser import ( "bytes" "errors" "fmt" "io" "strconv" "strings" "unicode" "unicode/utf8" "go.spiff.io/skim/lisp/skim" ) // nextfunc is a parsing function that modifies the decoder's state and returns another parsing // function. If nextfunc returns io.EOF, parsing is complete. Any other error halts parsing. type nextfunc func() (nextfunc, error) type scope struct { newPair func() *skim.Cons up *scope open bool // if true, requires a closing parenthesis head skim.Atom cdr *skim.Atom } func newScope(up *scope, open bool, newPair func() *skim.Cons) *scope { s := new(scope) s.reset(up, open, newPair) return s } func (s *scope) reset(up *scope, open bool, newPair func() *skim.Cons) { *s = scope{ newPair: newPair, up: up, open: open, head: nil, cdr: &s.head, } } func (s *scope) cons() skim.Atom { if s.head == nil { return s.newPair() } return s.head } func (s *scope) append(tip skim.Atom) { if v, ok := s.head.(skim.Vector); ok { s.head = append(v, tip) return } next := s.newPair() next.Car, *s.cdr, s.cdr = tip, next, &next.Cdr } // decoder is a wrapper around an io.Reader for the purpose of doing by-rune parsing of input. It // also holds enough state to track line, column, key prefixes (from sections), and errors. type decoder struct { rd io.Reader readrune func() (rune, int, error) err error current rune line, col int // Storage buffer bytes.Buffer key string // peek / next state havenext bool next rune nexterr error root scope last *scope pairbufSize int pairbufHead int pairbuf []skim.Cons } const ( rNewline = '\n' rComment = ';' rOpenParen = '(' rCloseParen = ')' rOpenBracket = '[' rCloseBracket = ']' rString = '"' rQuote = '\'' rBacktick = '`' rComma = ',' ) func (d *decoder) allocPair() *skim.Cons { sz := d.pairbufSize if sz == 1 { return new(skim.Cons) } head, buf := d.pairbufHead, d.pairbuf if head == len(buf) { head, buf = 0, make([]skim.Cons, sz) d.pairbuf = buf } d.pairbufHead = head + 1 return &buf[head] } func (d *decoder) readSyntax() (next nextfunc, err error) { if err = d.skipSpace(true); err != nil { return nil, err } else if d.err != nil { return nil, d.err } d.buffer.Reset() switch d.current { case rOpenParen: return d.readList() case rCloseParen: return d.closeList() case rComment: return d.readComment() case rQuote, rBacktick, rComma: return d.readLiteral() case rString: return d.readString() case rOpenBracket: return d.readVector() case rCloseBracket: return d.closeVector() default: return d.readSymbol() } return nil, d.syntaxerr(BadCharError(d.current)) } func (d *decoder) readHexCode(size int) (result rune, err error) { for i := 0; i < size; i++ { r, sz, err := d.nextRune() if err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return -1, d.syntaxerr(err, "expected hex code") } else if sz != 1 { // Quick size check return -1, d.syntaxerr(BadCharError(r), "expected hex code") } if r >= 'A' && r <= 'F' { r = 10 + (r - 'A') } else if r >= 'a' && r <= 'f' { r = 10 + (r - 'a') } else if r >= '0' && r <= '9' { r -= '0' } else { return -1, d.syntaxerr(BadCharError(r), "expected hex code") } result = result<<4 | r } return result, nil } func (d *decoder) readString() (next nextfunc, err error) { err = d.readUntilBuffer(runestr(`"\`)) if err == io.EOF { return nil, d.syntaxerr(UnclosedError('"'), "encountered EOF inside string") } else if err != nil { return nil, err } switch d.current { case '"': // done case '\\': r, _, err := d.nextRune() if err != nil { return nil, err } switch r { case 'x': // 1 octet r, err = d.readHexCode(2) d.buffer.WriteByte(byte(r & 0xFF)) case 'u': // 2 octets r, err = d.readHexCode(4) d.buffer.WriteRune(r) case 'U': // 4 octets r, err = d.readHexCode(8) d.buffer.WriteRune(r) default: d.buffer.WriteRune(escaped(r)) } return d.readString, err } d.last.append(skim.String(d.buffer.String())) if err = d.skip(); err == io.EOF { return nil, nil } return d.readSyntax, err } var sentinelRunes = runestr("()[]'\",`;") func isSymbolic(r rune) bool { return unicode.IsSpace(r) || sentinelRunes.Contains(r) } func (d *decoder) seal(force bool) (nextfunc, error) { for ; force || (d.last.up != nil && !d.last.open); force = false { a := d.last.cons() if a != nil { d.last.up.append(a) } d.last = d.last.up } return d.readSyntax, nil } func (d *decoder) close() (nextfunc, error) { if d.last.up == nil { return nil, d.syntaxerr(errors.New("cannot close current scope")) } return d.seal(true) } func (d *decoder) assign(a skim.Atom) (nextfunc, error) { d.last.append(a) return d.seal(false) } func (d *decoder) readSymbol() (next nextfunc, err error) { d.buffer.WriteRune(d.current) err = d.readUntilBuffer(runeFunc(isSymbolic)) if err == io.EOF { err = nil // handle it next time around } else if err != nil { return nil, err } txt := d.buffer.Bytes() // Try numbers { var ( n = len(txt) txt = txt first = txt[0] neg = first == '-' ) if neg || txt[0] == '+' { txt = txt[1:] if n--; n < 1 { goto symbol } first = txt[0] } zero := n > 0 && first == '0' if first == '.' { goto float } else if zero && n > 1 { var integer int64 switch second := txt[1]; second { case 'x': // hex (16) if integer, err = strconv.ParseInt(string(txt[2:]), 16, 64); err == nil { break } goto symbol case '0', '1', '2', '3', '4', '5', '6', '7': // octal (8) if integer, err = strconv.ParseInt(string(txt[1:]), 8, 64); err == nil { break } goto integer case '8', '9': goto integer case '.': goto float default: goto symbol } if neg { integer = -integer } return d.assign(skim.Int(integer)) } else if zero { return d.assign(skim.Int(0)) } integer: // base 10 if first < '0' || first > '9' { goto symbol } if integer, err := strconv.ParseInt(string(txt), 10, 64); err == nil { if neg { integer = -integer } return d.assign(skim.Int(integer)) } float: if fp, err := strconv.ParseFloat(string(txt), 64); err == nil { if neg { fp = -fp } return d.assign(skim.Float(fp)) } } symbol: var a skim.Atom if n := len(txt); txt[0] == '#' && n > 1 { switch second := txt[1]; { case n == 2 && (second == 't' || second == 'f'): a = skim.Bool(second == 't') case n == 4 && second == 'n': if txt[2] == 'i' && txt[3] == 'l' { a = nil break } fallthrough default: a = skim.Symbol(txt) } } else if n > 3 && d.current == '\n' && txt[2] == '<' && txt[1] == '<' && txt[0] == '<' { // HEREDOC end := make([]byte, n-3) copy(end, txt[3:]) d.buffer.Reset() for { err = d.readUntilBuffer(runeFunc(isSymbolic)) buf := d.buffer.Bytes() if (err == io.EOF || err == nil) && bytes.HasSuffix(buf, end) { buf = buf[:len(buf)-len(end)] if len(buf) == 0 || buf[len(buf)-1] == '\n' { a = skim.String(buf) break } } else if err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return nil, err } d.buffer.WriteRune(d.current) } } else { a = skim.Symbol(txt) } return d.assign(a) } func (d *decoder) closeVector() (next nextfunc, err error) { if _, ok := d.last.head.(skim.Vector); !ok || !d.last.open { return nil, d.syntaxerr(BadCharError(']')) } err = d.skip() if err == io.EOF { err = nil } else if err != nil { return nil, err } return d.close() } func (d *decoder) closeList() (next nextfunc, err error) { if _, ok := d.last.head.(*skim.Cons); (!ok && d.last.head != nil) || !d.last.open { return nil, d.syntaxerr(BadCharError(')')) } err = d.skip() if err == io.EOF { err = nil } else if err != nil { return nil, err } return d.close() } func (d *decoder) unimplemented() (nextfunc, error) { return nil, errors.New("unimplemented") } func (d *decoder) readList() (next nextfunc, err error) { d.push(scopeBraced) return d.readSyntax, d.skip() } func (d *decoder) readVector() (next nextfunc, err error) { d.push(scopeBraced) d.last.head = skim.Vector{} return d.readSyntax, d.skip() } func (d *decoder) push(open bool) *scope { s := newScope(d.last, open, d.allocPair) d.last = s return d.last } const scopeBraced = true const scopeQuoted = false func (d *decoder) readLiteral() (next nextfunc, err error) { sym := skim.Quote switch d.current { case rBacktick: sym = skim.Quasiquote case rComma: sym = skim.Unquote } // ok: d.push(scopeQuoted) d.last.append(sym) return d.readSyntax, d.skip() } func (d *decoder) start() (next nextfunc, err error) { _, _, err = d.nextRune() if err == io.EOF { return nil, nil } return d.readSyntax, err } func (d *decoder) readComment() (next nextfunc, err error) { if err = d.readUntilBuffer(oneRune(rNewline)); err == io.EOF { return nil, nil } return d.readSyntax, err } func (d *decoder) reset(r io.Reader) { const ( defaultPairbufSize = 16 defaultBufferCap = 64 ) d.root.reset(nil, false, d.allocPair) d.root.head = skim.Vector(nil) d.last = &d.root if rx, ok := r.(runeReader); ok { d.readrune = rx.ReadRune } else { d.readrune = nil } d.rd = r d.err = nil d.current = 0 d.line = 1 d.col = 0 d.buffer.Reset() d.buffer.Grow(defaultBufferCap) d.havenext = false d.nexterr = nil if d.pairbufSize <= 0 { d.pairbufSize = defaultPairbufSize } d.pairbufHead, d.pairbuf = 0, nil } func Read(r io.Reader) (skim.Vector, error) { var dec decoder return dec.Read(r) } func (d *decoder) Read(r io.Reader) (skim.Vector, error) { d.reset(r) if err := d.read(); err != nil { return nil, err } root := d.root.cons() d.root, d.last = scope{head: skim.Vector(nil)}, &d.root d.buffer.Reset() d.pairbufHead, d.pairbuf = 0, nil return root.(skim.Vector), nil } func (d *decoder) read() (err error) { defer func() { rc := recover() if perr, ok := rc.(error); ok { err = perr } else if rc != nil { err = fmt.Errorf("skim: panic: %v", rc) } if err == io.EOF { err = io.ErrUnexpectedEOF } }() var next nextfunc = d.start for next != nil && err == nil { next, err = next() } if err == io.EOF && d.last == &d.root { err = nil } return err } func (d *decoder) syntaxerr(err error, msg ...interface{}) *SyntaxError { if se, ok := err.(*SyntaxError); ok { return se } se := &SyntaxError{Line: d.line, Col: d.col, Err: err, Desc: fmt.Sprint(msg...)} return se } func isHorizSpace(r rune) bool { return r == ' ' || r == '\t' || r == '\r' } func (d *decoder) skipSpace(newlines bool) (err error) { fn := unicode.IsSpace if !newlines { fn = isHorizSpace } if !fn(d.current) { return nil } var r rune for { r, _, err = d.nextRune() if err != nil { return err } else if !fn(r) { return nil } } return err } func (d *decoder) nextRune() (r rune, size int, err error) { if d.err != nil { return 0, 1, d.err } if d.readrune != nil { r, size, err = d.readrune() } else { // slow fallback r, size, err = readrune(d.rd) } d.current = r if err != nil { d.err = err d.rd = nil } if d.current == '\n' { d.line++ d.col = 1 } return r, size, err } func (d *decoder) skip() error { _, _, err := d.nextRune() return err } func (d *decoder) readUntilBuffer(oneof runeset) (err error) { var r rune for out := &d.buffer; ; { r, _, err = d.nextRune() if err != nil { return err } else if oneof.Contains(r) { return nil } out.WriteRune(r) } } // Rune handling type runeReader interface { ReadRune() (rune, int, error) } func readrune(rd io.Reader) (r rune, size int, err error) { if rd, ok := rd.(runeReader); ok { return rd.ReadRune() } var b [4]byte for i, t := 0, 1; i < len(b); i, t = i+1, t+1 { _, err = rd.Read(b[i:t]) if err != nil { return r, size, err } else if c := b[:t]; utf8.FullRune(c) { r, size = utf8.DecodeRune(c) return r, size, err } } return unicode.ReplacementChar, 1, nil } type ( runeset interface { Contains(rune) bool } oneRune rune runeFunc func(rune) bool runestr string ) func (s runestr) Contains(r rune) bool { return strings.ContainsRune(string(s), r) } func (fn runeFunc) Contains(r rune) bool { return fn(r) } func (lhs oneRune) Contains(rhs rune) bool { return rune(lhs) == rhs } func escaped(r rune) rune { switch r { case '0': return 0 case 'a': return '\a' case 'b': return '\b' case 'f': return '\f' case 'n': return '\n' case 'r': return '\r' case 't': return '\t' case 'v': return '\v' default: return r } }
19.227886
97
0.592203
2a6d34736ea146609bbc0681b17dbc5010c5eb36
3,059
kt
Kotlin
src/main/kotlin/notifications/handler/RegistrationHandler.kt
MarcelBraghetto/AmazonSNSDemo
74b1a7064baa4b1af0184c7751c7df697cf6b842
[ "MIT" ]
2
2019-06-12T14:26:33.000Z
2021-12-02T17:43:42.000Z
src/main/kotlin/notifications/handler/RegistrationHandler.kt
MarcelBraghetto/AmazonSNSDemo
74b1a7064baa4b1af0184c7751c7df697cf6b842
[ "MIT" ]
null
null
null
src/main/kotlin/notifications/handler/RegistrationHandler.kt
MarcelBraghetto/AmazonSNSDemo
74b1a7064baa4b1af0184c7751c7df697cf6b842
[ "MIT" ]
1
2021-02-25T05:19:48.000Z
2021-02-25T05:19:48.000Z
/* MIT License Copyright (c) 2017 Marcel Braghetto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package notifications.handler import notifications.amazon.Amazon import notifications.framework.Platform import notifications.framework.ResponseBuilder import notifications.framework.parse import javax.ws.rs.Consumes import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response /** * This handler demonstrates how a client device could 'register' itself to our server with its push * notification token. Because Amazon requires knowledge of which platform tokens belong to, the client * needs to supply its platform on registration. * * In this example, we are simulating a particular 'userId' registering, to create an association to * a pretend 'user' with the given push notification token. */ @Path("/register") class RegistrationHandler { data class RequestBody(val platform: String, val userId: String, val token: String) @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) fun registerToken(json: String): Response { json.parse<RequestBody>()?.run { return when (platform) { Platform.IOS.jsonKey -> if (Amazon.registerEndPoint(Platform.IOS, userId, token)) { ResponseBuilder.success("iOS token registered successfully") } else { ResponseBuilder.internalServerError("iOS token failed to update") } Platform.ANDROID.jsonKey -> if (Amazon.registerEndPoint(Platform.ANDROID, userId, token)) { ResponseBuilder.success("Android token registered successfully") } else { ResponseBuilder.internalServerError("Android token failed to update") } else -> ResponseBuilder.badRequest("Missing valid platform type") } } return ResponseBuilder.badRequest("Bad registration request or request") } }
40.786667
107
0.729323
0c9818253b0b668f71e5179edb6b7d324ffdd07a
1,441
lua
Lua
FXServer_ESX/resources/[ESX]/[other]/esx_boat/locales/en.lua
Memor1es/VoidRP-FIveM-Server
ac534194afcc83667434b2facbada8909d16e62e
[ "Apache-2.0" ]
null
null
null
FXServer_ESX/resources/[ESX]/[other]/esx_boat/locales/en.lua
Memor1es/VoidRP-FIveM-Server
ac534194afcc83667434b2facbada8909d16e62e
[ "Apache-2.0" ]
9
2020-10-20T08:16:52.000Z
2020-12-04T22:06:27.000Z
server-data/resources/[esx]/[core_functions]/esx_boat/locales/en.lua
ZwinkaDink/FoxDev-FiveM-Dev-Server
3c1868ffa8eab0b20307d9353c5ca21b4b3d7354
[ "MIT" ]
1
2020-08-05T16:42:19.000Z
2020-08-05T16:42:19.000Z
Locales['en'] = { -- shop ['boat_shop'] = 'boat shop', ['boat_shop_open'] = 'press ~INPUT_CONTEXT~ to access the ~y~boat shop~s~.', ['boat_shop_confirm'] = 'buy <span style="color: yellow;">%s</span> for <span style="color: orange;">$%s</span>?', ['boat_shop_bought'] = 'you have ~y~bought~s~ a ~b~%s~s~ for ~g~$%s~s~', ['boat_shop_nomoney'] = 'you cannot ~r~afford~s~ this boat!', ['confirm_no'] = 'no', ['confirm_yes'] = 'yes', -- garage ['garage'] = 'boat garage', ['garage_open'] = 'press ~INPUT_CONTEXT~ to access your ~y~boat garage~s~.', ['garage_store'] = 'press ~INPUT_CONTEXT~ to ~y~store~s~ the boat in your garage.', ['garage_taken'] = 'the boat has been taken out!', ['garage_stored'] = 'the boat has been safely stored in your garage!', ['garage_noboats'] = 'you don\'t have any stored boats! Visit the ~y~boat shop~s~ to buy one.', ['garage_blocked'] = 'the boat cannot be taken out because another vehicle is blocking the spawn point!', ['garage_notowner'] = 'you don\'t own this boat!', -- license ['license_menu'] = 'buy Boat License?', ['license_buy_no'] = 'no', ['license_buy_yes'] = 'buy Boat License <span style="color: green;">$%s</span>', ['license_bought'] = 'you have bought the ~y~Boat License~s~ for ~g~$%s~s~', ['license_nomoney'] = 'you cannot ~r~afford~s~ the ~y~Boat License~s~!', -- blips ['blip_garage'] = 'boat Garage', ['blip_shop'] = 'boat Shop', }
45.03125
116
0.627342
c402b271c528f3f30ac1d07b1a9ade6e3719f17d
1,291
cpp
C++
ml_belowzerosrc/src/sys/_windows/msys_debugOS.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
20
2017-12-12T16:37:25.000Z
2022-02-19T10:35:46.000Z
ml_noisecorpsesrc/src/sys/_windows/msys_debugOS.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
null
null
null
ml_noisecorpsesrc/src/sys/_windows/msys_debugOS.cpp
mudlord/demos
359bada56a27ddbd4fcb846c0ff34bc474cb7f05
[ "Unlicense" ]
7
2017-12-29T23:19:18.000Z
2021-08-17T09:53:15.000Z
//--------------------------------------------------------------------------// // iq . 2003/2008 . code for 64 kb intros by RGBA // //--------------------------------------------------------------------------// #ifdef DEBUG #include <windows.h> #include <stdio.h> #include <stdarg.h> #include "../msys_debug.h" static FILE *fp; int msys_debugInit( void ) { fp = fopen( "debug.txt", "wt" ); if( !fp ) return( 0 ); fprintf( fp, "debug file\n" ); fprintf( fp, "-------------------------\n" ); fflush( fp ); return( 1 ); } void msys_debugEnd( void ) { fprintf( fp, "-------------------------\n" ); fflush( fp ); fclose( fp ); } void msys_debugPrintf( char *format, ... ) { va_list arglist; va_start( arglist, format ); vfprintf( fp, format, arglist ); fflush( fp ); va_end( arglist ); } void msys_debugCheckfor( bool expression, char *format, ... ) { char str[1024]; if( !expression ) { va_list arglist; va_start( arglist, format ); vsprintf( str, format, arglist ); va_end( arglist ); msys_debugHaltProgram( str ); } } void msys_debugHaltProgram( char *str ) { MessageBox( 0, str, "error", MB_OK ); DebugBreak(); } #endif
19.861538
78
0.464756
7c04df68b810abc881e1b5f71198af808205717a
1,213
py
Python
gen_shuangpin_dict.py
anselmwang/obsidian-vim-multibyte-char-search
18f89d09ca451bc7109da5e74ace2a2523426674
[ "MIT" ]
null
null
null
gen_shuangpin_dict.py
anselmwang/obsidian-vim-multibyte-char-search
18f89d09ca451bc7109da5e74ace2a2523426674
[ "MIT" ]
null
null
null
gen_shuangpin_dict.py
anselmwang/obsidian-vim-multibyte-char-search
18f89d09ca451bc7109da5e74ace2a2523426674
[ "MIT" ]
null
null
null
import pypinyin SHENGMU_DIC = { "zh": "v", "ch": "i", "sh": "u" } INPUT_PATH = "pinyin_search.dict.txt" OUTPUT_PATH = "shuangpin_search.dict.txt" # DATA_ROOT_PATH = r"C:\temp\test_obsidian_plugin\.obsidian\plugins\obsidian-vimrc-support" # import os # INPUT_PATH = os.path.join(DATA_ROOT_PATH, INPUT_PATH) # OUTPUT_PATH = os.path.join(DATA_ROOT_PATH, OUTPUT_PATH) meet_first_chinese_char = False with open(OUTPUT_PATH, "w", encoding="utf-8") as out_f: for line in open(INPUT_PATH, encoding="utf-8"): if line.startswith("的"): meet_first_chinese_char = True if not meet_first_chinese_char: out_f.write(line) else: ch = line[0] shengmu_set = set() for pinyin in pypinyin.pinyin(ch, style=pypinyin.Style.TONE3, heteronym=True)[0]: if pinyin[0] in ('a', 'e', 'o'): shengmu = 'o' elif pinyin[:2] in SHENGMU_DIC: shengmu = SHENGMU_DIC[pinyin[:2]] else: shengmu = pinyin[0] shengmu_set.add(shengmu) shengmu_str = "".join(shengmu_set) out_f.write(f"{ch} {shengmu_str}\n")
35.676471
93
0.584501
a360f1282f816f44d2e3a1cbc66ca6ea8fa2fa7b
9,837
java
Java
apps/UnifiedEmail/src/com/android/mail/drawer/DrawerItem.java
Keneral/apackages
af6a7ffde2e52d8d4e073b4030244551246248ad
[ "Unlicense" ]
null
null
null
apps/UnifiedEmail/src/com/android/mail/drawer/DrawerItem.java
Keneral/apackages
af6a7ffde2e52d8d4e073b4030244551246248ad
[ "Unlicense" ]
null
null
null
apps/UnifiedEmail/src/com/android/mail/drawer/DrawerItem.java
Keneral/apackages
af6a7ffde2e52d8d4e073b4030244551246248ad
[ "Unlicense" ]
null
null
null
/* * Copyright (C) 2013 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.mail.drawer; import android.support.annotation.IntDef; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.bitmap.BitmapCache; import com.android.mail.bitmap.ContactResolver; import com.android.mail.providers.Account; import com.android.mail.providers.Folder; import com.android.mail.ui.ControllableActivity; import com.android.mail.ui.FolderListFragment; import com.android.mail.utils.FolderUri; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * An element that is shown in the {@link com.android.mail.ui.FolderListFragment}. This class is * only used for elements that are shown in the {@link com.android.mail.ui.DrawerFragment}. * This class is an enumeration of a few element types: Account, a folder, a recent folder, * or a header (a resource string). A {@link DrawerItem} can only be one type and can never * switch types. Items are created using methods like * {@link DrawerItem#ofAccount(ControllableActivity, Account, int, boolean, BitmapCache, * ContactResolver)}, * {@link DrawerItem#ofWaitView(ControllableActivity)}, etc. * * Once created, the item can create a view using * {@link #getView(android.view.View, android.view.ViewGroup)}. */ public abstract class DrawerItem { public final Folder mFolder; public final Account mAccount; /** These are view types for view recycling purposes */ @Retention(RetentionPolicy.CLASS) @IntDef({VIEW_FOLDER, VIEW_HEADER, VIEW_BLANK_HEADER, VIEW_BOTTOM_SPACE, VIEW_ACCOUNT, VIEW_WAITING_FOR_SYNC, VIEW_FOOTER_HELP, VIEW_FOOTER_SETTINGS}) public @interface DrawerItemType {} /** A normal folder, also a child, if a parent is specified. */ public static final int VIEW_FOLDER = 0; /** A text-label which serves as a header in sectioned lists. */ public static final int VIEW_HEADER = 1; /** A blank divider which serves as a header in sectioned lists. */ public static final int VIEW_BLANK_HEADER = 2; /** A spacer which serves as a footer below the last item. */ public static final int VIEW_BOTTOM_SPACE = 3; /** An account object, which allows switching accounts rather than folders. */ public static final int VIEW_ACCOUNT = 4; /** An expandable object for expanding/collapsing more of the list */ public static final int VIEW_WAITING_FOR_SYNC = 5; /** A footer item for Help */ public static final int VIEW_FOOTER_HELP = 6; /** A footer item for Settings */ public static final int VIEW_FOOTER_SETTINGS = 7; /** The value (1-indexed) of the last View type. Useful when returning the number of types. */ private static final int LAST_FIELD = VIEW_FOOTER_SETTINGS + 1; /** The parent activity */ protected final ControllableActivity mActivity; protected final LayoutInflater mInflater; /** * These values determine the behavior of the drawer items. * * Either {@link #FOLDER_INBOX}, {@link #FOLDER_RECENT} or {@link #FOLDER_OTHER} when * {@link #getType()} is {@link #VIEW_FOLDER}, or {@link #NONFOLDER_ITEM} otherwise. */ @Retention(RetentionPolicy.CLASS) @IntDef({UNSET, NONFOLDER_ITEM, FOLDER_INBOX, FOLDER_RECENT, FOLDER_OTHER}) public @interface DrawerItemCategory {} public final @DrawerItemCategory int mItemCategory; /** Non existent item or folder type not yet set */ public static final int UNSET = 0; /** An unclickable text-header visually separating the different types. */ public static final int NONFOLDER_ITEM = 0; /** An inbox folder: Inbox, ...*/ public static final int FOLDER_INBOX = 1; /** A folder from whom a conversation was recently viewed */ public static final int FOLDER_RECENT = 2; /** A non-inbox folder that is shown in the "everything else" group. */ public static final int FOLDER_OTHER = 3; /** * Creates a drawer item with every instance variable specified. * * @param activity the underlying activity * @param folder a non-null folder, if this is a folder type * @param itemCategory the type of the folder. For folders this is: * {@link #FOLDER_INBOX}, {@link #FOLDER_RECENT}, {@link #FOLDER_OTHER}, * or for non-folders this is {@link #NONFOLDER_ITEM} * @param account the account object, for an account drawer element */ protected DrawerItem(ControllableActivity activity, Folder folder, @DrawerItemCategory int itemCategory, Account account) { mActivity = activity; mFolder = folder; mItemCategory = itemCategory; mAccount = account; mInflater = LayoutInflater.from(activity.getActivityContext()); } /** * Create a folder item with the given type. * * @param activity the underlying activity * @param folder a folder that this item represents * @param itemCategory one of {@link #FOLDER_INBOX}, {@link #FOLDER_RECENT} or * {@link #FOLDER_OTHER} * @return a drawer item for the folder. */ public static DrawerItem ofFolder(ControllableActivity activity, Folder folder, @DrawerItemCategory int itemCategory) { return new FolderDrawerItem(activity, folder, itemCategory); } /** * Creates an item from an account. * @param activity the underlying activity * @param account the account to create a drawer item for * @param unreadCount the unread count of the account, pass zero if * @param isCurrentAccount true if the account is the current account, false otherwise * @return a drawer item for the account. */ public static DrawerItem ofAccount(ControllableActivity activity, Account account, int unreadCount, boolean isCurrentAccount, BitmapCache cache, ContactResolver contactResolver) { return new AccountDrawerItem(activity, account, unreadCount, isCurrentAccount, cache, contactResolver); } /** * Create a header item with a string resource. * * @param activity the underlying activity * @param resource the string resource: R.string.all_folders_heading * @return a drawer item for the header. */ public static DrawerItem ofHeader(ControllableActivity activity, int resource) { return new HeaderDrawerItem(activity, resource); } public static DrawerItem ofBlankHeader(ControllableActivity activity) { return new BlankHeaderDrawerItem(activity); } public static DrawerItem ofBottomSpace(ControllableActivity activity) { return new BottomSpaceDrawerItem(activity); } /** * Create a "waiting for initialization" item. * * @param activity the underlying activity * @return a drawer item with an indeterminate progress indicator. */ public static DrawerItem ofWaitView(ControllableActivity activity) { return new WaitViewDrawerItem(activity); } public static DrawerItem ofHelpItem(ControllableActivity activity, Account account, FolderListFragment.DrawerStateListener drawerListener) { return new HelpItem(activity, account, drawerListener); } public static DrawerItem ofSettingsItem(ControllableActivity activity, Account account, FolderListFragment.DrawerStateListener drawerListener) { return new SettingsItem(activity, account, drawerListener); } /** * Returns a view for the given item. The method signature is identical to that required by a * {@link android.widget.ListAdapter#getView(int, android.view.View, android.view.ViewGroup)}. */ public abstract View getView(View convertView, ViewGroup parent); /** * Book-keeping for how many different view types there are. * @return number of different types of view items */ public static int getViewTypeCount() { return LAST_FIELD; } /** * Returns whether this view is enabled or not. An enabled view is one that accepts user taps * and acts upon them. * @return true if this view is enabled, false otherwise. */ public abstract boolean isItemEnabled(); /** * Returns whether this view is highlighted or not. * * * @param currentFolder The current folder, according to the * {@link com.android.mail.ui.FolderListFragment} * @param currentType The type of the current folder. We want to only highlight a folder once. * A folder might be in two places at once: in "All Folders", and in * "Recent Folder". Valid types of selected folders are : * {@link DrawerItem#FOLDER_INBOX}, {@link DrawerItem#FOLDER_RECENT} or * {@link DrawerItem#FOLDER_OTHER}, or {@link DrawerItem#UNSET}. * @return true if this DrawerItem results in a view that is highlighted (this DrawerItem is * the current folder. */ public abstract boolean isHighlighted(FolderUri currentFolder, int currentType); public abstract @DrawerItemType int getType(); public void onClick(View v) {} }
42.400862
99
0.6994
f1b4553674e1732e681beb5a7f6b1320ad2f6362
8,603
rb
Ruby
lib/orka_api_client/models/vm_configuration.rb
Homebrew/orka_api_client
5dd6d1e6ae6dbba10ba1a8e20e2c3d06e74a983b
[ "BSD-2-Clause" ]
null
null
null
lib/orka_api_client/models/vm_configuration.rb
Homebrew/orka_api_client
5dd6d1e6ae6dbba10ba1a8e20e2c3d06e74a983b
[ "BSD-2-Clause" ]
null
null
null
lib/orka_api_client/models/vm_configuration.rb
Homebrew/orka_api_client
5dd6d1e6ae6dbba10ba1a8e20e2c3d06e74a983b
[ "BSD-2-Clause" ]
1
2022-03-05T09:09:44.000Z
2022-03-05T09:09:44.000Z
# frozen_string_literal: true require_relative "lazy_model" module OrkaAPI module Models # A template configuration (a container template) consisting of a # {https://orkadocs.macstadium.com/docs/orka-glossary#base-image base image}, a # {https://orkadocs.macstadium.com/docs/orka-glossary#snapshot-image snapshot image}, and the number of CPU cores # to be used. To become a VM that you can run in the cloud, a VM configuration needs to be deployed to a {Node # node}. # # You can deploy multiple VMs from a single VM configuration. Once created, you can no longer modify a VM # configuration. # # Deleting a VM does not delete the VM configuration it was deployed from. class VMConfiguration < LazyModel # @return [String] The name of this VM configuration. attr_reader :name # @return [User] The owner of this VM configuration, i.e. the user which deployed it. lazy_attr :owner # @return [Image] The base image which newly deployed VMs of this configuration will boot from. lazy_attr :base_image # @return [Integer] The number of CPU cores to allocate to deployed VMs of this configuration. lazy_attr :cpu_cores # @return [ISO] The ISO to attach to deployed VMs of this configuration. lazy_attr :iso_image # @return [Image] The storage disk image to attach to deployed VMs of this configuration. lazy_attr :attached_disk # @return [Boolean] True if the VNC console should be enabled for deployed VMs of this configuration. lazy_attr :vnc_console? # @return [Boolean] True if IO boost should be enabled for deployed VMs of this configuration. lazy_attr :io_boost? # @return [Boolean] True if deployed VMs of this configuration should use a prior saved state (created via # {VMInstance#save_state}) rather than a clean base image. lazy_attr :use_saved_state? # @return [Boolean] True if GPU passthrough should be enabled for deployed VMs of this configuration. lazy_attr :gpu_passthrough? # @api private # @param [String] name # @param [Connection] conn # @return [VMConfiguration] def self.lazy_prepare(name:, conn:) new(conn: conn, name: name) end # @api private # @param [Hash] hash # @param [Connection] conn # @return [VMConfiguration] def self.from_hash(hash, conn:) new(conn: conn, hash: hash) end # @private # @param [Connection] conn # @param [String] name # @param [Hash] hash def initialize(conn:, name: nil, hash: nil) super(!hash.nil?) @conn = conn @name = name deserialize(hash) if hash end # Deploy the VM configuration to a node. If you don't specify a node, Orka chooses a node based on the # available resources. # # @macro auth_token # # @param [Node, String] node The node on which to deploy the VM. The node must have sufficient CPU and memory # to accommodate the VM. # @param [Integer] replicas The scale at which to deploy the VM configuration. If not specified, defaults to # +1+ (non-scaled). # @param [Array<PortMapping>] reserved_ports One or more port mappings that enable additional ports on your VM. # @param [Boolean] iso_install Set to +true+ if you want to use an ISO. # @param [Models::ISO, String] iso_image An ISO to attach to the VM during deployment. If already set in the # respective VM configuration and not set here, Orka applies the setting from the VM configuration. You can # also use this field to override any ISO specified in the VM configuration. # @param [Boolean] attach_disk Set to +true+ if you want to attach additional storage during deployment. # @param [Models::Image, String] attached_disk An additional storage disk to attach to the VM during # deployment. If already set in the respective VM configuration and not set here, Orka applies the setting # from the VM configuration. You can also use this field to override any storage specified in the VM # configuration. # @param [Boolean] vnc_console Enables or disables VNC for the VM. If not set in the VM configuration or here, # defaults to +true+. If already set in the respective VM configuration and not set here, Orka applies the # setting from the VM configuration. You can also use this field to override the VNC setting specified in the # VM configuration. # @param [Hash{String => String}] vm_metadata Inject custom metadata to the VM. If not set, only the built-in # metadata is injected into the VM. # @param [String] system_serial Assign an owned macOS system serial number to the VM. If already set in the # respective VM configuration and not set here, Orka applies the setting from the VM configuration. # @param [Boolean] gpu_passthrough Enables or disables GPU passthrough for the VM. If not set in the VM # configuration or here, defaults to +false+. If already set in the respective VM configuration and not set # here, Orka applies the setting from the VM configuration. You can also use this field to override the GPU # passthrough setting specified in the VM configuration. When enabled, +vnc_console+ is automatically # disabled. GPU passthrough is an experimental feature. GPU passthrough must first be enabled in your # cluster. # @return [VMDeploymentResult] Details of the just-deployed VM. def deploy(node: nil, replicas: nil, reserved_ports: nil, iso_install: nil, iso_image: nil, attach_disk: nil, attached_disk: nil, vnc_console: nil, vm_metadata: nil, system_serial: nil, gpu_passthrough: nil) VMResource.lazy_prepare(name: @name, conn: @conn).deploy( node: node, replicas: replicas, reserved_ports: reserved_ports, iso_install: iso_install, iso_image: iso_image, attach_disk: attach_disk, attached_disk: attached_disk, vnc_console: vnc_console, vm_metadata: vm_metadata, system_serial: system_serial, gpu_passthrough: gpu_passthrough, ) end # Remove the VM configuration and all VM deployments of it. # # If the VM configuration and its deployments belong to the user associated with the client's token then the # client only needs to be configured with a token. Otherwise, if you are removing a VM resource associated with # another user, you need to configure the client with both a token and a license key. # # @return [void] def purge VMResource.lazy_prepare(name: @name, conn: @conn).purge end # Delete the VM configuration state. Now when you deploy the VM configuration it will use the base image to # boot the VM. # # To delete a VM state, it must not be used by any deployed VM. # # @macro auth_token # # @return [void] def delete_saved_state @conn.delete("resources/vm/configs/#{@name}/delete-state") do |r| r.options.context = { orka_auth_type: :token, } end end private def lazy_initialize response = @conn.get("resources/vm/configs/#{@name}") do |r| r.options.context = { orka_auth_type: :token, } end configs = response.body["configs"] raise ResourceNotFoundError, "No VM configuration found matching \"#{@name}\"." if configs.empty? deserialize(configs.first) super end def deserialize(hash) @name = hash["orka_vm_name"] @owner = User.lazy_prepare(email: hash["owner"], conn: @conn) @base_image = Image.lazy_prepare(name: hash["orka_base_image"], conn: @conn) @cpu_cores = hash["orka_cpu_core"] @iso_image = if hash["iso_image"] == "None" nil else ISO.lazy_prepare(name: hash["iso_image"], conn: @conn) end @attached_disk = if hash["attached_disk"] == "None" nil else Image.lazy_prepare(name: hash["attached_disk"], conn: @conn) end @vnc_console = hash["vnc_console"] @io_boost = hash["io_boost"] @use_saved_state = hash["use_saved_state"] @gpu_passthrough = hash["gpu_passthrough"] end end end end
44.345361
117
0.656515
cd66e640f3d7f34d7cd768d3e278ac1593efd505
5,369
cs
C#
source/Assets/Scoreboard.cs
UngureanuDev/Natural-Selection
f86a8e480a488e7a43fab0051916d1f08227666a
[ "MIT" ]
null
null
null
source/Assets/Scoreboard.cs
UngureanuDev/Natural-Selection
f86a8e480a488e7a43fab0051916d1f08227666a
[ "MIT" ]
null
null
null
source/Assets/Scoreboard.cs
UngureanuDev/Natural-Selection
f86a8e480a488e7a43fab0051916d1f08227666a
[ "MIT" ]
null
null
null
using UnityEngine; using UnityEngine.UI; using Hashtable = ExitGames.Client.Photon.Hashtable; using TMPro; public class Scoreboard : MonoBehaviour { public GameObject[] Tiles; private string echipa; public GameObject ScorNatura; public GameObject ScorPoluare; public GameObject ProgresNatura; public GameObject ProgresPoluare; private void Awake() { echipa = (string)PhotonNetwork.player.CustomProperties["Echipa"]; ///setez scor initial la ambii playeri, 50. Hashtable CustomPropertiesToSet = new Hashtable() { { "Scor", "50" } }; PhotonNetwork.player.SetCustomProperties(CustomPropertiesToSet); } public int CalculatePointsPlayer() { if(echipa == null) echipa = (string)PhotonNetwork.player.CustomProperties["Echipa"]; int s = 0; Text text; foreach (GameObject tile in Tiles) { text = tile.GetComponentInChildren<Text>(); int curent; int.TryParse(text.text,out curent); if (text.color == new Color(0, 1, 0) && echipa == "Natura" || text.color == new Color(1, 0, 0) && echipa == "Poluare") s += curent; } return s; } public int CalculatePointsEnemy() { if (echipa == null) echipa = (string)PhotonNetwork.player.CustomProperties["Echipa"]; int s = 0; Text text; foreach (GameObject tile in Tiles) { text = tile.GetComponentInChildren<Text>(); int curent; int.TryParse(text.text,out curent); if (text.color == new Color(0, 1, 0) && echipa == "Poluare" || text.color == new Color(1, 0, 0) && echipa == "Natura") s += curent; } return s; } public void AplicaScor(int quantif) { int scorPlayer, scorInamic; int avantaj = CalculatePointsPlayer() - CalculatePointsEnemy(); int.TryParse((string)PhotonNetwork.player.CustomProperties["Scor"],out scorPlayer); int.TryParse((string) PhotonNetwork.otherPlayers[0].CustomProperties["Scor"],out scorInamic); scorPlayer = scorPlayer + avantaj * quantif; scorInamic = scorInamic - avantaj * quantif; Hashtable CustomPropertiesToSet = new Hashtable() { { "Scor", scorPlayer.ToString() } }; PhotonNetwork.player.SetCustomProperties(CustomPropertiesToSet); ///calculez manual pentru celalalt, in caz ca nu l-a updatat inca if ((string)PhotonNetwork.player.CustomProperties["Echipa"]== "Natura") UpdateUI(scorPlayer, scorInamic,avantaj); else UpdateUI(scorInamic, scorPlayer,avantaj); } public void Initialize_UI() { ScorNatura.GetComponent<TextMeshProUGUI>().SetText("50"); ScorPoluare.GetComponent<TextMeshProUGUI>().SetText("50"); ProgresNatura.SetActive(false); ProgresPoluare.SetActive(false); } private void UpdateUI(int natura, int poluare, int avantaj) { ScorNatura.GetComponent<TextMeshProUGUI>().SetText(natura.ToString()); ScorPoluare.GetComponent<TextMeshProUGUI>().SetText(poluare.ToString()); if (echipa == "Natura") { if (avantaj > 0) { ProgresNatura.SetActive(true); ProgresPoluare.SetActive(true); ProgresNatura.GetComponent<TextMeshProUGUI>().SetText("+" + avantaj.ToString()); ProgresPoluare.GetComponent<TextMeshProUGUI>().SetText("-" + avantaj.ToString()); } else if (avantaj < 0) { ProgresNatura.SetActive(true); ProgresPoluare.SetActive(true); ProgresNatura.GetComponent<TextMeshProUGUI>().SetText(avantaj.ToString()); ProgresPoluare.GetComponent<TextMeshProUGUI>().SetText("+" + (-avantaj).ToString()); } else { ProgresNatura.SetActive(false); ProgresPoluare.SetActive(false); //ProgresNatura.GetComponent<TextMeshProUGUI>().SetText(avantaj.ToString()); //ProgresPoluare.GetComponent<TextMeshProUGUI>().SetText(avantaj.ToString()); } } else ///daca sunt din echipa poluare { if (avantaj > 0) { ProgresNatura.SetActive(true); ProgresPoluare.SetActive(true); ProgresNatura.GetComponent<TextMeshProUGUI>().SetText("-" + avantaj.ToString()); ProgresPoluare.GetComponent<TextMeshProUGUI>().SetText("+" + avantaj.ToString()); } else if (avantaj < 0) { ProgresNatura.SetActive(true); ProgresPoluare.SetActive(true); ProgresNatura.GetComponent<TextMeshProUGUI>().SetText("+" + (-avantaj).ToString()); ProgresPoluare.GetComponent<TextMeshProUGUI>().SetText(avantaj.ToString()); } else { ProgresNatura.SetActive(false); ProgresPoluare.SetActive(false); //ProgresNatura.GetComponent<TextMeshProUGUI>().SetText(avantaj.ToString()); //ProgresPoluare.GetComponent<TextMeshProUGUI>().SetText(avantaj.ToString()); } } } }
40.067164
121
0.592848
58409509dee416b9cc87c7b9dba679db227f50c4
5,090
dart
Dart
lib/views/connections/connections_views.dart
scarnett/dispatcher
d621a625e57e9eab74d07b6eb4a6eea77ee19c62
[ "MIT" ]
3
2021-02-03T08:39:43.000Z
2021-06-03T17:38:43.000Z
lib/views/connections/connections_views.dart
scarnett/dispatcher
d621a625e57e9eab74d07b6eb4a6eea77ee19c62
[ "MIT" ]
1
2021-01-26T03:08:59.000Z
2021-01-26T03:08:59.000Z
lib/views/connections/connections_views.dart
scarnett/dispatcher
d621a625e57e9eab74d07b6eb4a6eea77ee19c62
[ "MIT" ]
2
2021-05-18T16:09:13.000Z
2021-11-22T07:36:55.000Z
import 'package:dispatcher/localization.dart'; import 'package:dispatcher/models/models.dart'; import 'package:dispatcher/utils/text_utils.dart'; import 'package:dispatcher/views/auth/bloc/bloc.dart'; import 'package:dispatcher/views/avatar/widgets/avatar_display.dart'; import 'package:dispatcher/views/connections/bloc/bloc.dart'; import 'package:dispatcher/views/connections/widgets/connections_appbar.dart'; import 'package:dispatcher/views/rooms/rooms_views.dart'; import 'package:dispatcher/widgets/none_found.dart'; import 'package:dispatcher/widgets/spinner.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ConnectionsView extends StatelessWidget { static Route route() => MaterialPageRoute<void>(builder: (_) => ConnectionsView()); const ConnectionsView({ Key key, }) : super(key: key); @override Widget build( BuildContext context, ) => BlocProvider<ConnectionsBloc>( create: (BuildContext context) => ConnectionsBloc(), child: ConnectionsPageView(), ); } class ConnectionsPageView extends StatefulWidget { ConnectionsPageView({ Key key, }) : super(key: key); @override State<StatefulWidget> createState() => _ConnectionsPageViewState(); } class _ConnectionsPageViewState extends State<ConnectionsPageView> with WidgetsBindingObserver, TickerProviderStateMixin { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); // The scroll controller for the ListView ScrollController _connectionsListViewController; @override void initState() { // Setup the ListView controller _connectionsListViewController = ScrollController(); super.initState(); WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _connectionsListViewController?.dispose(); super.dispose(); } @override Widget build( BuildContext context, ) => BlocBuilder<ConnectionsBloc, ConnectionsState>( builder: ( BuildContext context, ConnectionsState state, ) => Scaffold( key: _scaffoldKey, resizeToAvoidBottomInset: true, appBar: ConnectionsAppBar(height: 80.0), body: _buildContent(state), ), ); /// Builds the content Widget _buildContent( ConnectionsState state, ) { if ((state == null) || (context.bloc<AuthBloc>().state.user.connections == null)) { return Spinner( message: AppLocalizations.of(context).connectionsLoading, centered: false, ); } return Column( children: <Widget>[ _buildConnectionsList(state), ], ); } /// Builds a list of contact widgets. Widget _buildConnectionsList( ConnectionsState state, ) { List<UserConnection> connections = context.bloc<AuthBloc>().state.user.connections; if ((connections == null) || (connections.length == 0)) { return NoneFound( message: AppLocalizations.of(context).connectionsNone, ); } return Flexible( child: ListView.builder( controller: _connectionsListViewController, scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: connections?.length ?? 0, itemBuilder: ( BuildContext context, int index, ) { UserConnection connection = connections?.elementAt(index); return InkWell( onTap: () => _tapConnection(connection.connectionUser), child: Padding( padding: const EdgeInsets.symmetric( vertical: 10.0, horizontal: 20.0, ), child: Row( children: <Widget>[ Padding( padding: const EdgeInsets.only(right: 10.0), child: AvatarDisplay( user: connection.connectionUser, avatarRadius: 28.0, progressStrokeWidth: 2.0, ), ), _buildConnection(connection), ], ), ), ); }, ), ); } /// Builds a connection widget. Widget _buildConnection( UserConnection connection, ) { List<Widget> children = <Widget>[] ..add( Text( removeEmojis(connection.connectionUser.name), style: Theme.of(context).textTheme.headline6, ), ) ..add( Text( connection.connectionUser.email, style: Theme.of(context).textTheme.subtitle2, ), ); return Container( child: Flexible( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: children, ), ), ); } /// Handles the 'connection' tap void _tapConnection( User user, ) => Navigator.push(context, RoomView.route(user)); }
27.219251
78
0.621022
e77853608dfa431d202592b196ab99bbf6977384
1,586
php
PHP
resources/views/layouts/master.blade.php
yorch4/FestivarsLaravel
0037ecae044b0c7f250489e692b297d04411ee8a
[ "MIT" ]
null
null
null
resources/views/layouts/master.blade.php
yorch4/FestivarsLaravel
0037ecae044b0c7f250489e692b297d04411ee8a
[ "MIT" ]
4
2021-03-10T08:23:14.000Z
2022-02-26T23:56:47.000Z
resources/views/layouts/master.blade.php
yorch4/FestivarsLaravel
0037ecae044b0c7f250489e692b297d04411ee8a
[ "MIT" ]
null
null
null
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="//db.onlinewebfonts.com/c/23c0fcab84d99da0de762de7e220a6e1?family=Europa" rel="stylesheet" type="text/css"/> <link rel="stylesheet" type="text/css" href="{{url('css/index.css')}}"/> </head> <body class="text-uppercase"> @include('partials.navbar') <div class="container"> @yield('content') </div> @include('partials.footer') <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
61
212
0.744641
16f12a26ca1bb94fa40c23152d07ea60eef96bd5
6,763
lua
Lua
addons/GearSwap/beta_examples_and_information/Byrth_MNK.lua
sigilbaram/Lua
8a950dc13a8d828eaa3c7f0b30bc746e7756607e
[ "Unlicense" ]
167
2015-01-25T05:08:39.000Z
2022-02-18T12:12:19.000Z
addons/GearSwap/beta_examples_and_information/Byrth_MNK.lua
sigilbaram/Lua
8a950dc13a8d828eaa3c7f0b30bc746e7756607e
[ "Unlicense" ]
415
2015-01-03T04:51:19.000Z
2022-03-30T14:12:43.000Z
addons/GearSwap/beta_examples_and_information/Byrth_MNK.lua
sigilbaram/Lua
8a950dc13a8d828eaa3c7f0b30bc746e7756607e
[ "Unlicense" ]
437
2015-01-05T08:12:13.000Z
2022-03-11T06:25:36.000Z
include('organizer-lib') function get_sets() sets.weapons = {main="Suwaiyas"} sets.precast = {} --sets.precast.Boost = {hands="Anchorite's Gloves +1"} sets.precast.Chakra = {ammo="Iron Gobbet",body="Anchorite's Cyclas +1",hands="Hes. Gloves +1"} sets.precast.Counterstance = {feet="Hes. Gaiters +1"} sets.precast.Focus = {head="Anchorite's Crown +1"} sets.precast.Dodge = {feet="Anchorite's Gaiters +1"} sets.precast.Mantra = {feet="Hes. Gaiters +1"} sets.precast.Footwork = {feet="Shukuyu Sune-Ate"} sets.precast['Hundred Fists'] = {legs="Hes. Hose +1"} sets.Waltz = {head="Anwig Salade",neck="Unmoving Collar +1",ring1="Valseur's Ring",ring2="Carbuncle Ring +1", waist="Aristo Belt",legs="Desultor Tassets",feet="Dance Shoes"} sets.precast['Victory Smite'] = { ammo="Floestone", head={ name="Adhemar Bonnet +1", augments={'STR+12','DEX+12','Attack+20',}}, body={ name="Herculean Vest", augments={'Accuracy+21','Crit. hit damage +5%','DEX+9',}}, hands={ name="Adhemar Wrist. +1", augments={'DEX+12','AGI+12','Accuracy+20',}}, legs="Hiza. Hizayoroi +1", feet={ name="Herculean Boots", augments={'Accuracy+29','Crit. hit damage +5%','DEX+7','Attack+13',}}, neck="Fotia Gorget", waist="Moonbow Belt +1", left_ear={ name="Moonshade Earring", augments={'Attack+4','TP Bonus +25',}}, right_ear="Sherida Earring", left_ring="Begrudging Ring", left_ring="Niqmaddu Ring", back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','STR+10','Weapon skill damage +10%',}}, } sets.test = {lring="Ramuh Ring +1",rring="Ramuh Ring +1"} sets.test2 = {main="Numen Staff"} sets.precast['Howling Fist'] = { ammo="Floestone", head={ name="Adhemar Bonnet +1", augments={'STR+12','DEX+12','Attack+20',}}, body="Adhemar Jacket +1", hands="Adhemar Wrist. +1", legs="Hiza. Hizayoroi +1", feet={ name="Herculean Boots", augments={'Accuracy+25','"Triple Atk."+4','DEX+10',}}, neck="Caro Necklace", waist="Moonbow Belt +1", left_ear="Cessance Earring", right_ear="Sherida Earring", left_ring="Ifrit Ring +1", left_ring="Niqmaddu Ring", back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','STR+10','Weapon skill damage +10%',}}, } sets.precast['Tornado Kick'] = { ammo="Floestone", head={ name="Adhemar Bonnet +1", augments={'STR+12','DEX+12','Attack+20',}}, body="Adhemar Jacket +1", hands="Adhemar Wrist. +1", legs="Hiza. Hizayoroi +1", feet={ name="Herculean Boots", augments={'Accuracy+25','"Triple Atk."+4','DEX+10',}}, neck="Caro Necklace", waist="Moonbow Belt +1", left_ear="Moonshade Earring", right_ear="Sherida Earring", left_ring="Ifrit Ring +1", left_ring="Niqmaddu Ring", back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','STR+10','Weapon skill damage +10%',}}, } sets.precast['Spinning Attack'] = { ammo="Floestone", head={ name="Adhemar Bonnet +1", augments={'STR+12','DEX+12','Attack+20',}}, body="Adhemar Jacket +1", hands="Adhemar Wrist. +1", legs="Hiza. Hizayoroi +1", feet={ name="Herculean Boots", augments={'Accuracy+25','"Triple Atk."+4','DEX+10',}}, neck="Caro Necklace", waist="Moonbow Belt +1", left_ear="Cessance Earring", right_ear="Sherida Earring", left_ring="Ifrit Ring +1", left_ring="Niqmaddu Ring", back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','STR+10','Weapon skill damage +10%',}}, } sets.WS = { ammo="Floestone", head={ name="Adhemar Bonnet +1", augments={'STR+12','DEX+12','Attack+20',}}, body={ name="Herculean Vest", augments={'Accuracy+21','Crit. hit damage +5%','DEX+9',}}, hands="Adhemar Wrist. +1", legs="Hiza. Hizayoroi +1", feet={ name="Herculean Boots", augments={'Accuracy+29','Crit. hit damage +5%','DEX+7','Attack+13',}}, neck="Fotia Gorget", waist="Fotia Belt", left_ear="Moonshade Earring", right_ear="Sherida Earring", left_ring="Begrudging Ring", left_ring="Niqmaddu Ring", back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','STR+10','Weapon skill damage +10%',}}, } sets.TP = {} sets.TP.DD = { ammo="Ginsen", head={ name="Adhemar Bonnet +1", augments={'STR+12','DEX+12','Attack+20',}}, body="Adhemar Jacket +1", hands="Adhemar Wrist. +1", legs={ name="Samnuha Tights", augments={'STR+8','DEX+9','"Dbl.Atk."+3','"Triple Atk."+2',}}, feet={ name="Herculean Boots", augments={'Accuracy+25','"Triple Atk."+4','DEX+10',}}, neck="Combatant's Torque", waist="Moonbow Belt +1", left_ear="Cessance Earring", right_ear="Sherida Earring", left_ring="Niqmaddu Ring", right_ring="Epona's Ring", back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','"Dbl.Atk."+10',}}, } sets.status = {} sets.status.Engaged = sets.TP.DD sets.status.Idle = { ammo="Iron Gobbet", head="Lithelimb Cap", body="Emet Harness +1", hands={ name="Herculean Gloves", augments={'Accuracy+30','Damage taken-4%','STR+9','Attack+4',}}, legs="Mummu Kecks +1", feet="Herald's Gaiters", neck="Wiglen Gorget", waist="Moonbow Belt +1", left_ear="Novia Earring", right_ear="Genmei Earring", left_ring="Defending Ring", right_ring={ name="Dark Ring", augments={'Breath dmg. taken -4%','Phys. dmg. taken -6%','Magic dmg. taken -5%',}}, back={ name="Segomo's Mantle", augments={'STR+20','Accuracy+20 Attack+20','"Dbl.Atk."+10',}}, } send_command('input /macro book 15;wait .1;input /macro set 1') end function precast(spell) if spell.english == 'Tornado Kick' and buffactive.Footwork then equip(sets.precast[spell.english]) equip({feet="Shukuyu Sune-Ate"}) elseif sets.precast[spell.english] then equip(sets.precast[spell.english]) elseif spell.type=="WeaponSkill" then equip(sets.WS) elseif string.find(spell.english,'Waltz') then equip(sets.Waltz) end end function aftercast(spell) if sets.status[player.status] then equip(sets.status[player.status]) end end function status_change(new,old) if sets.status[new] then equip(sets.status[new]) end end
42.26875
122
0.587609
58856d347fc2dcb0962c72399be7108b411b145e
465
php
PHP
app/Models/Blog.php
AaEzha/laravel-tailwind-blog
b0c07f454e852df7ad660d211a515a5d27f7ad3d
[ "MIT" ]
null
null
null
app/Models/Blog.php
AaEzha/laravel-tailwind-blog
b0c07f454e852df7ad660d211a515a5d27f7ad3d
[ "MIT" ]
null
null
null
app/Models/Blog.php
AaEzha/laravel-tailwind-blog
b0c07f454e852df7ad660d211a515a5d27f7ad3d
[ "MIT" ]
null
null
null
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Blog extends Model { use HasFactory; /** * Get the category that owns the Blog * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function category(): BelongsTo { return $this->belongsTo(Category::class); } }
20.217391
64
0.701075
4f358967a148d28d37dc67b1036d1448874c354f
189
php
PHP
src/ElasticsearchBodyBuilder.php
zk-zeroking/php-elasticsearch-body-builder
560b8cc3b367e596307430f38464294001b269b2
[ "MIT" ]
null
null
null
src/ElasticsearchBodyBuilder.php
zk-zeroking/php-elasticsearch-body-builder
560b8cc3b367e596307430f38464294001b269b2
[ "MIT" ]
null
null
null
src/ElasticsearchBodyBuilder.php
zk-zeroking/php-elasticsearch-body-builder
560b8cc3b367e596307430f38464294001b269b2
[ "MIT" ]
null
null
null
<?php namespace ZZG\PhpElasticsearchBodyBuilder; class ElasticsearchBodyBuilder { public static function createSearchBody(){ return new Builder\Search\SearchBuilder(); } }
18.9
50
0.751323
7bf8bdbb2422e2230a356459c9ca154c7515aae5
1,851
cc
C++
zircon/system/ulib/storage/operation/operation.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
zircon/system/ulib/storage/operation/operation.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
zircon/system/ulib/storage/operation/operation.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <safemath/checked_math.h> #include <storage/operation/operation.h> #ifdef __Fuchsia__ #include <storage/operation/unbuffered_operation.h> #endif #include <ostream> namespace storage { const char* OperationTypeToString(OperationType type) { switch (type) { case OperationType::kRead: return "kRead"; case OperationType::kWrite: return "kWrite"; case OperationType::kTrim: return "kTrim"; default: return "<unknown>"; } } template <typename T> uint64_t BlockCountImpl(fbl::Span<const T> operations) { safemath::CheckedNumeric<uint64_t> total_length = 0; for (const auto& operation : operations) { total_length += operation.op.length; } return total_length.ValueOrDie(); } uint64_t BlockCount(fbl::Span<const BufferedOperation> operations) { return BlockCountImpl(operations); } #ifdef __Fuchsia__ uint64_t BlockCount(fbl::Span<const UnbufferedOperation> operations) { return BlockCountImpl(operations); } #endif std::ostream& operator<<(std::ostream& stream, const BufferedOperation& operation) { stream << "BufferedOperation {type: " << OperationTypeToString(operation.op.type) << " vmo_offset: " << operation.op.vmo_offset << " dev_offset: " << operation.op.dev_offset << " length: " << operation.op.length << "}"; return stream; } std::ostream& operator<<(std::ostream& stream, const fbl::Span<const BufferedOperation>& operations) { stream << "["; for (size_t i = 0; i < operations.size(); ++i) { if (i < operations.size() - 1) { stream << ", "; } stream << operations[i]; } stream << "]"; return stream; } } // namespace storage
27.220588
100
0.680173
b16a77889ab712bf2af3292ed5bc716cf444360b
2,385
swift
Swift
EAO/DataServices+Projects.swift
bcgov/field-inspection-app-ios
d3a064b685f9c87dda420641b850808a4ce127c3
[ "Apache-2.0" ]
6
2018-05-18T20:51:58.000Z
2021-08-23T04:01:39.000Z
EAO/DataServices+Projects.swift
bcgov/field-inspection-app-ios
d3a064b685f9c87dda420641b850808a4ce127c3
[ "Apache-2.0" ]
12
2018-11-23T23:03:45.000Z
2019-02-04T16:40:35.000Z
EAO/DataServices+Projects.swift
bcgov/field-inspection-app-ios
d3a064b685f9c87dda420641b850808a4ce127c3
[ "Apache-2.0" ]
11
2018-06-13T20:09:44.000Z
2019-04-11T23:34:46.000Z
// // DataServices+Projects.swift // Field Insp // // Created by Evgeny Yagrushkin on 2018-12-30. // Copyright © 2018 Province of British Columbia. All rights reserved. // import RealmSwift import Alamofire import AlamofireObjectMapper // MARK: Network Requests // TODO: move to the network manager extension DataServices { typealias FetchProjectListCompleted = (_ error: DataServicesError?) -> Void class func fetchProjectList(completion: FetchProjectListCompleted? = nil) { let sessionManager = Alamofire.SessionManager.default sessionManager.request(Constants.API.projectListURI).responseArray { (response: DataResponse<[EAOProject]>) in let (response, error) = NetworkManager.processResponse(response) if let error = error { print(error) DispatchQueue.main.async { completion?(DataServicesError.internalError(message: error.localizedDescription)) } return } // save/update all projects in the data base if let responseArray = response { do { let realm = try Realm() try realm.write { for responseObject in responseArray { realm.add(responseObject, update: true) } } completion?(nil) } catch let error as NSError { print(error) DispatchQueue.main.async { completion?(DataServicesError.requestFailed(error: error)) } } } } } } extension DataServices { func getProjects() -> Results<EAOProject>? { do { let realm = try Realm() let projects = realm.objects(EAOProject.self).sorted(byKeyPath: "name", ascending: true) return projects } catch { } return nil } func getProjectsAsStrings() -> [String] { guard let projects = getProjects() else { return [] } var projectStrings = [String]() projectStrings = projects.compactMap({ $0.name }) return projectStrings } }
29.8125
118
0.53543
57f86644776f3248d06d87be4cfe4e26deb832d7
1,855
php
PHP
src/Frontend/Modules/Blog/Actions/CommentsRss.php
vanMeerdervoort/forkcms
0eb0e992a5d8d0da6008ef7258e643c0b5e52afb
[ "MIT" ]
null
null
null
src/Frontend/Modules/Blog/Actions/CommentsRss.php
vanMeerdervoort/forkcms
0eb0e992a5d8d0da6008ef7258e643c0b5e52afb
[ "MIT" ]
1
2016-02-11T16:50:05.000Z
2016-02-11T16:50:05.000Z
src/Frontend/Modules/Blog/Actions/CommentsRss.php
vanMeerdervoort/forkcms
0eb0e992a5d8d0da6008ef7258e643c0b5e52afb
[ "MIT" ]
null
null
null
<?php namespace Frontend\Modules\Blog\Actions; use Frontend\Core\Engine\Base\Block as FrontendBaseBlock; use Frontend\Core\Language\Language as FL; use Frontend\Core\Engine\Navigation as FrontendNavigation; use Frontend\Core\Engine\Rss as FrontendRSS; use Frontend\Core\Engine\RssItem as FrontendRSSItem; use Frontend\Modules\Blog\Engine\Model as FrontendBlogModel; /** * This is the RSS-feed with all the comments */ class CommentsRss extends FrontendBaseBlock { public function execute(): void { parent::execute(); $this->generateRss(); } private function generateRss() { $blogPostComments = FrontendBlogModel::getAllComments(); $rss = new FrontendRSS( \SpoonFilter::ucfirst(FL::msg('BlogAllComments')), SITE_URL . FrontendNavigation::getUrlForBlock($this->getModule()), '' ); $blogPostUrlBase = SITE_URL . FrontendNavigation::getUrlForBlock($this->getModule(), 'Detail'); foreach ($blogPostComments as $blogPostComment) { $rss->addItem($this->getRssFeedItemForBlogPostComment($blogPostComment, $blogPostUrlBase)); } $rss->parse(); } private function getRssFeedItemForBlogPostComment( array $blogPostComment, string $blogPostUrlBase ): FrontendRSSItem { $rssItem = new FrontendRSSItem( $blogPostComment['author'] . ' ' . FL::lbl('On') . ' ' . $blogPostComment['post_title'], $blogPostUrlBase . '/' . $blogPostComment['post_irl'] . '/#comment-' . $blogPostComment['id'], $blogPostComment['text'] ); $rssItem->setPublicationDate($blogPostComment['created_on']); $rssItem->setAuthor(empty($blogPostComment['email']) ? $blogPostComment['author'] : $blogPostComment['email']); return $rssItem; } }
32.54386
119
0.657682
06d87a5030aa4c3d66fecce2cf63444714af647f
682
py
Python
Spidering.py
ExaByt3s/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
3
2021-01-22T19:32:23.000Z
2022-01-03T01:06:44.000Z
Spidering.py
a04512/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
null
null
null
Spidering.py
a04512/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
1
2019-06-18T22:10:53.000Z
2019-06-18T22:10:53.000Z
#!/usr/bin/python __author__ = 'kilroy' # (c) 2014, WasHere Consulting, Inc. # Written for Infinite Skills from HTMLParser import HTMLParser import urllib2 class myParser(HTMLParser): def handle_starttag(self, tag, attrs): if (tag == "a"): for a in attrs: if (a[0] == 'href'): link = a[1] if (link.find('http') >= 0): print(link) newParse = myParser() newParse.feed(link) url = "http://www.infiniteskills.com/" request = urllib2.Request(url) handle = urllib2.urlopen(request) parser = myParser() parser.feed(handle.read())
25.259259
48
0.545455
e8b92f5200a64b59b5367b6198c3b637d37a374f
642
swift
Swift
ZomatoApp/Helpers/UIHelper.swift
GermanHernandez91/ZomatoApp
215019043ce032d2c0033ad1ef5df7a21c8b6e67
[ "MIT" ]
3
2020-01-13T19:06:29.000Z
2022-03-26T09:51:14.000Z
ZomatoApp/Helpers/UIHelper.swift
GermanHernandez91/ZomatoApp
215019043ce032d2c0033ad1ef5df7a21c8b6e67
[ "MIT" ]
null
null
null
ZomatoApp/Helpers/UIHelper.swift
GermanHernandez91/ZomatoApp
215019043ce032d2c0033ad1ef5df7a21c8b6e67
[ "MIT" ]
null
null
null
// // UIHelper.swift // ZomatoApp // // Created by German on 13/01/2020. // Copyright © 2020 German Hernandez. All rights reserved. // import UIKit struct UIHelper { static func generateCollectionCellHorizontalCell(in view: UIView) -> UICollectionViewFlowLayout { let flowLayot = UICollectionViewFlowLayout() flowLayot.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) flowLayot.itemSize = CGSize(width: view.frame.width / 3, height: 120) flowLayot.scrollDirection = .horizontal flowLayot.minimumLineSpacing = 10 return flowLayot } }
25.68
101
0.663551
79d9a1ed5f2dfc496d8ea1437bd320d4b2dfcd49
6,091
php
PHP
app/Http/Controllers/Web/BrandController.php
OmarMarie/brandAdmin
fc831913b472af5f29087f9b9dcd2649f5ae3bad
[ "MIT" ]
null
null
null
app/Http/Controllers/Web/BrandController.php
OmarMarie/brandAdmin
fc831913b472af5f29087f9b9dcd2649f5ae3bad
[ "MIT" ]
4
2021-02-02T20:20:06.000Z
2022-02-27T10:28:10.000Z
app/Http/Controllers/Web/BrandController.php
OmarMarie/brandAdmin
fc831913b472af5f29087f9b9dcd2649f5ae3bad
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Web; use App\Models\Brand; use App\Models\BrandCampaign; use App\Models\Company; use App\Models\CompanyPackage; use App\Models\CompanyPackageLogs; use App\Models\Package; use App\Models\RoleUser; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Yajra\DataTables\Facades\DataTables; class BrandController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('brandpriers.brands.index'); } public function brandsDatable(Request $request) { if ($request->ajax()) { $data = Brand::latest()->get(); return Datatables::of($data) ->addIndexColumn() ->editColumn('status', function ($data) { return $data->status == 0 ? 'Inactive' : 'Active'; }) ->editColumn('company_id', function ($data) { $companyName = Company::where('id', $data->company_id)->value('name'); if ($companyName != '') return $companyName; else return null; }) ->editColumn('created_at', function ($data) { if ($data->created_at != '') $data->created_at->format('d m Y - g:i A'); return $data->created_at; }) ->make(true); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $companyPackages = Package::get(); $companies = Company::get(); return view('brandpriers.brands.create', compact('companyPackages', 'companies')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validations = Validator::make($request->all(), [ 'brand_name' => 'required|unique:brands', 'company_id' => 'required', 'status' => 'required', 'contract' => 'required|mimes:jpeg,png,jpg,pdf', 'ad_approval' => 'required|mimes:jpeg,png,jpg,gif,svg,pdf', ]); if ($validations->fails()) { return response()->json(['errors' => $validations->errors(), 'status' => 422]); } if (isset($request->brand_icon)) { $image = $request->file('brand_icon'); $icon = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('images/brand'), $icon); } else { $icon = null; } if (isset($request->contract)) { $image = $request->file('contract'); $contract = 'contract_' . time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('attachments/brand'), $contract); } if (isset($request->ad_approval)) { $image = $request->file('ad_approval'); $ad_approval = 'ad_approval_' . time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('attachments/brand'), $ad_approval); } Brand::create([ 'brand_name' => $request->brand_name, 'status' => $request->status, 'img' => $icon, 'user_id' => "", 'company_id' => $request->company_id, 'contract' => $contract, 'ad_approval' => $ad_approval ]); return response()->json(['message' => 'Added Brand successfully', 'status' => 200]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($local, Brand $brand) { $companyPackages = Package::get(); return view('brandpriers.brands.create', compact('brand', 'companyPackages')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update($local, Request $request, Brand $brand) { $validations = Validator::make($request->all(), [ 'brand_name' => 'required|unique:brands,brand_name,' . $brand->id, 'status' => 'required', ]); if ($validations->fails()) { return response()->json(['errors' => $validations->errors(), 'status' => 422]); } $brand->update([ 'brand_name' => $request->brand_name, 'status' => $request->status, ]); if (isset($request->brand_icon) && $request->brand_icon != $brand->img) { /*--------------delete img old--------*/ $file = 'images/brand/' . $brand->img; File::delete($file); $image = $request->file('brand_icon'); $icon = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('images/brand'), $icon); $brand->update([ 'img' => $icon ]); } return response()->json(['message' => 'Updated Brand successfully', 'status' => 200]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($local, Brand $brand) { $brand->delete(); if ($brand->img != null) { $file = 'images/tank/' . $brand->img; File::delete($file); } } }
29.004762
96
0.522574
1f425cc0411a6d2ba497f9d141e0e319add4132f
2,026
cs
C#
samples/server/petstore/aspnetcore-mixed/src/IO.Swagger/Controllers/AnotherFakeApi.cs
xiaomaolau/swagger-api
a39ea6f146476300e03539922d0a56c5a24cc419
[ "Apache-2.0" ]
null
null
null
samples/server/petstore/aspnetcore-mixed/src/IO.Swagger/Controllers/AnotherFakeApi.cs
xiaomaolau/swagger-api
a39ea6f146476300e03539922d0a56c5a24cc419
[ "Apache-2.0" ]
null
null
null
samples/server/petstore/aspnetcore-mixed/src/IO.Swagger/Controllers/AnotherFakeApi.cs
xiaomaolau/swagger-api
a39ea6f146476300e03539922d0a56c5a24cc419
[ "Apache-2.0" ]
null
null
null
/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using Swashbuckle.AspNetCore.SwaggerGen; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using IO.Swagger.Attributes; using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.Models; namespace IO.Swagger.Controllers { /// <summary> /// /// </summary> [ApiController] public class AnotherFakeApiController : ControllerBase { /// <summary> /// To test special tags /// </summary> /// <remarks>To test special tags</remarks> /// <param name="body">client model</param> /// <response code="200">successful operation</response> [HttpPatch] [Route("/v3/another-fake/dummy")] [ValidateModelState] [SwaggerOperation("TestSpecialTags")] [SwaggerResponse(statusCode: 200, type: typeof(Client), description: "successful operation")] public virtual IActionResult TestSpecialTags([FromBody]Client body) { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(200, default(Client)); string exampleJson = null; exampleJson = "{\n \"client\" : \"client\"\n}"; var example = exampleJson != null ? JsonConvert.DeserializeObject<Client>(exampleJson) : default(Client); //TODO: Change the data returned return new ObjectResult(example); } } }
36.836364
159
0.64462
79c8135aa16c105dfacd4ef795382a2c6ea117e2
1,931
php
PHP
View/News/News.php
gmammolo/SocialProject
023d864920c367dc4a4ef19b438e39e2b17bb7fe
[ "MIT" ]
null
null
null
View/News/News.php
gmammolo/SocialProject
023d864920c367dc4a4ef19b438e39e2b17bb7fe
[ "MIT" ]
null
null
null
View/News/News.php
gmammolo/SocialProject
023d864920c367dc4a4ef19b438e39e2b17bb7fe
[ "MIT" ]
null
null
null
<?php if(User::getUser()->hasAccess(Role::Register)) { ?> <div id="newComment"> <form name="newComment" method="POST" action="?formValidate=addPost" enctype="multipart/form-data"> <div class="row"> <span> <select name="switchUpload" onchange="WriteComment.switchUploadFunction()"> <option value="p_url">URL</option> <option value="p_file">Immagine</option> </select> </span> <span><input type="file" name="p_file" /></span> <span><input type="url" name="p_url" placeholder="http://" /></span> </div> <div class="row"></div> <div class="row"><textarea name="text" placeholder="A cosa stai pensando?" onKeyPress="WriteComment.abilityHelpUser(event)" onkeyup="WriteComment.ricercaUtenti(event)"></textarea></div> <div class="help_input"></div> <div class="row"><input type="text" name="luogo" title="Luogo dove è stata scattata" placeholder="Dove sei?" pattern="/[^'\x22]+/" /> </div> <div class="row"> <span class="finalRow"> Privacy: <select name="privacy"> <option value="privato">Privato</option> <option value="amici" selected="selected">Amici</option> <option value="amiciplus">Amici +</option> <option value="globale">Pubblico</option> </select> </span> <input type="button" name="invia" value="Invia" onclick="WriteComment.sendPost()" /> </div> </form> <script> $("input[name='p_file']").hide(); </script> </div> <?php } ?> <div id="Showcase" > <div id="Showcase-div"> </div> <div id="Showcase-other" onclick="News.showOther()">Altro..</div> </div> <script> var ascolto= false; var search =""; News.showOther(); </script>
38.62
193
0.546867
01b9805d55df7273eb2b6afb6b2aa2afb88e46fe
1,329
kt
Kotlin
src/main/kotlin/io/github/intellij/dlanguage/inspections/DeleteStatementsAreDeprecated.kt
madmax-inc/intellij-dlanguage
fb2faf2b2110ebb551b1c3a5779595b87233f0b8
[ "MIT" ]
182
2017-05-06T14:18:49.000Z
2022-03-20T02:37:10.000Z
src/main/kotlin/io/github/intellij/dlanguage/inspections/DeleteStatementsAreDeprecated.kt
madmax-inc/intellij-dlanguage
fb2faf2b2110ebb551b1c3a5779595b87233f0b8
[ "MIT" ]
513
2017-05-02T13:06:48.000Z
2022-03-09T20:00:32.000Z
src/main/kotlin/io/github/intellij/dlanguage/inspections/DeleteStatementsAreDeprecated.kt
madmax-inc/intellij-dlanguage
fb2faf2b2110ebb551b1c3a5779595b87233f0b8
[ "MIT" ]
41
2017-05-14T12:21:22.000Z
2022-03-04T19:43:52.000Z
package io.github.intellij.dlanguage.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import io.github.intellij.dlanguage.DlangBundle import io.github.intellij.dlanguage.psi.DlangVisitor import io.github.intellij.dlanguage.psi.impl.DLanguageDeleteExpressionImpl import io.github.intellij.dlanguage.psi.impl.DLanguageDeleteStatementImpl /** * Created by francis on 11/26/2017. */ class DeleteStatementsAreDeprecated : LocalInspectionTool() { override fun getDescriptionFileName(): String = "DeleteStatementsAreDeprecated.html" override fun getDisplayName(): String = "Delete Statements are Deprecated" override fun getGroupDisplayName(): String = DlangBundle.message("d.inspections.groupname") override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): DlangVisitor = DeleteStatementsVisitor(holder) } class DeleteStatementsVisitor(val holder: ProblemsHolder) : DlangVisitor() { override fun visitDeleteExpression(o: DLanguageDeleteExpressionImpl) { register(o) } override fun visitDeleteStatement(o: DLanguageDeleteStatementImpl) { register(o) } fun register(o: PsiElement) { holder.registerProblem(o, "Delete statements are deprecated") } }
39.088235
122
0.791573
b23757346a7a7e4f1b181f252df3a5b1e13afb49
113
asm
Assembly
asm/fpga_sys_debug.asm
FKD13/RCPU
1f27246494f60eaa2432470b2d218bb3f63578c7
[ "MIT" ]
17
2017-07-26T13:08:34.000Z
2022-02-19T20:44:02.000Z
asm/fpga_sys_debug.asm
FKD13/RCPU
1f27246494f60eaa2432470b2d218bb3f63578c7
[ "MIT" ]
4
2017-10-12T20:56:39.000Z
2020-05-04T09:19:44.000Z
asm/fpga_sys_debug.asm
FKD13/RCPU
1f27246494f60eaa2432470b2d218bb3f63578c7
[ "MIT" ]
4
2017-10-16T16:24:16.000Z
2022-03-21T19:07:06.000Z
.text .global main: test: LDV A, 20 PSH A POP D RET main: LDV A, test: CAL A HLT
8.071429
16
0.477876
77b876d7eb158e581dfd644a508ff50d928835a5
3,563
lua
Lua
menu.lua
cjm571/TargetFrameDimmer
64d53d17c9549e21964147391f53244bed448233
[ "MIT" ]
null
null
null
menu.lua
cjm571/TargetFrameDimmer
64d53d17c9549e21964147391f53244bed448233
[ "MIT" ]
null
null
null
menu.lua
cjm571/TargetFrameDimmer
64d53d17c9549e21964147391f53244bed448233
[ "MIT" ]
null
null
null
-- Filename: menu.lua -- Author: CJ McAllister -- Creation Date: 2020-Mar-29 -- -- Menu and settings handling functions -- Submodule declaration TFF.Menu = {} LAM2 = LibAddonMenu2 ----- -- Initialization ----- function TFF.Menu:Initialize() -- Configure master panel TFF.Menu.panel = { type = "panel", name = GetString(TFF_Name), displayName = GetString(TFF_Name), author = "cjm571", version = TFF.version, registerForRefresh = true, registerForDefaults = false, } -- Setup the initial panel LAM2:RegisterAddonPanel("TFF_Menu" , TFF.Menu.panel) -- Configure menu control options TFF.Menu:PopulateOptions() -- Setup the menus LAM2:RegisterOptionControls("TFF_Menu", TFF.Menu.options) end ----- -- Settings Update ----- function TFF.Menu.Update(setting, value) -- Set new value into settings TFF.vars[setting] = value -- Re-init animations to reflect new settings TFF.Animation:Initialize() end ----- -- Menu Creation ----- function TFF.Menu:PopulateOptions() TFF.Menu.options = { ----- -- In-Combat ----- -- Header { type = "header", name = GetString(TFF_InCombat_Header), width = "full" }, -- Opacity { type = "slider", name = GetString(TFF_Opac_Slider_Title), tooltip = GetString(TFF_Opac_Slider_Tooltip), min = 0, max = 100, step = 5, getFunc = function() return TFF.vars.inCombatOpacity end, setFunc = function(value) TFF.Menu.Update('inCombatOpacity', value) end, default = TFF.defaults.inCombatOpacity, }, -- Duration { type = "slider", name = GetString(TFF_Dur_Slider_Title), tooltip = GetString(TFF_Dur_Slider_Tooltip), min = 100, max = 1000, step = 50, getFunc = function() return TFF.vars.inCombatFadeDurationMs end, setFunc = function(value) TFF.Menu.Update('inCombatFadeDurationMs', value) end, default = TFF.defaults.inCombatFadeDurationMs, }, ----- -- Out-of-Combat ----- -- Header { type = "header", name = GetString(TFF_OutOfCombat_Header), width = "full" }, -- Opacity { type = "slider", name = GetString(TFF_Opac_Slider_Title), tooltip = GetString(TFF_Opac_Slider_Tooltip), min = 0, max = 100, step = 5, getFunc = function() return TFF.vars.outOfCombatOpacity end, setFunc = function(value) TFF.Menu.Update('outOfCombatOpacity', value) end, default = TFF.defaults.outOfCombatOpacity, }, -- Duration { type = "slider", name = GetString(TFF_Dur_Slider_Title), tooltip = GetString(TFF_Dur_Slider_Tooltip), min = 100, max = 2000, step = 50, getFunc = function() return TFF.vars.outOfCombatFadeDurationMs end, setFunc = function(value) TFF.Menu.Update('outOfCombatFadeDurationMs', value) end, default = TFF.defaults.outOfCombatFadeDurationMs, }, } end
28.733871
94
0.527645
9ccbb882128107b18c4b1ee29b82650877c03af5
1,185
lua
Lua
lua/libk/3rdparty/glib/containers/linkedlistnode.lua
askrealcookie/LibK
a433949d5e629cb8c9f29ad47ad0c5c8d09c9dc9
[ "MIT" ]
41
2015-01-07T02:14:44.000Z
2021-09-28T10:06:54.000Z
lua/libk/3rdparty/glib/containers/linkedlistnode.lua
askrealcookie/LibK
a433949d5e629cb8c9f29ad47ad0c5c8d09c9dc9
[ "MIT" ]
38
2015-01-04T18:38:07.000Z
2022-01-14T14:14:05.000Z
lua/libk/3rdparty/glib/containers/linkedlistnode.lua
askrealcookie/LibK
a433949d5e629cb8c9f29ad47ad0c5c8d09c9dc9
[ "MIT" ]
31
2015-07-30T07:41:51.000Z
2022-01-12T18:24:07.000Z
local self = {} GLib.Containers.LinkedListNode = GLib.MakeConstructor (self) function self:ctor () self.List = nil self.Next = nil self.Previous = nil self.Value = nil end function self:InsertNext (node) if node == nil then return end node.List = self.List node.Previous = self node.Next = self.Next self.Next = node if node.Next then node.Next.Previous = node end if self.List then self.List.Count = self.List.Count + 1 if self.List.Last == self then self.List.Last = node end end end function self:InsertPrevious (node) if node == nil then return end node.List = self.List node.Next = self node.Previous = self.Previous self.Previous = node if node.Previous then node.Previous.Next = node end if self.List then self.List.Count = self.List.Count + 1 if self.List.First == self then self.List.First = node end end end function self:ToString () if not self.Value then return "[nil]" end if type (self.Value) == "table" and self.Value.ToString then return self.Value:ToString () end if type (self.Value) == "string" then return "\"" .. GLib.String.Escape (self.Value) .. "\"" end return tostring (self.Value) end
21.545455
97
0.689451
6ba1f773d1370a245aeffdae6bda6a55e192c9b9
1,141
dart
Dart
lib/register/bloc/register_event.dart
kttl15/styleFlutter
6188bb7707f56084c1e48fc9efbc3eb95c4a4b51
[ "BSD-3-Clause" ]
null
null
null
lib/register/bloc/register_event.dart
kttl15/styleFlutter
6188bb7707f56084c1e48fc9efbc3eb95c4a4b51
[ "BSD-3-Clause" ]
null
null
null
lib/register/bloc/register_event.dart
kttl15/styleFlutter
6188bb7707f56084c1e48fc9efbc3eb95c4a4b51
[ "BSD-3-Clause" ]
null
null
null
part of 'register_bloc.dart'; abstract class RegisterEvent extends Equatable { const RegisterEvent(); @override List<Object> get props => []; } class EmailChanged extends RegisterEvent { //* notifies the bloc that user has changed email final String email; EmailChanged({@required this.email}); @override List<Object> get props => [email]; @override String toString() => 'EmailChanged { email :$email }'; } class PasswordChanged extends RegisterEvent { //* notifies bloc that user has changed password final String password; PasswordChanged({ @required this.password, }); @override List<Object> get props => [password]; @override String toString() { return 'PasswordChanged { password: $password }'; } } class Submitted extends RegisterEvent { //* notifies bloc that user has submitted the form final String email; final String password; Submitted({ @required this.email, @required this.password, }); @override List<Object> get props => [email, password]; @override String toString() { return 'Submitted { email: $email, password: $password }'; } }
19.672414
62
0.687993
b787c07c5eb0a779989ae7c92a2f257eb336b46e
1,574
cc
C++
TopQuarkAnalysis/TopJetCombination/src/TtSemiSimpleBestJetComb.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
TopQuarkAnalysis/TopJetCombination/src/TtSemiSimpleBestJetComb.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
TopQuarkAnalysis/TopJetCombination/src/TtSemiSimpleBestJetComb.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// // #include "TopQuarkAnalysis/TopJetCombination/interface/TtSemiSimpleBestJetComb.h" TtSemiSimpleBestJetComb::TtSemiSimpleBestJetComb() {} TtSemiSimpleBestJetComb::~TtSemiSimpleBestJetComb() {} int TtSemiSimpleBestJetComb::operator()(std::vector<TtSemiEvtSolution>& sols) { // search the highest probChi^2 value in the among the different jet combination solutions double maxProbChi2 = 0; for (unsigned int s = 0; s < sols.size(); s++) maxProbChi2 = std::max(maxProbChi2, sols[s].getProbChi2()); //search indices of original solutions with highest probChi2 value std::vector<unsigned int> indices; indices.clear(); for (unsigned int s = 0; s < sols.size(); s++) { if (fabs(sols[s].getProbChi2() - maxProbChi2) < 0.0001) indices.push_back(s); } int bestSol = -999; if (maxProbChi2 > 0.) { if (indices.size() == 1) bestSol = indices[0]; if (indices.size() == 2) { //typically only light jets constraints applied, so still b-jet ambiguity to resolve // -> look at DPhi(Whadr,bhadr) and choose smallest value double DPhi_Wb0 = fabs(sols[indices[0]].getFitHadW().phi() - sols[indices[0]].getFitHadb().phi()); double DPhi_Wb1 = fabs(sols[indices[1]].getFitHadW().phi() - sols[indices[1]].getFitHadb().phi()); if (DPhi_Wb0 > 3.1415) DPhi_Wb0 = 2. * 3.1415 - DPhi_Wb0; if (DPhi_Wb1 > 3.1415) DPhi_Wb1 = 2. * 3.1415 - DPhi_Wb1; if (DPhi_Wb0 < DPhi_Wb1) { bestSol = indices[0]; } else { bestSol = indices[1]; } } } return bestSol; }
34.217391
104
0.649936
cd96bec75aa4e464c4769dbd3da8e784e0153720
1,905
cs
C#
Biz.Morsink.Identity.Test/DecoratedIdentityTest.cs
joost-morsink/Identity
731875c716544907d6464eaef551545bdff24015
[ "MIT" ]
1
2017-04-13T19:26:46.000Z
2017-04-13T19:26:46.000Z
Biz.Morsink.Identity.Test/DecoratedIdentityTest.cs
joost-morsink/Identity
731875c716544907d6464eaef551545bdff24015
[ "MIT" ]
null
null
null
Biz.Morsink.Identity.Test/DecoratedIdentityTest.cs
joost-morsink/Identity
731875c716544907d6464eaef551545bdff24015
[ "MIT" ]
1
2022-01-20T01:30:28.000Z
2022-01-20T01:30:28.000Z
using Biz.Morsink.Identity.Decoration; using Biz.Morsink.Identity.Systems; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; namespace Biz.Morsink.Identity.Test { [TestClass] public class DecoratedIdentityTest { private TestIdProvider provider; [TestInitialize] public void Init() { provider = TestIdProvider.Instance; } [TestMethod] public void DecoratedId_Happy() { var id = FreeIdentity<Person>.Create(42); var decId = id.Decorate(new SystemIdentity("SYS")); Assert.AreEqual(typeof(Person), decId.ForType, "Decoration should preserve the ForType property." ); Assert.AreEqual("SYS", decId.For<Sys>().Value, "The decoration should be available in the Identities property."); Assert.AreEqual(42, decId.For<Person>().Value, "The original identity value should be preserved in the decorated value."); Assert.AreEqual(1, decId.Arity, "Decoration should preserve the Arity property."); } [TestMethod] public void DecoratedId_MapHappy() { var id = FreeIdentity<Person>.Create("42"); var decId = id.Decorate(new SystemIdentity("SYS")); var pid = provider.Translate(decId); Assert.AreEqual(typeof(Person), pid.ForType, "Translation after decoration should preserve the ForType property."); Assert.AreEqual("SYS", pid.For<Sys>().Value, "Translation should preserve the decoration."); Assert.AreEqual(42, pid.For<Person>().Value, "Translation after decoration should preserve the underlying Value."); Assert.AreEqual(1, pid.Arity,"Translation after decoration should preserve the Arity property."); } } }
41.413043
135
0.643045
b8bcde0032caf545b40619d7b25389d9287ca26f
252
h
C
chocChipChess/zobrist.h
GenericCinnamon/chocchipchess
793ea775b6b96df1157c9e712a420add7d21f89b
[ "MIT" ]
null
null
null
chocChipChess/zobrist.h
GenericCinnamon/chocchipchess
793ea775b6b96df1157c9e712a420add7d21f89b
[ "MIT" ]
null
null
null
chocChipChess/zobrist.h
GenericCinnamon/chocchipchess
793ea775b6b96df1157c9e712a420add7d21f89b
[ "MIT" ]
null
null
null
#pragma once #include <inttypes.h> namespace Zobrist { extern uint64_t PIECE_INTS[12][64]; extern uint64_t CASTLING_INTS[4]; extern uint64_t SIDE_IS_BLACK_INT; extern uint64_t EN_PASSENT_INTS[8]; void init(unsigned int seed); }
19.384615
39
0.722222
d27cd67f22352008a085179492037532af1b87ea
5,040
lua
Lua
vrp_newcoin/server.lua
kalinzange/vRP
83de0e7b76a5c6f9f3ee931ca390771dbcb146fb
[ "MIT" ]
41
2018-04-01T22:58:37.000Z
2021-12-29T04:38:06.000Z
vrp_newcoin/server.lua
kalinzange/vRP
83de0e7b76a5c6f9f3ee931ca390771dbcb146fb
[ "MIT" ]
18
2018-04-21T13:24:44.000Z
2022-03-27T19:44:22.000Z
vrp_newcoin/server.lua
kalinzange/vRP
83de0e7b76a5c6f9f3ee931ca390771dbcb146fb
[ "MIT" ]
325
2018-08-08T18:53:00.000Z
2022-03-05T04:41:19.000Z
--[[ SCRIPTER: DGVaniX [ DGVaniX#0096 ] WEBSITE: http://vanix.market --]] MySQL = module("vrp_mysql", "MySQL") local Tunnel = module("vrp", "lib/Tunnel") local Proxy = module("vrp", "lib/Proxy") vRP = Proxy.getInterface("vRP") vRPnc = {} Tunnel.bindInterface("vRP_newcoin",vRPnc) Proxy.addInterface("vRP_newcoin",vRPnc) vRPclient = Tunnel.getInterface("vRP","vRP_newcoin") MySQL.createCommand("vRP/coins_init_user","INSERT IGNORE INTO vrp_newcoin(user_id,coins) VALUES(@user_id,@coins)") MySQL.createCommand("vRP/get_coins","SELECT * FROM vrp_newcoin WHERE user_id = @user_id") MySQL.createCommand("vRP/set_coins","UPDATE vrp_newcoin SET coins = @coins WHERE user_id = @user_id") tmpCoins = {} function displayCoin(value) return "<span class=\"symbol\">$</span> "..value end function vRPnc.getCoins(user_id) local coins = tonumber(tmpCoins[user_id]) if coins ~= nil then return tonumber(tmpCoins[user_id]) else return 0 end end function vRPnc.setCoins(user_id,value) local coins = tonumber(tmpCoins[user_id]) if coins ~= nil then tmpCoins[user_id] = tonumber(value) end local source = vRP.getUserSource({user_id}) if source ~= nil then vRPclient.setDivContent(source,{"coins",displayCoin(value)}) end end function vRPnc.giveCoins(user_id,amount) local coins = vRPnc.getCoins(user_id) local newCoins = coins + amount vRPnc.setCoins(user_id,newCoins) end function vRPnc.takeCoins(user_id,amount) local coins = vRPnc.getCoins(user_id) local newCoins = coins - amount vRPnc.setCoins(user_id,newCoins) end function vRPnc.tryCoinPayment(user_id,amount) local coins = vRPnc.getCoins(user_id) if coins >= amount then vRPnc.setCoins(user_id,coins-amount) return true else return false end end AddEventHandler("vRP:playerJoin",function(user_id,source,name,last_login) local cfg = getCoinConfig() MySQL.execute("vRP/coins_init_user", {user_id = user_id, coins = cfg.open_coins}, function(affected) MySQL.query("vRP/get_coins", {user_id = user_id}, function(rows, affected) if #rows > 0 then tmpCoins[user_id] = tonumber(rows[1].coins) end end) end) end) AddEventHandler("vRP:playerLeave",function(user_id,source) local coins = tmpCoins[user_id] if coins and coins ~= nil then MySQL.execute("vRP/set_coins", {user_id = user_id, coins = coins}) end end) AddEventHandler("vRP:save", function() for i, v in pairs(tmpCoins) do if v ~= nil then MySQL.execute("vRP/set_coins", {user_id = i, coins = v}) end end end) AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn) if first_spawn then local cfg = getCoinConfig() local myCoins = vRPnc.getCoins(user_id) vRPclient.setDiv(source, {"coins", cfg.display_css, displayCoin(myCoins)}) end end) local function givePlayerCoins(player,choice) vRP.prompt({player, "User ID: ", "", function(player, user_id) user_id = tonumber(user_id) local target = vRP.getUserSource({user_id}) if target ~= nil then vRP.prompt({player, "Coins: ", "", function(player, coins) coins = coins if(tonumber(coins))then coins = tonumber(coins) vRPnc.giveCoins(user_id,coins) vRPclient.notify(player, {"~g~You gave ~w~"..GetPlayerName(target).." ~w~"..coins.." ~g~coins"}) vRPclient.notify(target, {"~w~"..GetPlayerName(player).."~g~ gave you ~w~"..coins.." ~g~coins"}) else vRP.notify(player, {"~r~Number has to be a number!"}) end end}) else vRPclient.notify(player, {"~r~Player not online!"}) end end}) end local function takePlayerCoins(player,choice) vRP.prompt({player, "User ID: ", "", function(player, user_id) user_id = tonumber(user_id) local target = vRP.getUserSource({user_id}) if target ~= nil then vRP.prompt({player, "Coins: ", "", function(player, coins) coins = coins local tCoins = tonumber(vRPnc.getCoins(user_id)) if(tonumber(coins))then coins = tonumber(coins) if(tCoins >= coins)then vRPnc.takeCoins(user_id,coins) vRPclient.notify(player, {"~g~You took ~w~"..GetPlayerName(target).." ~w~"..coins.." ~g~coins"}) vRPclient.notify(target, {"~w~"..GetPlayerName(player).."~g~ took ~w~"..coins.." ~g~coins from you"}) else vRPclient.notify(player, {"~r~Player only has ~w~"..tCoins.." ~g~Coins"}) end else vRPclient.notify(player, {"~r~Number has to be a number!"}) end end}) else vRPclient.notify(player, {"~r~Player not online!"}) end end}) end vRP.registerMenuBuilder({"admin", function(add, data) local user_id = vRP.getUserId({data.player}) if user_id ~= nil then local choices = {} if(vRP.hasPermission({user_id, "newcoin.give"}))then choices["Give Coins"] = {givePlayerCoins, "Give coins to a player"} end if(vRP.hasPermission({user_id, "newcoin.take"}))then choices["Take Coins"] = {takePlayerCoins, "Take coins from a player"} end add(choices) end end})
30.179641
115
0.678571
be80488da16aa289bb2807ca4cb1032780e6e8c8
676
ts
TypeScript
types/autoScaling/scheduledAction.ts
streamich/cloudform
31403f9540ab52e239bb3630827314cfb4130c5c
[ "MIT" ]
1
2021-02-08T13:04:36.000Z
2021-02-08T13:04:36.000Z
types/autoScaling/scheduledAction.ts
streamich/cloudform
31403f9540ab52e239bb3630827314cfb4130c5c
[ "MIT" ]
null
null
null
types/autoScaling/scheduledAction.ts
streamich/cloudform
31403f9540ab52e239bb3630827314cfb4130c5c
[ "MIT" ]
null
null
null
/* Generated from https://d3teyb21fexa9r.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json, version 2.0.0 */ import {ResourceBase} from '../resource' import {Value, List} from '../dataTypes' export interface ScheduledActionProperties { AutoScalingGroupName: Value<string> DesiredCapacity?: Value<number> EndTime?: Value<string> MaxSize?: Value<number> MinSize?: Value<number> Recurrence?: Value<string> StartTime?: Value<string> } export default class ScheduledAction extends ResourceBase { constructor(properties?: ScheduledActionProperties) { super('AWS::AutoScaling::ScheduledAction', properties) } }
27.04
126
0.733728
2c84199ab229310194aea678cdf24df2a4f73524
3,525
cpp
C++
src/silk/_pysilk.cpp
wyapx/Python-Silk-Module
65619c79f78ac930073a8424ddb981b66d97ecde
[ "BSD-2-Clause" ]
null
null
null
src/silk/_pysilk.cpp
wyapx/Python-Silk-Module
65619c79f78ac930073a8424ddb981b66d97ecde
[ "BSD-2-Clause" ]
null
null
null
src/silk/_pysilk.cpp
wyapx/Python-Silk-Module
65619c79f78ac930073a8424ddb981b66d97ecde
[ "BSD-2-Clause" ]
null
null
null
#include <pybind11/pybind11.h> #define NO_ASM #include "codec.h" #include <cstdlib> #define STRINGIFY(x) #x #define MACRO_STRINGIFY(x) STRINGIFY(x) #include <iostream> #include <cstdio> class dataItem { public: std::vector<unsigned char> v_data; dataItem() { } ~dataItem() { } void writeData(void* p, int len) { for (int i = 0; i < len; i++){ v_data.push_back( *((unsigned char*)p + i) ); } return; } const void* getData(){ const void *p = v_data.data(); return p; } const std::size_t getDataLen(){ return v_data.size(); } const void printVec(){ for( auto iter :v_data){ printf("%c" , iter); } return; } }; void* codecCallback(void* userdata, unsigned char* p, int len){ auto ud = (dataItem*)userdata; ud->writeData(p , len); return userdata; }//Debug flag: No errors namespace py = pybind11; PYBIND11_MODULE(coder, m) { m.doc() = R"pbdoc( Python silk decode/encoder bindings using pybind11 ----------------------- .. currentmodule:: pysilk._coder .. autosummary:: :toctree: _generate Many thanks to the silk SDK and libSilkCodec. I modified some of the code to make it compatible as python module. License is appended to the LICENSE file of the github repo. Author: DCZYewen Contact: contact@basicws.net )pbdoc"; m.def("silkDecode",[](py::bytes rdata , int sampleRate){ py::gil_scoped_release release; std::string s_data(rdata); int buf_size = s_data.length()*sizeof(unsigned char); unsigned char* data = (unsigned char*)malloc(buf_size); memcpy(data , s_data.c_str() , buf_size); dataItem di = dataItem(); int ret = silkDecode(data , buf_size, sampleRate, codecCallback, (void*)&di); free(data); py::gil_scoped_acquire acquire; if(!ret) { return py::bytes(0); }else{ //std::string ret_val( (char*)di.getData() , di.getDataLen() ); return py::bytes((char*)di.getData() , di.getDataLen()); } },py::arg("Stream") , py::arg("SampleRate") , R"pbdoc( To call this function, the first param should be a bytes, which refers to the data stream to be Decoded. The second should be the samplerate of demand. )pbdoc"); m.def("silkEncode",[](py::bytes rdata , int sampleRate){ py::gil_scoped_release release; std::string s_data(rdata); int buf_size = s_data.length()*sizeof(unsigned char); unsigned char* data = (unsigned char*)malloc(buf_size); memcpy(data , s_data.c_str() , buf_size); dataItem di = dataItem(); int ret = silkEncode(data , buf_size, sampleRate, codecCallback, (void*)&di); free(data); py::gil_scoped_acquire acquire; if(!ret) { return py::bytes(0); }else{ return py::bytes((char*)di.getData() , di.getDataLen()); } },py::arg("Stream") , py::arg("SampleRate") , R"pbdoc( To call this function, the first param should be a bytes, which refers to the data stream to be Decoded. The second should be the sample_rate of demand. )pbdoc"); #ifdef VERSION_INFO m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); #else m.attr("__version__") = "dev"; #endif } /* Legal issues and opensource licenses see LICENSE file. */
28.658537
85
0.590071
388cd7985f928021f8b43b90c766c27f86c57116
1,488
php
PHP
app/Http/Controllers/admin/dashController.php
ahmadim017/perpustakaan-laravel
f333fe71521cedc50fd1ab0b8f838eb2d98ec12f
[ "MIT" ]
2
2020-07-07T06:26:24.000Z
2020-07-10T05:33:58.000Z
app/Http/Controllers/admin/dashController.php
ahmadim017/perpustakaan-laravel
f333fe71521cedc50fd1ab0b8f838eb2d98ec12f
[ "MIT" ]
4
2021-02-02T19:06:09.000Z
2022-02-27T06:22:54.000Z
app/Http/Controllers/admin/dashController.php
ahmadim017/perpustakaan-laravel
f333fe71521cedc50fd1ab0b8f838eb2d98ec12f
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\book; use App\author; use App\borrow; use App\User; use Illuminate\Support\Facades\DB; class dashController extends Controller { public function index() { $book = book::count(); $author = author::count(); $borrow = borrow::where('return_at',null)->count(); $kembali = borrow::whereNotNull('return_at')->count(); $buku = DB::table('books')->join('authors','books.author_id','=','authors.id') ->select('authors.name', DB::raw('count(*) as total, name'))->groupBy('authors.name')->inRandomOrder()->take(10)->get(); $penulis = []; $total = []; foreach ($buku as $k) { $penulis[] = $k->name; $total[] = $k->total; } $kategori = DB::table('books')->join('kategori','books.kategori_id','=','kategori.id') ->select('kategori.nama_kategori',DB::raw('count(*) as totalkategori, nama_kategori')) ->where('nama_kategori','<>',1)->groupBy('nama_kategori')->get(); $datakategori = []; foreach ($kategori as $k){ $datakategori[] = [$k->nama_kategori,$k->totalkategori]; } //dd($datakategori); return view('admin.dashboard.index',['book' => $book,'author' => $author,'borrow' => $borrow,'kembali' => $kembali,'penulis' => $penulis,'total' => $total,'datakategori' => $datakategori]); } }
36.292683
197
0.585349
b9c437a6716ba94f87dcae9d9269dd2422ba236f
1,977
swift
Swift
Example/Carthage/Checkouts/ViewComposer/Source/Classes/Attributed/Attributed+Mergeable.swift
AlleniCode/Zesame
79d456985f81f7139469ed676b354be1f053b296
[ "MIT" ]
33
2017-06-02T12:13:22.000Z
2020-12-23T04:00:05.000Z
Example/Carthage/Checkouts/ViewComposer/Source/Classes/Attributed/Attributed+Mergeable.swift
AlleniCode/Zesame
79d456985f81f7139469ed676b354be1f053b296
[ "MIT" ]
4
2017-06-11T17:24:03.000Z
2017-07-16T12:45:47.000Z
Example/Carthage/Checkouts/ViewComposer/Source/Classes/Attributed/Attributed+Mergeable.swift
AlleniCode/Zesame
79d456985f81f7139469ed676b354be1f053b296
[ "MIT" ]
4
2017-06-12T07:32:09.000Z
2018-11-23T08:31:03.000Z
// // Attributed+Mergeable.swift // ViewComposer // // Created by Alexander Cyon on 2017-06-06. // // import Foundation public extension Attributed { func merge(slave: Self, intercept: Bool) -> Self { var intercepted = self if intercept { Self.mergeInterceptors.forEach { intercepted = $0.interceptMerge(master: intercepted, slave: slave) } } let unionSet = Set(intercepted.stripped).union(Set(slave.stripped)) let unionAttributes = (intercepted.attributes + slave.attributes).filter(stripped: Array(unionSet)) return Self(unionAttributes) } func merge(slave: [Attribute], intercept: Bool) -> Self { return merge(slave: Self(slave), intercept: intercept) } func merge(master: [Attribute], intercept: Bool) -> Self { return Self(master).merge(slave: self, intercept: intercept) } func merge(slave: Attribute, intercept: Bool) -> Self { return merge(slave: Self([slave]), intercept: intercept) } func merge(master: Self, intercept: Bool) -> Self { return master.merge(slave: self, intercept: intercept) } func merge(master: Attribute, intercept: Bool) -> Self { return Self([master]).merge(slave: self, intercept: intercept) } } public extension Attributed { func merge(slave: Self) -> Self { return merge(slave: slave, intercept: true) } func merge(slave: [Attribute]) -> Self { return merge(slave: slave, intercept: true) } func merge(master: [Attribute]) -> Self { return merge(master: master, intercept: true) } func merge(slave: Attribute) -> Self { return merge(slave: slave, intercept: true) } func merge(master: Self) -> Self { return merge(master: master, intercept: true) } func merge(master: Attribute) -> Self { return merge(master: master, intercept: true) } }
28.652174
113
0.621143
ef353dc6c6275099c0900301b51fc77d49476fee
3,140
go
Go
vendor/golang.org/x/image/ccitt/reader.go
by46/WhaleFS
20029ad9a9b59089a3fdd681699ddfb3a5624ebc
[ "MIT" ]
1
2018-06-10T08:54:54.000Z
2018-06-10T08:54:54.000Z
vendor/golang.org/x/image/ccitt/reader.go
by46/whalefs
20029ad9a9b59089a3fdd681699ddfb3a5624ebc
[ "MIT" ]
null
null
null
vendor/golang.org/x/image/ccitt/reader.go
by46/whalefs
20029ad9a9b59089a3fdd681699ddfb3a5624ebc
[ "MIT" ]
null
null
null
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:generate go run gen.go // Package ccitt implements a CCITT (fax) image decoder. package ccitt import ( "encoding/binary" "errors" "io" "math/bits" ) var ( errInvalidCode = errors.New("ccitt: invalid code") ) // Order specifies the bit ordering in a CCITT data stream. type Order uint32 const ( // LSB means Least Significant Bits first. LSB Order = iota // MSB means Most Significant Bits first. MSB ) type bitReader struct { r io.Reader // readErr is the error returned from the most recent r.Read call. As the // io.Reader documentation says, when r.Read returns (n, err), "always // process the n > 0 bytes returned before considering the error err". readErr error order Order // The low nBits bits of the bits field hold upcoming bits in LSB order. bits uint64 nBits uint32 // bytes[br:bw] holds bytes read from r but not yet loaded into bits. br uint32 bw uint32 bytes [1024]uint8 } func (b *bitReader) alignToByteBoundary() { n := b.nBits & 7 b.bits >>= n b.nBits -= n } // nextBitMaxNBits is the maximum possible value of bitReader.nBits after a // bitReader.nextBit call, provided that bitReader.nBits was not more than this // value before that call. // // Note that the decode function can unread bits, which can temporarily set the // bitReader.nBits value above nextBitMaxNBits. const nextBitMaxNBits = 31 func (b *bitReader) nextBit() (uint32, error) { for { if b.nBits > 0 { bit := uint32(b.bits) & 1 b.bits >>= 1 b.nBits-- return bit, nil } if available := b.bw - b.br; available >= 4 { // Read 32 bits, even though b.bits is a uint64, since the decode // function may need to unread up to maxCodeLength bits, putting // them back in the remaining (64 - 32) bits. TestMaxCodeLength // checks that the generated maxCodeLength constant fits. // // If changing the Uint32 call, also change nextBitMaxNBits. b.bits = uint64(binary.LittleEndian.Uint32(b.bytes[b.br:])) b.br += 4 b.nBits = 32 continue } else if available > 0 { b.bits = uint64(b.bytes[b.br]) b.br++ b.nBits = 8 continue } if b.readErr != nil { return 0, b.readErr } n, err := b.r.Read(b.bytes[:]) b.br = 0 b.bw = uint32(n) b.readErr = err if b.order != LSB { written := b.bytes[:b.bw] for i, x := range written { written[i] = bits.Reverse8(x) } } } } func decode(b *bitReader, decodeTable [][2]int16) (uint32, error) { nBitsRead, bitsRead, state := uint32(0), uint32(0), int32(1) for { bit, err := b.nextBit() if err != nil { return 0, err } bitsRead |= bit << nBitsRead nBitsRead++ // The "&1" is redundant, but can eliminate a bounds check. state = int32(decodeTable[state][bit&1]) if state < 0 { return uint32(^state), nil } else if state == 0 { // Unread the bits we've read, then return errInvalidCode. b.bits = (b.bits << nBitsRead) | uint64(bitsRead) b.nBits += nBitsRead return 0, errInvalidCode } } }
23.969466
79
0.665924
9fd6dd1ac38fa525972e69d2cf73e1771b428f0f
2,730
css
CSS
CSS/GitBlocks/style.css
JosephAMumford/CodingDojo
505be74d18d7a8f41c4b3576ca050b97f840f0a3
[ "MIT" ]
2
2018-08-18T15:14:45.000Z
2019-10-16T16:14:13.000Z
CSS/GitBlocks/style.css
JosephAMumford/CodingDojo
505be74d18d7a8f41c4b3576ca050b97f840f0a3
[ "MIT" ]
null
null
null
CSS/GitBlocks/style.css
JosephAMumford/CodingDojo
505be74d18d7a8f41c4b3576ca050b97f840f0a3
[ "MIT" ]
6
2018-05-05T18:13:05.000Z
2021-05-20T11:32:48.000Z
#wrapper { background-color: rgb(221,223,212); width: 920px; margin: 0px auto; padding: 10px; } #header { background-color: rgb(63,176,172); height: 56px; display: block; margin: 0px; padding: 8px; } #header img { width: 48px; height: 48px; } #header h1 { display: inline-block; position: relative; bottom: 12px; left: 6px; } .topLinks { display: inline-block; width: 600px; height: 18px; margin: 0px; padding: 0px; position: relative; bottom: 16px; left: 80px; } .topLinks a { color: white; margin: 10px; } #main { background-color: rgb(250,229,150); width: 900px; height: 590px; padding: 10px; display: inline-block; } #sidebar { background-color: rgb(23,63,67); width: 180px; height: 560px; display: inline-block; margin: 5px 0px 0px 0px; padding: 10px; vertical-align: top; } #sidebar h2 { margin: 0px; color: white; } #sidebar p { margin: 5px 10px; padding: 0px 5px; color: white; } #content { width: 670px; height: 560px; margin: 10px 0px 0px 10px; padding: 0px 0px 0px 10px; display: inline-block; } .box-1 { background-color: rgb(23,63,67); color: white; width: 200px; height: 160px; display: inline-block; margin: 15px 10px; vertical-align: top; } .box-1 h3 { margin: 10px; } .box-1 p { margin: 15px; } .box-1 a { color: turquoise; } .box-2 { background-color: rgb(23,63,67); color: white; width: 310px; height: 160px; display: inline-block; margin: 10px 10px 10px 10px; } .box-2 h3 { margin: 10px; } .box-2 p { margin: 15px; } .box-2 a { color: turquoise; } .box-3 { background-color: rgb(23,63,67); color: white; width: 640px; height: 160px; display: inline-block; margin: 10px 10px 10px 10px; } .box-3 h3 { margin: 10px; } .box-3 p { margin: 15px; } .box-3 a { color: turquoise; } #footer { background-color: rgb(63,176,172); height: 32px; margin: 0px; padding: 8px; display: block; } #footer p { height: 18px; display: inline-block; position: relative; bottom: 8px; left: 256px; }
17.5
40
0.478755
2c7fdde362e53ae77e884f8df0b864268c483ff4
5,130
cpp
C++
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
#include "api_plugin_number.h" #include "rodsDef.h" #include "rcConnect.h" #include "rodsPackInstruct.h" #include "rcMisc.h" #include "client_api_whitelist.hpp" #include "apiHandler.hpp" #include <functional> #ifdef RODS_SERVER // // Server-side Implementation // #include "objDesc.hpp" #include "irods_stacktrace.hpp" #include "irods_server_api_call.hpp" #include "irods_re_serialization.hpp" #include "rsModDataObjMeta.hpp" #include "scoped_privileged_client.hpp" #include "key_value_proxy.hpp" #include <string> #include <tuple> namespace { // // Function Prototypes // auto call_data_object_modify_info(irods::api_entry*, rsComm_t*, modDataObjMeta_t*) -> int; auto is_input_valid(const bytesBuf_t*) -> std::tuple<bool, std::string>; auto rs_data_object_modify_info(rsComm_t*, modDataObjMeta_t*) -> int; // // Function Implementations // auto call_data_object_modify_info(irods::api_entry* api, rsComm_t* comm, modDataObjMeta_t* input) -> int { return api->call_handler<modDataObjMeta_t*>(comm, input); } auto is_input_valid(const modDataObjMeta_t* input) -> std::tuple<bool, std::string> { if (!input) { return {false, "Input is null"}; } irods::experimental::key_value_proxy proxy{*input->regParam}; const auto is_invalid_keyword = [](const auto& handle) { // To allow modification of a column, comment out the condition // referencing that column. return handle.key() == CHKSUM_KW || handle.key() == COLL_ID_KW || //handle.key() == DATA_COMMENTS_KW || handle.key() == DATA_CREATE_KW || //handle.key() == DATA_EXPIRY_KW || handle.key() == DATA_ID_KW || handle.key() == DATA_MAP_ID_KW || handle.key() == DATA_MODE_KW || //handle.key() == DATA_MODIFY_KW || handle.key() == DATA_NAME_KW || handle.key() == DATA_OWNER_KW || handle.key() == DATA_OWNER_ZONE_KW || //handle.key() == DATA_RESC_GROUP_NAME_KW || // Not defined. handle.key() == DATA_SIZE_KW || //handle.key() == DATA_TYPE_KW || handle.key() == FILE_PATH_KW || handle.key() == REPL_NUM_KW || handle.key() == REPL_STATUS_KW || handle.key() == RESC_HIER_STR_KW || handle.key() == RESC_ID_KW || handle.key() == RESC_NAME_KW || handle.key() == STATUS_STRING_KW || handle.key() == VERSION_KW; }; if (std::any_of(std::begin(proxy), std::end(proxy), is_invalid_keyword)) { return {false, "Invalid keyword found"}; } return {true, ""}; } auto rs_data_object_modify_info(rsComm_t* comm, modDataObjMeta_t* input) -> int { if (auto [valid, msg] = is_input_valid(input); !valid) { rodsLog(LOG_ERROR, msg.data()); return USER_BAD_KEYWORD_ERR; } irods::experimental::scoped_privileged_client spc{*comm}; return rsModDataObjMeta(comm, input); } using operation = std::function<int(rsComm_t*, modDataObjMeta_t*)>; const operation op = rs_data_object_modify_info; #define CALL_DATA_OBJECT_MODIFY_INFO call_data_object_modify_info } // anonymous namespace #else // RODS_SERVER // // Client-side Implementation // #include "modDataObjMeta.h" namespace { using operation = std::function<int(rsComm_t*, modDataObjMeta_t*)>; const operation op{}; #define CALL_DATA_OBJECT_MODIFY_INFO nullptr } // anonymous namespace #endif // RODS_SERVER // The plugin factory function must always be defined. extern "C" auto plugin_factory(const std::string& _instance_name, const std::string& _context) -> irods::api_entry* { #ifdef RODS_SERVER irods::client_api_whitelist::instance().add(DATA_OBJECT_MODIFY_INFO_APN); #endif // RODS_SERVER // clang-format off irods::apidef_t def{DATA_OBJECT_MODIFY_INFO_APN, // API number RODS_API_VERSION, // API version NO_USER_AUTH, // Client auth NO_USER_AUTH, // Proxy auth "ModDataObjMeta_PI", 0, // In PI / bs flag nullptr, 0, // Out PI / bs flag op, // Operation "data_object_modify_info", // Operation name clearModDataObjMetaInp, // Null clear function (funcPtr) CALL_DATA_OBJECT_MODIFY_INFO}; // clang-format on auto* api = new irods::api_entry{def}; api->in_pack_key = "ModDataObjMeta_PI"; api->in_pack_value = ModDataObjMeta_PI; return api; }
32.675159
94
0.569591
a42f2265b1e1c75f26987662fdd9eae100045cd1
4,444
php
PHP
application/views/administrator/mod_domain/view_orders_report.php
ncip48/nusaserver
79b4529cc6be3fcfaf719b96ae5cc6c32f686624
[ "MIT" ]
null
null
null
application/views/administrator/mod_domain/view_orders_report.php
ncip48/nusaserver
79b4529cc6be3fcfaf719b96ae5cc6c32f686624
[ "MIT" ]
null
null
null
application/views/administrator/mod_domain/view_orders_report.php
ncip48/nusaserver
79b4529cc6be3fcfaf719b96ae5cc6c32f686624
[ "MIT" ]
null
null
null
<div class='col-md-12'> <div class='box box-info'> <div class='box-header with-border'> <h3 class='box-title'>Detail Data Orders Masuk</h3> <a target='_BLANK' class='pull-right btn btn-warning btn-sm' href='<?php echo base_url(); ?>administrator/print_orders'>Print Report</a> </div> <div class='box-body'> <div class='col-md-12 table-responsive'> <table id="example1" class='table table-hover table-condensed'> <thead> <tr> <th width="20px">No</th> <th>No Tagihan</th> <th>Nama Pelanggan</th> <th>Nama Domain</th> <th>TLD</th> <th>Durasi</th> <th>Harga</th> <th>Waktu Transaksi</th> <th></th> </tr> </thead> <tbody> <?php $no = 1; foreach ($record->result_array() as $row){ if ($row['aktif']=='0'){ $proses = '<i class="text-danger">Belum Aktif</i>'; $color = 'danger'; $text = 'Belum Aktif'; }elseif($row['aktif']=='1'){ $proses = '<i class="text-warning">Sudah Aktif</i>'; $color = 'warning'; $text = 'Sudah Aktif'; } $total = $this->db->query("SELECT a.kode_transaksi, a.kurir, a.service, a.proses, a.ongkir, e.nama_kota, f.nama_provinsi, sum((b.harga_jual*b.jumlah)-(c.diskon*b.jumlah)) as total FROM `rb_penjualan` a JOIN rb_penjualan_detail b ON a.id_penjualan=b.id_penjualan JOIN rb_produk c ON b.id_produk=c.id_produk JOIN rb_konsumen d ON a.id_pembeli=d.id_konsumen JOIN rb_kota e ON d.kota_id=e.kota_id JOIN rb_provinsi f ON e.provinsi_id=f.provinsi_id where a.kode_transaksi='$row[kode_transaksi]'")->row_array(); echo "<tr><td>$no</td> <td>$row[no_tagihan]</td> <td>$row[nama_lengkap]</td> <td>$row[nama_domain]</td> <td>$row[tld]</td> <td>$row[durasi_domain] Hari</td> <td style='color:red;'>Rp ".rupiah($row['harga_domain'])."</td> <td>".tgl_jam($row[tgl_daftar])."</td> <td width='150px'> <div class='btn-group'> <button style='width:70px' type='button' class='btn btn-$color btn-xs'>$text</button> <button type='button' class='btn btn-$color btn-xs dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'> <span class='caret'></span> <span class='sr-only'>Toggle Dropdown</span> </button> <ul class='dropdown-menu' style='border:1px solid #cecece;'> <li><a href='".base_url()."administrator/orders_status/$row[id_penjualan]/0' onclick=\"return confirm('Apa anda yakin untuk ubah status jadi NonAktif ?')\"> NonAktifkan</a></li> <li><a href='".base_url()."administrator/orders_status/$row[id_penjualan]/1' onclick=\"return confirm('Apa anda yakin untuk ubah status jadi Aktif ?')\"> Aktifkan</a></li> </ul> </div> </tr>"; $no++; } ?> </tbody> </table> </div> </div> </div> </div>
77.964912
538
0.391089
4e6494493193d1bcb5f2ad5fc9e58dda8b927e7b
71
sh
Shell
containers/php.sh
max-starikevich/bitrix-base-project
1d9c0ca1595c423f9b339419cdeea9d352a5036d
[ "MIT" ]
8
2018-08-08T14:09:29.000Z
2019-03-30T18:57:17.000Z
containers/php.sh
SergeiDudyuk/bitrix-base-project
1d9c0ca1595c423f9b339419cdeea9d352a5036d
[ "MIT" ]
null
null
null
containers/php.sh
SergeiDudyuk/bitrix-base-project
1d9c0ca1595c423f9b339419cdeea9d352a5036d
[ "MIT" ]
1
2018-11-28T09:14:24.000Z
2018-11-28T09:14:24.000Z
#!/bin/bash docker-compose run -u www-data --rm --entrypoint bash php
17.75
57
0.704225
7be76930a2d6cbc28e5a47e0443d13cee4afb2a2
1,219
cpp
C++
EntityComponentSystem/PbrRenderer/Material.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
EntityComponentSystem/PbrRenderer/Material.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
EntityComponentSystem/PbrRenderer/Material.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
#include "Material.hpp" renderer::MaterialTexture::MaterialTexture(const Texture* texture) : _texture(texture) {} renderer::MaterialTexture::MaterialTexture(float value) : _textureOwner(true) { auto tex = new Texture(); const uint8_t byteVal = uint8_t(value * 255.0f); tex->loadFromMemory(&byteVal, 1, 1, 1); _texture = tex; } renderer::MaterialTexture::MaterialTexture(const glm::vec3& value) { auto tex = new Texture(); const uint8_t byteVal[] = { uint8_t(value.x * 255.0f), uint8_t(value.y * 255.0f), uint8_t(value.z * 255.0f) }; tex->loadFromMemory(&byteVal[0], 3, 1, 1); _texture = tex; } renderer::MaterialTexture::MaterialTexture(MaterialTexture&& other) : _texture(other._texture), _textureOwner(other._textureOwner) { other._texture = nullptr; other._textureOwner = false; } renderer::MaterialTexture& renderer::MaterialTexture::operator=(MaterialTexture&& other) { _texture = other._texture; _textureOwner = other._textureOwner; other._texture = nullptr; other._textureOwner = false; return *this; } renderer::MaterialTexture::~MaterialTexture() { if (_textureOwner) delete _texture; } const renderer::Texture* renderer::MaterialTexture::getTexture() const { return _texture; }
25.395833
111
0.73913