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
6c610e0958b023c7f235705ccd3fc4dd44281a6f
275
dart
Dart
oxen_coin/lib/structs/subaddress_row.dart
jagerman/oxen-wallet
f641b5b129163ba1bb2ed43d24f2aa344510cfe2
[ "MIT" ]
14
2021-01-26T04:41:36.000Z
2021-11-28T11:20:52.000Z
oxen_coin/lib/structs/subaddress_row.dart
jagerman/oxen-wallet
f641b5b129163ba1bb2ed43d24f2aa344510cfe2
[ "MIT" ]
28
2021-01-19T02:36:34.000Z
2021-06-30T03:20:32.000Z
oxen_coin/lib/structs/subaddress_row.dart
jagerman/oxen-wallet
f641b5b129163ba1bb2ed43d24f2aa344510cfe2
[ "MIT" ]
15
2021-01-25T05:13:11.000Z
2022-03-06T21:43:32.000Z
import 'dart:ffi'; import 'package:ffi/ffi.dart'; class SubaddressRow extends Struct { @Int64() int id; Pointer<Utf8> address; Pointer<Utf8> label; String getLabel() => Utf8.fromUtf8(label); String getAddress() => Utf8.fromUtf8(address); int getId() => id; }
19.642857
48
0.68
7f8835276ae1caa39271b60ec0526adabafcd3b2
632
php
PHP
src/Oro/Bundle/ImportExportBundle/Tests/Unit/Event/AfterJobExecutionEventTest.php
raffaelecarelle/platform-1
e8d5d9d824080535b1f304c662c86351896958fa
[ "MIT" ]
173
2017-07-25T13:37:58.000Z
2022-02-17T18:24:37.000Z
src/Oro/Bundle/ImportExportBundle/Tests/Unit/Event/AfterJobExecutionEventTest.php
raffaelecarelle/platform-1
e8d5d9d824080535b1f304c662c86351896958fa
[ "MIT" ]
401
2017-07-24T23:04:42.000Z
2022-03-31T06:39:45.000Z
src/Oro/Bundle/ImportExportBundle/Tests/Unit/Event/AfterJobExecutionEventTest.php
raffaelecarelle/platform-1
e8d5d9d824080535b1f304c662c86351896958fa
[ "MIT" ]
171
2017-07-27T03:47:23.000Z
2022-03-30T21:31:56.000Z
<?php namespace Oro\Bundle\ImportExportBundle\Tests\Unit\Event; use Oro\Bundle\BatchBundle\Entity\JobExecution; use Oro\Bundle\ImportExportBundle\Event\AfterJobExecutionEvent; use Oro\Bundle\ImportExportBundle\Job\JobResult; class AfterJobExecutionEventTest extends \PHPUnit\Framework\TestCase { public function testEvent() { $jobExecution = new JobExecution(); $jobResult = new JobResult(); $event = new AfterJobExecutionEvent($jobExecution, $jobResult); $this->assertSame($jobExecution, $event->getJobExecution()); $this->assertSame($jobResult, $event->getJobResult()); } }
30.095238
71
0.732595
439da92598a7cc4c140ae44395effdd024dc6739
1,106
ts
TypeScript
clients/node/client-application-auto-scaling-node/types/InputTypesUnion.ts
pravgupt/aws-sdk-js-v3
1fd0fab5da141d934eb98624d6c23b347806bb47
[ "Apache-2.0" ]
null
null
null
clients/node/client-application-auto-scaling-node/types/InputTypesUnion.ts
pravgupt/aws-sdk-js-v3
1fd0fab5da141d934eb98624d6c23b347806bb47
[ "Apache-2.0" ]
null
null
null
clients/node/client-application-auto-scaling-node/types/InputTypesUnion.ts
pravgupt/aws-sdk-js-v3
1fd0fab5da141d934eb98624d6c23b347806bb47
[ "Apache-2.0" ]
null
null
null
import { DeleteScalingPolicyInput } from "./DeleteScalingPolicyInput"; import { DeleteScheduledActionInput } from "./DeleteScheduledActionInput"; import { DeregisterScalableTargetInput } from "./DeregisterScalableTargetInput"; import { DescribeScalableTargetsInput } from "./DescribeScalableTargetsInput"; import { DescribeScalingActivitiesInput } from "./DescribeScalingActivitiesInput"; import { DescribeScalingPoliciesInput } from "./DescribeScalingPoliciesInput"; import { DescribeScheduledActionsInput } from "./DescribeScheduledActionsInput"; import { PutScalingPolicyInput } from "./PutScalingPolicyInput"; import { PutScheduledActionInput } from "./PutScheduledActionInput"; import { RegisterScalableTargetInput } from "./RegisterScalableTargetInput"; export type InputTypesUnion = | DeleteScalingPolicyInput | DeleteScheduledActionInput | DeregisterScalableTargetInput | DescribeScalableTargetsInput | DescribeScalingActivitiesInput | DescribeScalingPoliciesInput | DescribeScheduledActionsInput | PutScalingPolicyInput | PutScheduledActionInput | RegisterScalableTargetInput;
50.272727
82
0.831826
ba6820401e31353be9b406bf5e7cf2d835f4f8fa
674
kt
Kotlin
idea/testData/inspections/recursivePropertyAccessor/recursivePropertyAccessors.kt
qussarah/declare
c83b764c7394efa3364915d973ae79c4ebed2437
[ "Apache-2.0" ]
null
null
null
idea/testData/inspections/recursivePropertyAccessor/recursivePropertyAccessors.kt
qussarah/declare
c83b764c7394efa3364915d973ae79c4ebed2437
[ "Apache-2.0" ]
null
null
null
idea/testData/inspections/recursivePropertyAccessor/recursivePropertyAccessors.kt
qussarah/declare
c83b764c7394efa3364915d973ae79c4ebed2437
[ "Apache-2.0" ]
null
null
null
class A { var x = 0 set(value) { x++ x += 1 x = value } var y = 0 get() { println("$y") y++ y += 1 return y } var z = 0 get() = z var w set(value) { field = w + value } var field = 0 get() { this.field return if (field != 0) field else -1 } set(value) { this.field = value if (value >= 0) field = value } companion object { var g = 0 set(value) { A.g = 99 } } }
16.439024
48
0.301187
4cf69d15b8b4539fe153095027acbad6190e6fe7
542
py
Python
CaterPillarMethod/count_distinct_slices.py
mamoudmatook/codility_solutions
0eb6936b2dddee46447fa6c0b0ef91b6784e58fb
[ "MIT" ]
null
null
null
CaterPillarMethod/count_distinct_slices.py
mamoudmatook/codility_solutions
0eb6936b2dddee46447fa6c0b0ef91b6784e58fb
[ "MIT" ]
null
null
null
CaterPillarMethod/count_distinct_slices.py
mamoudmatook/codility_solutions
0eb6936b2dddee46447fa6c0b0ef91b6784e58fb
[ "MIT" ]
null
null
null
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(M, A): hash = [0] * (M + 1) slices = 0 max_slices = 1000000000 head = 0 for tail in range(len(A)): while head < len(A) and ( not hash[A[head]]): hash[A[head]] = 1 slices += head - tail + 1 if slices > max_slices: return max_slices head += 1 hash[A[tail]] = False return slices solution(6, [3, 4, 5, 5, 2])
23.565217
54
0.49262
6af6751858fd668eedf0c1278550d5c0ac728f78
34,172
c
C
engine/code/sdl/sdl_input.c
bfakhri/dml_custom
1e908b10890df11e510d72c21f3125e3069a0eac
[ "CC-BY-4.0" ]
null
null
null
engine/code/sdl/sdl_input.c
bfakhri/dml_custom
1e908b10890df11e510d72c21f3125e3069a0eac
[ "CC-BY-4.0" ]
null
null
null
engine/code/sdl/sdl_input.c
bfakhri/dml_custom
1e908b10890df11e510d72c21f3125e3069a0eac
[ "CC-BY-4.0" ]
null
null
null
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #ifdef USE_LOCAL_HEADERS # include "SDL.h" #else # include <SDL.h> #endif #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include "../client/client.h" #include "../sys/sys_local.h" static cvar_t *in_keyboardDebug = NULL; static SDL_GameController *gamepad = NULL; static SDL_Joystick *stick = NULL; static qboolean mouseAvailable = qfalse; static qboolean mouseActive = qfalse; static cvar_t *in_mouse = NULL; static cvar_t *in_nograb; static cvar_t *in_joystick = NULL; static cvar_t *in_joystickThreshold = NULL; static cvar_t *in_joystickNo = NULL; static cvar_t *in_joystickUseAnalog = NULL; static int vidRestartTime = 0; static int in_eventTime = 0; static SDL_Window *SDL_window = NULL; #define CTRL(a) ((a)-'a'+1) /* =============== IN_PrintKey =============== */ static void IN_PrintKey( const SDL_Keysym *keysym, keyNum_t key, qboolean down ) { if( down ) Com_Printf( "+ " ); else Com_Printf( " " ); Com_Printf( "Scancode: 0x%02x(%s) Sym: 0x%02x(%s)", keysym->scancode, SDL_GetScancodeName( keysym->scancode ), keysym->sym, SDL_GetKeyName( keysym->sym ) ); if( keysym->mod & KMOD_LSHIFT ) Com_Printf( " KMOD_LSHIFT" ); if( keysym->mod & KMOD_RSHIFT ) Com_Printf( " KMOD_RSHIFT" ); if( keysym->mod & KMOD_LCTRL ) Com_Printf( " KMOD_LCTRL" ); if( keysym->mod & KMOD_RCTRL ) Com_Printf( " KMOD_RCTRL" ); if( keysym->mod & KMOD_LALT ) Com_Printf( " KMOD_LALT" ); if( keysym->mod & KMOD_RALT ) Com_Printf( " KMOD_RALT" ); if( keysym->mod & KMOD_LGUI ) Com_Printf( " KMOD_LGUI" ); if( keysym->mod & KMOD_RGUI ) Com_Printf( " KMOD_RGUI" ); if( keysym->mod & KMOD_NUM ) Com_Printf( " KMOD_NUM" ); if( keysym->mod & KMOD_CAPS ) Com_Printf( " KMOD_CAPS" ); if( keysym->mod & KMOD_MODE ) Com_Printf( " KMOD_MODE" ); if( keysym->mod & KMOD_RESERVED ) Com_Printf( " KMOD_RESERVED" ); Com_Printf( " Q:0x%02x(%s)\n", key, Key_KeynumToString( key ) ); } #define MAX_CONSOLE_KEYS 16 /* =============== IN_IsConsoleKey TODO: If the SDL_Scancode situation improves, use it instead of both of these methods =============== */ static qboolean IN_IsConsoleKey( keyNum_t key, int character ) { typedef struct consoleKey_s { enum { QUAKE_KEY, CHARACTER } type; union { keyNum_t key; int character; } u; } consoleKey_t; static consoleKey_t consoleKeys[ MAX_CONSOLE_KEYS ]; static int numConsoleKeys = 0; int i; // Only parse the variable when it changes if( cl_consoleKeys->modified ) { char *text_p, *token; cl_consoleKeys->modified = qfalse; text_p = cl_consoleKeys->string; numConsoleKeys = 0; while( numConsoleKeys < MAX_CONSOLE_KEYS ) { consoleKey_t *c = &consoleKeys[ numConsoleKeys ]; int charCode = 0; token = COM_Parse( &text_p ); if( !token[ 0 ] ) break; if( strlen( token ) == 4 ) charCode = Com_HexStrToInt( token ); if( charCode > 0 ) { c->type = CHARACTER; c->u.character = charCode; } else { c->type = QUAKE_KEY; c->u.key = Key_StringToKeynum( token ); // 0 isn't a key if( c->u.key <= 0 ) continue; } numConsoleKeys++; } } // If the character is the same as the key, prefer the character if( key == character ) key = 0; for( i = 0; i < numConsoleKeys; i++ ) { consoleKey_t *c = &consoleKeys[ i ]; switch( c->type ) { case QUAKE_KEY: if( key && c->u.key == key ) return qtrue; break; case CHARACTER: if( c->u.character == character ) return qtrue; break; } } return qfalse; } /* =============== IN_TranslateSDLToQ3Key =============== */ static keyNum_t IN_TranslateSDLToQ3Key( SDL_Keysym *keysym, qboolean down ) { keyNum_t key = 0; if( keysym->scancode >= SDL_SCANCODE_1 && keysym->scancode <= SDL_SCANCODE_0 ) { // Always map the number keys as such even if they actually map // to other characters (eg, "1" is "&" on an AZERTY keyboard). // This is required for SDL before 2.0.6, except on Windows // which already had this behavior. if( keysym->scancode == SDL_SCANCODE_0 ) key = '0'; else key = '1' + keysym->scancode - SDL_SCANCODE_1; } else if( keysym->sym >= SDLK_SPACE && keysym->sym < SDLK_DELETE ) { // These happen to match the ASCII chars key = (int)keysym->sym; } else { switch( keysym->sym ) { case SDLK_PAGEUP: key = K_PGUP; break; case SDLK_KP_9: key = K_KP_PGUP; break; case SDLK_PAGEDOWN: key = K_PGDN; break; case SDLK_KP_3: key = K_KP_PGDN; break; case SDLK_KP_7: key = K_KP_HOME; break; case SDLK_HOME: key = K_HOME; break; case SDLK_KP_1: key = K_KP_END; break; case SDLK_END: key = K_END; break; case SDLK_KP_4: key = K_KP_LEFTARROW; break; case SDLK_LEFT: key = K_LEFTARROW; break; case SDLK_KP_6: key = K_KP_RIGHTARROW; break; case SDLK_RIGHT: key = K_RIGHTARROW; break; case SDLK_KP_2: key = K_KP_DOWNARROW; break; case SDLK_DOWN: key = K_DOWNARROW; break; case SDLK_KP_8: key = K_KP_UPARROW; break; case SDLK_UP: key = K_UPARROW; break; case SDLK_ESCAPE: key = K_ESCAPE; break; case SDLK_KP_ENTER: key = K_KP_ENTER; break; case SDLK_RETURN: key = K_ENTER; break; case SDLK_TAB: key = K_TAB; break; case SDLK_F1: key = K_F1; break; case SDLK_F2: key = K_F2; break; case SDLK_F3: key = K_F3; break; case SDLK_F4: key = K_F4; break; case SDLK_F5: key = K_F5; break; case SDLK_F6: key = K_F6; break; case SDLK_F7: key = K_F7; break; case SDLK_F8: key = K_F8; break; case SDLK_F9: key = K_F9; break; case SDLK_F10: key = K_F10; break; case SDLK_F11: key = K_F11; break; case SDLK_F12: key = K_F12; break; case SDLK_F13: key = K_F13; break; case SDLK_F14: key = K_F14; break; case SDLK_F15: key = K_F15; break; case SDLK_BACKSPACE: key = K_BACKSPACE; break; case SDLK_KP_PERIOD: key = K_KP_DEL; break; case SDLK_DELETE: key = K_DEL; break; case SDLK_PAUSE: key = K_PAUSE; break; case SDLK_LSHIFT: case SDLK_RSHIFT: key = K_SHIFT; break; case SDLK_LCTRL: case SDLK_RCTRL: key = K_CTRL; break; #ifdef __APPLE__ case SDLK_RGUI: case SDLK_LGUI: key = K_COMMAND; break; #else case SDLK_RGUI: case SDLK_LGUI: key = K_SUPER; break; #endif case SDLK_RALT: case SDLK_LALT: key = K_ALT; break; case SDLK_KP_5: key = K_KP_5; break; case SDLK_INSERT: key = K_INS; break; case SDLK_KP_0: key = K_KP_INS; break; case SDLK_KP_MULTIPLY: key = K_KP_STAR; break; case SDLK_KP_PLUS: key = K_KP_PLUS; break; case SDLK_KP_MINUS: key = K_KP_MINUS; break; case SDLK_KP_DIVIDE: key = K_KP_SLASH; break; case SDLK_MODE: key = K_MODE; break; case SDLK_HELP: key = K_HELP; break; case SDLK_PRINTSCREEN: key = K_PRINT; break; case SDLK_SYSREQ: key = K_SYSREQ; break; case SDLK_MENU: key = K_MENU; break; case SDLK_APPLICATION: key = K_MENU; break; case SDLK_POWER: key = K_POWER; break; case SDLK_UNDO: key = K_UNDO; break; case SDLK_SCROLLLOCK: key = K_SCROLLOCK; break; case SDLK_NUMLOCKCLEAR: key = K_KP_NUMLOCK; break; case SDLK_CAPSLOCK: key = K_CAPSLOCK; break; default: if( !( keysym->sym & SDLK_SCANCODE_MASK ) && keysym->scancode <= 95 ) { // Map Unicode characters to 95 world keys using the key's scan code. // FIXME: There aren't enough world keys to cover all the scancodes. // Maybe create a map of scancode to quake key at start up and on // key map change; allocate world key numbers as needed similar // to SDL 1.2. key = K_WORLD_0 + (int)keysym->scancode; } break; } } if( in_keyboardDebug->integer ) IN_PrintKey( keysym, key, down ); if( IN_IsConsoleKey( key, 0 ) ) { // Console keys can't be bound or generate characters key = K_CONSOLE; } return key; } /* =============== IN_GobbleMotionEvents =============== */ static void IN_GobbleMotionEvents( void ) { SDL_Event dummy[ 1 ]; int val = 0; // Gobble any mouse motion events SDL_PumpEvents( ); while( ( val = SDL_PeepEvents( dummy, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION ) ) > 0 ) { } if ( val < 0 ) Com_Printf( "IN_GobbleMotionEvents failed: %s\n", SDL_GetError( ) ); } /* =============== IN_ActivateMouse =============== */ static void IN_ActivateMouse( void ) { if (!mouseAvailable || !SDL_WasInit( SDL_INIT_VIDEO ) ) return; if( !mouseActive ) { SDL_SetRelativeMouseMode( SDL_TRUE ); SDL_SetWindowGrab( SDL_window, SDL_TRUE ); IN_GobbleMotionEvents( ); } // in_nograb makes no sense in fullscreen mode if( !Cvar_VariableIntegerValue("r_fullscreen") ) { if( in_nograb->modified || !mouseActive ) { if( in_nograb->integer ) { SDL_SetRelativeMouseMode( SDL_FALSE ); SDL_SetWindowGrab( SDL_window, SDL_FALSE ); } else { SDL_SetRelativeMouseMode( SDL_TRUE ); SDL_SetWindowGrab( SDL_window, SDL_TRUE ); } in_nograb->modified = qfalse; } } mouseActive = qtrue; } /* =============== IN_DeactivateMouse =============== */ static void IN_DeactivateMouse( void ) { if( !SDL_WasInit( SDL_INIT_VIDEO ) ) return; // Always show the cursor when the mouse is disabled, // but not when fullscreen if( !Cvar_VariableIntegerValue("r_fullscreen") ) SDL_ShowCursor( 1 ); if( !mouseAvailable ) return; if( mouseActive ) { IN_GobbleMotionEvents( ); SDL_SetWindowGrab( SDL_window, SDL_FALSE ); SDL_SetRelativeMouseMode( SDL_FALSE ); // Don't warp the mouse unless the cursor is within the window if( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_MOUSE_FOCUS ) SDL_WarpMouseInWindow( SDL_window, cls.glconfig.vidWidth / 2, cls.glconfig.vidHeight / 2 ); mouseActive = qfalse; } } // We translate axes movement into keypresses static int joy_keys[16] = { K_LEFTARROW, K_RIGHTARROW, K_UPARROW, K_DOWNARROW, K_JOY17, K_JOY18, K_JOY19, K_JOY20, K_JOY21, K_JOY22, K_JOY23, K_JOY24, K_JOY25, K_JOY26, K_JOY27, K_JOY28 }; // translate hat events into keypresses // the 4 highest buttons are used for the first hat ... static int hat_keys[16] = { K_JOY29, K_JOY30, K_JOY31, K_JOY32, K_JOY25, K_JOY26, K_JOY27, K_JOY28, K_JOY21, K_JOY22, K_JOY23, K_JOY24, K_JOY17, K_JOY18, K_JOY19, K_JOY20 }; struct { qboolean buttons[SDL_CONTROLLER_BUTTON_MAX + 1]; // +1 because old max was 16, current SDL_CONTROLLER_BUTTON_MAX is 15 unsigned int oldaxes; int oldaaxes[MAX_JOYSTICK_AXIS]; unsigned int oldhats; } stick_state; /* =============== IN_InitJoystick =============== */ static void IN_InitJoystick( void ) { int i = 0; int total = 0; char buf[16384] = ""; if (gamepad) SDL_GameControllerClose(gamepad); if (stick != NULL) SDL_JoystickClose(stick); stick = NULL; gamepad = NULL; memset(&stick_state, '\0', sizeof (stick_state)); // SDL 2.0.4 requires SDL_INIT_JOYSTICK to be initialized separately from // SDL_INIT_GAMECONTROLLER for SDL_JoystickOpen() to work correctly, // despite https://wiki.libsdl.org/SDL_Init (retrieved 2016-08-16) // indicating SDL_INIT_JOYSTICK should be initialized automatically. if (!SDL_WasInit(SDL_INIT_JOYSTICK)) { Com_DPrintf("Calling SDL_Init(SDL_INIT_JOYSTICK)...\n"); if (SDL_Init(SDL_INIT_JOYSTICK) != 0) { Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError()); return; } Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) passed.\n"); } if (!SDL_WasInit(SDL_INIT_GAMECONTROLLER)) { Com_DPrintf("Calling SDL_Init(SDL_INIT_GAMECONTROLLER)...\n"); if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) { Com_DPrintf("SDL_Init(SDL_INIT_GAMECONTROLLER) failed: %s\n", SDL_GetError()); return; } Com_DPrintf("SDL_Init(SDL_INIT_GAMECONTROLLER) passed.\n"); } total = SDL_NumJoysticks(); Com_DPrintf("%d possible joysticks\n", total); // Print list and build cvar to allow ui to select joystick. for (i = 0; i < total; i++) { Q_strcat(buf, sizeof(buf), SDL_JoystickNameForIndex(i)); Q_strcat(buf, sizeof(buf), "\n"); } Cvar_Get( "in_availableJoysticks", buf, CVAR_ROM ); if( !in_joystick->integer ) { Com_DPrintf( "Joystick is not active.\n" ); SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); return; } in_joystickNo = Cvar_Get( "in_joystickNo", "0", CVAR_ARCHIVE ); if( in_joystickNo->integer < 0 || in_joystickNo->integer >= total ) Cvar_Set( "in_joystickNo", "0" ); in_joystickUseAnalog = Cvar_Get( "in_joystickUseAnalog", "0", CVAR_ARCHIVE ); stick = SDL_JoystickOpen( in_joystickNo->integer ); if (stick == NULL) { Com_DPrintf( "No joystick opened: %s\n", SDL_GetError() ); return; } if (SDL_IsGameController(in_joystickNo->integer)) gamepad = SDL_GameControllerOpen(in_joystickNo->integer); Com_DPrintf( "Joystick %d opened\n", in_joystickNo->integer ); Com_DPrintf( "Name: %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer) ); Com_DPrintf( "Axes: %d\n", SDL_JoystickNumAxes(stick) ); Com_DPrintf( "Hats: %d\n", SDL_JoystickNumHats(stick) ); Com_DPrintf( "Buttons: %d\n", SDL_JoystickNumButtons(stick) ); Com_DPrintf( "Balls: %d\n", SDL_JoystickNumBalls(stick) ); Com_DPrintf( "Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No" ); Com_DPrintf( "Is gamepad: %s\n", gamepad ? "Yes" : "No" ); SDL_JoystickEventState(SDL_QUERY); SDL_GameControllerEventState(SDL_QUERY); } /* =============== IN_ShutdownJoystick =============== */ static void IN_ShutdownJoystick( void ) { if ( !SDL_WasInit( SDL_INIT_GAMECONTROLLER ) ) return; if ( !SDL_WasInit( SDL_INIT_JOYSTICK ) ) return; if (gamepad) { SDL_GameControllerClose(gamepad); gamepad = NULL; } if (stick) { SDL_JoystickClose(stick); stick = NULL; } SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); SDL_QuitSubSystem(SDL_INIT_JOYSTICK); } static qboolean KeyToAxisAndSign(int keynum, int *outAxis, int *outSign) { char *bind; if (!keynum) return qfalse; bind = Key_GetBinding(keynum); if (!bind || *bind != '+') return qfalse; *outSign = 0; if (Q_stricmp(bind, "+forward") == 0) { *outAxis = j_forward_axis->integer; *outSign = j_forward->value > 0.0f ? 1 : -1; } else if (Q_stricmp(bind, "+back") == 0) { *outAxis = j_forward_axis->integer; *outSign = j_forward->value > 0.0f ? -1 : 1; } else if (Q_stricmp(bind, "+moveleft") == 0) { *outAxis = j_side_axis->integer; *outSign = j_side->value > 0.0f ? -1 : 1; } else if (Q_stricmp(bind, "+moveright") == 0) { *outAxis = j_side_axis->integer; *outSign = j_side->value > 0.0f ? 1 : -1; } else if (Q_stricmp(bind, "+lookup") == 0) { *outAxis = j_pitch_axis->integer; *outSign = j_pitch->value > 0.0f ? -1 : 1; } else if (Q_stricmp(bind, "+lookdown") == 0) { *outAxis = j_pitch_axis->integer; *outSign = j_pitch->value > 0.0f ? 1 : -1; } else if (Q_stricmp(bind, "+left") == 0) { *outAxis = j_yaw_axis->integer; *outSign = j_yaw->value > 0.0f ? 1 : -1; } else if (Q_stricmp(bind, "+right") == 0) { *outAxis = j_yaw_axis->integer; *outSign = j_yaw->value > 0.0f ? -1 : 1; } else if (Q_stricmp(bind, "+moveup") == 0) { *outAxis = j_up_axis->integer; *outSign = j_up->value > 0.0f ? 1 : -1; } else if (Q_stricmp(bind, "+movedown") == 0) { *outAxis = j_up_axis->integer; *outSign = j_up->value > 0.0f ? -1 : 1; } return *outSign != 0; } /* =============== IN_GamepadMove =============== */ static void IN_GamepadMove( void ) { int i; int translatedAxes[MAX_JOYSTICK_AXIS]; qboolean translatedAxesSet[MAX_JOYSTICK_AXIS]; SDL_GameControllerUpdate(); // check buttons for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) { qboolean pressed = SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_A + i); if (pressed != stick_state.buttons[i]) { Com_QueueEvent(in_eventTime, SE_KEY, K_PAD0_A + i, pressed, 0, NULL); stick_state.buttons[i] = pressed; } } // must defer translated axes until all real axes are processed // must be done this way to prevent a later mapped axis from zeroing out a previous one if (in_joystickUseAnalog->integer) { for (i = 0; i < MAX_JOYSTICK_AXIS; i++) { translatedAxes[i] = 0; translatedAxesSet[i] = qfalse; } } // check axes for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) { int axis = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTX + i); int oldAxis = stick_state.oldaaxes[i]; // Smoothly ramp from dead zone to maximum value float f = ((float)abs(axis) / 32767.0f - in_joystickThreshold->value) / (1.0f - in_joystickThreshold->value); if (f < 0.0f) f = 0.0f; axis = (int)(32767 * ((axis < 0) ? -f : f)); if (axis != oldAxis) { const int negMap[SDL_CONTROLLER_AXIS_MAX] = { K_PAD0_LEFTSTICK_LEFT, K_PAD0_LEFTSTICK_UP, K_PAD0_RIGHTSTICK_LEFT, K_PAD0_RIGHTSTICK_UP, 0, 0 }; const int posMap[SDL_CONTROLLER_AXIS_MAX] = { K_PAD0_LEFTSTICK_RIGHT, K_PAD0_LEFTSTICK_DOWN, K_PAD0_RIGHTSTICK_RIGHT, K_PAD0_RIGHTSTICK_DOWN, K_PAD0_LEFTTRIGGER, K_PAD0_RIGHTTRIGGER }; qboolean posAnalog = qfalse, negAnalog = qfalse; int negKey = negMap[i]; int posKey = posMap[i]; if (in_joystickUseAnalog->integer) { int posAxis = 0, posSign = 0, negAxis = 0, negSign = 0; // get axes and axes signs for keys if available posAnalog = KeyToAxisAndSign(posKey, &posAxis, &posSign); negAnalog = KeyToAxisAndSign(negKey, &negAxis, &negSign); // positive to negative/neutral -> keyup if axis hasn't yet been set if (posAnalog && !translatedAxesSet[posAxis] && oldAxis > 0 && axis <= 0) { translatedAxes[posAxis] = 0; translatedAxesSet[posAxis] = qtrue; } // negative to positive/neutral -> keyup if axis hasn't yet been set if (negAnalog && !translatedAxesSet[negAxis] && oldAxis < 0 && axis >= 0) { translatedAxes[negAxis] = 0; translatedAxesSet[negAxis] = qtrue; } // negative/neutral to positive -> keydown if (posAnalog && axis > 0) { translatedAxes[posAxis] = axis * posSign; translatedAxesSet[posAxis] = qtrue; } // positive/neutral to negative -> keydown if (negAnalog && axis < 0) { translatedAxes[negAxis] = -axis * negSign; translatedAxesSet[negAxis] = qtrue; } } // keyups first so they get overridden by keydowns later // positive to negative/neutral -> keyup if (!posAnalog && posKey && oldAxis > 0 && axis <= 0) Com_QueueEvent(in_eventTime, SE_KEY, posKey, qfalse, 0, NULL); // negative to positive/neutral -> keyup if (!negAnalog && negKey && oldAxis < 0 && axis >= 0) Com_QueueEvent(in_eventTime, SE_KEY, negKey, qfalse, 0, NULL); // negative/neutral to positive -> keydown if (!posAnalog && posKey && oldAxis <= 0 && axis > 0) Com_QueueEvent(in_eventTime, SE_KEY, posKey, qtrue, 0, NULL); // positive/neutral to negative -> keydown if (!negAnalog && negKey && oldAxis >= 0 && axis < 0) Com_QueueEvent(in_eventTime, SE_KEY, negKey, qtrue, 0, NULL); stick_state.oldaaxes[i] = axis; } } // set translated axes if (in_joystickUseAnalog->integer) { for (i = 0; i < MAX_JOYSTICK_AXIS; i++) { if (translatedAxesSet[i]) Com_QueueEvent(in_eventTime, SE_JOYSTICK_AXIS, i, translatedAxes[i], 0, NULL); } } } /* =============== IN_JoyMove =============== */ static void IN_JoyMove( void ) { unsigned int axes = 0; unsigned int hats = 0; int total = 0; int i = 0; if (gamepad) { IN_GamepadMove(); return; } if (!stick) return; SDL_JoystickUpdate(); // update the ball state. total = SDL_JoystickNumBalls(stick); if (total > 0) { int balldx = 0; int balldy = 0; for (i = 0; i < total; i++) { int dx = 0; int dy = 0; SDL_JoystickGetBall(stick, i, &dx, &dy); balldx += dx; balldy += dy; } if (balldx || balldy) { // !!! FIXME: is this good for stick balls, or just mice? // Scale like the mouse input... if (abs(balldx) > 1) balldx *= 2; if (abs(balldy) > 1) balldy *= 2; Com_QueueEvent( in_eventTime, SE_MOUSE, balldx, balldy, 0, NULL ); } } // now query the stick buttons... total = SDL_JoystickNumButtons(stick); if (total > 0) { if (total > ARRAY_LEN(stick_state.buttons)) total = ARRAY_LEN(stick_state.buttons); for (i = 0; i < total; i++) { qboolean pressed = (SDL_JoystickGetButton(stick, i) != 0); if (pressed != stick_state.buttons[i]) { Com_QueueEvent( in_eventTime, SE_KEY, K_JOY1 + i, pressed, 0, NULL ); stick_state.buttons[i] = pressed; } } } // look at the hats... total = SDL_JoystickNumHats(stick); if (total > 0) { if (total > 4) total = 4; for (i = 0; i < total; i++) { ((Uint8 *)&hats)[i] = SDL_JoystickGetHat(stick, i); } } // update hat state if (hats != stick_state.oldhats) { for( i = 0; i < 4; i++ ) { if( ((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i] ) { // release event switch( ((Uint8 *)&stick_state.oldhats)[i] ) { case SDL_HAT_UP: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL ); break; case SDL_HAT_RIGHT: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL ); break; case SDL_HAT_DOWN: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL ); break; case SDL_HAT_LEFT: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL ); break; case SDL_HAT_RIGHTUP: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL ); break; case SDL_HAT_RIGHTDOWN: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL ); break; case SDL_HAT_LEFTUP: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL ); break; case SDL_HAT_LEFTDOWN: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL ); break; default: break; } // press event switch( ((Uint8 *)&hats)[i] ) { case SDL_HAT_UP: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL ); break; case SDL_HAT_RIGHT: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL ); break; case SDL_HAT_DOWN: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL ); break; case SDL_HAT_LEFT: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL ); break; case SDL_HAT_RIGHTUP: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL ); break; case SDL_HAT_RIGHTDOWN: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL ); break; case SDL_HAT_LEFTUP: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL ); break; case SDL_HAT_LEFTDOWN: Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL ); break; default: break; } } } } // save hat state stick_state.oldhats = hats; // finally, look at the axes... total = SDL_JoystickNumAxes(stick); if (total > 0) { if (in_joystickUseAnalog->integer) { if (total > MAX_JOYSTICK_AXIS) total = MAX_JOYSTICK_AXIS; for (i = 0; i < total; i++) { Sint16 axis = SDL_JoystickGetAxis(stick, i); float f = ( (float) abs(axis) ) / 32767.0f; if( f < in_joystickThreshold->value ) axis = 0; if ( axis != stick_state.oldaaxes[i] ) { Com_QueueEvent( in_eventTime, SE_JOYSTICK_AXIS, i, axis, 0, NULL ); stick_state.oldaaxes[i] = axis; } } } else { if (total > 16) total = 16; for (i = 0; i < total; i++) { Sint16 axis = SDL_JoystickGetAxis(stick, i); float f = ( (float) axis ) / 32767.0f; if( f < -in_joystickThreshold->value ) { axes |= ( 1 << ( i * 2 ) ); } else if( f > in_joystickThreshold->value ) { axes |= ( 1 << ( ( i * 2 ) + 1 ) ); } } } } /* Time to update axes state based on old vs. new. */ if (axes != stick_state.oldaxes) { for( i = 0; i < 16; i++ ) { if( ( axes & ( 1 << i ) ) && !( stick_state.oldaxes & ( 1 << i ) ) ) { Com_QueueEvent( in_eventTime, SE_KEY, joy_keys[i], qtrue, 0, NULL ); } if( !( axes & ( 1 << i ) ) && ( stick_state.oldaxes & ( 1 << i ) ) ) { Com_QueueEvent( in_eventTime, SE_KEY, joy_keys[i], qfalse, 0, NULL ); } } } /* Save for future generations. */ stick_state.oldaxes = axes; } /* =============== IN_ProcessEvents =============== */ static void IN_ProcessEvents( void ) { SDL_Event e; keyNum_t key = 0; static keyNum_t lastKeyDown = 0; if( !SDL_WasInit( SDL_INIT_VIDEO ) ) return; while( SDL_PollEvent( &e ) ) { switch( e.type ) { case SDL_KEYDOWN: if ( e.key.repeat && Key_GetCatcher( ) == 0 ) break; if( ( key = IN_TranslateSDLToQ3Key( &e.key.keysym, qtrue ) ) ) Com_QueueEvent( in_eventTime, SE_KEY, key, qtrue, 0, NULL ); if( key == K_BACKSPACE ) Com_QueueEvent( in_eventTime, SE_CHAR, CTRL('h'), 0, 0, NULL ); else if( keys[K_CTRL].down && key >= 'a' && key <= 'z' ) Com_QueueEvent( in_eventTime, SE_CHAR, CTRL(key), 0, 0, NULL ); lastKeyDown = key; break; case SDL_KEYUP: if( ( key = IN_TranslateSDLToQ3Key( &e.key.keysym, qfalse ) ) ) Com_QueueEvent( in_eventTime, SE_KEY, key, qfalse, 0, NULL ); lastKeyDown = 0; break; case SDL_TEXTINPUT: if( lastKeyDown != K_CONSOLE ) { char *c = e.text.text; // Quick and dirty UTF-8 to UTF-32 conversion while( *c ) { int utf32 = 0; if( ( *c & 0x80 ) == 0 ) utf32 = *c++; else if( ( *c & 0xE0 ) == 0xC0 ) // 110x xxxx { utf32 |= ( *c++ & 0x1F ) << 6; utf32 |= ( *c++ & 0x3F ); } else if( ( *c & 0xF0 ) == 0xE0 ) // 1110 xxxx { utf32 |= ( *c++ & 0x0F ) << 12; utf32 |= ( *c++ & 0x3F ) << 6; utf32 |= ( *c++ & 0x3F ); } else if( ( *c & 0xF8 ) == 0xF0 ) // 1111 0xxx { utf32 |= ( *c++ & 0x07 ) << 18; utf32 |= ( *c++ & 0x3F ) << 12; utf32 |= ( *c++ & 0x3F ) << 6; utf32 |= ( *c++ & 0x3F ); } else { Com_DPrintf( "Unrecognised UTF-8 lead byte: 0x%x\n", (unsigned int)*c ); c++; } if( utf32 != 0 ) { if( IN_IsConsoleKey( 0, utf32 ) ) { Com_QueueEvent( in_eventTime, SE_KEY, K_CONSOLE, qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, K_CONSOLE, qfalse, 0, NULL ); } else Com_QueueEvent( in_eventTime, SE_CHAR, utf32, 0, 0, NULL ); } } } break; case SDL_MOUSEMOTION: if( mouseActive ) { if( !e.motion.xrel && !e.motion.yrel ) break; Com_QueueEvent( in_eventTime, SE_MOUSE, e.motion.xrel, e.motion.yrel, 0, NULL ); } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { int b; switch( e.button.button ) { case SDL_BUTTON_LEFT: b = K_MOUSE1; break; case SDL_BUTTON_MIDDLE: b = K_MOUSE3; break; case SDL_BUTTON_RIGHT: b = K_MOUSE2; break; case SDL_BUTTON_X1: b = K_MOUSE4; break; case SDL_BUTTON_X2: b = K_MOUSE5; break; default: b = K_AUX1 + ( e.button.button - SDL_BUTTON_X2 + 1 ) % 16; break; } Com_QueueEvent( in_eventTime, SE_KEY, b, ( e.type == SDL_MOUSEBUTTONDOWN ? qtrue : qfalse ), 0, NULL ); } break; case SDL_MOUSEWHEEL: if( e.wheel.y > 0 ) { Com_QueueEvent( in_eventTime, SE_KEY, K_MWHEELUP, qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, K_MWHEELUP, qfalse, 0, NULL ); } else if( e.wheel.y < 0 ) { Com_QueueEvent( in_eventTime, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL ); Com_QueueEvent( in_eventTime, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL ); } break; case SDL_CONTROLLERDEVICEADDED: case SDL_CONTROLLERDEVICEREMOVED: if (in_joystick->integer) IN_InitJoystick(); break; case SDL_QUIT: Cbuf_ExecuteText(EXEC_NOW, "quit Closed window\n"); break; case SDL_WINDOWEVENT: switch( e.window.event ) { case SDL_WINDOWEVENT_RESIZED: { int width, height; width = e.window.data1; height = e.window.data2; // ignore this event on fullscreen if( cls.glconfig.isFullscreen ) { break; } // check if size actually changed if( cls.glconfig.vidWidth == width && cls.glconfig.vidHeight == height ) { break; } Cvar_SetValue( "r_customwidth", width ); Cvar_SetValue( "r_customheight", height ); Cvar_Set( "r_mode", "-1" ); // Wait until user stops dragging for 1 second, so // we aren't constantly recreating the GL context while // he tries to drag... vidRestartTime = Sys_Milliseconds( ) + 1000; } break; case SDL_WINDOWEVENT_MINIMIZED: Cvar_SetValue( "com_minimized", 1 ); break; case SDL_WINDOWEVENT_RESTORED: case SDL_WINDOWEVENT_MAXIMIZED: Cvar_SetValue( "com_minimized", 0 ); break; case SDL_WINDOWEVENT_FOCUS_LOST: Cvar_SetValue( "com_unfocused", 1 ); break; case SDL_WINDOWEVENT_FOCUS_GAINED: Cvar_SetValue( "com_unfocused", 0 ); break; } break; default: break; } } } /* =============== IN_Frame =============== */ void IN_Frame( void ) { qboolean loading; IN_JoyMove( ); // If not DISCONNECTED (main menu) or ACTIVE (in game), we're loading loading = ( clc.state != CA_DISCONNECTED && clc.state != CA_ACTIVE ); if( !cls.glconfig.isFullscreen && ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) { // Console is down in windowed mode IN_DeactivateMouse( ); } else if( !cls.glconfig.isFullscreen && loading ) { // Loading in windowed mode IN_DeactivateMouse( ); } else if( !( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_INPUT_FOCUS ) ) { // Window not got focus IN_DeactivateMouse( ); } else IN_ActivateMouse( ); IN_ProcessEvents( ); // Set event time for next frame to earliest possible time an event could happen in_eventTime = Sys_Milliseconds( ); // In case we had to delay actual restart of video system if( ( vidRestartTime != 0 ) && ( vidRestartTime < Sys_Milliseconds( ) ) ) { vidRestartTime = 0; Cbuf_AddText( "vid_restart\n" ); } } /* =============== IN_Init =============== */ void IN_Init( void *windowData ) { int appState; if( !SDL_WasInit( SDL_INIT_VIDEO ) ) { Com_Error( ERR_FATAL, "IN_Init called before SDL_Init( SDL_INIT_VIDEO )" ); return; } SDL_window = (SDL_Window *)windowData; Com_DPrintf( "\n------- Input Initialization -------\n" ); in_keyboardDebug = Cvar_Get( "in_keyboardDebug", "0", CVAR_ARCHIVE ); // mouse variables in_mouse = Cvar_Get( "in_mouse", "1", CVAR_ARCHIVE ); in_nograb = Cvar_Get( "in_nograb", "0", CVAR_ARCHIVE ); in_joystick = Cvar_Get( "in_joystick", "0", CVAR_ARCHIVE|CVAR_LATCH ); in_joystickThreshold = Cvar_Get( "joy_threshold", "0.15", CVAR_ARCHIVE ); SDL_StartTextInput( ); mouseAvailable = ( in_mouse->value != 0 ); IN_DeactivateMouse( ); appState = SDL_GetWindowFlags( SDL_window ); Cvar_SetValue( "com_unfocused", !( appState & SDL_WINDOW_INPUT_FOCUS ) ); Cvar_SetValue( "com_minimized", appState & SDL_WINDOW_MINIMIZED ); IN_InitJoystick( ); Com_DPrintf( "------------------------------------\n" ); } /* =============== IN_Shutdown =============== */ void IN_Shutdown( void ) { SDL_StopTextInput( ); IN_DeactivateMouse( ); mouseAvailable = qfalse; IN_ShutdownJoystick( ); SDL_window = NULL; } /* =============== IN_Restart =============== */ void IN_Restart( void ) { IN_ShutdownJoystick( ); IN_Init( SDL_window ); }
26.759593
187
0.618343
cb7f9b0ac88babc95253a5cf43e9e8d2ca580da6
3,541
c
C
u-boot/board/samsung/smdkv310/smdkv310.c
rgomulin/aml_s905_uboot
550de48829e852678f6cef98e94e1a97c040c1fc
[ "MIT" ]
35
2019-04-26T04:00:10.000Z
2022-03-30T11:37:06.000Z
u-boot/board/samsung/smdkv310/smdkv310.c
rgomulin/aml_s905_uboot
550de48829e852678f6cef98e94e1a97c040c1fc
[ "MIT" ]
4
2016-08-30T11:30:25.000Z
2020-12-27T09:58:07.000Z
u-boot/board/samsung/smdkv310/smdkv310.c
rgomulin/aml_s905_uboot
550de48829e852678f6cef98e94e1a97c040c1fc
[ "MIT" ]
11
2020-01-07T05:39:10.000Z
2021-12-26T07:27:21.000Z
/* * Copyright (C) 2011 Samsung Electronics * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/gpio.h> #include <asm/io.h> #include <netdev.h> #include <asm/arch/cpu.h> #include <asm/arch/mmc.h> #include <asm/arch/periph.h> #include <asm/arch/pinmux.h> #include <asm/arch/sromc.h> DECLARE_GLOBAL_DATA_PTR; static void smc9115_pre_init(void) { u32 smc_bw_conf, smc_bc_conf; /* gpio configuration GPK0CON */ gpio_cfg_pin(EXYNOS4_GPIO_Y00 + CONFIG_ENV_SROM_BANK, S5P_GPIO_FUNC(2)); /* Ethernet needs bus width of 16 bits */ smc_bw_conf = SROMC_DATA16_WIDTH(CONFIG_ENV_SROM_BANK); smc_bc_conf = SROMC_BC_TACS(0x0F) | SROMC_BC_TCOS(0x0F) | SROMC_BC_TACC(0x0F) | SROMC_BC_TCOH(0x0F) | SROMC_BC_TAH(0x0F) | SROMC_BC_TACP(0x0F) | SROMC_BC_PMC(0x0F); /* Select and configure the SROMC bank */ s5p_config_sromc(CONFIG_ENV_SROM_BANK, smc_bw_conf, smc_bc_conf); } int board_init(void) { smc9115_pre_init(); gd->bd->bi_boot_params = (PHYS_SDRAM_1 + 0x100UL); return 0; } int dram_init(void) { gd->ram_size = get_ram_size((long *)PHYS_SDRAM_1, PHYS_SDRAM_1_SIZE) + get_ram_size((long *)PHYS_SDRAM_2, PHYS_SDRAM_2_SIZE) + get_ram_size((long *)PHYS_SDRAM_3, PHYS_SDRAM_3_SIZE) + get_ram_size((long *)PHYS_SDRAM_4, PHYS_SDRAM_4_SIZE); return 0; } void dram_init_banksize(void) { gd->bd->bi_dram[0].start = PHYS_SDRAM_1; gd->bd->bi_dram[0].size = get_ram_size((long *)PHYS_SDRAM_1, \ PHYS_SDRAM_1_SIZE); gd->bd->bi_dram[1].start = PHYS_SDRAM_2; gd->bd->bi_dram[1].size = get_ram_size((long *)PHYS_SDRAM_2, \ PHYS_SDRAM_2_SIZE); gd->bd->bi_dram[2].start = PHYS_SDRAM_3; gd->bd->bi_dram[2].size = get_ram_size((long *)PHYS_SDRAM_3, \ PHYS_SDRAM_3_SIZE); gd->bd->bi_dram[3].start = PHYS_SDRAM_4; gd->bd->bi_dram[3].size = get_ram_size((long *)PHYS_SDRAM_4, \ PHYS_SDRAM_4_SIZE); } int board_eth_init(bd_t *bis) { int rc = 0; #ifdef CONFIG_SMC911X rc = smc911x_initialize(0, CONFIG_SMC911X_BASE); #endif return rc; } #ifdef CONFIG_DISPLAY_BOARDINFO int checkboard(void) { printf("\nBoard: SMDKV310\n"); return 0; } #endif #ifdef CONFIG_GENERIC_MMC int board_mmc_init(bd_t *bis) { int i, err; /* * MMC2 SD card GPIO: * * GPK2[0] SD_2_CLK(2) * GPK2[1] SD_2_CMD(2) * GPK2[2] SD_2_CDn * GPK2[3:6] SD_2_DATA[0:3](2) */ for (i = EXYNOS4_GPIO_K20; i < EXYNOS4_GPIO_K27; i++) { /* GPK2[0:6] special function 2 */ gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2)); /* GPK2[0:6] drv 4x */ gpio_set_drv(i, S5P_GPIO_DRV_4X); /* GPK2[0:1] pull disable */ if (i == EXYNOS4_GPIO_K20 || i == EXYNOS4_GPIO_K21) { gpio_set_pull(i, S5P_GPIO_PULL_NONE); continue; } /* GPK2[2:6] pull up */ gpio_set_pull(i, S5P_GPIO_PULL_UP); } err = s5p_mmc_init(2, 4); return err; } #endif static int board_uart_init(void) { int err; err = exynos_pinmux_config(PERIPH_ID_UART0, PINMUX_FLAG_NONE); if (err) { debug("UART0 not configured\n"); return err; } err = exynos_pinmux_config(PERIPH_ID_UART1, PINMUX_FLAG_NONE); if (err) { debug("UART1 not configured\n"); return err; } err = exynos_pinmux_config(PERIPH_ID_UART2, PINMUX_FLAG_NONE); if (err) { debug("UART2 not configured\n"); return err; } err = exynos_pinmux_config(PERIPH_ID_UART3, PINMUX_FLAG_NONE); if (err) { debug("UART3 not configured\n"); return err; } return 0; } #ifdef CONFIG_BOARD_EARLY_INIT_F int board_early_init_f(void) { int err; err = board_uart_init(); if (err) { debug("UART init failed\n"); return err; } return err; } #endif
21.460606
73
0.701497
8da391be7b09b1cf1a1c01a90bd7db56bad19951
146
js
JavaScript
JSProject/Webpack/source/index.js
Lay4U/Study
8c7d1d36e33fec2d49eae5cdcc4fe076aca02f29
[ "MIT" ]
null
null
null
JSProject/Webpack/source/index.js
Lay4U/Study
8c7d1d36e33fec2d49eae5cdcc4fe076aca02f29
[ "MIT" ]
null
null
null
JSProject/Webpack/source/index.js
Lay4U/Study
8c7d1d36e33fec2d49eae5cdcc4fe076aca02f29
[ "MIT" ]
null
null
null
import hello_word from '/hello.js'; import world_word from '/world.js'; document.querySelector('#root').innerHTML = hello_word + ' ' + world_word;
48.666667
74
0.739726
b016d60c38d3c0a566ff51537431da767f666349
918
py
Python
pipeline/schemas/friend_invite.py
mystic-ai/pipeline
487c5e755a862a12c90572b0eff170853ecb3790
[ "Apache-2.0" ]
7
2022-01-28T20:27:50.000Z
2022-02-22T15:30:00.000Z
pipeline/schemas/friend_invite.py
mystic-ai/pipeline
487c5e755a862a12c90572b0eff170853ecb3790
[ "Apache-2.0" ]
17
2022-01-11T12:05:38.000Z
2022-03-25T15:29:43.000Z
pipeline/schemas/friend_invite.py
neuro-ai-dev/pipeline
c7edcc83576158062fe48f266dfaea62d754e761
[ "Apache-2.0" ]
null
null
null
from enum import Enum from .base import BaseModel class FriendInviteStatus(Enum): CREATED = "created" #: Friend has accepted the invite ACCEPTED = "accepted" #: The friend is still under trial period TRIAL = "trial" #: Cycle complete, the inviter has been credited COMPLETE = "complete" class FriendInviteBase(BaseModel): #: The ID of the User who sent the invite inviter_id: str #: The email the invite is to be sent to invitee_email: str class FriendInviteCreate(FriendInviteBase): """Create an invitation for a friend to join""" pass class FriendInviteGet(FriendInviteBase): """View of an invitation for a friend to join""" #: The ID of this invite id: str #: The status of the invite status: FriendInviteStatus class FriendInvitePatch(BaseModel): """Patch the status of a friend invitation""" status: FriendInviteStatus
21.857143
52
0.696078
b76795b3b0cab5ae05c8db6538c373cab3873f30
665
swift
Swift
kpz-mpk/kpz-mpk/Map/IncidentAnnotation.swift
angrynerds-pl/kpz-mpk-ios
5a5ef5e08d29ccdfdac9421a4ed66aaf84eb52a7
[ "MIT" ]
2
2020-03-02T12:33:08.000Z
2020-03-04T15:00:28.000Z
kpz-mpk/kpz-mpk/Map/IncidentAnnotation.swift
angrynerds-pl/kpz-mpk-ios
5a5ef5e08d29ccdfdac9421a4ed66aaf84eb52a7
[ "MIT" ]
8
2020-03-02T20:52:23.000Z
2020-03-19T17:49:09.000Z
kpz-mpk/kpz-mpk/Map/IncidentAnnotation.swift
angrynerds-pl/kpz-mpk-ios
5a5ef5e08d29ccdfdac9421a4ed66aaf84eb52a7
[ "MIT" ]
1
2020-05-13T12:14:33.000Z
2020-05-13T12:14:33.000Z
// // IncidentAnnotation.swift // kpz-mpk // // Created by Wojciech Konury on 15/04/2020. // Copyright © 2020 kpz-mpk. All rights reserved. // import Foundation import MapKit class IncidentAnnotation: NSObject, MKAnnotation { var incident: Incident var title: String? var subtitle: String? var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D( latitude: incident.location.latitude, longitude: incident.location.longitude ) } init(forIncident incident: Incident) { self.incident = incident self.title = incident.type.prettyName self.subtitle = ("\(incident.routeId) \(incident.tripHeadsign)") } }
22.166667
68
0.708271
0d36c6c75dfa2f554a02ed61bd61b3fd10fb5288
19,217
h
C
FireRender.Max.Plugin/plugin/light/FireRenderIES_Panel.h
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
6
2020-05-24T12:00:43.000Z
2021-07-13T06:22:49.000Z
FireRender.Max.Plugin/plugin/light/FireRenderIES_Panel.h
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
4
2020-09-17T17:05:38.000Z
2021-06-23T14:29:14.000Z
FireRender.Max.Plugin/plugin/light/FireRenderIES_Panel.h
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
8
2020-05-15T08:29:17.000Z
2021-07-14T08:38:07.000Z
/********************************************************************** Copyright 2020 Advanced Micro Devices, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ #pragma once #include <functional> #include "frScope.h" #include "utils/KelvinToColor.h" FIRERENDER_NAMESPACE_BEGIN class FireRenderIESLight; /* This class contains common code for 3dsMax specific controls 'ControlTraits' must have: TControl typedef which represents 3dsMax control static TControl* Capture(HWND) method static void Release(TControl*) method */ template<typename ControlTraits> class MaxControl { using TControl = typename ControlTraits::TControl; public: using Traits = ControlTraits; MaxControl() : m_ctrl(nullptr) {} MaxControl(MaxControl&& that) { MoveFrom(that); } MaxControl(const MaxControl&) = delete; ~MaxControl() { Release(); } void Capture(HWND dialog, int control) { // Release previous control Release(); HWND controlHwnd = GetDlgItem(dialog, control); if (controlHwnd == nullptr) { FASSERT(!"Failed to capture the control"); return; } m_ctrl = ControlTraits::Capture(controlHwnd); FASSERT(m_ctrl != nullptr); } void Release() { if (m_ctrl != nullptr) { ControlTraits::Release(m_ctrl); m_ctrl = nullptr; } } void Enable() { FASSERT(m_ctrl != nullptr); m_ctrl->Enable(TRUE); } void Disable() { FASSERT(m_ctrl != nullptr); m_ctrl->Enable(FALSE); } TControl* GetControl() const { return m_ctrl; } MaxControl& operator=(const MaxControl&) = delete; MaxControl& operator=(MaxControl&& that) { Release(); MoveFrom(that); return *this; } protected: void MoveFrom(MaxControl& that) { m_ctrl = that.m_ctrl; that.m_ctrl = nullptr; } TControl* m_ctrl; }; class MaxSpinnerTraits { public: using TControl = ISpinnerControl; static TControl* Capture(HWND wnd) { return GetISpinner(wnd); } static void Release(TControl* ctrl) { ReleaseISpinner(ctrl); } }; class MaxEditTraits { public: using TControl = ICustEdit; static TControl* Capture(HWND wnd) { return GetICustEdit(wnd); } static void Release(TControl* ctrl) { ReleaseICustEdit(ctrl); } }; class MaxButtonTraits { public: using TControl = ICustButton; static TControl* Capture(HWND wnd) { return GetICustButton(wnd); } static void Release(TControl* ctrl) { ReleaseICustButton(ctrl); } }; class MaxColorSwatchTraits { public: using TControl = IColorSwatch; static TControl* Capture(HWND wnd) { return GetIColorSwatch(wnd); } static void Release(TControl* ctrl) { ReleaseIColorSwatch(ctrl); } }; /* This class wraps 3dsMax ISpinnerControl */ class MaxSpinner : public MaxControl<MaxSpinnerTraits> { using ParentClass = MaxControl<MaxSpinnerTraits>; public: using ParentClass::ParentClass; using ParentClass::operator=; struct DefaultFloatSettings { static const float Min; static const float Max; static const float Default; static const float Delta; }; struct DefaultRotationSettings { static const float Min; static const float Max; static const float Default; static const float Delta; }; template<typename T> void SetLimits(T min, T max, bool limitCurrent = false) { FASSERT(m_ctrl != nullptr); m_ctrl->SetLimits(min, max, limitCurrent); } template<typename T> void SetResetValue(T resetValue) { FASSERT(m_ctrl != nullptr); m_ctrl->SetResetValue(resetValue); } void SetScale(float scale) { FASSERT(m_ctrl != nullptr); m_ctrl->SetScale(scale); } template<typename T> void SetValue(T value, bool notify = false) { FASSERT(m_ctrl != nullptr); m_ctrl->SetValue(value, notify); } template<typename Settings> void SetSettings() { SetLimits(Settings::Min, Settings::Max); SetResetValue(Settings::Default); SetScale(Settings::Delta); } template<typename T> T GetValue() const { FASSERT(m_ctrl != nullptr); return static_cast<T>(GetValueHelper<T>::GetValue(m_ctrl)); } private: template<typename T, typename Enable = void> struct GetValueHelper; // Specialization for integral types template<typename T> struct GetValueHelper<T, std::enable_if_t<std::is_integral<T>::value>> { static int GetValue(Traits::TControl* pControl) { return pControl->GetIVal(); } }; // Specialization for floating-point types template<typename T> struct GetValueHelper<T, std::enable_if_t<std::is_floating_point<T>::value>> { static float GetValue(Traits::TControl* pControl) { return pControl->GetFVal(); } }; }; /* This class wraps 3dsMax ICustEdit control */ class MaxEdit : public MaxControl<MaxEditTraits> { using ParentClass = MaxControl<MaxEditTraits>; public: using ParentClass::ParentClass; using ParentClass::operator=; template<typename T> T GetValue() const { FASSERT(m_ctrl != nullptr); return static_cast<T>(GetValueHelper<T>::GetValue(m_ctrl)); } private: template<typename T, typename Enable = void> struct GetValueHelper; // Specialization for integral types template<typename T> struct GetValueHelper<T, std::enable_if_t<std::is_integral<T>::value>> { static int GetValue(Traits::TControl* pControl) { return pControl->GetInt(); } }; // Specialization for floating-point types template<typename T> struct GetValueHelper<T, std::enable_if_t<std::is_floating_point<T>::value>> { static float GetValue(Traits::TControl* pControl) { return pControl->GetFloat(); } }; }; /* This class wraps 3dsMax ICustButton control */ class MaxButton : public MaxControl<MaxButtonTraits> { using ParentClass = MaxControl<MaxButtonTraits>; public: using ParentClass::ParentClass; using ParentClass::operator=; void SetType(CustButType type) { FASSERT(m_ctrl != nullptr); m_ctrl->SetType(type); } void SetButtonDownNotify(bool notify) { FASSERT(m_ctrl != nullptr); m_ctrl->SetButtonDownNotify(notify); } RECT GetRect() const { FASSERT(m_ctrl != nullptr); RECT rect; BOOL ret = GetWindowRect(m_ctrl->GetHwnd(), &rect); FASSERT(ret); return rect; } bool PointIsOver(POINT pt) const { RECT rect = GetRect(); return bool_cast(PtInRect(&rect, pt)); } bool CursorIsOver() const { POINT cursorPos; BOOL ret = GetCursorPos(&cursorPos); FASSERT(ret); return PointIsOver(cursorPos); } }; class MaxColorSwatch : public MaxControl<MaxColorSwatchTraits> { using ParentClass = MaxControl<MaxColorSwatchTraits>; public: using ParentClass::ParentClass; using ParentClass::operator=; Color GetColor() const { FASSERT(m_ctrl != nullptr); COLORREF c = m_ctrl->GetColor(); Color result; result.r = GetRValue(c) / 255.f; result.g = GetGValue(c) / 255.f; result.b = GetBValue(c) / 255.f; return result; } void SetColor(Color c) { FASSERT(m_ctrl != nullptr); m_ctrl->SetColor(c); } }; /* This class contains common code for Windows controls */ class WinControl { public: WinControl() : m_hWnd(nullptr) {} void Capture(HWND parentWindow, int controlId) { m_hWnd = GetDlgItem(parentWindow, controlId); CheckControl(); } void Release() { m_hWnd = nullptr; } protected: void CheckControl() const { FASSERT(m_hWnd != nullptr); } HWND m_hWnd; }; // Combines 3dsMax edit and spinner controls in one object class MaxEditAndSpinner { public: MaxEditAndSpinner() = default; MaxEditAndSpinner(MaxEditAndSpinner&&) = default; MaxEditAndSpinner(const MaxEditAndSpinner&) = delete; void Capture(HWND hWnd, int editId, int spinnerId) { m_edit.Capture(hWnd, editId); m_spinner.Capture(hWnd, spinnerId); } void Bind(EditSpinnerType editType) { ICustEdit* pEdit = m_edit.GetControl(); ISpinnerControl* pSpinner = m_spinner.GetControl(); pSpinner->LinkToEdit(pEdit->GetHwnd(), editType); } void Release() { m_edit.Release(); m_spinner.Release(); } void Enable() { m_edit.Enable(); m_spinner.Enable(); } void Disable() { m_edit.Disable(); m_spinner.Disable(); } template<typename T> T GetValue() const { return m_spinner.GetValue<T>(); } MaxEdit& GetEdit() { return m_edit; } MaxSpinner& GetSpinner() { return m_spinner; } const MaxEdit& GetEdit() const { return m_edit; } const MaxSpinner& GetSpinner() const { return m_spinner; } MaxEditAndSpinner& operator=(MaxEditAndSpinner&&) = default; MaxEditAndSpinner& operator=(const MaxEditAndSpinner&) = delete; private: MaxEdit m_edit; MaxSpinner m_spinner; }; // Combines 3dsMax colors watch, edit and spinner controls in one object class MaxKelvinColor { public: MaxKelvinColor() = default; MaxKelvinColor(MaxKelvinColor&&) = default; MaxKelvinColor(const MaxKelvinColor&) = delete; void Capture(HWND window, int colorsWatch, int edit, int spinnerId) { m_color.Capture(window, colorsWatch); m_kelvin.Capture(window, edit, spinnerId); m_kelvin.Bind(EditSpinnerType::EDITTYPE_FLOAT); MaxSpinner& spinner = m_kelvin.GetSpinner(); spinner.SetLimits(MinKelvin, MaxKelvin); spinner.SetResetValue(DefaultKelvin); spinner.SetScale(10.f); } float GetTemperature() const { return m_kelvin.GetValue<float>(); } Color GetColor() const { return m_color.GetColor(); } void SetTemperature(float value) { m_kelvin.GetSpinner().SetValue(value); UpdateColor(); } void UpdateColor() { m_color.SetColor(KelvinToColor(GetTemperature())); } void Release() { m_color.Release(); m_kelvin.Release(); } void Enable() { m_color.Enable(); m_kelvin.Enable(); } void Disable() { m_color.Disable(); m_kelvin.Disable(); } MaxKelvinColor& operator=(MaxKelvinColor&&) = default; MaxKelvinColor& operator=(const MaxKelvinColor&) = delete; private: MaxColorSwatch m_color; MaxEditAndSpinner m_kelvin; }; /* Wraps Windows button control */ class WinButton : public WinControl { public: bool IsChecked() const { CheckControl(); int result = Button_GetCheck(m_hWnd); FASSERT(result != BST_INDETERMINATE); return result == BST_CHECKED; } void SetCheck(bool checked) { CheckControl(); Button_SetCheck(m_hWnd, checked ? BST_CHECKED : BST_UNCHECKED); } void Enable() { CheckControl(); Button_Enable(m_hWnd, TRUE); } void Disable() { CheckControl(); Button_Enable(m_hWnd, FALSE); } }; /* Wraps Windows combo box control */ class WinCombobox : public WinControl { using TString = std::basic_string<TCHAR>; public: enum class Style { Dropdown, DropdownList }; // Returns the index of selected item. // Returns -1 if nothing is selected int GetSelectedIndex() const { CheckControl(); return ComboBox_GetCurSel(m_hWnd); } TString GetItemText(int index) const { TString result; GetItemText(index, result); return result; } void GetItemText(int index, TString& outText) const { CheckControl(); int chars = ComboBox_GetLBTextLen(m_hWnd, index); FASSERT(chars != CB_ERR && "Index out of range"); int len = chars + 1; outText.resize(len); int getLBText_result = ComboBox_GetLBText(m_hWnd, index, &outText[0]); FASSERT(getLBText_result != CB_ERR && getLBText_result == chars); } int AddItem(const TCHAR* name) { CheckControl(); int index = ComboBox_AddString(m_hWnd, name); FASSERT(index != CB_ERR); FASSERT(index != CB_ERRSPACE); return index; } void DeleteItem(int index) { CheckControl(); int res = ComboBox_DeleteString(m_hWnd, index); FASSERT(res != CB_ERR); } void SetItemData(int index, size_t data) { CheckControl(); int ret = ComboBox_SetItemData(m_hWnd, index, data); FASSERT(ret != CB_ERR); } bool SetSelected(const TCHAR* text) { FASSERT(text != nullptr); return ForEachItem([&](int index, const TString& str) { if (_tcscmp(text, str.c_str()) == 0) { SetSelected(index); return true; } return false; }); } // -1 to clear selection void SetSelected(int index) { CheckControl(); int ret = ComboBox_SetCurSel(m_hWnd, index); // -1 is valid input but ComboBox_SetCurSel returns CB_ERR in this case FASSERT(ret == -1 || ret != CB_ERR); } int GetItemsCount() const { CheckControl(); int result = ComboBox_GetCount(m_hWnd); FASSERT(result != CB_ERR); return result; } void Enable() { CheckControl(); ComboBox_Enable(m_hWnd, TRUE); } void Disable() { CheckControl(); ComboBox_Enable(m_hWnd, FALSE); } bool ForEachItem(std::function<bool(int index, const TString& str)> f) { int cnt = GetItemsCount(); TString cache; for (int i = 0; i < cnt; ++i) { GetItemText(i, cache); if (f(i, cache)) { return true; } } return false; } }; /* This class contains common code to manage 3dsMax rollup pages. * Derived class must define: * static DialogId variable; * static PanelName variable. */ template<typename Derived> class IES_Panel { public: using BasePanel = IES_Panel; IES_Panel(FireRenderIESLight* parent) : m_panel(nullptr), m_parent(parent) {} bool IsInitialized() const { return m_panel != nullptr; } void BeginEdit(IObjParam* objParam, ULONG flags, Animatable* prev) { FASSERT(m_panel == nullptr); Derived* _this = static_cast<Derived*>(this); m_panel = objParam->AddRollupPage( fireRenderHInstance, MAKEINTRESOURCE(Derived::DialogId), Derived::DlgProc, Derived::PanelName, (LPARAM)_this); LONG_PTR wndContext = reinterpret_cast<LONG_PTR>(_this); LONG_PTR prevLong = SetWindowLongPtr(m_panel, GWLP_USERDATA, wndContext); _this->InitializePage(objParam->GetTime()); objParam->RegisterDlgWnd(m_panel); FASSERT(prevLong == 0); } void EndEdit(IObjParam* objParam, ULONG flags, Animatable* next) { FASSERT(IsInitialized()); Derived* _this = static_cast<Derived*>(this); _this->UninitializePage(); objParam->DeleteRollupPage(m_panel); m_panel = nullptr; } // These methods are optional to override in the derived class // Capture and initialize page controls bool InitializePage(TimeValue time) { return true; } // Release page controls void UninitializePage() {} // WM_COMMAND simplified event bool HandleControlCommand(TimeValue t, WORD code, WORD controlId) { return false; } // 3ds Max custom edit change event bool OnEditChange(TimeValue t, int editId, HWND editHWND) { return false; } // Spinner change event bool OnSpinnerChange(TimeValue t, ISpinnerControl* spinner, WORD controlId, bool isDragging) { return false; } // Color shatch change event bool OnColorSwatchChange(TimeValue t, IColorSwatch* colorSwatch, WORD controlId, bool final) { return false; } // Returns message for undo / redo stack const TCHAR* GetAcceptMessage(WORD controlId) const { return _T("IES light: change parameter"); } // Update controls state from param block void UpdateUI(TimeValue t) {} // Enable controls on the panel void Enable() {} // Disable controls on the panel void Disable() {} protected: HWND m_panel; FireRenderIESLight* m_parent; private: static void BeginUndoDelta() { theHold.Begin(); } static void EndUndoDelta(bool accept, Derived* _this, int control) { if (accept) { theHold.Accept(_this->GetAcceptMessage(control)); } else { theHold.Cancel(); } } static INT_PTR CALLBACK DlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: return TRUE; break; case BM_CLICK: FASSERT(false); break; case WM_COMMAND: { if (lParam != 0) { TimeValue time = GetCOREInterface()->GetTime(); WORD code = HIWORD(wParam); WORD controlId = LOWORD(wParam); Derived* _this = GetAttachedThis(hWnd); BeginUndoDelta(); bool accept = _this->HandleControlCommand(time, code, controlId); EndUndoDelta(accept, _this, controlId); } } break; case WM_CUSTEDIT_ENTER: { WPARAM customEditId = wParam; HWND customEditHWND = reinterpret_cast<HWND>(lParam); Derived* _this = GetAttachedThis(hWnd); TimeValue time = GetCOREInterface()->GetTime(); BeginUndoDelta(); bool accept = _this->OnEditChange(time, customEditId, customEditHWND); EndUndoDelta(accept, _this, customEditId); return TRUE; } break; // start dragging the spinner case CC_SPINNER_BUTTONDOWN: BeginUndoDelta(); break; // on change value in the spinner case CC_SPINNER_CHANGE: { ISpinnerControl* spinner = reinterpret_cast<ISpinnerControl*>(lParam); WORD spinnerId = LOWORD(wParam); WORD isDragging = HIWORD(wParam); Derived* _this = GetAttachedThis(hWnd); TimeValue time = GetCOREInterface()->GetTime(); if (!isDragging) { BeginUndoDelta(); } bool accept = _this->OnSpinnerChange(time, spinner, spinnerId, bool_cast(isDragging)); if (!isDragging) { EndUndoDelta(accept, _this, spinnerId); } return TRUE; } break; // finish spinner editing case CC_SPINNER_BUTTONUP: { Derived* _this = GetAttachedThis(hWnd); ISpinnerControl* spinner = reinterpret_cast<ISpinnerControl*>(lParam); WORD spinnerId = LOWORD(wParam); WORD accept = HIWORD(wParam); TimeValue time = GetCOREInterface()->GetTime(); bool retVal = _this->OnSpinnerChange(time, spinner, spinnerId, false); EndUndoDelta( bool_cast(accept), _this, spinnerId); } break; case CC_COLOR_CHANGE: case CC_COLOR_CLOSE: { IColorSwatch* controlPtr = reinterpret_cast<IColorSwatch*>(lParam); WORD controlId = LOWORD(wParam); Derived* _this = GetAttachedThis(hWnd); TimeValue time = GetCOREInterface()->GetTime(); BeginUndoDelta(); bool accept = _this->OnColorSwatchChange(time, controlPtr, controlId, msg == CC_COLOR_CLOSE); EndUndoDelta(accept, _this, controlId); } break; } return FALSE; } static Derived* GetAttachedThis(HWND hWnd) { LONG_PTR wndUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA); Derived* _this = reinterpret_cast<Derived*>(wndUserData); FASSERT(_this != nullptr); return _this; } }; namespace ies_panel_utils { // Need this helper to use partial specialization template<typename Control, bool enable> struct EnableControlHelper { static void EnablePanel(Control& control) { control.Enable(); } }; // Disable case specialization template<typename Control> struct EnableControlHelper<Control, false> { static void EnablePanel(Control& control) { control.Disable(); } }; template<bool enable, typename Control> void EnableControl(Control& control) { EnableControlHelper<Control, enable>::EnablePanel(control); } template<bool enable, typename... Control> void EnableControls(Control&... controls) { // Call EnableControl for each control (void)std::initializer_list<int> { (EnableControl<enable>(controls), 0)... }; } } FIRERENDER_NAMESPACE_END
20.465389
111
0.702867
2478e7bcc9930b89ef6d6b3780579d310638551f
136
php
PHP
vendor/doctrine/dbal/tests/Doctrine/Tests/DbalTestCase.php
nassafou/SiQ
c8c602f5e773a0b195be55f93a61d7a2485f6e5f
[ "MIT" ]
30
2015-04-04T06:34:09.000Z
2021-06-07T04:13:23.000Z
vendor/doctrine/orm/tests/Doctrine/Tests/DbalTestCase.php
pmartelletti/prode-exa
71c05e26ec06688869c0e124870b2f562cab25ee
[ "MIT" ]
1
2017-01-06T15:38:36.000Z
2017-01-06T15:38:36.000Z
vendor/doctrine/orm/tests/Doctrine/Tests/DbalTestCase.php
Lisjann/repairlivegit
c950dca7ec5d7e3cdbf94fae5a654d054a0a3f45
[ "MIT" ]
16
2015-01-11T20:21:54.000Z
2019-02-20T10:00:36.000Z
<?php namespace Doctrine\Tests; /** * Base testcase class for all dbal testcases. */ class DbalTestCase extends DoctrineTestCase { }
13.6
46
0.742647
56e19961abd9841213658fc8ac09cd11c87213ca
163
rs
Rust
arrow-datafusion-fun/src/main.rs
dudw/rust-playground
916c150cd6e59ff662e51fbcb649a92546d782c5
[ "Unlicense" ]
151
2019-09-03T16:46:32.000Z
2022-03-16T06:17:51.000Z
arrow-datafusion-fun/src/main.rs
dudw/rust-playground
916c150cd6e59ff662e51fbcb649a92546d782c5
[ "Unlicense" ]
3
2020-05-17T10:28:08.000Z
2021-02-25T02:46:28.000Z
arrow-datafusion-fun/src/main.rs
dudw/rust-playground
916c150cd6e59ff662e51fbcb649a92546d782c5
[ "Unlicense" ]
46
2019-03-20T21:07:40.000Z
2022-03-11T14:20:42.000Z
mod sql; mod dataframe; #[tokio::main] async fn main() -> datafusion::error::Result<()> { sql::compute().await?; dataframe::compute().await?; Ok(()) }
18.111111
50
0.595092
74cd3b6474eeb53c5aa441f504a2bf5888b8ee8c
2,161
lua
Lua
src/model/puzzle.lua
veu/sketch-share-solve
fa8e0c20ef5d24ab5d8ed66c53088c0443940b4e
[ "CC-BY-4.0" ]
11
2022-03-01T04:00:38.000Z
2022-03-22T01:24:30.000Z
src/model/puzzle.lua
veu/sketch-share-solve
fa8e0c20ef5d24ab5d8ed66c53088c0443940b4e
[ "CC-BY-4.0" ]
null
null
null
src/model/puzzle.lua
veu/sketch-share-solve
fa8e0c20ef5d24ab5d8ed66c53088c0443940b4e
[ "CC-BY-4.0" ]
1
2022-03-01T09:02:25.000Z
2022-03-01T09:02:25.000Z
class("Puzzle").extends() function Puzzle:init(puzzle, save) self.id = puzzle.id self._save = save self.title = puzzle.title self.width = puzzle.width or 15 self.height = puzzle.height or 10 local size = self.width * self.height self.grid = table.create(size, 0) local values = {string.byte(puzzle.grid, 1, size)} for i = 1, size do self.grid[i] = values[i] - 48 end self.hasBeenSolved = false end function Puzzle:isSolved(solution) local grid = self.grid for i = 1, self.width * self.height do if grid[i] ~= solution[i] & 1 then return false end end self.hasBeenSolved = true return true end function Puzzle:isTrivial() for i, v in ipairs(self.grid) do if v == 1 then return false end end return true end function Puzzle:isCellKnownEmpty(cellX, cellY) return self:isColumnKnownEmpty(cellX) or self:isRowKnownEmpty(cellY) end function Puzzle:isColumnKnownEmpty(cellX) for y = 1, self.height do local index = cellX - 1 + (y - 1) * self.width + 1 if self.grid[index] == 1 then return false end end return true end function Puzzle:isRowKnownEmpty(cellY) for x = 1, self.width do local index = x - 1 + (cellY - 1) * self.width + 1 if self.grid[index] == 1 then return false end end return true end function Puzzle:save(context) local puzzle = { id = self.id, title = self.title, grid = table.concat(self.grid) } context.save.puzzles[self.id] = puzzle table.insert(context.player.created, self.id) save(context) end function Puzzle:delete(context) local puzzleIndex = nil local created = context.creator.created for i = 1, #created do if created[i] == self.id then puzzleIndex = i break end end if puzzleIndex then table.remove(created, puzzleIndex) end context.save.puzzles[self.id] = nil save(context) end Puzzle.load = function (context, id, save) return Puzzle((save or context.save).puzzles[id], save) end Puzzle.createEmpty = function (width, height) width = width or 15 height = height or 10 return Puzzle({ id = playdate.string.UUID(16), grid = string.rep("0", width * height), width = width, height = height, title = "", }) end
18.470085
69
0.693198
2c3a9dff5dfd5a1decacff4d6b0170d119614513
225
py
Python
GetTempAndHumidityOnce.py
HaroldPetersInskipp/Raspberry-Pi-GPIO-Scripts
b29266eb06f18e84606c4868ddb5afe11d87f737
[ "Unlicense" ]
null
null
null
GetTempAndHumidityOnce.py
HaroldPetersInskipp/Raspberry-Pi-GPIO-Scripts
b29266eb06f18e84606c4868ddb5afe11d87f737
[ "Unlicense" ]
null
null
null
GetTempAndHumidityOnce.py
HaroldPetersInskipp/Raspberry-Pi-GPIO-Scripts
b29266eb06f18e84606c4868ddb5afe11d87f737
[ "Unlicense" ]
null
null
null
import time import board import adafruit_si7021 import sys sensor = adafruit_si7021.SI7021(board.I2C()) print("\nTemperature: %0.1f C" % sensor.temperature) print("Humidity: %0.1f %%" % sensor.relative_humidity) sys.exit(0)
22.5
54
0.76
f453c5861a8caba0a0f923b2314a25c5f649ea50
4,623
cs
C#
src/SQLite.Net.Cipher/Interfaces/ISecureDatabase.cs
has-taiar/SQLite.Net.Cipher
fb7d4514cf4d68017deaff7b24c6f693deaac02a
[ "MIT" ]
23
2015-08-06T06:52:47.000Z
2021-02-28T11:32:39.000Z
src/SQLite.Net.Cipher/Interfaces/ISecureDatabase.cs
has-taiar/SQLite.Net.Cipher
fb7d4514cf4d68017deaff7b24c6f693deaac02a
[ "MIT" ]
7
2015-10-30T19:49:32.000Z
2019-03-08T03:15:17.000Z
src/SQLite.Net.Cipher/Interfaces/ISecureDatabase.cs
has-taiar/SQLite.Net.Cipher
fb7d4514cf4d68017deaff7b24c6f693deaac02a
[ "MIT" ]
22
2015-08-18T01:15:48.000Z
2020-10-16T14:52:59.000Z
using System; using System.Collections.Generic; namespace SQLite.Net.Cipher.Interfaces { public interface ISecureDatabase : IDisposable { /// <summary> /// Inserts into the database /// Before inserting, it encrypts all propertiese that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be inserted</typeparam> /// <param name="obj"> the object to be inserted to the database</param> /// <param name="keySeed">The encryption key seed. You must use the same key seed when accessing the object out of the database.</param> /// <returns>no of affected rows</returns> int SecureInsert<T>(T obj, string keySeed) where T : class, IModel, new(); /// <summary> /// Inserts or Replace object into the database /// Before inserting, it encrypts all propertiese that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be inserted</typeparam> /// <param name="obj"> the object to be inserted to the database</param> /// <param name="keySeed">The encryption key seed. You must use the same key seed when accessing the object out of the database.</param> /// <returns>no of affected rows</returns> int SecureInsertOrReplace<T>(T obj, string keySeed) where T : class, IModel, new(); /// <summary> /// Updates a row in the database /// Before Before Updating, it encrypts all propertiese that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be updated</typeparam> /// <param name="obj"> the object to be updated to the database</param> /// <param name="keySeed">The encryption key seed. You must use the same key seed when accessing the object out of the database.</param> /// <returns>no of affected rows</returns> int SecureUpdate<T>(T obj, string keySeed) where T : class, IModel, new(); /// <summary> /// deletes a row in the database /// </summary> /// <typeparam name="T">The Type of the object to be deleted</typeparam> /// <param name="id">The id of the object to be deleted.</param> /// <returns>no of affected rows</returns> int SecureDelete<T>(string id) where T : class, IModel, new(); /// <summary> /// Gets an object of the database /// If the object is found, before returned, this method will decrypt all its properties that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be accessed</typeparam> /// <param name="id">The id of the object to be accessed.</param> /// <param name="keySeed">The encryption key seed (must be the same that you use when inserted into the database).</param> /// <returns>returns an instance of T if found.</returns> T SecureGet<T>(string id, string keySeed) where T : class, IModel, new(); /// <summary> /// Gets a list of T objects from the database /// If any objects were found, before returned, this method will decrypt all their properties that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be accessed</typeparam> /// <param name="keySeed">The encryption key seed (must be the same that you use when inserted into the database).</param> /// <returns>returns a List of T if found.</returns> List<T> SecureGetAll<T>(string keySeed) where T : class, IModel, new(); /// <summary> /// Gets a count of all rows in the table that matches the type T /// </summary> /// <typeparam name="T">The type of the object we are trying to get the count for.</typeparam> /// <returns>int that represent the no of rows (of T) in the db. </returns> int SecureGetCount<T>() where T : class, IModel, new(); /// <summary> /// Executes an sql query against the database. /// This method does not do anything more than the base.ExecuteScalar(); /// </summary> /// <param name="query"></param> /// <param name="args"></param> /// <returns>no of affected rows</returns> int SecureExecuteScalar(string query, params object[] args); /// <summary> /// gets a list of objects from the database using Query() method /// and it decrypt all object properties that have the attribute Secure. /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="query">The Sql query</param> /// <param name="keySeed">The encryption key seed (must be the same that you use when inserted into the database).</param> /// <param name="args">The sql query parameters.</param> /// <returns>List of T </returns> List<T> SecureQuery<T>(string query, string keySeed, params object[] args) where T : class, IModel, new(); } }
48.663158
138
0.687216
8988169c22c8153e46ee4a894c468518fb777afb
918
sql
SQL
trunk/src/db/schedule/upgrade/026_addTournamentGamesToFlight.sql
giannini5/fields
70b584c77a8c0b9e7ff281968806c4d3bc569d52
[ "MIT" ]
null
null
null
trunk/src/db/schedule/upgrade/026_addTournamentGamesToFlight.sql
giannini5/fields
70b584c77a8c0b9e7ff281968806c4d3bc569d52
[ "MIT" ]
null
null
null
trunk/src/db/schedule/upgrade/026_addTournamentGamesToFlight.sql
giannini5/fields
70b584c77a8c0b9e7ff281968806c4d3bc569d52
[ "MIT" ]
null
null
null
drop procedure if exists 026_addTournamentGamesToFlight; delimiter $$ create procedure 026_addTournamentGamesToFlight() begin if not exists( select * from information_schema.columns where TABLE_SCHEMA = DATABASE() and TABLE_NAME = 'flight' and COLUMN_NAME = 'include5th6thGame') then alter table flight add COLUMN includeChampionshipGame tinyint not NULL default 0 after name; alter table flight add COLUMN includeSemiFinalGames tinyint not NULL default 0 after name; alter table flight add COLUMN include3rd4thGame tinyint not NULL default 0 after name; alter table flight add COLUMN include5th6thGame tinyint not NULL default 0 after name; end if; end $$ delimiter ; call 026_addTournamentGamesToFlight(); drop procedure if exists 026_addTournamentGamesToFlight;
34
102
0.696078
a3c4d1738a30ac49dec2b47dffd68947201263e6
10,228
java
Java
src/main/java/net/reldo/taskstracker/TasksTrackerPlugin.java
tylerthardy/combat-tasks-plugin
d1d9ccb82663f96e851954c1a14fb596493654da
[ "BSD-2-Clause" ]
null
null
null
src/main/java/net/reldo/taskstracker/TasksTrackerPlugin.java
tylerthardy/combat-tasks-plugin
d1d9ccb82663f96e851954c1a14fb596493654da
[ "BSD-2-Clause" ]
null
null
null
src/main/java/net/reldo/taskstracker/TasksTrackerPlugin.java
tylerthardy/combat-tasks-plugin
d1d9ccb82663f96e851954c1a14fb596493654da
[ "BSD-2-Clause" ]
null
null
null
package net.reldo.taskstracker; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Provides; import net.reldo.taskstracker.bosses.BossData; import net.reldo.taskstracker.data.LongSerializer; import net.reldo.taskstracker.data.TaskSave; import net.reldo.taskstracker.data.TrackerDataStore; import net.reldo.taskstracker.panel.TasksTrackerPluginPanel; import net.reldo.taskstracker.quests.QuestData; import net.reldo.taskstracker.tasktypes.AbstractTaskManager; import net.reldo.taskstracker.tasktypes.Export; import net.reldo.taskstracker.tasktypes.Task; import net.reldo.taskstracker.tasktypes.TaskType; import net.reldo.taskstracker.tasktypes.combattask.CombatTaskManager; import net.reldo.taskstracker.tasktypes.generic.GenericTaskManager; import net.reldo.taskstracker.tasktypes.league3.League3TaskManager; import java.awt.Color; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.image.BufferedImage; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import javax.inject.Inject; import javax.inject.Named; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.Player; import net.runelite.api.events.ChatMessage; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameTick; import net.runelite.api.events.ScriptPostFired; import net.runelite.api.events.WidgetLoaded; import net.runelite.client.callback.ClientThread; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; import net.runelite.client.game.SkillIconManager; import net.runelite.client.game.SpriteManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginManager; import net.runelite.client.ui.ClientToolbar; import net.runelite.client.ui.NavigationButton; import net.runelite.client.util.ImageUtil; @Slf4j @PluginDescriptor( name = "Tasks Tracker" ) public class TasksTrackerPlugin extends Plugin { public int[] playerSkills; public HashMap<TaskType, AbstractTaskManager> taskManagers = new HashMap<>(); public TaskType selectedTaskType; public String taskTextFilter; public boolean isIncompleteFilter = true; public boolean isCompleteFilter = true; public boolean isIgnoredFilter = false; public boolean isNotIgnoredFilter = true; public boolean isTrackedFilter = true; public boolean isUntrackedFilter = true; public TasksTrackerPluginPanel pluginPanel; private NavigationButton navButton; @Inject @Named("runelite.version") private String runeliteVersion; @Inject private Client client; @Inject private SpriteManager spriteManager; @Inject private PluginManager pluginManager; @Inject private ConfigManager configManager; @Inject private SkillIconManager skillIconManager; @Inject private ClientToolbar clientToolbar; @Inject private ClientThread clientThread; @Inject private ChatMessageManager chatMessageManager; @Inject private TasksTrackerConfig config; @Inject private TrackerDataStore trackerDataStore; private boolean shouldGetName; @Provides TasksTrackerConfig getConfig(ConfigManager configManager) { return configManager.getConfig(TasksTrackerConfig.class); } @Override protected void startUp() throws Exception { pluginPanel = new TasksTrackerPluginPanel(this, clientThread, spriteManager, skillIconManager); SwingUtilities.invokeLater(() -> pluginPanel.setLoggedIn(isLoggedInState(client.getGameState()))); final BufferedImage icon = ImageUtil.loadImageResource(getClass(), "panel_icon.png"); navButton = NavigationButton.builder() .tooltip("Task Tracker") .icon(icon) .priority(5) .panel(pluginPanel) .build(); clientToolbar.addNavigation(navButton); log.info("Tasks Tracker started!"); } @Override protected void shutDown() throws Exception { pluginPanel = null; clientToolbar.removeNavigation(navButton); log.info("Tasks Tracker stopped!"); } @Subscribe public void onChatMessage(ChatMessage chatMessage) { handleOnChatMessage(chatMessage); } private void handleOnChatMessage(ChatMessage chatMessage) { taskManagers.values().forEach(tm -> tm.handleChatMessage(chatMessage)); } @Subscribe public void onConfigChanged(ConfigChanged configChanged) { } @Subscribe public void onGameStateChanged(GameStateChanged gameStateChanged) { handleOnGameStateChanged(gameStateChanged); } private void handleOnGameStateChanged(GameStateChanged gameStateChanged) { SwingUtilities.invokeLater(() -> { pluginPanel.setLoggedIn(isLoggedInState(gameStateChanged.getGameState())); if (gameStateChanged.getGameState() == GameState.LOGGING_IN) { trackerDataStore.loadProfile(); shouldGetName = true; TaskType selectedType = trackerDataStore.currentData.settings.selectedTaskType; setSelectedTaskType(selectedType != null ? selectedType : TaskType.COMBAT); pluginPanel.redraw(); } if (!isLoggedInState(gameStateChanged.getGameState())) { taskManagers.clear(); } }); } private String getDisplayName() { Player localPlayer = client.getLocalPlayer(); if (localPlayer == null) { return null; } return localPlayer.getName(); } private boolean isLoggedInState(GameState gameState) { return gameState != GameState.LOGIN_SCREEN && gameState != GameState.LOGIN_SCREEN_AUTHENTICATOR; } @Subscribe public void onGameTick(GameTick gameTick) { handleOnGameTick(gameTick); } private void handleOnGameTick(GameTick gameTick) { int[] newSkills = client.getRealSkillLevels(); boolean changed = !Arrays.equals(playerSkills, newSkills); if (changed) { playerSkills = client.getRealSkillLevels(); SwingUtilities.invokeLater(() -> pluginPanel.refresh(null)); } if (shouldGetName) { trackerDataStore.currentData.settings.displayName = getDisplayName(); shouldGetName = false; } } @Subscribe public void onWidgetLoaded(WidgetLoaded widgetLoaded) { handleOnWidgetLoaded(widgetLoaded); } private void handleOnWidgetLoaded(WidgetLoaded widgetLoaded) { taskManagers.values().forEach(tm -> tm.handleOnWidgetLoaded(widgetLoaded)); } @Subscribe public void onScriptPostFired(ScriptPostFired scriptPostFired) { handleOnScriptPostFired(scriptPostFired); } private void handleOnScriptPostFired(ScriptPostFired scriptPostFired) { taskManagers.values().forEach(tm -> tm.handleOnScriptPostFired(scriptPostFired)); } public void setSelectedTaskType(TaskType type) { selectedTaskType = type; trackerDataStore.currentData.settings.selectedTaskType = type; if (!taskManagers.containsKey(type)) { taskManagers.put(type, getTaskTypeManager(type)); } } public void refresh() { taskManagers.get(selectedTaskType).refresh(null); } public void sendChatMessage(String chatMessage, Color color) { final String message = new ChatMessageBuilder() .append(color, "Task Tracker: ") .append(color, chatMessage) .build(); chatMessageManager.queue( QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); } private AbstractTaskManager getTaskTypeManager(TaskType type) { if (type == TaskType.COMBAT) { return new CombatTaskManager(client, clientThread, this, trackerDataStore); } if (type == TaskType.LEAGUE_3) { return new League3TaskManager(client, clientThread, this, trackerDataStore); } return new GenericTaskManager(type, this, trackerDataStore); } public void trackTask(Task task) { // TODO: Move this responsibility; not correct to be here trackerDataStore.saveTask(task); } public void ignoreTask(Task task) { // TODO: Move this responsibility; not correct to be here trackerDataStore.saveTask(task); } public void copyJsonToClipboard(TaskType taskType) { clientThread.invokeLater(() -> { String exportJson = exportToJson(taskType); final StringSelection stringSelection = new StringSelection(exportJson); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); showMessageBox( "Data Exported!", "Exported " + taskType.getDisplayString() + " data copied to clipboard!" ); }); } private String exportToJson(TaskType taskType) { Gson gson = new GsonBuilder() .registerTypeAdapter(float.class, new LongSerializer()) .create(); if (taskType == null) { return gson.toJson(trackerDataStore.currentData); } else { Export export = new Export(); export.setQuests(new QuestData(client)); export.setBosses(new BossData(pluginManager, configManager)); export.setDisplayName(trackerDataStore.currentData.settings.displayName); export.setRunescapeVersion(client.getRevision()); export.setRuneliteVersion(runeliteVersion); export.setTimestamp(Instant.now().toEpochMilli()); export.setTaskType(taskType.name()); export.setVarbits(taskManagers.get(selectedTaskType).getVarbits()); export.setVarps(taskManagers.get(selectedTaskType).getVarps()); // TODO: Hello God, I am so sorry for this code. I will clean it up. // TODO: Grab ids for other task types and skip this kludge between string/int HashMap<String, TaskSave> taskSaves = trackerDataStore.currentData.tasksByType.get(taskType); if (taskType == TaskType.LEAGUE_3) { HashMap<String, TaskSave> tasksById = new HashMap<>(); taskSaves.forEach((key, value) -> tasksById.put(String.valueOf(value.getId()), value)); export.setTasks(tasksById); } else { export.setTasks(trackerDataStore.currentData.tasksByType.get(taskType)); } return gson.toJson(export); } } private static void showMessageBox(final String title, final String message) { SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog( null, message, title, JOptionPane.INFORMATION_MESSAGE)); } }
29.732558
100
0.777865
d2b81115c4d8ed503a72e817ca0af2df873e3a27
4,437
ps1
PowerShell
DSIT.ps1
agowa338/Damn-Small-Inventory-Tool
1e1b97d68bf98b01912a8740dc56acd0b6ea6bfa
[ "MIT" ]
2
2019-10-15T21:36:18.000Z
2021-05-15T11:24:51.000Z
DSIT.ps1
agowa338/Damn-Small-Inventory-Tool
1e1b97d68bf98b01912a8740dc56acd0b6ea6bfa
[ "MIT" ]
null
null
null
DSIT.ps1
agowa338/Damn-Small-Inventory-Tool
1e1b97d68bf98b01912a8740dc56acd0b6ea6bfa
[ "MIT" ]
null
null
null
############ Settings ############## $InventoryPath = "E:\DSIT" ## TODO: $InventoryDevices = "E:\DSIT\hostnames.txt" ######### // Settings // ########### ############ Preinit ############### Set-Location $InventoryPath $computername = $env:COMPUTERNAME ## later changes to the current computer in the $InventoryDevices list mkdir "$InventoryPath\$computername" ######### // Preinit // ############ # Network Drives Get-CimInstance -ClassName Win32_MappedLogicalDisk | Select-Object Name,ProviderName | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Network_Drives.csv" # Powershell Version $PSVersionTable.PSVersion | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Powershell_Version.csv" # Get all Printer Get-CimInstance -ClassName Win32_Printer | Select-Object -Property Name,PortName,Default | Sort-Object Name |Sort-Object Default -Descending | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Printer.csv" # Get Office Get-CimInstance -ClassName Win32_Product -Filter "name like '%office%'" | Select-Object -Property Vendor,Name,Version | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Installed_Office_Products.csv" # Get all Applications Get-CimInstance -ClassName Win32_Product | Select-Object -Property Vendor,Name,Version | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Installed_Applications.csv" # Local Drives (with ntfs): Get-CimInstance -ClassName win32_volume -Filter "filesystem like 'ntfs'" | Sort-Object Name | Select-Object Name,Label | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Local_NTFS_Drives.csv" # Find all local PST-Files # Get-ChildItem -Path C:\ -Filter *.pst -Recurse -ErrorAction SilentlyContinue Get-CimInstance -ClassName win32_volume -Filter "filesystem like 'ntfs' and DriveLetter like '%'" | foreach-object {Get-ChildItem -Path $_.name -Filter *.pst -Recurse -Force -ErrorAction SilentlyContinue | Select-Object FullName} | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\PST_Files.csv" # Processor and Windows Architecture Get-CimInstance -ClassName Win32_processor | Select-Object Name,Caption,AddressWidth,DataWidth | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Processor.csv" Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object OSArchitecture | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\OperatingSystem.csv" # Get Bios Information Get-CimInstance -ClassName win32_bios | Select-Object SerialNumber,Manufacturer,BiosVersion,ReleaseDate,SMBIOSBIOSVersion,SMBIOSMajorVersion,SMBIOSMinorVersion | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Bios.csv" Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object Manufacturer,Model,NumberOfProcessors,NumberOfLogicalProcessors | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\ComputerSystem.csv" # Environment Variables Get-ChildItem Env: | Export-Csv -Encoding ASCII -Force -Path "$InventoryPath\$computername\Environment.csv" # # Get EventLog mkdir $InventoryPath\$computername\Eventlog Get-EventLog -LogName * | ForEach-Object {$p = $_; $p.Entries |Export-Csv -path $InventoryPath\$computername\Eventlog\$($p.LogDisplayName).csv} # The MIT License (MIT) # # Copyright (c) 2016 agowa338 # # 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.
60.780822
316
0.773045
e1a0147277de077bbf1aee125dd4e79a10396edd
732
rb
Ruby
exercises/RB101_small_problems/medium_1/05_diamonds_further_exploration.rb
cyberflamingo/launch-school-rb101
8261194e465c6750d5fd7dbda696a12ca62a30df
[ "MIT" ]
2
2021-04-21T17:06:57.000Z
2022-01-25T05:16:57.000Z
exercises/RB101_small_problems/medium_1/05_diamonds_further_exploration.rb
cyberflamingo/launch-school-rb101
8261194e465c6750d5fd7dbda696a12ca62a30df
[ "MIT" ]
null
null
null
exercises/RB101_small_problems/medium_1/05_diamonds_further_exploration.rb
cyberflamingo/launch-school-rb101
8261194e465c6750d5fd7dbda696a12ca62a30df
[ "MIT" ]
5
2021-06-16T17:03:26.000Z
2022-03-01T18:52:04.000Z
def print_row(grid_size, distance_from_center) number_of_stars = grid_size - 2 * distance_from_center number_of_spaces = 0 number_of_spaces = number_of_stars - 2 unless number_of_stars < 2 if number_of_spaces == 0 stars = '*' else stars = '*' + (' ' * number_of_spaces) + '*' end puts stars.center(grid_size) end def diamond(grid_size) max_distance = (grid_size - 1) / 2 max_distance.downto(0) { |distance| print_row(grid_size, distance) } 1.upto(max_distance) { |distance| print_row(grid_size, distance) } end diamond(1) # * diamond(3) # * # * * # * diamond(5) # * # * * # * * # * * # * diamond(9) # * # * * # * * # * * # * * # * * # * * # * * # *
16.636364
70
0.569672
56ed381736d270665ee2665dccbde59c973ebf39
3,625
swift
Swift
Tests/TPPDFTests/Pagination/PDFPaginationStyle+Equatable_Spec.swift
chepiok/TPPDF
a90c393d666d6c75831ee4d6a7b99bdd078a71b8
[ "MIT" ]
301
2019-02-24T14:05:47.000Z
2022-03-26T04:58:46.000Z
Tests/TPPDFTests/Pagination/PDFPaginationStyle+Equatable_Spec.swift
chepiok/TPPDF
a90c393d666d6c75831ee4d6a7b99bdd078a71b8
[ "MIT" ]
160
2019-02-15T09:45:22.000Z
2022-02-27T16:02:50.000Z
Tests/TPPDFTests/Pagination/PDFPaginationStyle+Equatable_Spec.swift
chepiok/TPPDF
a90c393d666d6c75831ee4d6a7b99bdd078a71b8
[ "MIT" ]
69
2019-03-15T03:53:05.000Z
2022-03-21T09:11:25.000Z
// // PDFPaginationStyle+Equatable_Spec.swift // TPPDF_Tests // // Created by Philip Niedertscheider on 27.12.17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import Quick import Nimble @testable import TPPDF class PDFPaginationStyle_Equatable_Spec: QuickSpec { override func spec() { describe("PDFPaginationStyle") { context("Equatable") { it("is equal when both default") { let lhsPagination = PDFPaginationStyle.default let rhsPagination = PDFPaginationStyle.default expect(lhsPagination) == rhsPagination } it("is not equal with different roman template") { let firstPagination = PDFPaginationStyle.roman(template: "123") let secondPagination = PDFPaginationStyle.roman(template: "123") let thirdPagination = PDFPaginationStyle.roman(template: "456") expect(firstPagination) == firstPagination expect(firstPagination) == secondPagination expect(firstPagination) != thirdPagination expect(secondPagination) != thirdPagination } it("is not equal with different custom number formatter") { let firstFormatter = NumberFormatter() firstFormatter.numberStyle = NumberFormatter.Style.percent let secondFormatter = NumberFormatter() secondFormatter.numberStyle = NumberFormatter.Style.decimal let firstTemplate = "123" let secondTemplate = "456" let paginations = [ PDFPaginationStyle.customNumberFormat(template: firstTemplate, formatter: firstFormatter), PDFPaginationStyle.customNumberFormat(template: firstTemplate, formatter: secondFormatter), PDFPaginationStyle.customNumberFormat(template: secondTemplate, formatter: firstFormatter), PDFPaginationStyle.customNumberFormat(template: secondTemplate, formatter: secondFormatter) ] expect(paginations[0]) == paginations[0] expect(paginations[0]) != paginations[1] expect(paginations[0]) != paginations[2] expect(paginations[0]) != paginations[3] expect(paginations[1]) != paginations[0] expect(paginations[1]) == paginations[1] expect(paginations[1]) != paginations[2] expect(paginations[1]) != paginations[3] expect(paginations[2]) != paginations[0] expect(paginations[2]) != paginations[1] expect(paginations[2]) == paginations[2] expect(paginations[2]) != paginations[3] expect(paginations[3]) != paginations[0] expect(paginations[3]) != paginations[1] expect(paginations[3]) != paginations[2] expect(paginations[3]) == paginations[3] } it("is never equal with custom closure") { let pagination = PDFPaginationStyle.customClosure { (page, total) -> String in return "" } expect(pagination) != pagination expect(pagination.format(page: 1, total: 2)) == "" } } } } }
39.835165
115
0.550897
b208c52fc7f4ab9526f49256255597978cd5b6e6
3,083
swift
Swift
UnitTests/TestsHelper.swift
Keemotion/SwiftGen
fd1833e1b301dd2694d67f039898e4b52965a0b5
[ "MIT" ]
null
null
null
UnitTests/TestsHelper.swift
Keemotion/SwiftGen
fd1833e1b301dd2694d67f039898e4b52965a0b5
[ "MIT" ]
null
null
null
UnitTests/TestsHelper.swift
Keemotion/SwiftGen
fd1833e1b301dd2694d67f039898e4b52965a0b5
[ "MIT" ]
null
null
null
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Foundation import XCTest import PathKit private let colorCode: (String) -> String = ProcessInfo().environment["XcodeColors"] == "YES" ? { "\u{001b}[\($0);" } : { _ in "" } private let (msgColor, reset) = (colorCode("fg250,0,0"), colorCode("")) private let okCode = (num: colorCode("fg127,127,127"), code: colorCode("")) private let koCode = (num: colorCode("fg127,127,127") + colorCode("bg127,0,0"), code: colorCode("fg250,250,250") + colorCode("bg127,0,0")) func diff(_ result: String, _ expected: String) -> String? { guard result != expected else { return nil } var firstDiff: Int? = nil let nl = CharacterSet.newlines let lhsLines = result.components(separatedBy: nl) let rhsLines = expected.components(separatedBy: nl) for (idx, pair) in zip(lhsLines, rhsLines).enumerated() { if pair.0 != pair.1 { firstDiff = idx break } } if let badLineIdx = firstDiff { let slice = { (lines: [String], context: Int) -> ArraySlice<String> in let start = max(0, badLineIdx-context) let end = min(badLineIdx+context, lines.count-1) return lines[start...end] } let addLineNumbers = { (slice: ArraySlice) -> [String] in slice.enumerated().map { (idx: Int, line: String) in let num = idx + slice.startIndex let lineNum = "\(num+1)".padding(toLength: 3, withPad: " ", startingAt: 0) + "|" let clr = num == badLineIdx ? koCode : okCode return "\(clr.num)\(lineNum)\(reset)\(clr.code)\(line)\(reset)" } } let lhsNum = addLineNumbers(slice(lhsLines, 4)).joined(separator: "\n") let rhsNum = addLineNumbers(slice(rhsLines, 4)).joined(separator: "\n") return "\(msgColor)Mismatch at line \(badLineIdx)\(reset)\n>>>>>> result\n\(lhsNum)\n======\n\(rhsNum)\n<<<<<< expected" } return nil } func XCTDiffStrings(_ result: String, _ expected: String, file: StaticString = #file, line: UInt = #line) { guard let error = diff(result, expected) else { return } XCTFail(error, file: file, line: line) } class Fixtures { private static let testBundle = Bundle(for: Fixtures.self) private init() {} static func directory(subDirectory subDir: String? = nil) -> Path { guard let rsrcURL = testBundle.resourceURL else { fatalError("Unable to find resource directory URL") } let rsrc = Path(rsrcURL.path) guard let dir = subDir else { return rsrc } return rsrc + dir } static func path(for name: String, subDirectory: String? = nil) -> Path { guard let path = testBundle.path(forResource: name, ofType: "", inDirectory: subDirectory) else { fatalError("Unable to find fixture \"\(name)\"") } return Path(path) } static func string(for name: String, encoding: String.Encoding = .utf8) -> String { let subDir: String? = name.hasSuffix(".stencil") ? "templates" : nil do { return try path(for: name, subDirectory: subDir).read(encoding) } catch let e { fatalError("Unable to load fixture content: \(e)") } } }
36.270588
138
0.644502
a3cdd16d565e27ddc1ee3b987494bceb8aff87e0
1,124
java
Java
tests/SymInferASE/complexity/gulwani_pldi09/Fig4_4.java
unsat/d
c986b5f486eaf2394fbf659dba09c6f522291386
[ "MIT" ]
14
2020-06-17T21:05:01.000Z
2021-12-20T03:44:42.000Z
tests/SymInferASE/complexity/gulwani_pldi09/Fig4_4.java
dynaroars/dig
a6a4d045182d627d53c9970f8a77340f6f6b7afb
[ "MIT" ]
31
2020-03-23T14:16:45.000Z
2022-01-10T02:49:00.000Z
tests/SymInferASE/complexity/gulwani_pldi09/Fig4_4.java
dynaroars/dig
a6a4d045182d627d53c9970f8a77340f6f6b7afb
[ "MIT" ]
9
2020-06-22T11:22:29.000Z
2021-12-10T13:28:48.000Z
public class Fig4_4 { public static void main (String[] args) { mainQ(Integer.parseInt(args[0]), Integer.parseInt(args[1])); } public static int mainQ(int n, int m){ assert (m>0); assert (n>0); int i = n; int t = 0; int h = n/m; /* int h = 0; */ /* while(m*h<=n){ */ /* h++; */ /* } */ /* h--; */ while(i>0){ if (i < m) { i--; }else{ i = i-m; } t++; } /* assert(n%m==0); */ /* int i = n; */ /* int t = 0; */ /* while(i>0){ */ /* if (i < m) { */ /* i--; */ /* }else{ */ /* i = i-m; */ /* } */ /* t++; */ /* } */ //%%%traces: int n, int m, int t, int h //dig2: l26: -c2 <= -1, c2*m - c2 - n + t == 0, c1 - m <= -1, -t <= -2, c1 + c2 - t == 0, c2 - t <= 0 //Note: I got the above results which I think are right. But I have to manually pass in the flag -maxdeg 3 (i.e., DIG attempts to use maxdeg 4 automatically, but this requires many traces that it wasn't able to get). return 0; } }
19.37931
220
0.402135
a84636fa860e981a49a0b92751e5df3aa0a066f4
216
swift
Swift
PubSub/Sources/Models/PublishResponse.swift
NeoGolightly/google-cloud-kit
409c2fe50359b20c0db40c848ddda3866aff5346
[ "MIT" ]
19
2020-03-19T18:34:52.000Z
2022-02-15T15:28:26.000Z
PubSub/Sources/Models/PublishResponse.swift
NeoGolightly/google-cloud-kit
409c2fe50359b20c0db40c848ddda3866aff5346
[ "MIT" ]
13
2020-04-10T17:12:46.000Z
2022-01-04T11:27:26.000Z
PubSub/Sources/Models/PublishResponse.swift
NeoGolightly/google-cloud-kit
409c2fe50359b20c0db40c848ddda3866aff5346
[ "MIT" ]
13
2020-04-09T12:27:29.000Z
2022-01-07T04:36:50.000Z
// // PublishResponse.swift // // // Created by Susheel Athmakuri on 6/21/21. // import Core import Foundation public struct GoogleCloudPublishResponse: GoogleCloudModel { public let messageIds: [String] }
15.428571
60
0.726852
cdb7ede8cf347f06421b857fea8e6cec0b5ca57c
5,668
cs
C#
Game.NET/GameConsole.cs
calebc107/Game.NET
0a73bbcf60ba6442172a6163d6f0c97be85d7428
[ "Apache-2.0" ]
1
2019-07-08T15:37:26.000Z
2019-07-08T15:37:26.000Z
Game.NET/GameConsole.cs
calebc107/Game.NET
0a73bbcf60ba6442172a6163d6f0c97be85d7428
[ "Apache-2.0" ]
null
null
null
Game.NET/GameConsole.cs
calebc107/Game.NET
0a73bbcf60ba6442172a6163d6f0c97be85d7428
[ "Apache-2.0" ]
null
null
null
using System; using GameNET; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Threading; namespace GameNET { static class GameConsole { static string input = ""; /// <summary> /// Loop to read from console as long as engine is running /// </summary> public static void ReadFromConsole() { while (!Engine.abort) { if (Console.KeyAvailable) input = Console.ReadLine(); else Thread.Sleep(100); } } /// <summary> /// take action on any input, if there is any /// </summary> public static void Read() { if (!string.IsNullOrEmpty(input)) { Parse(input.Split(' ')); input = ""; } } /// <summary> /// Execute command /// </summary> /// <param name="input"></param> public static void Parse(string[] input) { Console.WriteLine(); GameConsole.input = ""; try { switch (input[0]) { //delete {gameobject} [count] - delete an object case "delete": if (input.Length == 2) if ('0' < input[1][0] && input[1][0] <= '9') //parse as int DeleteObjects(int.Parse(input[1])); else DeleteObjects(input[1]); break; //fps {new target fps} - set new fps case "fps": SetFPS(int.Parse(input[1])); break; //new {gameobject name} {x} {y} {count} case "new": CreateObject(input[1], int.Parse(input[2]), int.Parse(input[3]), int.Parse(input[4])); break; // gc - Force a garbage Collection case "gc": ForceGC(); break; //status - pring game engine and memory status case "status": PrintStatus(); break; //light - enable or disable lighting system case "light": Light.active = !Light.active; Console.WriteLine("Lighting " + (Light.active ? "on" : "off")); break; //showbounds - show boxes around game objects case "showbounds": Engine.showBounds = !Engine.showBounds; Console.WriteLine("Borders " + (Engine.showBounds ? "on" : "off")); break; case "exit": case "quit": Engine.Stop(); break; default: Console.WriteLine("Unrecognized Command"); break; } } catch (Exception e) { Console.WriteLine(e.Message); } } public static void DeleteObjects(int index) { Engine.DestroyObject(Engine.objects[index]); } public static void DeleteObjects(string objectType) { Engine.onCreateQueue.Enqueue(delegate { lock (Engine.objects) for (int i = 0; i < Engine.objects.Count; i++) { if (Engine.objects[i].GetType().Name.ToLower() == objectType.ToLower()) Engine.DestroyObject(Engine.objects[i]); } }); } public static void SetFPS(int newfps) { Engine.targetfps = newfps; } public static void CreateObject(string stype, int x, int y, int quantity) { var assembly = Assembly.GetEntryAssembly(); Type type = null; foreach (var type2 in assembly.GetTypes()) { if (type2.Name.ToLower() == stype.ToLower()) type = type2; } for (int i = 0; i < quantity; i++) { object newob = type.GetConstructors()[0].Invoke(new object[] { }); Engine.AddObject((GameObject)newob, x, y); } } public static void ForceGC() { long original = GC.GetTotalMemory(false); GC.Collect(int.MaxValue, GCCollectionMode.Forced, true, true); long now = GC.GetTotalMemory(false); var freed = ((original - now) / 1000000.0).ToString("0.##"); Console.WriteLine("Collected " + freed + "MB of garbage"); } public static void PrintStatus() { var actives = 0; foreach (var item in Engine.objects) if (item.active) actives++; string status = "STATUS:" + "\n" + actives + "/" + Engine.objects.Count + " Objects, " + Engine.expansions.Count + " Expansions" + "\nMEMORY: " + (GC.GetTotalMemory(false) / 1000000).ToString("0.##") + "MB USED" + "\nFPS: " + Engine.fps + " TPS: " + Engine.tps; Console.WriteLine(status); } } }
33.538462
118
0.431369
39120600b17830a4692227cfa6c4a77d41a2bb7e
7,419
py
Python
sphereNearPlane/sphereNearPlane.py
pcmagic/stokes_flow
464d512d3739eee77b33d1ebf2f27dae6cfa0423
[ "MIT" ]
1
2018-11-11T05:00:53.000Z
2018-11-11T05:00:53.000Z
sphereNearPlane/sphereNearPlane.py
pcmagic/stokes_flow
464d512d3739eee77b33d1ebf2f27dae6cfa0423
[ "MIT" ]
null
null
null
sphereNearPlane/sphereNearPlane.py
pcmagic/stokes_flow
464d512d3739eee77b33d1ebf2f27dae6cfa0423
[ "MIT" ]
null
null
null
import sys import petsc4py petsc4py.init(sys.argv) # from scipy.io import savemat, loadmat # from src.ref_solution import * # import warnings # from memory_profiler import profile # from time import time from src.myio import * from src.objComposite import * from src.StokesFlowMethod import * from src.geo import * from src import stokes_flow as sf # from src import slender_body as slb from codeStore.helix_common import * def get_problem_kwargs(**main_kwargs): problem_kwargs = get_solver_kwargs() OptDB = PETSc.Options() fileHandle = OptDB.getString('f', 'sphereNearPlane') OptDB.setValue('f', fileHandle) problem_kwargs['fileHandle'] = fileHandle kwargs_list = (get_sphere_kwargs(), get_forcefree_kwargs(), main_kwargs,) for t_kwargs in kwargs_list: for key in t_kwargs: problem_kwargs[key] = t_kwargs[key] err_msg = 'current version only accept single sphere. ' assert problem_kwargs['sphere_coord'].size == 3, err_msg h2Plane = OptDB.getReal('h2Plane', 100) problem_kwargs['sphere_coord'] = problem_kwargs['sphere_coord'] + (0, 0, h2Plane) return problem_kwargs def get_twoSphereProblem_kwargs(**main_kwargs): problem_kwargs = get_problem_kwargs(**main_kwargs) rs = problem_kwargs['rs'] move_x = OptDB.getReal('move_x', rs * 2) move_y = OptDB.getReal('move_y', 0) move_z = OptDB.getReal('move_z', 0) move_r = np.linalg.norm(np.array((move_x, move_y, move_z))) err_msg = 'move_r > rs' assert move_r > rs, err_msg sphere_coord = problem_kwargs['sphere_coord'][0] sphere_coord0 = sphere_coord - (move_x, move_y, move_z) sphere_coord1 = sphere_coord + (move_x, move_y, move_z) problem_kwargs['sphere_coord'] = np.vstack((sphere_coord0, sphere_coord1)) sphere_velocity = problem_kwargs['sphere_velocity'][0] problem_kwargs['sphere_velocity'] = np.vstack((sphere_velocity, sphere_velocity)) return problem_kwargs def print_case_info(**problem_kwargs): fileHandle = problem_kwargs['fileHandle'] print_solver_info(**problem_kwargs) print_forcefree_info(**problem_kwargs) print_sphere_info(fileHandle, **problem_kwargs) return True def main_resistanceMatrix(**main_kwargs): # OptDB = PETSc.Options() main_kwargs['zoom_factor'] = 1 problem_kwargs = get_problem_kwargs(**main_kwargs) matrix_method = problem_kwargs['matrix_method'] fileHandle = problem_kwargs['fileHandle'] rs = problem_kwargs['rs'] print_case_info(**problem_kwargs) # create sphere sphere_obj = create_sphere(**problem_kwargs)[0] sphere_center = sphere_obj.get_u_geo().get_center() sphere_norm = sphere_obj.get_u_geo().get_geo_norm() # sphere_comp = sf.ForceFreeComposite(center=sphere_center, norm=sphere_norm, name='sphereComp') # sphere_comp.add_obj(sphere_obj, rel_U=np.zeros(6)) # sphere_comp.show_u_nodes() problem = sf.problem_dic[matrix_method](**problem_kwargs) # problem = sf.ForceFreeProblem(**problem_kwargs) problem.add_obj(sphere_obj) problem.print_info() problem.create_matrix() # AtBtCt_full(problem, save_vtk=False, pick_M=False, center=sphere_center, save_name=fileHandle, # uNormFct=(6 * np.pi * rs), wNormFct=(6 * np.pi * rs ** 3), # uwNormFct=(6 * np.pi * rs ** 2), ) AtBtCt_multiObj(problem, save_vtk=False, pick_M=False, save_name=fileHandle, uNormFct=(6 * np.pi * rs), wNormFct=(6 * np.pi * rs ** 3), uwNormFct=(6 * np.pi * rs ** 2), ) return True def main_resistanceMatrix_twoSphere(**main_kwargs): # OptDB = PETSc.Options() main_kwargs['zoom_factor'] = 1 problem_kwargs = get_twoSphereProblem_kwargs(**main_kwargs) matrix_method = problem_kwargs['matrix_method'] fileHandle = problem_kwargs['fileHandle'] rs = problem_kwargs['rs'] print_case_info(**problem_kwargs) # create sphere # sphere0_obj = create_sphere(**problem_kwargs)[0] # sphere1_obj = sphere0_obj.copy() # sphere0_obj.set_name('sphereObj_0') # sphere1_obj.set_name('sphereObj_1') # sphere0_obj.move((-move_x, 0, 0)) # sphere1_obj.move((move_x, 0, 0)) # problem_center = (sphere0_obj.get_u_geo().get_center() # + sphere1_obj.get_u_geo().get_center()) / 2 # # objtype = sf.obj_dic[matrix_method] # # all_obj = objtype() # # all_obj.combine((sphere0_obj, sphere1_obj), set_re_u=True, set_force=True) sphere0_obj, sphere1_obj = create_sphere(**problem_kwargs) # sphere0_obj.show_u_nodes() # sphere1_obj.show_u_nodes() problem = sf.problem_dic[matrix_method](**problem_kwargs) problem.add_obj(sphere0_obj) problem.add_obj(sphere1_obj) problem.print_info() problem.create_matrix() AtBtCt_multiObj(problem, save_vtk=False, pick_M=False, save_name=fileHandle, print_each=False, uNormFct=1, wNormFct=1, uwNormFct=1, ) return True def main_xu20201104(**main_kwargs): # OptDB = PETSc.Options() main_kwargs['zoom_factor'] = 1 problem_kwargs = get_twoSphereProblem_kwargs(**main_kwargs) matrix_method = problem_kwargs['matrix_method'] fileHandle = problem_kwargs['fileHandle'] rs = problem_kwargs['rs'] print_case_info(**problem_kwargs) # create sphere # sphere0_obj = create_sphere(**problem_kwargs)[0] # sphere1_obj = sphere0_obj.copy() # sphere0_obj.set_name('sphereObj_0') # sphere1_obj.set_name('sphereObj_1') # sphere0_obj.move((-move_x, 0, 0)) # sphere1_obj.move((move_x, 0, 0)) # problem_center = (sphere0_obj.get_u_geo().get_center() # + sphere1_obj.get_u_geo().get_center()) / 2 # # objtype = sf.obj_dic[matrix_method] # # all_obj = objtype() # # all_obj.combine((sphere0_obj, sphere1_obj), set_re_u=True, set_force=True) sphere0_obj, _ = create_sphere(**problem_kwargs) problem_kwargs['rs'] = problem_kwargs['rs'] / 4 problem_kwargs['ds'] = problem_kwargs['ds'] / 4 _, sphere1_obj = create_sphere(**problem_kwargs) # sphere0_obj.show_u_nodes() # sphere1_obj.show_u_nodes() problem = sf.problem_dic[matrix_method](**problem_kwargs) problem.add_obj(sphere0_obj) problem.add_obj(sphere1_obj) # problem.show_u_nodes() problem.print_info() problem.create_matrix() AtBtCt_multiObj(problem, save_vtk=False, pick_M=False, save_name=fileHandle, print_each=False, uNormFct=1, wNormFct=1, uwNormFct=1, ) return True if __name__ == '__main__': OptDB = PETSc.Options() # mpirun -np 4 python ../sphereNearPlane.py -main_resistanceMatrix_twoSphere 1 -sm rs_plane -epsilon 0.3 -rs 1.000000 -ds 0.05 -es 0.000000 -h2Plane 1.5 -ksp_max_it 1000 -ksp_rtol 1.000000e-10 -ksp_atol 1.000000e-100 -move_x 2 -f h1.50_movex2 matrix_method = OptDB.getString('sm', 'pf') # assert matrix_method == 'rs_plane', matrix_method if OptDB.getBool('main_resistanceMatrix', False): OptDB.setValue('main_fun', False) main_resistanceMatrix() if OptDB.getBool('main_resistanceMatrix_twoSphere', False): OptDB.setValue('main_fun', False) main_resistanceMatrix_twoSphere() if OptDB.getBool('main_xu20201104', False): OptDB.setValue('main_fun', False) main_xu20201104() # if OptDB.getBool('main_fun', True): # main_fun()
38.640625
249
0.692411
5275e98d7ace1b303acae266799eff66f437d943
62
rb
Ruby
lib/freq_stats.rb
ddavisgraphics/freq_stats
aa316a872dba7dd0160d9cca980eb7cc20bfa09c
[ "MIT" ]
null
null
null
lib/freq_stats.rb
ddavisgraphics/freq_stats
aa316a872dba7dd0160d9cca980eb7cc20bfa09c
[ "MIT" ]
null
null
null
lib/freq_stats.rb
ddavisgraphics/freq_stats
aa316a872dba7dd0160d9cca980eb7cc20bfa09c
[ "MIT" ]
null
null
null
require 'freq_stats/version' require 'freq_stats/super_array'
20.666667
32
0.83871
2910b76302ebd9e7706814176f37c6ff57a0869a
1,672
swift
Swift
Pee break/ToiletsFlow/ToiletsController/Cell/ToiletCellViewModel.swift
leobouilloux/PeeBreak
b8c2baa47ac1048df89e412ea44024201c637824
[ "MIT" ]
1
2019-02-25T01:02:04.000Z
2019-02-25T01:02:04.000Z
Pee break/ToiletsFlow/ToiletsController/Cell/ToiletCellViewModel.swift
leobouilloux/PeeBreak
b8c2baa47ac1048df89e412ea44024201c637824
[ "MIT" ]
null
null
null
Pee break/ToiletsFlow/ToiletsController/Cell/ToiletCellViewModel.swift
leobouilloux/PeeBreak
b8c2baa47ac1048df89e412ea44024201c637824
[ "MIT" ]
null
null
null
// // ToiletCellViewModel.swift // Pee break // // Created by Leo Marcotte on 23/02/2019. // Copyright © 2019 Leo Marcotte. All rights reserved. // import RxCocoa import RxSwift final class ToiletCellViewModel: ToiletCellViewModelInterface { let address: BehaviorRelay<String> let hours: BehaviorRelay<String> let distance = BehaviorRelay<String>(value: "NaN") let favoriteImage = BehaviorRelay<UIImage>(value: UIImage()) let chevronImage = BehaviorRelay<UIImage>(value: Asset.chevronRight.image.withRenderingMode(.alwaysTemplate)) private let isFavorite: BehaviorRelay<Bool> private let bag = DisposeBag() init(with data: ToiletData) { self.address = BehaviorRelay<String>(value: data.address) let formattedHours = " \(data.hours.replacingOccurrences(of: " ", with: "")) " self.hours = BehaviorRelay<String>(value: formattedHours) self.isFavorite = BehaviorRelay<Bool>(value: data.isFavorite) if let distance = data.distance.value { if Int(distance) / 1000 == 0 { self.distance.accept(String(format: "%.0fm", distance)) } else { self.distance.accept(String(format: "%.1fkm", distance / 1000)) } } setupRxBindings() } func setupRxBindings() { bindIsFavorite() } func bindIsFavorite() { isFavorite .subscribe(onNext: { [weak self] isFavorite in let image = isFavorite ? Asset.favourite.image.withRenderingMode(.alwaysTemplate) : UIImage() self?.favoriteImage.accept(image) }) .disposed(by: bag) } }
30.962963
113
0.636364
b0be8894f64600fd0757eaf6f3ee2d6d81f5af64
1,248
py
Python
taesko/web-server/bin/gen_test_files.py
taesko/training-projects
638649b0b5987ba971ae5ce1f171642de3cde739
[ "Apache-2.0" ]
null
null
null
taesko/web-server/bin/gen_test_files.py
taesko/training-projects
638649b0b5987ba971ae5ce1f171642de3cde739
[ "Apache-2.0" ]
null
null
null
taesko/web-server/bin/gen_test_files.py
taesko/training-projects
638649b0b5987ba971ae5ce1f171642de3cde739
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import argparse import io UNITS = { 'B': 1, 'KB': 1024, 'MB': 1024 * 1024, 'GB': 1024 * 1024 * 1024 } WRITE_CHUNK_SIZE = 4096 def generate_file(size): for _ in range(size): yield 'a' def main(): parser = argparse.ArgumentParser() parser.add_argument('size', help='File size (default in KB)', type=int, default=1) parser.add_argument('-p', '--path', help='File path where to save the file.') parser.add_argument('-u', '--unit', help='Unit of size argument', default='KB', choices=UNITS.keys()) args = parser.parse_args() size = args.size * UNITS[args.unit] line = 'Test file of size around {} {}'.format(args.size, args.unit) if args.path: file_gen = generate_file(size) with open(args.path, mode='w') as f: f.write(line) for c in file_gen: f.write(c) else: buf = io.StringIO() for c in generate_file(size): buf.write(c) chunk = buf.read(WRITE_CHUNK_SIZE) while chunk: print(chunk) chunk = buf.read(WRITE_CHUNK_SIZE) if __name__ == '__main__': main()
24
75
0.546474
389561d4e2d36c09ceb11155b1fb7942bd151996
14,140
php
PHP
web/core/modules/media_library/tests/src/Kernel/MediaLibraryAccessTest.php
rc100/awfd8-migrate
a1ff33e0a9274af57e09fe74bc103dc24d849965
[ "MIT" ]
6
2015-12-02T14:12:20.000Z
2020-11-01T18:42:54.000Z
web/core/modules/media_library/tests/src/Kernel/MediaLibraryAccessTest.php
rc100/awfd8-migrate
a1ff33e0a9274af57e09fe74bc103dc24d849965
[ "MIT" ]
77
2019-04-17T00:11:30.000Z
2021-06-17T09:35:29.000Z
web/core/modules/media_library/tests/src/Kernel/MediaLibraryAccessTest.php
rc100/awfd8-migrate
a1ff33e0a9274af57e09fe74bc103dc24d849965
[ "MIT" ]
5
2019-05-23T19:38:53.000Z
2022-03-09T11:21:47.000Z
<?php namespace Drupal\Tests\media_library\Kernel; use Drupal\Core\Access\AccessResult; use Drupal\Core\Access\AccessResultReasonInterface; use Drupal\entity_test\Entity\EntityTest; use Drupal\entity_test\Entity\EntityTestBundle; use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldStorageConfig; use Drupal\image\Entity\ImageStyle; use Drupal\KernelTests\KernelTestBase; use Drupal\media_library\MediaLibraryState; use Drupal\Tests\user\Traits\UserCreationTrait; use Drupal\views\Views; /** * Tests the media library access. * * @group media_library */ class MediaLibraryAccessTest extends KernelTestBase { use UserCreationTrait; /** * {@inheritdoc} */ protected static $modules = [ 'entity_test', 'media', 'media_library', 'media_library_test', 'filter', 'file', 'field', 'image', 'system', 'views', 'user', ]; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installEntitySchema('user'); $this->installEntitySchema('file'); $this->installSchema('file', 'file_usage'); $this->installSchema('system', ['sequences', 'key_value_expire']); $this->installEntitySchema('entity_test'); $this->installEntitySchema('filter_format'); $this->installEntitySchema('media'); $this->installConfig([ 'field', 'system', 'file', 'image', 'media', 'media_library', ]); EntityTestBundle::create(['id' => 'test'])->save(); $field_storage = FieldStorageConfig::create([ 'type' => 'entity_reference', 'field_name' => 'field_test_media', 'entity_type' => 'entity_test', 'settings' => [ 'target_type' => 'media', ], ]); $field_storage->save(); FieldConfig::create([ 'field_storage' => $field_storage, 'bundle' => 'test', ])->save(); // Create an account with special UID 1. $this->createUser([]); } /** * Tests that users can't delete the 'media_library' image style. */ public function testMediaLibraryImageStyleAccess() { // Create a user who can manage the image styles. $user = $this->createUser([ 'access administration pages', 'administer image styles', ]); // The user should be able to delete the 'medium' image style, but not the // 'media_library' image style. $this->assertTrue(ImageStyle::load('medium')->access('delete', $user)); $this->assertFalse(ImageStyle::load('media_library')->access('delete', $user)); } /** * Tests that the field widget opener respects entity creation permissions. */ public function testFieldWidgetEntityCreateAccess() { /** @var \Drupal\media_library\MediaLibraryUiBuilder $ui_builder */ $ui_builder = $this->container->get('media_library.ui_builder'); // Create a media library state to test access. $state = MediaLibraryState::create('media_library.opener.field_widget', ['file', 'image'], 'file', 2, [ 'entity_type_id' => 'entity_test', 'bundle' => 'test', 'field_name' => 'field_test_media', ]); $access_result = $ui_builder->checkAccess($this->createUser(), $state); $this->assertAccess($access_result, FALSE, "The following permissions are required: 'administer entity_test content' OR 'administer entity_test_with_bundle content' OR 'create test entity_test_with_bundle entities'.", [], ['url.query_args', 'user.permissions']); // Create a user with the appropriate permissions and assert that access is // granted. $account = $this->createUser([ 'create test entity_test_with_bundle entities', 'view media', ]); $access_result = $ui_builder->checkAccess($account, $state); $this->assertAccess($access_result, TRUE, NULL, Views::getView('media_library')->storage->getCacheTags(), ['url.query_args', 'user.permissions']); } /** * @covers \Drupal\media_library\MediaLibraryEditorOpener::checkAccess * * @param bool $media_embed_enabled * Whether to test with media_embed filter enabled on the text format. * @param bool $can_use_format * Whether the logged in user is allowed to use the text format. * * @dataProvider editorOpenerAccessProvider */ public function testEditorOpenerAccess($media_embed_enabled, $can_use_format) { $format = $this->container ->get('entity_type.manager') ->getStorage('filter_format')->create([ 'format' => $this->randomMachineName(), 'name' => $this->randomString(), 'filters' => [ 'media_embed' => ['status' => $media_embed_enabled], ], ]); $format->save(); $permissions = [ 'access media overview', 'view media', ]; if ($can_use_format) { $permissions[] = $format->getPermissionName(); } $state = MediaLibraryState::create( 'media_library.opener.editor', ['image'], 'image', 1, ['filter_format_id' => $format->id()] ); $access_result = $this->container ->get('media_library.ui_builder') ->checkAccess($this->createUser($permissions), $state); if ($media_embed_enabled && $can_use_format) { $this->assertAccess($access_result, TRUE, NULL, Views::getView('media_library')->storage->getCacheTags(), ['user.permissions']); } else { $this->assertAccess($access_result, FALSE, NULL, [], ['user.permissions']); } } /** * Data provider for ::testEditorOpenerAccess. */ public function editorOpenerAccessProvider() { return [ 'media_embed filter enabled' => [ TRUE, TRUE, ], 'media_embed filter disabled' => [ FALSE, TRUE, ], 'media_embed filter enabled, user not allowed to use text format' => [ TRUE, FALSE, ], ]; } /** * Tests that the field widget opener respects entity-specific access. */ public function testFieldWidgetEntityEditAccess() { /** @var \Drupal\media_library\MediaLibraryUiBuilder $ui_builder */ $ui_builder = $this->container->get('media_library.ui_builder'); $forbidden_entity = EntityTest::create([ 'type' => 'test', // This label will automatically cause an access denial. // @see \Drupal\entity_test\EntityTestAccessControlHandler::checkAccess() 'name' => 'forbid_access', ]); $forbidden_entity->save(); // Create a media library state to test access. $state = MediaLibraryState::create('media_library.opener.field_widget', ['file', 'image'], 'file', 2, [ 'entity_type_id' => $forbidden_entity->getEntityTypeId(), 'bundle' => $forbidden_entity->bundle(), 'field_name' => 'field_test_media', 'entity_id' => $forbidden_entity->id(), ]); $access_result = $ui_builder->checkAccess($this->createUser(), $state); $this->assertAccess($access_result, FALSE, NULL, [], ['url.query_args']); $neutral_entity = EntityTest::create([ 'type' => 'test', // This label will result in neutral access. // @see \Drupal\entity_test\EntityTestAccessControlHandler::checkAccess() 'name' => $this->randomString(), ]); $neutral_entity->save(); $parameters = $state->getOpenerParameters(); $parameters['entity_id'] = $neutral_entity->id(); $state = MediaLibraryState::create( $state->getOpenerId(), $state->getAllowedTypeIds(), $state->getSelectedTypeId(), $state->getAvailableSlots(), $parameters ); $access_result = $ui_builder->checkAccess($this->createUser(), $state); $this->assertTrue($access_result->isNeutral()); $this->assertAccess($access_result, FALSE, NULL, [], ['url.query_args', 'user.permissions']); // Give the user permission to edit the entity and assert that access is // granted. $account = $this->createUser([ 'administer entity_test content', 'view media', ]); $access_result = $ui_builder->checkAccess($account, $state); $this->assertAccess($access_result, TRUE, NULL, Views::getView('media_library')->storage->getCacheTags(), ['url.query_args', 'user.permissions']); } /** * Tests that the field widget opener respects entity field-level access. */ public function testFieldWidgetEntityFieldAccess() { $field_storage = FieldStorageConfig::create([ 'type' => 'entity_reference', 'entity_type' => 'entity_test', // The media_library_test module will deny access to this field. // @see media_library_test_entity_field_access() 'field_name' => 'field_media_no_access', 'settings' => [ 'target_type' => 'media', ], ]); $field_storage->save(); FieldConfig::create([ 'field_storage' => $field_storage, 'bundle' => 'test', ])->save(); /** @var \Drupal\media_library\MediaLibraryUiBuilder $ui_builder */ $ui_builder = $this->container->get('media_library.ui_builder'); // Create an account with administrative access to the test entity type, // so that we can be certain that field access is checked. $account = $this->createUser(['administer entity_test content']); // Test that access is denied even without an entity to work with. $state = MediaLibraryState::create('media_library.opener.field_widget', ['file', 'image'], 'file', 2, [ 'entity_type_id' => 'entity_test', 'bundle' => 'test', 'field_name' => $field_storage->getName(), ]); $access_result = $ui_builder->checkAccess($account, $state); $this->assertAccess($access_result, FALSE, 'Field access denied by test module', [], ['url.query_args', 'user.permissions']); // Assert that field access is also checked with a real entity. $entity = EntityTest::create([ 'type' => 'test', 'name' => $this->randomString(), ]); $entity->save(); $parameters = $state->getOpenerParameters(); $parameters['entity_id'] = $entity->id(); $state = MediaLibraryState::create( $state->getOpenerId(), $state->getAllowedTypeIds(), $state->getSelectedTypeId(), $state->getAvailableSlots(), $parameters ); $access_result = $ui_builder->checkAccess($account, $state); $this->assertAccess($access_result, FALSE, 'Field access denied by test module', [], ['url.query_args', 'user.permissions']); } /** * Tests that media library access respects the media_library view. */ public function testViewAccess() { /** @var \Drupal\media_library\MediaLibraryUiBuilder $ui_builder */ $ui_builder = $this->container->get('media_library.ui_builder'); // Create a media library state to test access. $state = MediaLibraryState::create('media_library.opener.field_widget', ['file', 'image'], 'file', 2, [ 'entity_type_id' => 'entity_test', 'bundle' => 'test', 'field_name' => 'field_test_media', ]); // Create a clone of the view so we can reset the original later. $view_original = clone Views::getView('media_library'); // Create our test users. Both have permission to create entity_test content // so that we can specifically test Views-related access checking. // @see ::testEntityCreateAccess() $forbidden_account = $this->createUser([ 'create test entity_test_with_bundle entities', ]); $allowed_account = $this->createUser([ 'create test entity_test_with_bundle entities', 'view media', ]); // Assert the 'view media' permission is needed to access the library and // validate the cache dependencies. $access_result = $ui_builder->checkAccess($forbidden_account, $state); $this->assertAccess($access_result, FALSE, "The 'view media' permission is required.", $view_original->storage->getCacheTags(), ['url.query_args', 'user.permissions']); // Assert that the media library access is denied when the view widget // display is deleted. $view_storage = Views::getView('media_library')->storage; $displays = $view_storage->get('display'); unset($displays['widget']); $view_storage->set('display', $displays); $view_storage->save(); $access_result = $ui_builder->checkAccess($allowed_account, $state); $this->assertAccess($access_result, FALSE, 'The media library widget display does not exist.', $view_original->storage->getCacheTags()); // Restore the original view and assert that the media library controller // works again. $view_original->storage->save(); $access_result = $ui_builder->checkAccess($allowed_account, $state); $this->assertAccess($access_result, TRUE, NULL, $view_original->storage->getCacheTags(), ['url.query_args', 'user.permissions']); // Assert that the media library access is denied when the entire media // library view is deleted. Views::getView('media_library')->storage->delete(); $access_result = $ui_builder->checkAccess($allowed_account, $state); $this->assertAccess($access_result, FALSE, 'The media library view does not exist.'); } /** * Asserts various aspects of an access result. * * @param \Drupal\Core\Access\AccessResult $access_result * The access result. * @param bool $is_allowed * The expected access status. * @param string $expected_reason * (optional) The expected reason attached to the access result. * @param string[] $expected_cache_tags * (optional) The expected cache tags attached to the access result. * @param string[] $expected_cache_contexts * (optional) The expected cache contexts attached to the access result. */ private function assertAccess(AccessResult $access_result, $is_allowed, $expected_reason = NULL, array $expected_cache_tags = [], array $expected_cache_contexts = []) { $this->assertSame($is_allowed, $access_result->isAllowed()); if ($access_result instanceof AccessResultReasonInterface && isset($expected_reason)) { $this->assertSame($expected_reason, $access_result->getReason()); } $this->assertSame($expected_cache_tags, $access_result->getCacheTags()); $this->assertSame($expected_cache_contexts, $access_result->getCacheContexts()); } }
35.797468
266
0.660891
c3cbec61444db76b69b21a3f4a480e31a1280ccd
1,456
cs
C#
SqlMapper.Tests/Mocks/CommandMock.cs
AndrewFahmy/SQLMapper
cc769a2ed6bfdc82c4aa9e387c1b95d1bd128bc2
[ "MIT" ]
7
2017-02-21T09:03:23.000Z
2021-04-18T08:15:41.000Z
SqlMapper.Tests/Mocks/CommandMock.cs
AndrewFahmy/SQLMapper
cc769a2ed6bfdc82c4aa9e387c1b95d1bd128bc2
[ "MIT" ]
null
null
null
SqlMapper.Tests/Mocks/CommandMock.cs
AndrewFahmy/SQLMapper
cc769a2ed6bfdc82c4aa9e387c1b95d1bd128bc2
[ "MIT" ]
4
2017-02-21T09:03:25.000Z
2020-04-09T09:26:15.000Z
using System.Data; using System.Data.Common; namespace SqlMapper.Tests.Mocks { public class CommandMock : DbCommand { private ParameterCollectionMock _parameters; public CommandMock() { _parameters = new ParameterCollectionMock(); } public override void Cancel() { //not needed } public override int ExecuteNonQuery() { return 1; } public override object ExecuteScalar() { return new {}; } public override void Prepare() { //not needed } public override string CommandText { get; set; } public override int CommandTimeout { get; set; } public override CommandType CommandType { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } protected override DbConnection DbConnection { get; set; } protected override DbParameterCollection DbParameterCollection => _parameters; protected override DbTransaction DbTransaction { get; set; } public override bool DesignTimeVisible { get; set; } protected override DbParameter CreateDbParameter() { return new ParameterMock(); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return new ReaderMock(CommandText); } } }
26.472727
86
0.604396
dda83c9561ce31ea52f76cb71dec80f96395c0c3
5,187
java
Java
app/src/main/java/com/example/lifepath/MovementFragment.java
Danval-003/Lifepath
00c6f3d6574049ef83346e421ccca11130d808cc
[ "MIT" ]
null
null
null
app/src/main/java/com/example/lifepath/MovementFragment.java
Danval-003/Lifepath
00c6f3d6574049ef83346e421ccca11130d808cc
[ "MIT" ]
null
null
null
app/src/main/java/com/example/lifepath/MovementFragment.java
Danval-003/Lifepath
00c6f3d6574049ef83346e421ccca11130d808cc
[ "MIT" ]
null
null
null
package com.example.lifepath; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.fragment.app.Fragment; /** * A simple {@link Fragment} subclass. * Use the {@link MovementFragment#newInstance} factory method to * create an instance of this fragment. */ public class MovementFragment extends Fragment implements View.OnClickListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private Button start, stop,reset; private boolean isOn=false; Thread cronos; TextView crono; private int mili=0, seg=0, minutos=0; private Handler h =new Handler(); public MovementFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MovementFragment. */ // TODO: Rename and change types and number of parameters public static MovementFragment newInstance(String param1, String param2) { MovementFragment fragment = new MovementFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View j= inflater.inflate(R.layout.fragment_movement, container, false); start=(Button) j.findViewById(R.id.stat); stop=(Button) j.findViewById(R.id.ssp); reset=(Button) j.findViewById(R.id.reset); crono = (TextView) j.findViewById(R.id.numeros); start.setOnClickListener(this); stop.setOnClickListener(this); reset.setOnClickListener(this); cronos = new Thread(new Runnable() { @Override public void run() { while (true){ if (isOn){ try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } mili++; if (mili==999){ seg++; mili=0; } if(seg==59){ minutos++; seg=0; } h.post(new Runnable() { @Override public void run() { String m ="", s="", mi=""; if(mili<10){ m="00"+mili; }else if (mili<100){ m="0"+mili; }else{ m=""+mili;} if (seg<10){ s="0"+seg; }else {s=""+seg;} if (minutos<10){ mi="0"+minutos; }else {mi=""+minutos;} crono.setText(mi+":"+s+":"+m); } }); } } } }); cronos.start(); Button s = (Button) j.findViewById(R.id.rut); s.setOnClickListener(view -> { Intent o= new Intent(getActivity(), Rutinas.class); getActivity().startActivity(o); }); return j; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.stat: isOn=true; break; case R.id.ssp: isOn=false; break; case R.id.reset: isOn=false; mili=0; seg=0; minutos=0; crono.setText("00:00:000"); break; } } }
33.901961
81
0.47754
3170986bb1271e77cc3a6af315beaba405f0ada9
751
sql
SQL
MySQL/25_Advance Stored Procedure.sql
ajsamant/SampleCodeAjinkya
f7515ca879efd01c67047d2527819a1366861e94
[ "MIT" ]
null
null
null
MySQL/25_Advance Stored Procedure.sql
ajsamant/SampleCodeAjinkya
f7515ca879efd01c67047d2527819a1366861e94
[ "MIT" ]
null
null
null
MySQL/25_Advance Stored Procedure.sql
ajsamant/SampleCodeAjinkya
f7515ca879efd01c67047d2527819a1366861e94
[ "MIT" ]
null
null
null
DROP PROCEDURE IF EXISTS spCheckFruitstockLevel; DELIMITER // CREATE PROCEDURE spCheckFruitstockLevel(IN pFruit_Id SMALLINT(5), OUT pStockLevel VARCHAR(6)) BEGIN DECLARE stockNumber SMALLINT; SELECT Fruits.Inventory into stockNumber FROM Fruits INNER JOIN Units ON Fruits.Unit_Id = Units.Unit_Id WHERE Fruits.Fruit_Id = pFruit_Id; IF stockNumber > 10 THEN SET pStockLevel = 'High'; ELSEIF ( stockNumber <= 10 AND stockNumber >= 5) THEN SET pStockLevel = 'Medium'; ELSEIF ( stockNumber < 5) THEN SET pStockLevel = 'Low - Please Replace Now!'; END IF; End // DELIMITER ; #TEST STORED PROCEDURE CALL spCheckFruitstockLevel(1, @stockLevel); select @stockLevel; # Drop Procedure DROP PROCEDURE spCheckFruitstockLevel;
22.088235
93
0.750999
2c76ac4fc6dcbeb3a656e9839bd6eaea94463abc
3,674
cpp
C++
linux/SensorsLinuxInterface.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
7
2021-10-29T20:29:48.000Z
2022-03-03T01:38:45.000Z
linux/SensorsLinuxInterface.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
null
null
null
linux/SensorsLinuxInterface.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * Copyright (C) 2019-2020 STMicroelectronics * * 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. */ #include <cstdlib> #include <cerrno> #include <iostream> #include <cstring> #include "SensorsLinuxInterface.h" #include "LinuxPropertiesLoader.h" #include <IConsole.h> static const std::string configFilename = "/etc/stm-sensors-hal/config"; SensorsLinuxInterface::SensorsLinuxInterface(void) : sensorsCore(ISTMSensorsHAL::getInstance()), console(IConsole::getInstance()), propertiesManager(PropertiesManager::getInstance()) { } /** * initialize: initialize the interface * * Return value: 0 on success, else a negative error code. */ int SensorsLinuxInterface::initialize(void) { LinuxPropertiesLoader linuxPropertiesLoader; if (!linuxPropertiesLoader.loadFromConfigFile(configFilename)) { propertiesManager.load(linuxPropertiesLoader); } sensorsCore.initialize(*dynamic_cast<ISTMSensorsCallback *>(this)); return 0; } /** * getSensorsList: retrieve sensors list * * Return value: const reference of sensors list. */ const std::vector<STMSensor>& SensorsLinuxInterface::getSensorsList(void) const { return sensorsCore.getSensorsList().getList(); } /** * enable: enable or disable specified sensor * @handle: sensor handle ID (retrieved from sensors list). * @enable: enable or disable flag. * * Return value: 0 on success, else a negative error code. */ int SensorsLinuxInterface::enable(uint32_t handle, bool enable) { return sensorsCore.activate(handle, enable); } /** * setRate: set sensor sampling period and batch time * @handle: sensor handle ID (retrieved from sensors list). * @samplingPeriodNanoSec: sensor sampling period in nsec. * @maxReportLatencyNanoSec: sensor batch time in nsec. * * Return value: 0 on success, else a negative error code. */ int SensorsLinuxInterface::setRate(uint32_t handle, int64_t samplingPeriodNanoSec, int64_t maxReportLatencyNanoSec) { return sensorsCore.setRate(handle, samplingPeriodNanoSec, maxReportLatencyNanoSec); } /** * onNewSensorsData: receive data from STMSensorsHAL, * reference: ISTMSensorsCallbackData class */ void SensorsLinuxInterface::onNewSensorsData(const std::vector<ISTMSensorsCallbackData> &sensorsData) { (void) sensorsData; } /** * onSaveDataRequest: receive data to store, * reference: ISTMSensorsCallbackData class */ int SensorsLinuxInterface::onSaveDataRequest(const std::string& resourceID, const void *data, ssize_t len) { (void) resourceID; (void) data; (void) len; return 0; } /** * onLoadDataRequest: load data from disk, * reference: ISTMSensorsCallbackData class */ int SensorsLinuxInterface::onLoadDataRequest(const std::string& resourceID, void *data, ssize_t len) { (void) resourceID; (void) data; (void) len; return 0; }
28.703125
96
0.688351
5da760efdd8c8eaa8b7bff8dbd6d3dc1c382a22f
4,019
cpp
C++
simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "SleMatrixBuilder.h" namespace fvmsolver { SleMatrixBuilder::SleMatrixBuilder( AbstractCoeffsCalculator& coeffsCalculator, uPtrDataPort spData) : spDataPort_(std::move(spData)), dataPort_(*spDataPort_), coeffsCalculator_(coeffsCalculator), aP_(dataPort_.getAp()), aW_(dataPort_.getAw()), aE_(dataPort_.getAe()), aN_(dataPort_.getAn()), aS_(dataPort_.getAs()) { } void SleMatrixBuilder::build(std::shared_ptr<SleSolver> sleSolver) { pSleSolver_ = sleSolver; createMatrixAndVectors(); buildInterior(); buildBoundary(); } void SleMatrixBuilder::buildInterior() { size_t domainParts = dataPort_.getInteriorPartsAmount(); for (size_t partId = 0; partId < domainParts; partId++) { std::string name = dataPort_.getInteriorName(partId); coeffsCalculator_.chooseActualDomainPart(name); size_t partCells = dataPort_.getPartCellsAmount(name); for (size_t i = 0; i < partCells; i++) { coeffsCalculator_.calculateInterior(i); placeAllCoeffs(); } } } void SleMatrixBuilder::buildBoundary() { size_t domainParts = dataPort_.getBcPartsAmount(); for (size_t partId = 0; partId < domainParts; partId++) { std::string name = dataPort_.getBoundaryName(partId); coeffsCalculator_.chooseActualDomainPart(name); size_t partCells = dataPort_.getPartCellsAmount(name); for (size_t i = 0; i < partCells; i++) { coeffsCalculator_.calculateBoundary(i); placeAllCoeffs(); } } } void SleMatrixBuilder::placeAllCoeffs() { double a_w = coeffsCalculator_.getAw(); double a_e = coeffsCalculator_.getAe(); double a_n = coeffsCalculator_.getAn(); double a_s = coeffsCalculator_.getAs(); double a_p = coeffsCalculator_.getAp(); size_t posW_ = coeffsCalculator_.get_wNum(); size_t posE_ = coeffsCalculator_.get_eNum(); size_t posN_ = coeffsCalculator_.get_nNum(); size_t posS_ = coeffsCalculator_.get_sNum(); size_t posP_ = coeffsCalculator_.get_pNum() - 1; bool isInteriorW_ = coeffsCalculator_.is_wInterior(); bool isInteriorE_ = coeffsCalculator_.is_eInterior(); bool isInteriorN_ = coeffsCalculator_.is_nInterior(); bool isInteriorS_ = coeffsCalculator_.is_sInterior(); placeCoeffsOtherDiags(posP_, posW_, -a_w, isInteriorW_); placeCoeffsOtherDiags(posP_, posE_, -a_e, isInteriorE_); placeCoeffsOtherDiags(posP_, posN_, -a_n, isInteriorN_); placeCoeffsOtherDiags(posP_, posS_, -a_s, isInteriorS_); placeCoeffsMainDiag(posP_, posP_, a_p); pSleSolver_->placeRhsValue(posP_, coeffsCalculator_.getRHS()); aP_[posP_] = a_p; dataPort_.setRhs(posP_, coeffsCalculator_.getRHS()); dataPort_.set_b(posP_, coeffsCalculator_.get_b()); saveCoeff(posW_, a_w, aW_); saveCoeff(posE_, a_e, aE_); saveCoeff(posN_, a_n, aN_); saveCoeff(posS_, a_s, aS_); } void SleMatrixBuilder::placeCoeffsMainDiag(size_t rowNum, size_t colNum, double value) { pSleSolver_->placeCoeff(rowNum, colNum, value); } void SleMatrixBuilder::placeCoeffsOtherDiags(size_t rowNum, size_t colNum, double value, bool isInteriorCell) { if (isInteriorCell) { pSleSolver_->placeCoeff(rowNum, colNum - 1, value); } } void SleMatrixBuilder::createMatrixAndVectors() { size_t matrixDimention_ = dataPort_.getAllCellsAmount(); pSleSolver_->createContainers(matrixDimention_); } void SleMatrixBuilder::saveCoeff(size_t pos, double value, std::vector<double>& coeff) { if (0 < pos) { coeff.at(pos - 1) = value; } } }
33.491667
91
0.631003
388a992f5d6f1c6238d88b46aadb29834f2e2e23
1,595
php
PHP
app/controllers/ServicesController.php
cmink-alone/hotel_laravel
fa2730d52fd8e6a229676ed46e2b212de5d6204c
[ "MIT" ]
null
null
null
app/controllers/ServicesController.php
cmink-alone/hotel_laravel
fa2730d52fd8e6a229676ed46e2b212de5d6204c
[ "MIT" ]
null
null
null
app/controllers/ServicesController.php
cmink-alone/hotel_laravel
fa2730d52fd8e6a229676ed46e2b212de5d6204c
[ "MIT" ]
null
null
null
<?php class ServicesController extends Controller{ public function getIndex(){ $key = Input::get('search'); if(isset($key)){ $data = Services::where('name', 'like', '%'.$key.'%')->orderBy('id', 'desc')->paginate(10); }else{ $data = Services::orderBy('id', 'desc')->paginate(10); } return View::make('home/dashboard',array())->nest('content', 'services/index',array('data'=>$data)); } public function getAdd(){ return View::make('home/dashboard',array())->nest('content', 'services/add',array()); } public function getSave(){ $id = Input::get('id'); if($id){ $services = Services::find($id); $services->name = Input::get('name'); $services->price = Input::get('price'); $services->save(); Session::flash('message', 'The records are updated successfully'); }else{ $services = new Services; $services->name = Input::get('name'); $services->price = Input::get('price'); $services->save(); Session::flash('message', 'The records are inserted successfully'); } return Redirect::to('services'); } public function getShow($id){ $data = Services::find($id); return View::make('home/dashboard',array())->nest('content', 'services/show',array('data'=>$data)); } public function getEdit($id){ $data = Services::find($id); return View::make('home/dashboard',array())->nest('content', 'services/edit',array('data'=>$data)); } public function getDelete($id){ $services = Services::find($id); $services->delete(); Session::flash('message', 'The records are deleted successfully'); return Redirect::to('services'); } }
29.537037
102
0.637618
dc9e25552350d68169c1b3cba40f5ee8d96fa332
4,327
tsx
TypeScript
src/overlays/Tooltip/index.tsx
x86chi/class101-ui
f9f0000372a176d1254e2467ea38445a6a60bca4
[ "MIT" ]
1
2021-06-12T08:22:14.000Z
2021-06-12T08:22:14.000Z
src/overlays/Tooltip/index.tsx
SoonGwan/class101-ui
197bfd2fed275850b1a814510183b826d4aed803
[ "MIT" ]
null
null
null
src/overlays/Tooltip/index.tsx
SoonGwan/class101-ui
197bfd2fed275850b1a814510183b826d4aed803
[ "MIT" ]
null
null
null
import React, { useCallback, useEffect, useState } from 'react'; import { Manager, Popper, Reference } from 'react-popper'; import styled from 'styled-components'; import { Position } from '../../core'; import { elevation2 } from '../../core/ElevationStyles'; import { body2, caption1 } from '../../core/TextStyles'; import { isClient } from '../../utils'; import { Portal } from '../Portal'; import { tooltipBackgroundColors, TooltipColor, tooltipColors } from './colors'; import { adjustPositionWithTooltip } from './utils'; interface Props { position?: Position; content: React.ReactNode; contentTitle?: string; color?: TooltipColor; children: string | JSX.Element; wrapperTagName?: string; wrapperStyle?: React.CSSProperties; targetStyle?: React.CSSProperties; fill?: boolean; isOpen?: boolean; } export const Tooltip: React.FC<Props> = React.memo(props => { const { position = Position.BOTTOM, content, contentTitle, wrapperStyle, color = TooltipColor.DEFAULT, children, targetStyle, wrapperTagName = 'span', fill, ...restProps } = props; const [opened, setOpened] = useState(props.isOpen ?? false); const handleMouseEnter = useCallback(() => { if (!opened) { setOpened(true); } }, [opened, setOpened]); const handleMouseLeave = useCallback(() => { if (opened) { setOpened(false); } }, [opened, setOpened]); useEffect(() => { if (props.isOpen !== undefined && props.isOpen !== null) { setOpened(props.isOpen); } }, [setOpened, props.isOpen]); const renderChild = useCallback( (ref: React.Ref<any>) => { const childProps = { ref, style: { display: fill ? 'flex' : 'inline-flex', ...(wrapperStyle || {}) }, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, ...restProps, }; return React.createElement(wrapperTagName, childProps, children); }, [children, wrapperTagName, handleMouseEnter, handleMouseLeave, wrapperStyle, fill, restProps] ); if (!isClient()) { return null; } return ( <Manager> <Reference>{({ ref }) => renderChild(ref)}</Reference> <Portal container={document.body}> <Popper placement={adjustPositionWithTooltip(position)} modifiers={{ preventOverflow: { boundariesElement: 'viewport', }, }} > {({ ref, style, placement }) => ( <PopoverTarget isVisible={opened} ref={ref} style={{ ...style, ...(targetStyle || {}) }}> <PopoverContent tooltipColor={color} data-placement={placement}> {contentTitle && <PopoverTitle>{contentTitle}</PopoverTitle>} {content} </PopoverContent> <PopperArrow data-placement={placement} tooltipColor={color} /> </PopoverTarget> )} </Popper> </Portal> </Manager> ); }); export { TooltipColor }; const ArrowSVG = (props: { tooltipColor: TooltipColor; className?: string }) => ( <svg viewBox="7 10 10 5" width="16px" {...props}> <path fill={tooltipBackgroundColors[props.tooltipColor]} fillRule="evenodd" d="M17 10l-5 5-5-5z" /> </svg> ); const PopperArrow = styled(ArrowSVG)` position: absolute; &[data-placement*='bottom'] { top: 0; left: calc(50% - 8px); transform: rotate(180deg); } &[data-placement*='top'] { left: calc(50% - 8px); bottom: 0; } &[data-placement*='right'] { left: -4px; top: calc(50% - 4px); transform: rotate(90deg); } &[data-placement*='left'] { right: -4px; top: calc(50% - 4px); transform: rotate(270deg); } `; const PopoverTitle = styled.h2` ${body2}; color: inherit; font-weight: bold; margin-bottom: 2px; `; const PopoverTarget = styled.div<{ isVisible: boolean }>` opacity: ${props => (props.isVisible ? 1 : 0)}; visibility: ${props => (props.isVisible ? 'visible' : 'hidden')}; transition: opacity 200ms; `; const PopoverContent = styled.div<{ tooltipColor: TooltipColor }>` ${caption1}; margin: 8px; padding: 12px; border-radius: 3px; color: ${props => tooltipColors[props.tooltipColor]}; background-color: ${props => tooltipBackgroundColors[props.tooltipColor]}; ${elevation2}; `;
27.04375
103
0.611971
c6e554445c46e29341e6d17871cb18be25f8820e
2,328
rb
Ruby
app/controllers/payment_providers_controller.rb
paviliondev/invoices
13000ea3203ee2fdf97fbdba586d1f623d860389
[ "MIT" ]
null
null
null
app/controllers/payment_providers_controller.rb
paviliondev/invoices
13000ea3203ee2fdf97fbdba586d1f623d860389
[ "MIT" ]
null
null
null
app/controllers/payment_providers_controller.rb
paviliondev/invoices
13000ea3203ee2fdf97fbdba586d1f623d860389
[ "MIT" ]
null
null
null
class PaymentProvidersController < ApplicationController before_action :set_payment_provider, only: [:show, :edit, :update, :destroy] before_action :ensure_member # GET /payment_providers # GET /payment_providers.json def index @payment_providers = PaymentProvider.all end # GET /payment_providers/1 # GET /payment_providers/1.json def show end # GET /payment_providers/new def new @payment_provider = PaymentProvider.new end # GET /payment_providers/1/edit def edit end # POST /payment_providers # POST /payment_providers.json def create @payment_provider = PaymentProvider.new(payment_provider_params) respond_to do |format| if @payment_provider.save format.html { redirect_to settings_payments_path, notice: 'Payment provider was successfully created.' } format.json { render :show, status: :created, location: @payment_provider } else format.html { render :new } format.json { render json: @payment_provider.errors, status: :unprocessable_entity } end end end # PATCH/PUT /payment_providers/1 # PATCH/PUT /payment_providers/1.json def update respond_to do |format| if @payment_provider.update(payment_provider_params) format.html { redirect_to settings_payments_path, notice: 'Payment provider was successfully updated.' } format.json { render :show, status: :ok, location: @payment_provider } else format.html { render :edit } format.json { render json: @payment_provider.errors, status: :unprocessable_entity } end end end # DELETE /payment_providers/1 # DELETE /payment_providers/1.json def destroy @payment_provider.destroy respond_to do |format| format.html { redirect_to settings_payments_path, notice: 'Payment provider was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_payment_provider @payment_provider = PaymentProvider.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def payment_provider_params params.require(:payment_provider).permit(:label, :connected, :provider_type, :api_key) end end
30.631579
112
0.717354
38a3d61b354cbc17436d88dc084862570ba48739
2,548
php
PHP
App/Controllers/MethodCat.php
mprzybycien/wallet-mvc
9801155c7e9b875b043dbecca1a8a60e40cd5069
[ "MIT" ]
null
null
null
App/Controllers/MethodCat.php
mprzybycien/wallet-mvc
9801155c7e9b875b043dbecca1a8a60e40cd5069
[ "MIT" ]
null
null
null
App/Controllers/MethodCat.php
mprzybycien/wallet-mvc
9801155c7e9b875b043dbecca1a8a60e40cd5069
[ "MIT" ]
null
null
null
<?php namespace App\Controllers; use \Core\View; use \App\Auth; use \App\Flash; use \App\Models\User; use \App\Models\IncomeModel; use \App\Models\MethodCatModel; /** * Profile controller * * PHP version 7.0 */ class MethodCat extends Authenticated { protected function before() { parent::before(); $this->user = Auth::getUser(); } public function newAction() { View::renderTemplate('MethodCat/new.html'); } public function createAction() { $methodCatModel = new MethodCatModel($_POST); if ($methodCatModel->save()) { Flash::addMessage('New payment method category added'); $this->redirect('/MethodCat/show'); } else { Flash::addMessage('New payment method category has not been added', Flash::WARNING); View::renderTemplate('MethodCat/new.html',['methodCatModel' => $methodCatModel ]); } } public function showAction() { $arg['methods'] = MethodCatModel::getMethodCategories(); View::renderTemplate('MethodCat/show.html', $arg); } public function editAction() { $methodCatModel = new MethodCatModel($_POST); $_SESSION['current_category'] = $methodCatModel->findByID($_POST['catId']); $arg['cat'] = $_SESSION['current_category']; View::renderTemplate('MethodCat/edit.html', $arg); } public function editedAction() { $methodCatModel = new MethodCatModel($_POST); if ($methodCatModel->edit()) { Flash::addMessage('Payment method category name changed'); $this->redirect('/MethodCat/show'); } else { Flash::addMessage('Payment method category has not been changed', Flash::WARNING); $arg['methodCatModel'] = $methodCatModel; $arg['cat'] = $_SESSION['current_category']; View::renderTemplate('MethodCat/edit.html', $arg); } } public function deleteAction() { $methodCatModel = new MethodCatModel($_POST); if ($methodCatModel->delete()) { Flash::addMessage('Payment method with all associated records deleted'); $this->redirect('/MethodCat/show'); } else { Flash::addMessage('Payment method category has not been deleted', Flash::WARNING); $arg['methods'] = MethodCatModel::getMethodCategories(); View::renderTemplate('MethodCat/show.html', $arg); } } }
28.311111
96
0.592229
d7f4bc81bd088b706996e410126117d3fbd63ecc
2,317
rb
Ruby
lib/ins_n_outs/comment_parser.rb
JessicaGillan/ins_n_outs
92f2ab58e99428091def1244ea7914b006761312
[ "MIT" ]
null
null
null
lib/ins_n_outs/comment_parser.rb
JessicaGillan/ins_n_outs
92f2ab58e99428091def1244ea7914b006761312
[ "MIT" ]
null
null
null
lib/ins_n_outs/comment_parser.rb
JessicaGillan/ins_n_outs
92f2ab58e99428091def1244ea7914b006761312
[ "MIT" ]
null
null
null
MethodData = Struct.new(:container, :name, :input_types, :output_types) class CommentParser REGEX = { token: /#\s*DELIMITER:\s*(\S+)/, ins: /ins:\s*(.+),|ins:\s*(.+)outs:|ins:\s*(.+)/, outs: /outs:\s*(.+),|outs:\s*(.+)ins:|outs:\s*(.+)/, container: /class\s+(\w+)|module\s+(\w+)/ } def initialize @method_data_factory = MethodData end def parse_method_data(lines) @token = set_token(lines) @container = find_container(lines) populate_token_regex(token) specifications = find_methods(lines) populate_method_data(specifications) end private attr_reader :token, :tkn_regex, :container # Will find the FIRST delimter set w/: DELIMITER: # And set the delimiter token to any non-whitespace characters following it def set_token(lines) match = nil lines.find_index { |line| match = line.match(REGEX[:token]) } raise "No Delimiter Token Set" if match.nil? match.captures[0] end def find_container(lines) i = lines.find_index do |line| line.match(REGEX[:container]) end i.nil? ? nil : find_match(lines[i], REGEX[:container]) end def find_methods(lines) lines.select do |line| line.match(tkn_regex[:methods]) end end # ** my_test, ins: String, outs: Bool def populate_method_data(specifications) specifications.map do |spec| method_data = @method_data_factory.new method_data.container = container method_data.name = find_match(spec, tkn_regex[:name])[0] method_data.input_types = separate_types( find_match(spec, REGEX[:ins]) ) method_data.output_types = separate_types( find_match(spec, REGEX[:outs]) ) method_data end end def find_match(spec, match_exp) match = spec.match(match_exp) match.nil? ? nil : match.captures.select { |group| !group.nil? } end def separate_types(types) types.map do |group| group.split(" ") end.flatten end def populate_token_regex(token) @tkn_regex = { methods: /#\s*#{Regexp.quote(token)}\s*/, name: /#\s*#{Regexp.quote(token)}\s*(\w+)/ } end end
27.583333
84
0.594303
72f82db841740b05bf98989e6e570ccc66d78047
4,159
cs
C#
Public/Src/Cache/ContentStore/Distributed/Services/ServicesCreatorBase.cs
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
null
null
null
Public/Src/Cache/ContentStore/Distributed/Services/ServicesCreatorBase.cs
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
null
null
null
Public/Src/Cache/ContentStore/Distributed/Services/ServicesCreatorBase.cs
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; #nullable enable namespace BuildXL.Cache.ContentStore.Distributed.Services { /// <summary> /// Base helper class for service creation. /// </summary> public class ServicesCreatorBase { /// <summary> /// Creates a service which specifies a condition gating its availability /// </summary> public OptionalServiceDefinition<T> CreateOptional<T>(Func<bool> isAvailable, Func<T> createService) { return new OptionalServiceDefinition<T>(new ServiceDefinition<T>(isAvailable, createService)); } /// <summary> /// Creates a service definition /// </summary> public IServiceDefinition<T> Create<T>(Func<T> createService) { return new ServiceDefinition<T>(() => true, createService); } } /// <summary> /// Defines a service instantiation /// </summary> public interface IServiceDefinition<out T> { /// <summary> /// Checks if the service is available /// </summary> bool IsAvailable { get; } /// <summary> /// Gets the singleton instance of the service /// </summary> T Instance { get; } } /// <summary> /// Defines a service instantiation /// </summary> public class ServiceDefinition<T> : IServiceDefinition<T> { /// <inheritdoc /> public bool IsAvailable => _isAvailable.Value; /// <inheritdoc /> public T Instance => IsAvailable ? _instance.Value : throw new Exception("Service not available"); private readonly Lazy<T> _instance; private readonly Lazy<bool> _isAvailable; /// <nodoc /> public ServiceDefinition(Func<bool> isAvailable, Func<T> createService) { _instance = new(createService); _isAvailable = new(isAvailable); } } /// <summary> /// Wraps service so that checking availability of service is required to get instance /// </summary> public struct OptionalServiceDefinition<T> { private readonly IServiceDefinition<T>? _serviceDefinition; public OptionalServiceDefinition(IServiceDefinition<T> serviceDefinition) { _serviceDefinition = serviceDefinition; } /// <summary> /// Gets the underlying service definition. /// </summary> internal IServiceDefinition<T> UnsafeGetServiceDefinition() => _serviceDefinition!; /// <summary> /// Gets the instance throwing if it is not available. /// </summary> public T GetRequiredInstance() => InstanceOrDefault() ?? throw new Exception("Service not available"); /// <summary> /// Attempts to get instance of service if it is available /// </summary> public bool TryGetInstance([NotNullWhen(true)] out T? instance) { if (_serviceDefinition?.IsAvailable == true) { instance = _serviceDefinition.Instance!; return true; } else { instance = default; return false; } } /// <summary> /// Attempts to get instance of service if it is available /// </summary> public T? InstanceOrDefault() { return TryGetInstance(out var instance) ? instance : default; } } /// <nodoc /> public static class ServiceDefinitionExtensions { /// <summary> /// Wraps service so that checking availability of service is required to get instance /// </summary> public static OptionalServiceDefinition<T> AsOptional<T>(this IServiceDefinition<T> serviceDefinition) { return new OptionalServiceDefinition<T>(serviceDefinition); } } }
31.992308
111
0.577062
1b4534915ccd8b625d42e8bbcc64951f114d46cb
283
rb
Ruby
2020/ruby/day-2-password-philosophy/part_one.rb
hailelagi/advent-of-code
bd3c696c700a7f12616a1c7c8e29ce5e17ba01af
[ "MIT" ]
null
null
null
2020/ruby/day-2-password-philosophy/part_one.rb
hailelagi/advent-of-code
bd3c696c700a7f12616a1c7c8e29ce5e17ba01af
[ "MIT" ]
null
null
null
2020/ruby/day-2-password-philosophy/part_one.rb
hailelagi/advent-of-code
bd3c696c700a7f12616a1c7c8e29ce5e17ba01af
[ "MIT" ]
null
null
null
passwords_input = File.read('puzzle_input.txt').split(/\n/) valid = 0 for input in passwords_input /(\d+)-(\d+) (\w): (\w+)/.match(input) lowest, highest = $1.to_i, $2.to_i chars = $4.scan(/#{$3}/).size valid += 1 if (chars >= lowest and chars <= highest) end puts valid
20.214286
59
0.611307
9ecf1baddb0dd87293aa3f101e28c840627bc1a4
1,721
lua
Lua
nnname.lua
felixgwu/nnname
e8ba6e15857f460437ad551b7f7ea49428c910d9
[ "MIT" ]
1
2017-02-20T18:07:28.000Z
2017-02-20T18:07:28.000Z
nnname.lua
felixgwu/nnname
e8ba6e15857f460437ad551b7f7ea49428c910d9
[ "MIT" ]
null
null
null
nnname.lua
felixgwu/nnname
e8ba6e15857f460437ad551b7f7ea49428c910d9
[ "MIT" ]
null
null
null
if not nn then require 'nn' end if not dpnn then require 'dpnn' end nnname = { version = 1, } -- find a module by its name function nn.Module:find(name, last) local modules = self:findAll(name) return last and modules[#modules] or modules[1] end -- find all module by its name function nn.Module:findAll(name) local modules = {} for i, m in ipairs(self:listModules()) do if m.name == name then table.insert(modules, m) end end return modules end -- set the name of a module function nn.Module:setName(name) self.name = name return self end -- show name when printing the module for k, v in pairs(nn) do if torch.isTypeOf(v, 'nn.Module') then if v.__tostring__ then local oldtostring = v.__tostring__ v.__tostring__ = function(self) return (self.name and '[' .. self.name .. '] ' or '') .. oldtostring(self) end elseif v.__tostring then local oldtostring = v.__tostring v.__tostring = function(self) return (self.name and '[' .. self.name .. '] ' or '') .. oldtostring(self) end end end end -- dealing with cudnn.torch modules if cudnn then for k, v in pairs(cudnn) do if torch.isTypeOf(v, 'nn.Module') then if v.__tostring then local oldtostring = v.__tostring v.__tostring = function(self) local name = (self.name and '[' .. self.name .. '] ' or '') local old = oldtostring(self) return stringx.startswith(old, name) and old or name .. old end end end end end
27.31746
90
0.568855
cdb53ed8e9b2289d50ab6004ed8b6a9c3809aa3c
6,928
cs
C#
sdk/dotnet/Kusto/V20190121/Enums.cs
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/dotnet/Kusto/V20190121/Enums.cs
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/dotnet/Kusto/V20190121/Enums.cs
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.ComponentModel; using Pulumi; namespace Pulumi.AzureNative.Kusto.V20190121 { /// <summary> /// SKU name. /// </summary> [EnumType] public readonly struct AzureSkuName : IEquatable<AzureSkuName> { private readonly string _value; private AzureSkuName(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static AzureSkuName Standard_DS13_v2_1TB_PS { get; } = new AzureSkuName("Standard_DS13_v2+1TB_PS"); public static AzureSkuName Standard_DS13_v2_2TB_PS { get; } = new AzureSkuName("Standard_DS13_v2+2TB_PS"); public static AzureSkuName Standard_DS14_v2_3TB_PS { get; } = new AzureSkuName("Standard_DS14_v2+3TB_PS"); public static AzureSkuName Standard_DS14_v2_4TB_PS { get; } = new AzureSkuName("Standard_DS14_v2+4TB_PS"); public static AzureSkuName Standard_D13_v2 { get; } = new AzureSkuName("Standard_D13_v2"); public static AzureSkuName Standard_D14_v2 { get; } = new AzureSkuName("Standard_D14_v2"); public static AzureSkuName Standard_L8s { get; } = new AzureSkuName("Standard_L8s"); public static AzureSkuName Standard_L16s { get; } = new AzureSkuName("Standard_L16s"); public static AzureSkuName Standard_D11_v2 { get; } = new AzureSkuName("Standard_D11_v2"); public static AzureSkuName Standard_D12_v2 { get; } = new AzureSkuName("Standard_D12_v2"); public static AzureSkuName Standard_L4s { get; } = new AzureSkuName("Standard_L4s"); public static AzureSkuName Dev_No_SLA_Standard_D11_v2 { get; } = new AzureSkuName("Dev(No SLA)_Standard_D11_v2"); public static bool operator ==(AzureSkuName left, AzureSkuName right) => left.Equals(right); public static bool operator !=(AzureSkuName left, AzureSkuName right) => !left.Equals(right); public static explicit operator string(AzureSkuName value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is AzureSkuName other && Equals(other); public bool Equals(AzureSkuName other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// SKU tier. /// </summary> [EnumType] public readonly struct AzureSkuTier : IEquatable<AzureSkuTier> { private readonly string _value; private AzureSkuTier(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static AzureSkuTier Basic { get; } = new AzureSkuTier("Basic"); public static AzureSkuTier Standard { get; } = new AzureSkuTier("Standard"); public static bool operator ==(AzureSkuTier left, AzureSkuTier right) => left.Equals(right); public static bool operator !=(AzureSkuTier left, AzureSkuTier right) => !left.Equals(right); public static explicit operator string(AzureSkuTier value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is AzureSkuTier other && Equals(other); public bool Equals(AzureSkuTier other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The data format of the message. Optionally the data format can be added to each message. /// </summary> [EnumType] public readonly struct DataFormat : IEquatable<DataFormat> { private readonly string _value; private DataFormat(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static DataFormat MULTIJSON { get; } = new DataFormat("MULTIJSON"); public static DataFormat JSON { get; } = new DataFormat("JSON"); public static DataFormat CSV { get; } = new DataFormat("CSV"); public static DataFormat TSV { get; } = new DataFormat("TSV"); public static DataFormat SCSV { get; } = new DataFormat("SCSV"); public static DataFormat SOHSV { get; } = new DataFormat("SOHSV"); public static DataFormat PSV { get; } = new DataFormat("PSV"); public static DataFormat TXT { get; } = new DataFormat("TXT"); public static DataFormat RAW { get; } = new DataFormat("RAW"); public static DataFormat SINGLEJSON { get; } = new DataFormat("SINGLEJSON"); public static DataFormat AVRO { get; } = new DataFormat("AVRO"); public static bool operator ==(DataFormat left, DataFormat right) => left.Equals(right); public static bool operator !=(DataFormat left, DataFormat right) => !left.Equals(right); public static explicit operator string(DataFormat value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is DataFormat other && Equals(other); public bool Equals(DataFormat other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// Kind of the endpoint for the data connection /// </summary> [EnumType] public readonly struct Kind : IEquatable<Kind> { private readonly string _value; private Kind(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static Kind EventHub { get; } = new Kind("EventHub"); public static Kind EventGrid { get; } = new Kind("EventGrid"); public static bool operator ==(Kind left, Kind right) => left.Equals(right); public static bool operator !=(Kind left, Kind right) => !left.Equals(right); public static explicit operator string(Kind value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is Kind other && Equals(other); public bool Equals(Kind other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
45.281046
121
0.672921
ba62a17da0831144b0505a398cc415a59ebec190
291
sh
Shell
luas_wa_bridesglen.sh
vfonic/RgbMatrixLuas
8fb52b1b3232d92c68bfe924c6a0fb46a70ca554
[ "MIT" ]
null
null
null
luas_wa_bridesglen.sh
vfonic/RgbMatrixLuas
8fb52b1b3232d92c68bfe924c6a0fb46a70ca554
[ "MIT" ]
null
null
null
luas_wa_bridesglen.sh
vfonic/RgbMatrixLuas
8fb52b1b3232d92c68bfe924c6a0fb46a70ca554
[ "MIT" ]
null
null
null
#!/bin/bash # curl --silent "http://www.luas.ie/luaspid.html?get=Windy%20Arbour" \ cat /home/pi/scripts/luas_times.html \ | grep Brides | sed -E 's#[^B]+Brides Glen</div><div class="time">([0-9]+|DUE)([^B]+Brides Glen</div><div class="time">([0-9]+|DUE))?.*#\1 \3#' \ | sed -E 's/^ *| *$//'
48.5
145
0.587629
8d9ad66141d7593b7ea26ca013e607a134307b85
299
js
JavaScript
pages-redux-ok/index.js
Rakeshshinedezign/Testimonial
26361bd165af5053162ae76910970eefe7ea6060
[ "MIT" ]
null
null
null
pages-redux-ok/index.js
Rakeshshinedezign/Testimonial
26361bd165af5053162ae76910970eefe7ea6060
[ "MIT" ]
null
null
null
pages-redux-ok/index.js
Rakeshshinedezign/Testimonial
26361bd165af5053162ae76910970eefe7ea6060
[ "MIT" ]
null
null
null
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import App from './redux/App.js'; import store from './redux/store.js'; const Index = () => ( <div> <Provider store={store}> <App /> </Provider> </div> ); export default Index;
17.588235
39
0.625418
79deeff9da225bcf3da28a8554ead0c9277dc2b7
1,465
php
PHP
tests/UnFreezeAccountTest.php
supine-win/adapay
028f392bf08a22344455dfc238f221a250eca97b
[ "MIT" ]
2
2021-09-05T14:56:18.000Z
2022-02-12T07:57:56.000Z
tests/UnFreezeAccountTest.php
supine-win/adapay
028f392bf08a22344455dfc238f221a250eca97b
[ "MIT" ]
null
null
null
tests/UnFreezeAccountTest.php
supine-win/adapay
028f392bf08a22344455dfc238f221a250eca97b
[ "MIT" ]
null
null
null
<?php use PHPUnit\Framework\TestCase; class UnFreezeAccountTest extends TestCase { public function testCreate() { SupineWin\Adapay\AdapayCore\AdaPay::$gateWayType = 'api'; # 初始化解冻账户对象类 $obj = new \SupineWin\Adapay\AdapaySdk\UnFreezeAccount(); $un_fz_params = array( 'app_id'=> 'app_7d87c043-aae3-4357-9b2c-269349a980d6', 'order_no'=> 'FZ_'. date("YmdHis").rand(100000, 999999), 'account_freeze_id'=> '002112020111717230410174704123849117696' ); # 创建解冻账户 $obj->create($un_fz_params); print("创建解冻支付对象".$obj->isError().'=>'.json_encode($obj->result)."\n"); $this->assertTrue($obj->isError()); } public function testList() { SupineWin\Adapay\AdapayCore\AdaPay::$gateWayType = 'api'; # 初始化解冻账户对象类 $obj = new \SupineWin\Adapay\AdapaySdk\FreezeAccount(); $un_fz_params = array( 'app_id'=> 'app_7d87c043-aae3-4357-9b2c-269349a980d6', 'order_no'=> 'FZ_'. date("YmdHis").rand(100000, 999999), 'status'=> 'succeeded', //succeeded-成功,failed-失败,pending-处理中 'page_index'=> 1, 'page_size'=> 1, 'created_gte'=> '', 'created_lte'=> '' ); # 查询解冻账户 $obj->queryList($un_fz_params); print("创建解冻支付对象".$obj->isError().'=>'.json_encode($obj->result)."\n"); $this->assertTrue($obj->isError()); } }
1,465
1,465
0.574061
06faa994d32ecf945ca2ab1aed8e72b2c0d2fc89
1,188
py
Python
python/factualaudio/plot.py
factualaudio/factualaudio
8b9b824e98710470d9d09931688277f667b85a6e
[ "CC-BY-4.0" ]
4
2017-11-20T21:25:24.000Z
2019-12-13T06:52:51.000Z
python/factualaudio/plot.py
factualaudio/factualaudio
8b9b824e98710470d9d09931688277f667b85a6e
[ "CC-BY-4.0" ]
null
null
null
python/factualaudio/plot.py
factualaudio/factualaudio
8b9b824e98710470d9d09931688277f667b85a6e
[ "CC-BY-4.0" ]
null
null
null
from factualaudio.data import noise from factualaudio.decibel import to_decibels import numpy as np def waveform(axes, wave, sample_rate, *args, **kwargs): return axes.plot(np.arange(0, wave.size) * (1000 / sample_rate), wave, *args, **kwargs) # Equivalent to axes.amplitude_spectrum(), but plots on an RMS amplitude scale. # (i.e. an input sine wave of RMS amplitude X will show up as X on the plot) def rms_amplitude_spectrum(axes, wave, noise_level=1e-14, *args, **kwargs): kwargs.setdefault("window", np.ones(wave.size)) kwargs.setdefault("scale", "dB") # Add some noise to avoid numerical issues when converting to dB wave += noise(wave.size) * noise_level return axes.magnitude_spectrum(wave * np.sqrt(2), *args, **kwargs) def transfer_function_gain(axes, transfer_function, corner_frequency=1000): x = np.linspace(0, 20000, num=1000) return axes.semilogx(x, to_decibels(np.absolute(transfer_function(x * (1j / corner_frequency))))) def transfer_function_phase(axes, transfer_function, corner_frequency=1000): x = np.linspace(0, 20000, num=1000) return axes.semilogx(x, np.angle(transfer_function(x * (1j / corner_frequency)), deg=True))
49.5
101
0.736532
d652617e6c218d1189663fcdfcca2d5d02981729
3,098
cs
C#
SharpRemote.Test/CodeGeneration/Serialization/BinarySerializerTest.cs
StefanSturm87/SharpRemote
74e83a34b96a9f5c76d1db8cf975a97d38f62f38
[ "MIT" ]
11
2015-05-13T17:32:26.000Z
2021-11-18T23:08:06.000Z
SharpRemote.Test/CodeGeneration/Serialization/BinarySerializerTest.cs
StefanSturm87/SharpRemote
74e83a34b96a9f5c76d1db8cf975a97d38f62f38
[ "MIT" ]
72
2015-08-13T17:57:56.000Z
2021-05-21T09:51:31.000Z
SharpRemote.Test/CodeGeneration/Serialization/BinarySerializerTest.cs
StefanSturm87/SharpRemote
74e83a34b96a9f5c76d1db8cf975a97d38f62f38
[ "MIT" ]
5
2018-05-11T08:49:18.000Z
2022-02-03T10:34:08.000Z
using System; using FluentAssertions; using Moq; using NUnit.Framework; using SharpRemote.Test.Types.Classes; using SharpRemote.Test.Types.Interfaces; namespace SharpRemote.Test.CodeGeneration.Serialization { [TestFixture] public sealed class BinarySerializerTest { [Test] [Description("Verifies that the caching-mechanism for RegisterType works and returns the same serialization methods for [ByReference] types")] public void TestRegisterType1() { var serializer = new BinarySerializer(); BinarySerializer.SerializationMethods methods; serializer.RegisterType<IByReferenceType>(out methods); methods.Should().NotBeNull(); BinarySerializer.SerializationMethods methods2; serializer.RegisterType<ByReferenceClass>(out methods2); methods2.Should().BeSameAs(methods); } [Test] [Description("Verifies that the caching-mechanism for RegisterType works and returns the same serialization methods for typeof(Type) and typeof(Type).GetType()")] public void TestRegisterType2() { var serializer = new BinarySerializer(); BinarySerializer.SerializationMethods methods; serializer.RegisterType<Type>(out methods); methods.Should().NotBeNull(); BinarySerializer.SerializationMethods methods2; serializer.RegisterType(typeof(Type).GetType(), out methods2); methods2.Should().BeSameAs(methods); } [Test] [Description("Verifies that ReadObject throws a TypeLoadException when the type resolver returns null")] public void TestReadObject1() { var resolver = new Mock<ITypeResolver>(); resolver.Setup(x => x.GetType(It.IsAny<string>())).Returns((Type) null); var serializer = new BinarySerializer(resolver.Object); new Action(() => serializer.Roundtrip("Foobar")) .Should().Throw<TypeLoadException>() .WithMessage(string.Format("Unable to load '{0}': The type resolver returned null", typeof(string).AssemblyQualifiedName)); } [Test] [Description("Verifies that ReadObject throws a TypeLoadException when the type resolver throws another exception")] public void TestReadObject2() { var resolver = new Mock<ITypeResolver>(); resolver.Setup(x => x.GetType(It.IsAny<string>())).Throws<InvalidOperationException>(); var serializer = new BinarySerializer(resolver.Object); new Action(() => serializer.Roundtrip("Foobar")) .Should().Throw<TypeLoadException>() .WithMessage(string.Format("Unable to load '{0}': The type resolver threw an exception while resolving the type", typeof(string).AssemblyQualifiedName)) .WithInnerException<InvalidOperationException>(); } [Test] [Description("Verifies that ReadObject throws a TypeLoadException when the type resolver throws another exception")] public void TestReadObject3() { var resolver = new Mock<ITypeResolver>(); resolver.Setup(x => x.GetType(It.IsAny<string>())).Throws<TypeLoadException>(); var serializer = new BinarySerializer(resolver.Object); new Action(() => serializer.Roundtrip("Foobar")) .Should().Throw<TypeLoadException>(); } } }
38.246914
164
0.736281
05b007a00217d2af68bbaa5fe4304dbc30f869b4
2,685
py
Python
openGaussBase/testcase/KEYWORDS/password/Opengauss_Function_Keyword_Password_Case0020.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/password/Opengauss_Function_Keyword_Password_Case0020.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/password/Opengauss_Function_Keyword_Password_Case0020.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ ''' #-- @testpoint:opengauss关键字password(非保留),作为目录对象名 ''' import unittest from testcase.utils.Logger import Logger from testcase.utils.Constant import Constant from testcase.utils.CommonSH import CommonSH logger = Logger() commonsh = CommonSH('dbuser') constant = Constant() class Hostname(unittest.TestCase): def setUp(self): logger.info("------------------------ Opengauss_Function_Keyword_Password_Case0020 开始执行--------------------------") # 关键字作为目录对象名不带双引号 - 成功 def test_password_1(self): SqlMdg = commonsh.execut_db_sql('''create directory password as '/tmp/'; drop directory password;''') logger.info(SqlMdg) self.assertIn(constant.CREATE_DIRECTORY_SUCCESS_MSG, SqlMdg) self.assertIn(constant.DROP_DIRECTORY_SUCCESS_MSG, SqlMdg) # 关键字作为目录对象名带双引号—成功 def test_password_2(self): SqlMdg = commonsh.execut_db_sql('''create directory "password" as '/tmp/'; drop directory "password";''') logger.info(SqlMdg) self.assertIn(constant.CREATE_DIRECTORY_SUCCESS_MSG, SqlMdg) self.assertIn(constant.DROP_DIRECTORY_SUCCESS_MSG, SqlMdg) # 关键字作为目录对象名带单引号 - 合理报错 def test_password_3(self): SqlMdg = commonsh.execut_db_sql('''drop directory if exists 'password';''') logger.info(SqlMdg) self.assertIn(constant.SYNTAX_ERROR_MSG, SqlMdg) SqlMdg = commonsh.execut_db_sql(''' create directory 'password' as '/tmp/';''') logger.info(SqlMdg) self.assertIn(constant.SYNTAX_ERROR_MSG, SqlMdg) #关键字作为目录对象名带反引号 - 合理报错 def test_password_4(self): SqlMdg = commonsh.execut_db_sql('''drop directory if exists \`password\`;''') logger.info(SqlMdg) self.assertIn(constant.SYNTAX_ERROR_MSG, SqlMdg) SqlMdg = commonsh.execut_db_sql('''create directory \`password\` as '/tmp/';''') logger.info(SqlMdg) self.assertIn(constant.SYNTAX_ERROR_MSG, SqlMdg) def tearDown(self): logger.info('------------------------ Opengauss_Function_Keyword_Password_Case0020 执行结束--------------------------')
36.283784
124
0.665922
b78f0a6dcf3abebb29e73f7a85a2c8747404b0fb
345
kt
Kotlin
src/_04interfaces/main.kt
Ladicek/kotlin-talk-examples
9a89e01f88dd8b0170fe92200acd7b66bb63f3d2
[ "Apache-2.0" ]
null
null
null
src/_04interfaces/main.kt
Ladicek/kotlin-talk-examples
9a89e01f88dd8b0170fe92200acd7b66bb63f3d2
[ "Apache-2.0" ]
null
null
null
src/_04interfaces/main.kt
Ladicek/kotlin-talk-examples
9a89e01f88dd8b0170fe92200acd7b66bb63f3d2
[ "Apache-2.0" ]
null
null
null
package _04interfaces interface Foo { fun foo(): String } interface Bar { fun bar(): String { return "bar" } } interface Baz { fun baz() = "baz" } class Fubar : Foo, Bar, Baz { override fun foo() = "foo" fun fubar() { println("${foo()}-${bar()}-${baz()}") } } fun main() { Fubar().fubar() }
12.321429
45
0.507246
72f9d063b467118a471116df2ce2e8696d38b960
11,276
cs
C#
src/HttpBuilder/Request/RequestHandlerExtentionMethods.cs
elamaunt/HttpBuilder
b9b4ebeb3ab0333ff3acdf201bb147514869ac7e
[ "MIT" ]
1
2021-08-06T22:38:34.000Z
2021-08-06T22:38:34.000Z
src/HttpBuilder/Request/RequestHandlerExtentionMethods.cs
elamaunt/HttpBuilder
b9b4ebeb3ab0333ff3acdf201bb147514869ac7e
[ "MIT" ]
null
null
null
src/HttpBuilder/Request/RequestHandlerExtentionMethods.cs
elamaunt/HttpBuilder
b9b4ebeb3ab0333ff3acdf201bb147514869ac7e
[ "MIT" ]
null
null
null
using System; using System.Collections; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace HttpBuilder { /// <summary> /// Delegate type for handling file upload progress /// </summary> public delegate void ProgressHandler(long totalBytes, long readedBytes, float percentage); public static class RequestHandlerExtentionMethods { /// <summary> /// Adds validation of the Http request result for code 200. If the code is different, an exception will be thrown /// </summary> /// <param name="self">Reference to the current handler</param> /// <returns>Returns the transformed query result handler</returns> public static RequestHandler<HttpResponseMessage> ValidateSuccessStatusCode(this RequestHandler<HttpResponseMessage> self) { return self.Validate(res => { try { res.EnsureSuccessStatusCode(); } catch (HttpRequestException ex) { throw new HttpException(self.Observer.BuildHttpExceptionMessage(self.Builder, res, ex), self.Builder, res, ex); } }); } /// <summary> /// Creates a result handler with intermediate conversion of the request to Json /// </summary> /// <typeparam name="B">Required type</typeparam> /// <param name="self">Reference to the current request handler</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<B> Json<B>(this RequestHandler<string> self) { return self.Continue(JsonConvert.DeserializeObject<B>); } /// <summary> /// Creates a result handler with intermediate conversion of the request result to Json /// </summary> /// <typeparam name="B">Required type</typeparam> /// <param name="self">Reference to the current request handler</param> /// <param name="serializer">Setting up serialization</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<B> Json<B>(this RequestHandler<HttpResponseMessage> self, JsonSerializer serializer) { return self.Continue(mes => mes.Content.ReadAsStreamAsync()) .Continue(stream => { using (var sr = new StreamReader(stream)) { using (var jsonTextReader = new JsonTextReader(sr)) { return serializer.Deserialize<B>(jsonTextReader); } } }); } /// <summary> /// Creates a result handler with intermediate content extraction from the response message /// </summary> /// <param name="self">Reference to the current request handler</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<HttpContent> Content(this RequestHandler<HttpResponseMessage> self) { return self.Continue(mes => mes.Content); } /// <summary> /// Creates a result handler with intermediate content extraction as a string from the response message /// </summary> /// <param name="self">Reference to the current request handler</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<string> String(this RequestHandler<HttpContent> self) { return self.Continue(content => content.ReadAsStringAsync()); } /// <summary> /// Creates a result handler with intermediate content extraction as a data stream from the response message /// </summary> /// <param name="self">Reference to the current request handler</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<Stream> Stream(this RequestHandler<HttpContent> self) { return self.Continue(content => content.ReadAsStreamAsync()); } /// <summary> /// Creates a result handler with intermediate content extraction as an array of bytes from the response message /// </summary> /// <param name="self">Reference to the current request handler</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<byte[]> ByteArray(this RequestHandler<HttpContent> self) { return self.Continue(content => content.ReadAsByteArrayAsync()); } /// <summary> /// Creates a result handler that will intermediate load the request content into the specified data stream. /// Allows you to track the download of a file. /// </summary> /// <param name="self">Reference to the current request handler</param> /// <param name="token">Cancellation token</param> /// <param name="destinationStream">Target stream to save the content file</param> /// <param name="bufferSize">Buffer size when loading</param> /// <param name="handler">Delegate - Load Handler</param> /// <param name="readsOfOneUpdate">Content stream reads before invoking the update delegate</param> /// <returns>Returns the transformed requests result handler</returns> public static RequestHandler<Stream> ProcessLoading(this RequestHandler<HttpContent> self, CancellationToken token, Stream destinationStream, long bufferSize, ProgressHandler handler, int readsOfOneUpdate = 100) { return self.Continue(async content => { token.ThrowIfCancellationRequested(); var stream = await content.ReadAsStreamAsync(); var totalDownloadSize = content.Headers.ContentLength; var totalBytesRead = 0L; var readCount = 0L; var buffer = new byte[bufferSize]; var isMoreToRead = true; do { token.ThrowIfCancellationRequested(); var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) { isMoreToRead = false; handler(totalDownloadSize.GetValueOrDefault(), totalBytesRead, 1f); continue; } await destinationStream.WriteAsync(buffer, 0, bytesRead); totalBytesRead += bytesRead; readCount += 1; if (readCount % readsOfOneUpdate == 0) { var sizeValue = totalDownloadSize.GetValueOrDefault(); if (sizeValue == 0) handler(sizeValue, totalBytesRead, 0f); else handler(sizeValue, totalBytesRead, (float)Math.Round((double)totalBytesRead / sizeValue, 2)); } } while (isMoreToRead); token.ThrowIfCancellationRequested(); return destinationStream; }); } /// <summary> /// Return true, if enumerable is null or empty /// </summary> /// <param name="self">Self reference</param> /// <returns>Bool</returns> internal static bool IsNullOrEmpty(this IEnumerable self) { return self == null || !self.Cast<object>().Any(); } /// <summary> /// Return true, if collection is null or empty /// </summary> /// <param name="self">Self reference</param> /// <returns>Bool</returns> internal static bool IsNullOrEmpty(this ICollection self) { return self == null || self.Count == 0; } /// <summary> /// Return true, if string is null or empty /// </summary> /// <param name="self">Self reference</param> /// <returns>Bool</returns> internal static bool IsNullOrEmpty(this string self) { return string.IsNullOrEmpty(self); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void NoWarning(this Task task) { /* nothing */ } /// <summary> /// Return true, if string is null or contains only whitespaces /// </summary> /// <param name="self">Self reference</param> /// <returns>Bool</returns> internal static bool IsNullOrWhiteSpace(this string self) { return string.IsNullOrWhiteSpace(self); } /// <summary> /// Converts task to "Task without Continue" if operation has been cancelled /// </summary> /// <param name="originalTask">Original unsafe task</param> /// <param name="ct">Token</param> /// <returns>Task</returns> public static async Task<TResult> WithBlockingCancellation<TResult>(this Task<TResult> originalTask, CancellationToken ct) { var blockingTask = new TaskCompletionSource<TResult>(); var cancelTask = new TaskCompletionSource<Void>(); using (ct.Register(t => ((TaskCompletionSource<Void>)t).TrySetResult(new Void()), cancelTask)) { Task any = await Task.WhenAny(originalTask, cancelTask.Task); if (any != cancelTask.Task && !originalTask.IsCanceled) { if (originalTask.IsFaulted) blockingTask.SetException(originalTask.Exception); else blockingTask.SetResult(originalTask.Result); } } return await blockingTask.Task; } /// <summary> /// Converts task to "Task without Continue" if operation has been cancelled /// </summary> /// <param name="originalTask">Original unsafe task</param> /// <param name="ct">Token</param> /// <returns>Task</returns> public static async Task WithBlockingCancellation(this Task originalTask, CancellationToken ct) { var blockingTask = new TaskCompletionSource<Void>(); var cancelTask = new TaskCompletionSource<Void>(); using (ct.Register(t => ((TaskCompletionSource<Void>)t).TrySetResult(new Void()), cancelTask)) { Task any = await Task.WhenAny(originalTask, cancelTask.Task); if (any != cancelTask.Task && !originalTask.IsCanceled) { if (originalTask.IsFaulted) blockingTask.SetException(originalTask.Exception); else blockingTask.SetResult(new Void()); } } await blockingTask.Task; } public struct Void { } } }
41.003636
219
0.58221
ef54c8f41c75ba1da3aabe4acca2a0753f457c8e
1,733
php
PHP
local-vendor/members/src/Models/MemberWithLatestPoints.php
dansk-badminton-tech/nembadminton
f48042ff3edd58ba84e349e6e9b711742a5a8335
[ "MIT" ]
null
null
null
local-vendor/members/src/Models/MemberWithLatestPoints.php
dansk-badminton-tech/nembadminton
f48042ff3edd58ba84e349e6e9b711742a5a8335
[ "MIT" ]
8
2022-02-05T11:48:43.000Z
2022-03-21T22:34:01.000Z
local-vendor/members/src/Models/MemberWithLatestPoints.php
dansk-badminton-tech/nembadminton
f48042ff3edd58ba84e349e6e9b711742a5a8335
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace FlyCompany\Members\Models; use App\Models\Club; use App\Models\Point; use Carbon\Carbon; use Carbon\CarbonInterface; use FlyCompany\BadmintonPlayerAPI\Util; use FlyCompany\BadmintonPlayerAPI\Vintage; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Facades\Auth; /** * @property-read int $id * @property string $refId * @property string $name * @property string $gender * @property CarbonInterface|null $birthday * @property bool $hide * @property CarbonInterface $created_at * @property CarbonInterface $updated_at * @property int|null $latest_level_points * @property int|null $latest_level_position * @property CarbonInterface $latest_level_version * @property int|null $latest */ class MemberWithLatestPoints extends Model { protected $table = 'members_with_latest_points'; public function clubs(): BelongsToMany { return $this->belongsToMany(Club::class, 'club_member', 'member_id', 'club_id'); } public function points(): HasMany { return $this->hasMany(Point::class, 'member_id'); } public function scopeMyClub(Builder $builder): Builder { return $builder->whereHas('clubs', function (Builder $builder) { $builder->where('id', Auth::user()->organization_id); }); } public function getVintage() : string{ return Util::calculateVintage($this->getBirthday())->value; } public function getBirthday() : Carbon { return Carbon::createFromFormat('ymd', substr($this->refId, 0, 6)); } }
27.078125
88
0.716099
bb5abc542c0a420badb0e53f7bd89232c997dfb4
2,920
cs
C#
SftpWrapper.Sdk/Services/Upload.cs
rodrigodosanjosoliveira/sftpwrapper
97694fbcf5bbb62174adec9347bdc3328f1b9624
[ "MIT" ]
2
2017-12-21T17:23:02.000Z
2018-01-10T17:41:33.000Z
SftpWrapper.Sdk/Services/Upload.cs
rodrigodosanjosoliveira/SftpWrapper
97694fbcf5bbb62174adec9347bdc3328f1b9624
[ "MIT" ]
3
2019-07-04T23:15:16.000Z
2020-05-06T04:52:46.000Z
SftpWrapper.Sdk/Services/Upload.cs
rodrigodosanjosoliveira/SftpWrapper
97694fbcf5bbb62174adec9347bdc3328f1b9624
[ "MIT" ]
null
null
null
using System; using System.IO; using System.Net.Sockets; using Renci.SshNet; using Renci.SshNet.Common; using SftpWrapper.Sdk.Models; namespace SftpWrapper.Sdk.Services { public class Upload : IDisposable { private readonly SftpClient _client; public bool UploadSuccess { get; set; } protected SftpFileInfo File { get; set; } public Upload(Models.ConnectionInfo info, string sourcePath, string destinationPath) { _client = new SftpClient(info.Host, info.Port, info.UserName, info.Password); File = new SftpFileInfo(Valid(sourcePath), destinationPath); } public void UploadToSftp() { try { Connect(); _client.ChangeDirectory(File.DestinationPath); using (var fs = new FileStream(File.SourcePath, FileMode.Open)) { _client.BufferSize = 4 * 1024; _client.UploadFile(fs, File.Name); } UploadSuccess = _client.Exists($"{File.DestinationPath}{File.Name}"); DeleteSourceFolder(); } catch (InvalidOperationException ioe) { throw new InvalidOperationException(ioe.Message, ioe.InnerException); } catch (SocketException se) { throw new SocketException(se.ErrorCode); } catch (SshConnectionException sce) { throw new SshConnectionException(sce.Message); } catch (SshAuthenticationException sae) { throw new SshAuthenticationException(sae.Message, sae.InnerException); } } #region Private Methods private void Connect() { _client.Connect(); } private void Disconnect() { _client.Disconnect(); } private static string Valid(string sourcePath) { if (System.IO.File.Exists(sourcePath)) return sourcePath; throw new ArgumentException("Invalid path or file not found."); } private void DeleteSourceFolder() { if (!UploadSuccess) return; if (System.IO.File.Exists(File.SourcePath)) System.IO.File.Delete(File.SourcePath); } #endregion #region IDisposable Members protected virtual void Dispose(bool disposing) { Disconnect(); if (!disposing) return; _client?.Dispose(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Upload() { Dispose(false); } #endregion } }
27.28972
86
0.523973
9acb50b4fa2981e26df99fb818531568abf3f96a
8,653
sql
SQL
log4mssql/LoggerBase/Stored Procedures/InstallToRemote.sql
jbpion/log4mssql
881fc2ab728fb48fb63961ea1a17b7c88336dfd0
[ "MIT" ]
1
2021-01-30T07:35:12.000Z
2021-01-30T07:35:12.000Z
log4mssql/LoggerBase/Stored Procedures/InstallToRemote.sql
jbpion/log4mssql
881fc2ab728fb48fb63961ea1a17b7c88336dfd0
[ "MIT" ]
1
2021-07-06T08:17:32.000Z
2021-07-06T08:17:32.000Z
log4mssql/LoggerBase/Stored Procedures/InstallToRemote.sql
jbpion/log4mssql
881fc2ab728fb48fb63961ea1a17b7c88336dfd0
[ "MIT" ]
null
null
null
/********************************************************************************************* PROCEDURE LoggerBase.InstallToRemote Date: 03/14/2019 Author: Jerome Pion Description: Installs the framework on another database in the instance pointing back to the main logging database. --TEST --CREATE DATABASE LogInstallTest EXEC LoggerBase.InstallToRemote 'LogInstallTest' **********************************************************************************************/ CREATE PROCEDURE LoggerBase.InstallToRemote ( @DatabaseName SYSNAME ,@Debug BIT = 0 ) AS SET NOCOUNT ON; DECLARE @Message NVARCHAR(MAX);SELECT @Message = CONCAT(CONVERT(NVARCHAR(50),GETDATE(),121),':Installation started'); RAISERROR(@Message,0,1); DECLARE @V VARCHAR(50) = (SELECT [Version] FROM LoggerBase.VersionInfo()) DECLARE @SQL NVARCHAR(MAX) DECLARE @ObjectName VARCHAR(MAX) SET @Message = CONCAT('| Logging database ', DB_NAME(), ' is at version ', @V, ' |') PRINT CONCAT('+', REPLICATE('-', LEN(@Message)-2), '+') PRINT @Message PRINT CONCAT('+', REPLICATE('-', LEN(@Message)-2), '+') --Schema SET @ObjectName = 'Logger' PRINT CONCAT('***Checking for schema ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = ''', @ObjectName, ''') BEGIN PRINT ''Create schema ''''', @ObjectName, ''''''' EXEC(''CREATE SCHEMA ', @ObjectName, ''') END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase' PRINT CONCAT('***Checking for schema ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = ''', @ObjectName, ''') BEGIN PRINT ''Create schema ''''', @ObjectName, ''''''' EXEC(''CREATE SCHEMA ', @ObjectName, ''') END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL ----Synonym SET @ObjectName = 'Logger.Tokens_List' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.Configuration_Get' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.Configuration_Set' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.CorrelationId_Helper' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.DefaultErrorMessage' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.Logger_Base' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.Layout_Tokens_Pivot' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL SET @ObjectName = 'LoggerBase.Util_Configuration_Properties' PRINT CONCAT('***Checking for synonym ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create synonym ', @ObjectName, ''' CREATE SYNONYM ', @ObjectName, ' FOR [', DB_NAME(), '].', @ObjectName, ' END') IF (@Debug = 1) PRINT @SQL EXEC sp_executesql @SQL ----User Defined Types PRINT '***Checking for user-defined type dbo.LogConfiguration***' SELECT @SQL = CONCAT('USE ', @DatabaseName, '; IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N''LogConfiguration'' AND ss.name = N''dbo'') BEGIN PRINT ''Create type LogConfiguration'' CREATE TYPE [dbo].[LogConfiguration] FROM [nvarchar](max) NULL END') EXEC sp_executesql @SQL ----Stored Procedures SET @ObjectName = 'Logger.CorrelationId' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.DefaultErrorMessage' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.Configure' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.Debug' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.Error' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.Fatal' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.Info' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL SET @ObjectName = 'Logger.Warn' PRINT CONCAT('***Checking for stored procedure ', @ObjectName, '***') SELECT @SQL = CONCAT('USE ', @DatabaseName, ';IF OBJECT_ID(''', @ObjectName, ''') IS NULL BEGIN PRINT ''Create procedure ', @ObjectName, ''' EXEC(''', REPLACE(OBJECT_DEFINITION(OBJECT_ID(@ObjectName)), '''', ''''''), ''') END') EXEC sp_executesql @SQL RAISERROR('',0,1)WITH NOWAIT; RAISERROR('+-----------------------------------------+',0,1)WITH NOWAIT; RAISERROR('| |',0,1)WITH NOWAIT; RAISERROR('| log4mssql remote installation complete |',0,1)WITH NOWAIT; RAISERROR('| |',0,1)WITH NOWAIT; RAISERROR('+-----------------------------------------+',0,1)WITH NOWAIT; GO
57.304636
315
0.638969
8e7e82e21115dbb42edf2bc97ead58c5f766801b
14,106
js
JavaScript
packages/benefit-docs-old/theme/components/Page.js
gastonfartek/benefit
dc35d0509736345b052a4bd2d2e195896271c9de
[ "MIT" ]
53
2019-03-14T18:08:35.000Z
2022-02-12T21:30:14.000Z
packages/benefit-docs-old/theme/components/Page.js
gastonfartek/benefit
dc35d0509736345b052a4bd2d2e195896271c9de
[ "MIT" ]
59
2019-05-05T04:52:16.000Z
2022-02-26T16:43:06.000Z
packages/benefit-docs-old/theme/components/Page.js
gastonfartek/benefit
dc35d0509736345b052a4bd2d2e195896271c9de
[ "MIT" ]
5
2019-05-06T00:04:48.000Z
2021-04-23T20:36:08.000Z
/** @jsx jsx */ import React, { useEffect, useState } from "react" import { useConfig, useMenus, useDocs, Link, doczState } from "docz" import { css, keyframes } from "emotion" import { ArrowLeft, ArrowRight, GitHub, ChevronsRight } from "react-feather" import { Box, ConfigConsumer, jsx } from "benefit-react" import Container from "./Container" import Logo from "../../components/Logo" import { theme } from "benefit" import Icon, { Layout, Type, Background, Border, Space, Size, Effects, Interactivity, Svg, Flexbox, Table, } from "../../components/Icons.js" import Loader from "./Loader.js" const { colors } = theme const page = css` display: grid; height: 100vh; -webkit-overflow-scrolling: touch; grid-template-columns: [content-start] minmax(auto, 1024px) [content-end]; @media (min-width: 1025px) { grid-template-columns: [fullbleed-start] minmax(1.2rem, 1fr) [content-start] minmax(auto, 1024px) [content-end] minmax(1.2rem, 1fr) [fullbleed-end]; } ` function PageContainer({ children, isMenuOpen }) { return ( <Box className={`${page} ${ isMenuOpen ? "overflow-y-hidden" : "overflow-y-scroll" }`} > {children} </Box> ) } const rightBg = css` background-color: ${colors.gray[200]}; background-image: url("data:image/svg+xml,%3Csvg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20 20.5V18H0v-2h20v-2H0v-2h20v-2H0V8h20V6H0V4h20V2H0V0h22v20h2V0h2v20h2V0h2v20h2V0h2v20h2V0h2v20h2v2H20v-1.5zM0 20h2v20H0V20zm4 0h2v20H4V20zm4 0h2v20H8V20zm4 0h2v20h-2V20zm4 0h2v20h-2V20zm4 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2z' fill='%2322292f' fill-opacity='0.02' fill-rule='evenodd'/%3E%3C/svg%3E"); background-image: linear-gradient( to right, ${colors.gray[200]} 520px, rgba(255, 255, 255, 0) ), url("data:image/svg+xml,%3Csvg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20 20.5V18H0v-2h20v-2H0v-2h20v-2H0V8h20V6H0V4h20V2H0V0h22v20h2V0h2v20h2V0h2v20h2V0h2v20h2V0h2v20h2v2H20v-1.5zM0 20h2v20H0V20zm4 0h2v20H4V20zm4 0h2v20H8V20zm4 0h2v20h-2V20zm4 0h2v20h-2V20zm4 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2z' fill='%2322292f' fill-opacity='0.02' fill-rule='evenodd'/%3E%3C/svg%3E"); ` const leftBg = css` background-color: ${colors.gray[900]}; background-image: url("data:image/svg+xml,%3Csvg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20 20.5V18H0v-2h20v-2H0v-2h20v-2H0V8h20V6H0V4h20V2H0V0h22v20h2V0h2v20h2V0h2v20h2V0h2v20h2V0h2v20h2v2H20v-1.5zM0 20h2v20H0V20zm4 0h2v20H4V20zm4 0h2v20H8V20zm4 0h2v20h-2V20zm4 0h2v20h-2V20zm4 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2z' fill='%23f6f8fa' fill-opacity='0.02' fill-rule='evenodd'/%3E%3C/svg%3E"); background-image: linear-gradient( to left, ${colors.gray[900]} 520px, transparent ), url("data:image/svg+xml,%3Csvg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20 20.5V18H0v-2h20v-2H0v-2h20v-2H0V8h20V6H0V4h20V2H0V0h22v20h2V0h2v20h2V0h2v20h2V0h2v20h2V0h2v20h2v2H20v-1.5zM0 20h2v20H0V20zm4 0h2v20H4V20zm4 0h2v20H8V20zm4 0h2v20h-2V20zm4 0h2v20h-2V20zm4 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2zm0 4h20v2H20v-2z' fill='%23f6f8fa' fill-opacity='0.02' fill-rule='evenodd'/%3E%3C/svg%3E"); ` function FullBleed() { return ( <Box style={{ gridRow: "1 / -1", gridColumn: "fullbleed-start / fullbleed-end", display: "grid", gridTemplateColumns: "repeat(2, 1fr)", }} > <Box className={leftBg} /> <Box className={rightBg} /> </Box> ) } function Main({ children }) { return ( <Box style={{ gridRow: "1 / -1", gridColumn: "content-start / content-end", }} className="flex" > {children} </Box> ) } const partialUnderline = css` /* position: relative; &:before { content: ""; background: rgba(255, 255, 255, 0.06); width: auto; left: 2rem; right: 2rem; border-radius: 12px; height: 1px; bottom: 0; position: absolute; } */ ` const styledLink = css` &, &:visited, &:active { text-decoration: none; color: ${colors.gray["500"]} !important; } transition: 0.15s ease-in-out; &:hover:not(.active) { transform: translateX(0.25rem); } &.active { color: white !important; background: linear-gradient( to left, ${colors.gray["800"]}, ${colors.gray["900"]} ); } ` const menuHeading = css` position: relative; &::after { content: ""; position: absolute; bottom: 0; right: 0; height: 1px; width: 100%; background: linear-gradient( to left, rgba(255, 255, 255, 0) 0.25rem, ${colors.gray["800"]}, rgba(255, 255, 255, 0) ); } & svg { width: 16px; } ` const pagingLink = css` & svg { width: 16px; } min-width: 6rem; &, &:visited, &:active { display: inline-block; text-decoration: none; color: ${colors.blue["500"]}; transition: all 0.2s ease; } &:hover { transform: translateY(-1px); } ` function renderSubMenu(menuItems, category, iconName) { return ( <React.Fragment> <Box className={`${menuHeading} ${partialUnderline} uppercase tracking-wide text-xs flex justify-between items-center py-2 px-4 md:px-8 text-gray-700 mt-4`} > {category} <Icon name={iconName} className="w-4 text-gray-700" /> </Box> {menuItems .filter((item) => item.parent === category) .map((item) => ( <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} key={item.id} to={item.route} > {item.name} </Link> ))} </React.Fragment> ) } const sideMenuHeader = css` position: relative; &::before { content: ""; left: 0; bottom: 0; position: absolute; height: 1px; width: 100%; background-image: linear-gradient( to left, ${colors.gray["800"]}, transparent ); } ` function SideBar({ isOpen, onClose }) { const menuItems = useMenus() useEffect(() => { const sideMenu = document.querySelector(".side-menu") sideMenu.scrollTop = localStorage.getItem("menuScroll") || 0 sideMenu.onscroll = ({ target }) => { localStorage.setItem("menuScroll", target.scrollTop) } }) return ( <Box className={`bg-gray-900 text-gray-300 md:w-64 ${ isOpen ? "z-30 block" : "hidden" } absolute inset-0 md:static md:block`} > <Box className={`side-menu h-screen md:sticky top-0 ${ isOpen ? "overflow-y-auto" : "overflow-y-hidden" } overflow-x-hidden md:overflow-y-scroll scrolling-touch`} > <Box className="py-8 pt-16 md:pt-8"> <Box className="fixed block top-0 inset-x-0 bg-gray-900 z-10 md:hidden"> <Box is="button" className="bg-gray-800 w-full shadow p-4 flex items-center justify-between" type="button" onClick={onClose} > Close Menu <Icon name="x" className="text-gray-700" /> </Box> </Box> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/" > Introduction </Link> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/getting-started" > Getting Started </Link> <Box className={`${menuHeading} ${partialUnderline} uppercase tracking-wide text-xs flex justify-between items-center py-2 px-4 md:px-8 text-gray-700 mt-4`} > Customization <Icon name="settings" className="w-4 text-gray-700" /> </Box> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/customization/overview" > Overview </Link> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/customization/theme" > Theme </Link> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/customization/normalize" > Normalize </Link> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/customization/utilities" > Utilities </Link> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/customization/variants" > Variants </Link> <Link className={`px-4 md:px-8 py-2 no-underline hover:text-white block ${styledLink}`} to="/customization/apply" > Apply </Link> {renderSubMenu(menuItems, "Layout", "layout")} {renderSubMenu(menuItems, "Typography", "type")} {renderSubMenu(menuItems, "Background", "image")} {renderSubMenu(menuItems, "Border", "square")} {renderSubMenu(menuItems, "Flexbox", "columns")} {renderSubMenu(menuItems, "Space", "maximize")} {renderSubMenu(menuItems, "Size", "move")} {renderSubMenu(menuItems, "Tables", "align-justify")} {renderSubMenu(menuItems, "Effects", "loader")} {renderSubMenu(menuItems, "Interactivity", "mouse-pointer")} {renderSubMenu(menuItems, "Svg", "pen-tool")} </Box> </Box> </Box> ) } function Content({ children, isMenuOpen }) { return ( <Box className={`${ isMenuOpen ? "hidden" : "block" } bg-gray-200 flex-1 z-10 pt-16 md:pt-0`} > {children} </Box> ) } const accent = css` position: relative; display: inline-block; &::before { content: ""; left: 0; bottom: 0; position: absolute; height: 3px; border-radius: 2px; width: 30%; background: #63b3ed; } ` const fadingBorder = css` position: relative; &::before { content: ""; left: 0; bottom: 0; position: absolute; height: 1px; width: 100%; background-image: linear-gradient( to right, #d4dae1, rgba(255, 255, 255, 0) ); } ` const fadeIn = keyframes` from { opacity: 0; transform: translateY(100px); } to { opacity: 1; transform: translateY(0); } ` function contentEnter(delay = "0s") { return css` animation: ${fadeIn} 0.2s ${delay} ease-in-out; ` } export default function Page({ children, doc, location }) { const [isMenuOpen, toggleMenu] = useState(false) return ( <PageContainer isMenuOpen={isMenuOpen}> <FullBleed /> <Main> <SideBar isOpen={isMenuOpen} onClose={() => toggleMenu(!isMenuOpen)} /> <Content isMenuOpen={isMenuOpen}> <Box className={`fixed top-0 inset-x-0 z-50 bg-white p-4 md:relative md:bg-transparent md:p-8 flex justify-between items-center ${fadingBorder}`} style={{ backgroundImage: "linear-gradient(to right, white, rgba(255, 255, 255, 0))", }} > <Box is="button" className="md:hidden" type="button" onClick={() => toggleMenu(!isMenuOpen)} > <Icon name="menu" /> </Box> <Link to="/"> <Logo className="w-24" /> </Link> <Box className={`${css` & svg { width: 20px; } `} text-blue-500 rounded-full inline-flex items-center justify-center`} > <Box is="a" href="https://github.com/cdonohue/benefit" className="hover:text-blue-800" > <GitHub /> </Box> </Box> </Box> <Box className="p-4 md:p-8"> <Box className="text-5xl mb-8 font-thin text-gray-700"> <Box className="text-sm uppercase font-hairline text-gray-500"> {doc.parent} </Box> <Box className={`${accent} py-4`}>{doc.name}</Box> </Box> {children} <Box className="flex justify-between border-t mt-8 pt-4 border-gray-400 border-dashed"> <div> {doc.previousRoute && ( <Link className={`${pagingLink} text-blue-500 no-underline hover:text-blue-700`} to={doc.previousRoute} > <Box className="flex justify-between items-center text-sm"> <ArrowLeft /> Previous </Box> <Box className="font-bold text-right"> {doc.previousLabel} </Box> </Link> )} </div> <div> {doc.nextRoute && ( <Link className={`${pagingLink} text-blue-500 no-underline hover:text-blue-700`} to={doc.nextRoute} > <Box className="flex justify-between items-center text-sm"> Next <ArrowRight /> </Box> <Box className="font-bold">{doc.nextLabel}</Box> </Link> )} </div> </Box> </Box> </Content> </Main> </PageContainer> ) }
29.024691
469
0.55806
e3194d55c28c8561a6a625d4ee3e0dca45000a93
844
rb
Ruby
spec/unit/mutest/reporter/cli/printer/subject_progress_spec.rb
ch1c0t/mutest
45722b2320d90c020916824e0a697ac25580c487
[ "MIT" ]
55
2017-01-30T02:26:07.000Z
2018-03-31T21:37:58.000Z
spec/unit/mutest/reporter/cli/printer/subject_progress_spec.rb
ch1c0t/mutest
45722b2320d90c020916824e0a697ac25580c487
[ "MIT" ]
41
2017-01-30T02:45:15.000Z
2017-11-10T20:02:36.000Z
spec/unit/mutest/reporter/cli/printer/subject_progress_spec.rb
ch1c0t/mutest
45722b2320d90c020916824e0a697ac25580c487
[ "MIT" ]
6
2017-01-30T02:30:17.000Z
2018-01-16T19:26:19.000Z
RSpec.describe Mutest::Reporter::CLI::Printer::SubjectProgress do setup_shared_context let(:reportable) { subject_a_result } describe '.call' do context 'on full coverage' do it_reports <<-'STR' subject-a mutations: 2 .. (02/02) 100% - killtime: 2.00s runtime: 2.00s overhead: 0.00s STR end context 'on partial coverage' do with(:mutation_a_test_result) { { passed: true } } it_reports <<-'STR' subject-a mutations: 2 F. (01/02) 50% - killtime: 2.00s runtime: 2.00s overhead: 0.00s STR end context 'without results' do with(:subject_a_result) { { mutation_results: [] } } it_reports <<-'STR' subject-a mutations: 2 (00/02) 100% - killtime: 0.00s runtime: 0.00s overhead: 0.00s STR end end end
24.114286
69
0.597156
97c7061135ef17e6afd4a405231fef723f17cc86
1,067
dart
Dart
lib/sharepoint_auth/helper/token_storage.dart
luv4ever2shail/spmconnectflutter
6cfc88500f284bd69975842fcfd4091955455b39
[ "Apache-2.0" ]
1
2019-04-15T12:06:12.000Z
2019-04-15T12:06:12.000Z
lib/sharepoint_auth/helper/token_storage.dart
luv4ever2shail/spmconnectflutter
6cfc88500f284bd69975842fcfd4091955455b39
[ "Apache-2.0" ]
4
2019-04-26T15:20:33.000Z
2019-05-15T19:21:50.000Z
lib/sharepoint_auth/helper/token_storage.dart
spmconnect/spmconnectflutter
6cfc88500f284bd69975842fcfd4091955455b39
[ "Apache-2.0" ]
null
null
null
import 'dart:async'; import "dart:convert" as Convert; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:spmconnectapp/sharepoint_auth/model/token.dart'; class TokenStorage { static TokenStorage shared = new TokenStorage(); FlutterSecureStorage _secureStorage = FlutterSecureStorage(); final String _identifier = "Token"; Future<void> saveTokenToCache(Token token) async { var data = Token.toJsonMap(token); var json = Convert.jsonEncode(data); await _secureStorage.write(key: _identifier, value: json); } Future<T> loadTokenToCache<T extends Token>() async { var json = await _secureStorage.read(key: _identifier); if (json == null) return null; try { var data = Convert.jsonDecode(json); return _getTokenFromMap<T>(data); } catch (exception) { print(exception); return null; } } Token _getTokenFromMap<T extends Token>(Map<String, dynamic> data) => Token.fromJson(data); Future clear() async { _secureStorage.delete(key: _identifier); } }
29.638889
71
0.710403
073df237df661a022ccc4c64a1b648f115261283
388
css
CSS
src/components/ShoppingCart/ProductList/ProductList.css
ivanrdvc/react-ecommerce
511d9ac9456942286586e2f6172d82470d0180ee
[ "MIT" ]
1
2020-04-21T20:51:21.000Z
2020-04-21T20:51:21.000Z
src/components/ShoppingCart/ProductList/ProductList.css
ivanrdvc/react-ecommerce
511d9ac9456942286586e2f6172d82470d0180ee
[ "MIT" ]
null
null
null
src/components/ShoppingCart/ProductList/ProductList.css
ivanrdvc/react-ecommerce
511d9ac9456942286586e2f6172d82470d0180ee
[ "MIT" ]
null
null
null
.ProductList-header { border-bottom: 1px solid #d3d1d0; padding-bottom: 0.5rem; display: flex; } .ProductList-title { color: #828282; font-size: 14px; text-transform: uppercase; } .ProductList-title:nth-child(1) { flex: 0 0 58.33333%; } .ProductList-title:nth-child(2) { flex: 0 0 25%; } .ProductList-title:nth-child(3) { flex: 0 0 16.66667%; text-align: right; }
15.52
35
0.659794
6be0d9c2e70cb535e89012d41f8191b69cbda1c1
10,566
sql
SQL
jassimbooks.sql
u1676570/advance-web
e4f66c5860bef3c0671d4aa7dce9df6bfff747aa
[ "MIT" ]
null
null
null
jassimbooks.sql
u1676570/advance-web
e4f66c5860bef3c0671d4aa7dce9df6bfff747aa
[ "MIT" ]
null
null
null
jassimbooks.sql
u1676570/advance-web
e4f66c5860bef3c0671d4aa7dce9df6bfff747aa
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.8.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Nov 12, 2019 at 02:59 AM -- Server version: 10.1.31-MariaDB -- PHP Version: 7.2.4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `jassimbooks` -- -- -------------------------------------------------------- -- -- Table structure for table `authors` -- CREATE TABLE `authors` ( `authorid` int(5) NOT NULL, `authorname` varchar(50) NOT NULL, `authordob` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `authors` -- INSERT INTO `authors` (`authorid`, `authorname`, `authordob`) VALUES (1, 'Kennedy Ryan', '1988-10-02'), (2, 'Jaci Burton', '1988-09-03'), (3, 'Lisa Brennan', '1985-01-10'), (4, 'Maxwell King', '1989-05-07'), (5, 'Ngozi Ukazu', '1989-09-06'), (6, 'Whitney Gardner', '1988-12-03'), (7, 'Merve Emre', '1980-10-12'), (8, 'Neil deGrasse Tyson', '1975-12-28'), (9, 'Robert Galbraith', '1965-06-30'), (10, 'Kate Morton', '1990-03-05'), (11, 'Ellen Hopkins', '1955-02-10'), (12, 'Atticus Poetry', '1978-08-15'), (13, 'Courtney Summers', '1975-11-10'), (14, 'Mary Kubica', '1980-04-20'); -- -------------------------------------------------------- -- -- Table structure for table `books` -- CREATE TABLE `books` ( `bookid` int(5) NOT NULL, `title` text NOT NULL, `isbn` int(11) NOT NULL, `language` varchar(30) NOT NULL, `pages` int(11) NOT NULL, `publishdate` date NOT NULL, `authorid` int(5) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `books` -- INSERT INTO `books` (`bookid`, `title`, `isbn`, `language`, `pages`, `publishdate`, `authorid`) VALUES (1, 'Block Shot', 1732144311, 'English', 444, '2018-09-10', 1), (2, 'Hope Flames', 425259765, 'English', 320, '2014-01-07', 2), (3, 'Riding Wild', 425219313, 'English', 278, '2008-02-08', 2), (5, 'The Clockmaker\'s Daughter', 1451649398, 'English', 485, '2018-10-05', 10), (6, 'Small Fry', 802128238, 'English', 400, '2018-09-04', 3), (7, 'The Good Neighbor: The Life and Work of Fred Roger', 1419727729, 'English', 416, '2018-09-04', 4), (8, 'Check, Please!:', 1250177952, 'English', 288, '2018-09-18', 5), (9, 'Fake Blood', 1481495569, 'English', 300, '2018-09-04', 6), (10, 'The Personality Brokers: The Strange History of Myers', 385541902, 'English', 288, '2018-09-11', 7), (11, 'Accessory to War: The Unspoken Alliance Between Astrophysics and the Military', 393064441, 'English', 576, '2018-09-11', 8), (12, 'Sadie', 1250105714, 'English', 300, '2018-09-04', 13), (13, 'The Good Girl', 778316556, 'English', 352, '2014-07-09', 14), (14, 'People Kill People', 1481442937, 'English', 431, '2018-08-11', 11), (15, 'The Dark Between Stars', 1982104864, 'English', 239, '2018-08-04', 12), (16, 'When the Lights Go Out', 525219414, 'English', 384, '2018-02-02', 14); -- -------------------------------------------------------- -- -- Table structure for table `book_genre` -- CREATE TABLE `book_genre` ( `id` int(11) NOT NULL, `bookid` int(5) NOT NULL, `genreid` int(5) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `book_genre` -- INSERT INTO `book_genre` (`id`, `bookid`, `genreid`) VALUES (1, 1, 8), (3, 5, 3), (4, 6, 4), (5, 7, 5), (6, 8, 6), (7, 9, 7), (8, 10, 8), (9, 11, 4), (10, 12, 5), (11, 13, 7), (12, 14, 4), (13, 15, 2), (14, 16, 3); -- -------------------------------------------------------- -- -- Table structure for table `genre` -- CREATE TABLE `genre` ( `genreid` int(5) NOT NULL, `name` varchar(20) NOT NULL, `description` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `genre` -- INSERT INTO `genre` (`genreid`, `name`, `description`) VALUES (1, 'Fiction', 'Fiction is the telling of stories which are not real. More specifically, fiction is an imaginative form of narrative, one of the four basic rhetorical modes. Although the word fiction is derived from the Latin fingo, fingere, finxi, fictum, \"to form, create\", works of fiction need not be entirely imaginary and may include real people, places, and events.'), (2, 'Biography', 'A biography (from the Greek words bios meaning \"life\", and graphos meaning \"write\") is an account of a person\'s life, usually published in the form of a book or essay, or in some other form, such as a film.'), (3, 'Comics', 'A comic book or comicbook, also called comic magazine or simply comic, is a publication that consists of comic art in the form of sequential juxtaposed panels that represent individual scenes. Panels are often accompanied by brief descriptive prose and written narrative, usually dialog contained in word balloons emblematic of the comics art form.'), (4, 'History', 'History (from Greek iotopia - historia, meaning inquiry, knowledge acquired by investigation) is the discovery, collection, organization, and presentation of information about past events. History can also mean the period of time after writing was invented. Scholars who write about history are called historians. '), (5, 'Mystery', 'Mystery fiction is a loosely-defined term that is often used as a synonym of detective fiction - in other words a novel or short story in which a detective (either professional or amateur) solves a crime. '), (6, 'Poetry', 'Poetry is a form of literary art in which language is used for its aesthetic and evocative qualities in addition to, or in lieu of, its apparent meaning. Poetry may be written independently, as discrete poems, or may occur in conjunction with other arts, as in poetic drama, hymns or lyrics.\r\n'), (7, 'Thriller', 'Thrillers are characterized by fast pacing, frequent action, and resourceful heroes who must thwart the plans of more-powerful and better-equipped villains. Literary devices such as suspense, red herrings and cliffhangers are used extensively.'), (8, 'Sports', 'Sports : engagement in physical activity intended to create a benefit to the participant. Ranging from Amateur to Professional, from incompetent to proficient, for all levels of ability, all nations, all creeds, all genders. As James Joyce said \"I am, a stride at a time\"'); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`migration`, `batch`) VALUES ('2014_10_12_000000_create_users_table', 1), ('2014_10_12_100000_create_password_resets_table', 1); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (2, 'admin', 'admin@admin.com', '$2y$10$K/IAoJc8vbd6DZnUwlQF6.ihf3g8VzfPr2mOiQSkRcxPKRaNGd3Bm', 'GTdOF8B0pW5E7TTjgZgVBBwl1BE1GO24cVR5YcYJnzh6BFqMsGUpuhcwI2uu', '2019-11-10 08:08:52', '2019-11-11 10:18:52'); -- -- Indexes for dumped tables -- -- -- Indexes for table `authors` -- ALTER TABLE `authors` ADD PRIMARY KEY (`authorid`); -- -- Indexes for table `books` -- ALTER TABLE `books` ADD PRIMARY KEY (`bookid`), ADD UNIQUE KEY `isbn` (`isbn`), ADD KEY `authorid` (`authorid`); -- -- Indexes for table `book_genre` -- ALTER TABLE `book_genre` ADD PRIMARY KEY (`id`), ADD KEY `bookid` (`bookid`), ADD KEY `genreid` (`genreid`); -- -- Indexes for table `genre` -- ALTER TABLE `genre` ADD PRIMARY KEY (`genreid`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`), ADD KEY `password_resets_token_index` (`token`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `authors` -- ALTER TABLE `authors` MODIFY `authorid` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `books` -- ALTER TABLE `books` MODIFY `bookid` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22; -- -- AUTO_INCREMENT for table `book_genre` -- ALTER TABLE `book_genre` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; -- -- AUTO_INCREMENT for table `genre` -- ALTER TABLE `genre` MODIFY `genreid` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- Constraints for dumped tables -- -- -- Constraints for table `books` -- ALTER TABLE `books` ADD CONSTRAINT `books_ibfk_1` FOREIGN KEY (`authorid`) REFERENCES `authors` (`authorid`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `book_genre` -- ALTER TABLE `book_genre` ADD CONSTRAINT `book_genre_ibfk_1` FOREIGN KEY (`genreid`) REFERENCES `genre` (`genreid`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `book_genre_ibfk_2` FOREIGN KEY (`bookid`) REFERENCES `books` (`bookid`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
34.529412
377
0.679538
0df71aa2bfd51a9d0cf97fa901ecb6497b2b2abe
137
cs
C#
PAEF1a/Core/Events/AfterCatSavedEventArgs.cs
chrhodes/Applications
d48e73993e8c11c5d7ce14b4214ba225a88bf89c
[ "MIT" ]
1
2021-03-31T09:15:01.000Z
2021-03-31T09:15:01.000Z
PAEF1a/Core/Events/AfterCatSavedEventArgs.cs
chrhodes/Applications
d48e73993e8c11c5d7ce14b4214ba225a88bf89c
[ "MIT" ]
null
null
null
PAEF1a/Core/Events/AfterCatSavedEventArgs.cs
chrhodes/Applications
d48e73993e8c11c5d7ce14b4214ba225a88bf89c
[ "MIT" ]
null
null
null
using VNC.Core.Events; namespace PAEF1a.Core.Events { public class AfterCatSavedEventArgs : AfterDetailSavedEventArgs { } }
15.222222
67
0.737226
9fd3402e164c4c99693bbf3c5e5f4252e5113069
480
py
Python
app/__init__.py
pedroermarinho/Dominik
3be83039f4622c52ee43e5f1e6ea277d4c0fb484
[ "MIT" ]
null
null
null
app/__init__.py
pedroermarinho/Dominik
3be83039f4622c52ee43e5f1e6ea277d4c0fb484
[ "MIT" ]
null
null
null
app/__init__.py
pedroermarinho/Dominik
3be83039f4622c52ee43e5f1e6ea277d4c0fb484
[ "MIT" ]
null
null
null
# -*- coding:utf-8 -*- from flask import Flask from app.modules import init_app from app.controllers.database import init_db from app.modules.chat_bot import init_chat_bot from app.modules.arduino import init_arduino from app.modules.services import init_services def create_app(): app: Flask = Flask(__name__) app.config.from_object('configFlask') init_db(app) init_app(app) init_services(app) init_chat_bot(app) init_arduino(app) return app
22.857143
46
0.75
110ab8aa92b237ae750437f7343a4a346b46e685
2,479
kt
Kotlin
src/test/kotlin/de/klg71/keycloakmigration/changeControl/actions/client/mapper/AddGroupMembershipMapperActionIntegTest.kt
Interview-IA/keycloakmigration
f02f6b1fb88b95392407df17d19220f2582e9854
[ "MIT" ]
null
null
null
src/test/kotlin/de/klg71/keycloakmigration/changeControl/actions/client/mapper/AddGroupMembershipMapperActionIntegTest.kt
Interview-IA/keycloakmigration
f02f6b1fb88b95392407df17d19220f2582e9854
[ "MIT" ]
null
null
null
src/test/kotlin/de/klg71/keycloakmigration/changeControl/actions/client/mapper/AddGroupMembershipMapperActionIntegTest.kt
Interview-IA/keycloakmigration
f02f6b1fb88b95392407df17d19220f2582e9854
[ "MIT" ]
1
2021-09-15T06:28:07.000Z
2021-09-15T06:28:07.000Z
package de.klg71.keycloakmigration.changeControl.actions.client.mapper import de.klg71.keycloakmigration.AbstractIntegrationTest import de.klg71.keycloakmigration.changeControl.actions.client.AddSimpleClientAction import de.klg71.keycloakmigration.keycloakapi.KeycloakClient import de.klg71.keycloakmigration.keycloakapi.clientUUID import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.koin.core.inject class AddGroupMembershipMapperActionIntegTest : AbstractIntegrationTest() { val client by inject<KeycloakClient>() @Test fun testAddMapper() { AddSimpleClientAction(testRealm, "simpleClient").executeIt() val mapperName = "testMapper" val protocol = "openid-connect" val protocolMapper = "oidc-group-membership-mapper" AddGroupMembershipMapperAction(testRealm, "simpleClient", mapperName).executeIt() val mappers = client.mappers(client.clientUUID("simpleClient", testRealm), testRealm) assertThat(mappers).hasSize(1) val mapper = mappers[0] assertThat(mapper.name).isEqualTo(mapperName) assertThat(mapper.protocol).isEqualTo(protocol) assertThat(mapper.protocolMapper).isEqualTo(protocolMapper) assertThat(mapper.config["claim.name"]).isEqualTo(mapperName) } @Test fun testAddMapper_claimNameGiven() { AddSimpleClientAction(testRealm, "simpleClient").executeIt() val mapperName = "testMapper" val claimName = "claimName" AddGroupMembershipMapperAction(testRealm, "simpleClient", mapperName, claimName = claimName).executeIt() val mappers = client.mappers(client.clientUUID("simpleClient", testRealm), testRealm) assertThat(mappers).hasSize(1) val mapper = mappers[0] assertThat(mapper.name).isEqualTo(mapperName) assertThat(mapper.config["claim.name"]).isEqualTo(claimName) } @Test fun testAddMapper_fullPathFalse() { AddSimpleClientAction(testRealm, "simpleClient").executeIt() val mapperName = "testMapper" AddGroupMembershipMapperAction(testRealm, "simpleClient", mapperName, fullGroupPath = false).executeIt() val mappers = client.mappers(client.clientUUID("simpleClient", testRealm), testRealm) assertThat(mappers).hasSize(1) val mapper = mappers[0] assertThat(mapper.name).isEqualTo(mapperName) assertThat(mapper.config["full.path"]).isEqualTo("false") } }
39.983871
112
0.73094
e14f413eba2296b17e31917b52284a9f8fc349a6
266
go
Go
api/internal/service/kube/resource/base.go
z131031231/mogo
a6d67dfb092d4bec2bc87fdd226c547bcc3bf613
[ "MIT" ]
331
2021-12-29T15:56:30.000Z
2022-03-30T02:19:51.000Z
api/internal/service/kube/resource/base.go
z131031231/mogo
a6d67dfb092d4bec2bc87fdd226c547bcc3bf613
[ "MIT" ]
27
2022-01-13T03:56:24.000Z
2022-03-31T02:32:25.000Z
api/internal/service/kube/resource/base.go
z131031231/mogo
a6d67dfb092d4bec2bc87fdd226c547bcc3bf613
[ "MIT" ]
55
2022-01-04T02:12:20.000Z
2022-03-30T02:19:54.000Z
package resource import ( "net/http" k8serrors "k8s.io/apimachinery/pkg/api/errors" ) func NotFound(err error) bool { if status, ok := err.(*k8serrors.StatusError); ok { if status.ErrStatus.Code == http.StatusNotFound { return true } } return false }
15.647059
52
0.695489
74461d8cc0ba85c8e520013f1de4b28820d86dbc
960
sql
SQL
db/ems_schema.sql
marora7926/employee-management-system
dc40ca581b0493220e350fd7c1c0b3bc1745e223
[ "MIT" ]
null
null
null
db/ems_schema.sql
marora7926/employee-management-system
dc40ca581b0493220e350fd7c1c0b3bc1745e223
[ "MIT" ]
null
null
null
db/ems_schema.sql
marora7926/employee-management-system
dc40ca581b0493220e350fd7c1c0b3bc1745e223
[ "MIT" ]
null
null
null
-- drop databae with name ems_schema if already exist DROP DATABASE IF EXISTS employeedb; -- create a dtaabase from scratch CREATE DATABASE employeedb; -- use the existing database just created USE employeedb; -- create a table with a name "department", defining variable within this table and defining property of each of the variables CREATE TABLE department ( d_id INTEGER AUTO_INCREMENT, name VARCHAR(30) NOT NULL, PRIMARY KEY (d_id) ); -- create a table with a name "role" CREATE TABLE role ( r_id INT AUTO_INCREMENT, title VARCHAR(30) NOT NULL, salary DECIMAL(6) NOT NULL, d_id INT NOT NULL, PRIMARY KEY (r_id), FOREIGN KEY (d_id) REFERENCES department(d_id) ); -- create a table with a name "employee" CREATE TABLE employee ( e_id INT AUTO_INCREMENT, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, r_id INT NOT NULL, manager_id INT, PRIMARY KEY (e_id), FOREIGN KEY (r_id) REFERENCES role(r_id) );
26.666667
127
0.741667
58981e0596488f843fb116d7b8fd030e3cbedeaf
141
rb
Ruby
db/migrate/20200211105406_remove_verify_response_from_claim.rb
lwlsns/claim-additional-payments-for-teaching
325ec09f584ff4e699a5ec65701b7c2650cf6dd4
[ "MIT" ]
8
2020-08-14T12:38:41.000Z
2022-03-29T11:12:17.000Z
db/migrate/20200211105406_remove_verify_response_from_claim.rb
lwlsns/claim-additional-payments-for-teaching
325ec09f584ff4e699a5ec65701b7c2650cf6dd4
[ "MIT" ]
351
2019-05-23T13:57:38.000Z
2020-03-24T18:00:29.000Z
db/migrate/20200211105406_remove_verify_response_from_claim.rb
lwlsns/claim-additional-payments-for-teaching
325ec09f584ff4e699a5ec65701b7c2650cf6dd4
[ "MIT" ]
9
2020-03-31T11:18:55.000Z
2021-04-10T21:45:50.000Z
class RemoveVerifyResponseFromClaim < ActiveRecord::Migration[6.0] def change remove_column :claims, :verify_response, :json end end
23.5
66
0.780142
bb3e41446ebd6f2ec1e44984c97d2cb17fa6caa7
1,190
swift
Swift
Frameworks/InAppServices/Sources/Features/PushNotification/PushNotificationIpcMethodHandler.swift
antigp/Mixbox
b787fa76b0d861e05dd6a467039f63e1dc931ff0
[ "MIT" ]
null
null
null
Frameworks/InAppServices/Sources/Features/PushNotification/PushNotificationIpcMethodHandler.swift
antigp/Mixbox
b787fa76b0d861e05dd6a467039f63e1dc931ff0
[ "MIT" ]
null
null
null
Frameworks/InAppServices/Sources/Features/PushNotification/PushNotificationIpcMethodHandler.swift
antigp/Mixbox
b787fa76b0d861e05dd6a467039f63e1dc931ff0
[ "MIT" ]
2
2019-09-30T12:32:49.000Z
2020-09-17T20:41:13.000Z
#if MIXBOX_ENABLE_IN_APP_SERVICES import Foundation import MixboxIpc import MixboxIpcCommon import MixboxFoundation import UIKit final class PushNotificationIpcMethodHandler: IpcMethodHandler { let method = PushNotificationIpcMethod() func handle( arguments: PushNotificationIpcMethod.Arguments, completion: @escaping (PushNotificationIpcMethod.ReturnValue) -> ()) { guard let data = arguments.data(using: .utf8), let anyNotification = try? JSONSerialization.jsonObject(with: data), let notification = anyNotification as? [AnyHashable: Any] else { completion( IpcThrowingFunctionResult.threw( ErrorString("Не удалось получить уведомление из полученой строки") ) ) return } DispatchQueue.main.async { UIApplication.shared.delegate?.application?( UIApplication.shared, didReceiveRemoteNotification: notification ) completion(IpcThrowingFunctionResult.returned(IpcVoid())) } } } #endif
27.674419
86
0.614286
20f587d4841bfc1eb4ee255e77ccd96851c5aebe
204
py
Python
mmfashion/utils/__init__.py
lijiancheng0614/mmfashion
f67b6ebc45252356d9f40a185c40894429f43a13
[ "Apache-2.0" ]
2
2020-05-26T03:14:24.000Z
2021-01-31T18:23:47.000Z
mmfashion/utils/__init__.py
ceciliaAI/mmfashion
0161ec8717f129433271a796a3d3a6b540b005a3
[ "Apache-2.0" ]
null
null
null
mmfashion/utils/__init__.py
ceciliaAI/mmfashion
0161ec8717f129433271a796a3d3a6b540b005a3
[ "Apache-2.0" ]
null
null
null
from .checkpoint import init_weights_from from .image import get_img_tensor from .registry import Registry, build_from_cfg __all__ = ['Registry', 'build_from_cfg', 'get_img_tensor', 'init_weights_from']
34
79
0.813725
43e621232b5246ba69c205feefb662e8dde27da2
750
ts
TypeScript
src/resolvers/vehicle.ts
nnance/swapi-apollo
de450d4c42b42c61d194b152122b7ba45b0fa62c
[ "ISC" ]
38
2016-07-29T15:52:46.000Z
2020-08-08T13:12:20.000Z
src/resolvers/vehicle.ts
nnance/swapi-apollo
de450d4c42b42c61d194b152122b7ba45b0fa62c
[ "ISC" ]
2
2016-08-16T22:54:33.000Z
2016-12-05T14:57:55.000Z
src/resolvers/vehicle.ts
nnance/swapi-apollo
de450d4c42b42c61d194b152122b7ba45b0fa62c
[ "ISC" ]
12
2016-07-11T23:00:09.000Z
2020-06-25T10:18:34.000Z
import { getPageFetcher } from '../connectors/swapi' const path = '/vehicles/' export default (fetch) => ({ RootQuery: { allVehicles: (_, params) => getPageFetcher(fetch)(path, params.offset, params.limit), vehicle: (_, params) => fetch(params.id || `${path}${params.vehicleID}/`), }, Vehicle: { id: (vehicle) => vehicle.url, costInCredits: (vehicle) => vehicle.cost_in_credits, maxAtmospheringSpeed: (vehicle) => vehicle.max_atmosphering_speed, cargoCapacity: (vehicle) => vehicle.cargo_capacity, vehicleClass: (vehicle) => vehicle.vehicle_class, pilots: (vehicle, _, context) => context.loader.loadMany(vehicle.pilots), films: (vehicle, _, context) => context.loader.loadMany(vehicle.films), }, })
37.5
91
0.673333
1c093621fcff5bf8a907495fabbc3130d854103f
2,080
sh
Shell
Linux/Ubuntu/vps_py.sh
ivitan/vimrc
95841da10b8be3e7eb0fc6970bb2ca961b778f9a
[ "MIT" ]
1
2020-02-11T10:21:06.000Z
2020-02-11T10:21:06.000Z
Linux/Ubuntu/vps_py.sh
ivitan/UnixConfig
95841da10b8be3e7eb0fc6970bb2ca961b778f9a
[ "MIT" ]
null
null
null
Linux/Ubuntu/vps_py.sh
ivitan/UnixConfig
95841da10b8be3e7eb0fc6970bb2ca961b778f9a
[ "MIT" ]
1
2021-01-25T03:47:19.000Z
2021-01-25T03:47:19.000Z
#!/usr/bin/env bash # !!!note: use "source vps_py.sh" to execute # pyenv need sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \ libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev # https://github.com/yyuu/pyenv curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash cp ./ubuntu_zshenv ~/.zshenv #exec $SHELL alias pyenv="~/.pyenv/bin/pyenv" pyenv install 2.7.11 pyenv install 3.5.0 # https://github.com/yyuu/pyenv-virtualenv pyenv virtualenv 2.7.11 pyenv_2.7.11 pyenv virtualenv 3.5.0 pyenv_3.5.0 mkdir -p ~/project/pyenv_2.7.11 mkdir -p ~/project/pyenv_3.5.0 #for python #export EDITOR=vim #export PYTHONIOENCODING=UTF-8 # for python moidfy rc file bashrc or zshrc sudo apt-get install -y build-essential libssl-dev libevent-dev libjpeg-dev libxml2-dev libxslt-dev build-dep libpq-dev sudo apt-get install -y python-pip sudo apt-get install -y python-distribute sudo apt-get install -y python-dev sudo apt-get install -y ipython sudo apt-get install -y zlib1g-dev sudo apt-get install -y libudev-dev sudo apt-get install -y libffi-dev # for brycpt # https://github.com/docker-library/buildpack-deps/blob/e7534be05255522954f50542ebf9c5f06485838d/jessie/Dockerfile sudo apt-get install -y --no-install-recommends \ autoconf \ automake \ bzip2 \ file \ g++ \ gcc \ imagemagick \ libbz2-dev \ libc6-dev \ libcurl4-openssl-dev \ libdb-dev \ libevent-dev \ libffi-dev \ libgeoip-dev \ libglib2.0-dev \ libjpeg-dev \ liblzma-dev \ libmagickcore-dev \ libmagickwand-dev \ libmysqlclient-dev \ libncurses-dev \ libpng-dev \ libpq-dev \ libreadline-dev \ libsqlite3-dev \ libssl-dev \ libtool \ libwebp-dev \ libxml2-dev \ libxslt-dev \ libyaml-dev \ make \ patch \ xz-utils \ zlib1g-dev \
27.368421
119
0.652885
b0ee70154108e7598c880b34c6336f4ce901fbad
486
h
C
Examples/NeoEfx_Subclass/NeoSubclassWindow.h
HiFashionTech/NeoEffects
b48b3169f72a27b32b55f8c1dca3801343c3bf31
[ "Apache-2.0" ]
4
2015-11-19T07:35:13.000Z
2020-05-11T14:54:05.000Z
Examples/NeoEfx_Subclass/NeoSubclassWindow.h
HiFashionTech/NeoEffects
b48b3169f72a27b32b55f8c1dca3801343c3bf31
[ "Apache-2.0" ]
2
2016-11-07T02:21:29.000Z
2016-12-07T11:05:26.000Z
Examples/NeoEfx_Subclass/NeoSubclassWindow.h
HiFashionTech/NeoEffects
b48b3169f72a27b32b55f8c1dca3801343c3bf31
[ "Apache-2.0" ]
null
null
null
// NeoSubclassWindow - a subclass of NeoWindow to add rainbow efx // effect is taken from the Adafruit_NeoPixel Library's strandtest example #include "NeoEffects.h" #include "NeoWindow.h" class NeoSubclassWindow : public NeoWindow { public: NeoSubclassWindow(NeoStrip *strip, int startPixel, int len); void setNewRainbowEfx(uint16_t wait, int type); // type 0 or 1; 1 evenly distributes color private: void newRainbowEfxUpdate(void); int curColor; int rainbowType; };
27
92
0.761317
ee906b0c31fe9627a4d53fa55ef0a34e340c9cb4
11,473
go
Go
sdk/go/aws/dataexchange/dataSet.go
dmelo/pulumi-aws
dd1a08d1fb93bab0d046aa410ca660f05ca0a58c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/go/aws/dataexchange/dataSet.go
dmelo/pulumi-aws
dd1a08d1fb93bab0d046aa410ca660f05ca0a58c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/go/aws/dataexchange/dataSet.go
dmelo/pulumi-aws
dd1a08d1fb93bab0d046aa410ca660f05ca0a58c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package dataexchange import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Provides a resource to manage AWS Data Exchange DataSets. // // ## Example Usage // // ```go // package main // // import ( // "github.com/pulumi/pulumi-aws/sdk/v4/go/aws/dataexchange" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // _, err := dataexchange.NewDataSet(ctx, "example", &dataexchange.DataSetArgs{ // AssetType: pulumi.String("S3_SNAPSHOT"), // Description: pulumi.String("example"), // }) // if err != nil { // return err // } // return nil // }) // } // ``` // // ## Import // // DataExchange DataSets can be imported by their arn // // ```sh // $ pulumi import aws:dataexchange/dataSet:DataSet example arn:aws:dataexchange:us-west-2:123456789012:data-sets/4fa784c7-ccb4-4dbf-ba4f-02198320daa1 // ``` type DataSet struct { pulumi.CustomResourceState // The Amazon Resource Name of this data set. Arn pulumi.StringOutput `pulumi:"arn"` // The type of asset that is added to a data set. Valid values are: `S3_SNAPSHOT`, `REDSHIFT_DATA_SHARE`, and `API_GATEWAY_API`. AssetType pulumi.StringOutput `pulumi:"assetType"` // A description for the data set. Description pulumi.StringOutput `pulumi:"description"` // The name of the data set. Name pulumi.StringOutput `pulumi:"name"` // A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. Tags pulumi.StringMapOutput `pulumi:"tags"` // A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). TagsAll pulumi.StringMapOutput `pulumi:"tagsAll"` } // NewDataSet registers a new resource with the given unique name, arguments, and options. func NewDataSet(ctx *pulumi.Context, name string, args *DataSetArgs, opts ...pulumi.ResourceOption) (*DataSet, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.AssetType == nil { return nil, errors.New("invalid value for required argument 'AssetType'") } if args.Description == nil { return nil, errors.New("invalid value for required argument 'Description'") } var resource DataSet err := ctx.RegisterResource("aws:dataexchange/dataSet:DataSet", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetDataSet gets an existing DataSet resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetDataSet(ctx *pulumi.Context, name string, id pulumi.IDInput, state *DataSetState, opts ...pulumi.ResourceOption) (*DataSet, error) { var resource DataSet err := ctx.ReadResource("aws:dataexchange/dataSet:DataSet", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering DataSet resources. type dataSetState struct { // The Amazon Resource Name of this data set. Arn *string `pulumi:"arn"` // The type of asset that is added to a data set. Valid values are: `S3_SNAPSHOT`, `REDSHIFT_DATA_SHARE`, and `API_GATEWAY_API`. AssetType *string `pulumi:"assetType"` // A description for the data set. Description *string `pulumi:"description"` // The name of the data set. Name *string `pulumi:"name"` // A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. Tags map[string]string `pulumi:"tags"` // A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). TagsAll map[string]string `pulumi:"tagsAll"` } type DataSetState struct { // The Amazon Resource Name of this data set. Arn pulumi.StringPtrInput // The type of asset that is added to a data set. Valid values are: `S3_SNAPSHOT`, `REDSHIFT_DATA_SHARE`, and `API_GATEWAY_API`. AssetType pulumi.StringPtrInput // A description for the data set. Description pulumi.StringPtrInput // The name of the data set. Name pulumi.StringPtrInput // A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. Tags pulumi.StringMapInput // A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). TagsAll pulumi.StringMapInput } func (DataSetState) ElementType() reflect.Type { return reflect.TypeOf((*dataSetState)(nil)).Elem() } type dataSetArgs struct { // The type of asset that is added to a data set. Valid values are: `S3_SNAPSHOT`, `REDSHIFT_DATA_SHARE`, and `API_GATEWAY_API`. AssetType string `pulumi:"assetType"` // A description for the data set. Description string `pulumi:"description"` // The name of the data set. Name *string `pulumi:"name"` // A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. Tags map[string]string `pulumi:"tags"` // A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). TagsAll map[string]string `pulumi:"tagsAll"` } // The set of arguments for constructing a DataSet resource. type DataSetArgs struct { // The type of asset that is added to a data set. Valid values are: `S3_SNAPSHOT`, `REDSHIFT_DATA_SHARE`, and `API_GATEWAY_API`. AssetType pulumi.StringInput // A description for the data set. Description pulumi.StringInput // The name of the data set. Name pulumi.StringPtrInput // A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. Tags pulumi.StringMapInput // A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). TagsAll pulumi.StringMapInput } func (DataSetArgs) ElementType() reflect.Type { return reflect.TypeOf((*dataSetArgs)(nil)).Elem() } type DataSetInput interface { pulumi.Input ToDataSetOutput() DataSetOutput ToDataSetOutputWithContext(ctx context.Context) DataSetOutput } func (*DataSet) ElementType() reflect.Type { return reflect.TypeOf((**DataSet)(nil)).Elem() } func (i *DataSet) ToDataSetOutput() DataSetOutput { return i.ToDataSetOutputWithContext(context.Background()) } func (i *DataSet) ToDataSetOutputWithContext(ctx context.Context) DataSetOutput { return pulumi.ToOutputWithContext(ctx, i).(DataSetOutput) } // DataSetArrayInput is an input type that accepts DataSetArray and DataSetArrayOutput values. // You can construct a concrete instance of `DataSetArrayInput` via: // // DataSetArray{ DataSetArgs{...} } type DataSetArrayInput interface { pulumi.Input ToDataSetArrayOutput() DataSetArrayOutput ToDataSetArrayOutputWithContext(context.Context) DataSetArrayOutput } type DataSetArray []DataSetInput func (DataSetArray) ElementType() reflect.Type { return reflect.TypeOf((*[]*DataSet)(nil)).Elem() } func (i DataSetArray) ToDataSetArrayOutput() DataSetArrayOutput { return i.ToDataSetArrayOutputWithContext(context.Background()) } func (i DataSetArray) ToDataSetArrayOutputWithContext(ctx context.Context) DataSetArrayOutput { return pulumi.ToOutputWithContext(ctx, i).(DataSetArrayOutput) } // DataSetMapInput is an input type that accepts DataSetMap and DataSetMapOutput values. // You can construct a concrete instance of `DataSetMapInput` via: // // DataSetMap{ "key": DataSetArgs{...} } type DataSetMapInput interface { pulumi.Input ToDataSetMapOutput() DataSetMapOutput ToDataSetMapOutputWithContext(context.Context) DataSetMapOutput } type DataSetMap map[string]DataSetInput func (DataSetMap) ElementType() reflect.Type { return reflect.TypeOf((*map[string]*DataSet)(nil)).Elem() } func (i DataSetMap) ToDataSetMapOutput() DataSetMapOutput { return i.ToDataSetMapOutputWithContext(context.Background()) } func (i DataSetMap) ToDataSetMapOutputWithContext(ctx context.Context) DataSetMapOutput { return pulumi.ToOutputWithContext(ctx, i).(DataSetMapOutput) } type DataSetOutput struct{ *pulumi.OutputState } func (DataSetOutput) ElementType() reflect.Type { return reflect.TypeOf((**DataSet)(nil)).Elem() } func (o DataSetOutput) ToDataSetOutput() DataSetOutput { return o } func (o DataSetOutput) ToDataSetOutputWithContext(ctx context.Context) DataSetOutput { return o } type DataSetArrayOutput struct{ *pulumi.OutputState } func (DataSetArrayOutput) ElementType() reflect.Type { return reflect.TypeOf((*[]*DataSet)(nil)).Elem() } func (o DataSetArrayOutput) ToDataSetArrayOutput() DataSetArrayOutput { return o } func (o DataSetArrayOutput) ToDataSetArrayOutputWithContext(ctx context.Context) DataSetArrayOutput { return o } func (o DataSetArrayOutput) Index(i pulumi.IntInput) DataSetOutput { return pulumi.All(o, i).ApplyT(func(vs []interface{}) *DataSet { return vs[0].([]*DataSet)[vs[1].(int)] }).(DataSetOutput) } type DataSetMapOutput struct{ *pulumi.OutputState } func (DataSetMapOutput) ElementType() reflect.Type { return reflect.TypeOf((*map[string]*DataSet)(nil)).Elem() } func (o DataSetMapOutput) ToDataSetMapOutput() DataSetMapOutput { return o } func (o DataSetMapOutput) ToDataSetMapOutputWithContext(ctx context.Context) DataSetMapOutput { return o } func (o DataSetMapOutput) MapIndex(k pulumi.StringInput) DataSetOutput { return pulumi.All(o, k).ApplyT(func(vs []interface{}) *DataSet { return vs[0].(map[string]*DataSet)[vs[1].(string)] }).(DataSetOutput) } func init() { pulumi.RegisterInputType(reflect.TypeOf((*DataSetInput)(nil)).Elem(), &DataSet{}) pulumi.RegisterInputType(reflect.TypeOf((*DataSetArrayInput)(nil)).Elem(), DataSetArray{}) pulumi.RegisterInputType(reflect.TypeOf((*DataSetMapInput)(nil)).Elem(), DataSetMap{}) pulumi.RegisterOutputType(DataSetOutput{}) pulumi.RegisterOutputType(DataSetArrayOutput{}) pulumi.RegisterOutputType(DataSetMapOutput{}) }
39.02381
284
0.760481
08dbc523b11432dc57ad6459ae0396f496e0dc93
949
sql
SQL
coral-trino/src/test/resources/product_test_cases_expected/q25_expected.sql
NobiGo/coral
a662f800b761de50a67cb7d98c2c25bb5b78014a
[ "BSD-2-Clause" ]
387
2020-03-19T19:37:55.000Z
2022-03-31T00:14:48.000Z
coral-trino/src/test/resources/product_test_cases_expected/q25_expected.sql
NobiGo/coral
a662f800b761de50a67cb7d98c2c25bb5b78014a
[ "BSD-2-Clause" ]
127
2020-06-30T01:14:11.000Z
2022-03-25T21:20:18.000Z
coral-trino/src/test/resources/product_test_cases_expected/q25_expected.sql
NobiGo/coral
a662f800b761de50a67cb7d98c2c25bb5b78014a
[ "BSD-2-Clause" ]
104
2020-03-19T19:28:45.000Z
2022-03-28T02:40:21.000Z
select `i_item_id`, `i_item_desc`, `s_store_id`, `s_store_name`, sum(`ss_net_profit`) as `store_sales_profit`, sum(`sr_net_loss`) as `store_returns_loss`, sum(`cs_net_profit`) as `catalog_sales_profit` from `store_sales` where `d1`.`d_moy` = 4 and `d1`.`d_year` = 2001 and `d1`.`d_date_sk` = `ss_sold_date_sk` and `i_item_sk` = `ss_item_sk` and `s_store_sk` = `ss_store_sk` and `ss_customer_sk` = `sr_customer_sk` and `ss_item_sk` = `sr_item_sk` and `ss_ticket_number` = `sr_ticket_number` and `sr_returned_date_sk` = `d2`.`d_date_sk` and `d2`.`d_moy` between asymmetric 4 and 10 and `d2`.`d_year` = 2001 and `sr_customer_sk` = `cs_bill_customer_sk` and `sr_item_sk` = `cs_item_sk` and `cs_sold_date_sk` = `d3`.`d_date_sk` and `d3`.`d_moy` between asymmetric 4 and 10 and `d3`.`d_year` = 2001 group by `i_item_id`, `i_item_desc`, `s_store_id`, `s_store_name` order by `i_item_id`, `i_item_desc`, `s_store_id`, `s_store_name` fetch next 100 rows only
158.166667
571
0.735511
be3d3b846c0537951d42938771a007ef8e07fad3
142
ts
TypeScript
kata/8 kyu/how-many-lightsabers-do-you-own/index.ts
marcobiedermann/codewars
59ff0eac8d8787f23558266c51743a78ffb868c8
[ "MIT" ]
1
2022-01-25T13:57:47.000Z
2022-01-25T13:57:47.000Z
kata/8 kyu/how-many-lightsabers-do-you-own/index.ts
marcobiedermann/codewars
59ff0eac8d8787f23558266c51743a78ffb868c8
[ "MIT" ]
222
2020-02-03T05:02:05.000Z
2022-03-21T09:47:36.000Z
kata/8 kyu/how-many-lightsabers-do-you-own/index.ts
marcobiedermann/codewars
59ff0eac8d8787f23558266c51743a78ffb868c8
[ "MIT" ]
1
2020-02-21T14:30:06.000Z
2020-02-21T14:30:06.000Z
function howManyLightsabersDoYouOwn(name?: string): 18 | 0 { return name === 'Zach' ? 18 : 0; } export default howManyLightsabersDoYouOwn;
23.666667
60
0.725352
9756f46db2129b937daffd6ec1105e8a7308b53e
47
ts
TypeScript
angular-app/src/app/model/domain.model.ts
pi-id/etl-framework
931530c4cdde6d8f3fa47ed058202dac819caef9
[ "MIT" ]
null
null
null
angular-app/src/app/model/domain.model.ts
pi-id/etl-framework
931530c4cdde6d8f3fa47ed058202dac819caef9
[ "MIT" ]
1
2020-08-26T13:07:14.000Z
2020-08-27T14:25:30.000Z
angular-app/src/app/model/domain.model.ts
pi-id/etl-framework
931530c4cdde6d8f3fa47ed058202dac819caef9
[ "MIT" ]
null
null
null
export class Domain{ domain_value_value; }
15.666667
24
0.744681
37a2e63e039db6948eb9c6110c63c7ee9adcffcd
82
sql
SQL
migrations/2019-10-05-003235_add_prefs_leaderboard/up.sql
umpyre-code/rolodex
3ed2072d82a47e6b3c19d39a255baee8e49399e1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
migrations/2019-10-05-003235_add_prefs_leaderboard/up.sql
umpyre-code/rolodex
3ed2072d82a47e6b3c19d39a255baee8e49399e1
[ "ECL-2.0", "Apache-2.0" ]
173
2019-10-10T04:17:19.000Z
2021-07-31T04:12:01.000Z
migrations/2019-10-05-003235_add_prefs_leaderboard/up.sql
umpyre-code/rolodex
3ed2072d82a47e6b3c19d39a255baee8e49399e1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
ALTER TABLE prefs ADD COLUMN include_in_leaderboard BOOLEAN NOT NULL DEFAULT TRUE
41
81
0.865854
da23d791de0b4ab79668fe2ff08b819dcb9f497a
37,255
php
PHP
src/SwedbankPay/Core/Adapter/WC_Adapter.php
Frojd/swedbank-pay-woocommerce-core
854bd39f97a6ab6d3f011321fd5378ea17699c46
[ "Apache-2.0" ]
null
null
null
src/SwedbankPay/Core/Adapter/WC_Adapter.php
Frojd/swedbank-pay-woocommerce-core
854bd39f97a6ab6d3f011321fd5378ea17699c46
[ "Apache-2.0" ]
null
null
null
src/SwedbankPay/Core/Adapter/WC_Adapter.php
Frojd/swedbank-pay-woocommerce-core
854bd39f97a6ab6d3f011321fd5378ea17699c46
[ "Apache-2.0" ]
null
null
null
<?php namespace SwedbankPay\Core\Adapter; use SwedbankPay\Core\Exception; use SwedbankPay\Core\Log\LogLevel; use SwedbankPay\Core\PaymentAdapter; use SwedbankPay\Core\PaymentAdapterInterface; use SwedbankPay\Core\ConfigurationInterface; use SwedbankPay\Core\Order\PlatformUrlsInterface; use SwedbankPay\Core\OrderInterface; use SwedbankPay\Core\OrderItemInterface; use SwedbankPay\Core\Order\RiskIndicatorInterface; use SwedbankPay\Core\Order\PayeeInfoInterface; use WC_Payment_Gateway; use WC_Log_Levels; use WC_Order_Item_Product; use WC_Order_Item_Fee; use WC_Payment_Token_Swedbank_Pay; /** * Class WC_Adapter * @package SwedbankPay\Core\Adapter * @SuppressWarnings(PHPMD.CamelCaseClassName) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ // phpcs:ignore class WC_Adapter extends PaymentAdapter implements PaymentAdapterInterface { /** * @var WC_Payment_Gateway */ private $gateway; /** * WC_Adapter constructor. * * @param WC_Payment_Gateway $gateway */ public function __construct(WC_Payment_Gateway $gateway) { $this->gateway = $gateway; } /** * Log a message. * * @param $level * @param $message * @param array $context * * @see WC_Log_Levels */ public function log($level, $message, array $context = array()) { $logger = wc_get_logger(); if (!is_string($message)) { $message = var_export($message, true); } $logger->log( $level, sprintf('[%s] %s [%s]', $level, $message, count($context) > 0 ? var_export($context, true) : ''), array_merge( $context, array( 'source' => $this->gateway->id, '_legacy' => true, ) ) ); } /** * Get Initiating System User Agent. * * @return string */ public function getInitiatingSystemUserAgent() { include_once(ABSPATH . 'wp-admin/includes/plugin.php'); switch ($this->gateway->id) { case 'payex_checkout': $plugins = get_plugins(); foreach ($plugins as $file => $plugin) { if (strpos($file, 'swedbank-pay-woocommerce-checkout.php') !== false) { return 'swedbankpay-woocommerce-checkout/' . $plugin['Version']; } } return ''; default: $plugins = get_plugins(); foreach ($plugins as $file => $plugin) { if (strpos($file, 'swedbank-pay-woocommerce-payments.php') !== false) { return 'swedbankpay-woocommerce-payments/' . $plugin['Version']; } } return ''; } } /** * Get Adapter Configuration. * * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getConfiguration() { // phpcs:disable return array( ConfigurationInterface::DEBUG => 'yes' === $this->gateway->debug, ConfigurationInterface::ACCESS_TOKEN => $this->gateway->access_token, ConfigurationInterface::PAYEE_ID => $this->gateway->payee_id, ConfigurationInterface::PAYEE_NAME => get_bloginfo('name'), ConfigurationInterface::MODE => 'yes' === $this->gateway->testmode, ConfigurationInterface::AUTO_CAPTURE => 'yes' === $this->gateway->auto_capture, ConfigurationInterface::SUBSITE => $this->gateway->subsite, ConfigurationInterface::LANGUAGE => $this->gateway->culture, ConfigurationInterface::CHECKOUT_METHOD => $this->gateway->method, ConfigurationInterface::SAVE_CC => property_exists($this->gateway, 'save_cc') ? 'yes' === $this->gateway->save_cc : false, ConfigurationInterface::TERMS_URL => property_exists($this->gateway, 'terms_url') ? $this->gateway->terms_url : '', ConfigurationInterface::LOGO_URL => property_exists($this->gateway, 'logo_url') ? $this->gateway->logo_url : '', ConfigurationInterface::USE_PAYER_INFO => property_exists($this->gateway, 'use_payer_info') ? 'yes' === $this->gateway->use_payer_info : true, ConfigurationInterface::USE_CARDHOLDER_INFO => property_exists($this->gateway, 'use_cardholder_info') ? 'yes' === $this->gateway->use_cardholder_info : true, ConfigurationInterface::REJECT_CREDIT_CARDS => property_exists($this->gateway, 'reject_credit_cards') ? 'yes' === $this->gateway->reject_credit_cards : true, ConfigurationInterface::REJECT_DEBIT_CARDS => property_exists($this->gateway, 'reject_debit_cards') ? 'yes' === $this->gateway->reject_debit_cards : true, ConfigurationInterface::REJECT_CONSUMER_CARDS => property_exists($this->gateway, 'reject_consumer_cards') ? 'yes' === $this->gateway->reject_consumer_cards : true, ConfigurationInterface::REJECT_CORPORATE_CARDS => property_exists($this->gateway, 'reject_corporate_cards') ? 'yes' === $this->gateway->reject_corporate_cards : true, ); // phpcs:enable } /** * Get Platform Urls of Actions of Order (complete, cancel, callback urls). * * @param mixed $orderId * * @return array */ public function getPlatformUrls($orderId) { $order = wc_get_order($orderId); $callbackUrl = add_query_arg( array( 'order_id' => $order->get_id(), 'key' => $order->get_order_key(), ), WC()->api_request_url(get_class($this->gateway)) ); if ($this->gateway->is_new_credit_card) { return array( PlatformUrlsInterface::COMPLETE_URL => add_query_arg( 'action', 'swedbank_card_store', admin_url('admin-ajax.php') ), PlatformUrlsInterface::CANCEL_URL => wc_get_account_endpoint_url('payment-methods'), PlatformUrlsInterface::CALLBACK_URL => $callbackUrl, PlatformUrlsInterface::TERMS_URL => $this->getConfiguration()[ConfigurationInterface::TERMS_URL], PlatformUrlsInterface::LOGO_URL => $this->getConfiguration()[ConfigurationInterface::LOGO_URL], PlatformUrlsInterface::PAYMENT_URL => add_query_arg(array('payment_url' => '1'), wc_get_checkout_url()) ); } if ($this->gateway->is_change_credit_card) { return array( PlatformUrlsInterface::COMPLETE_URL => add_query_arg( array( 'verify' => 'true', 'key' => $order->get_order_key(), ), $this->gateway->get_return_url($order) ), PlatformUrlsInterface::CANCEL_URL => $order->get_cancel_order_url_raw(), PlatformUrlsInterface::CALLBACK_URL => $callbackUrl, PlatformUrlsInterface::TERMS_URL => $this->getConfiguration()[ConfigurationInterface::TERMS_URL], PlatformUrlsInterface::LOGO_URL => $this->getConfiguration()[ConfigurationInterface::LOGO_URL], PlatformUrlsInterface::PAYMENT_URL => add_query_arg(array('payment_url' => '1'), wc_get_checkout_url()) ); } return array( PlatformUrlsInterface::COMPLETE_URL => $this->gateway->get_return_url($order), PlatformUrlsInterface::CANCEL_URL => $order->get_cancel_order_url_raw(), PlatformUrlsInterface::CALLBACK_URL => $callbackUrl, PlatformUrlsInterface::TERMS_URL => $this->getConfiguration()[ConfigurationInterface::TERMS_URL], PlatformUrlsInterface::LOGO_URL => $this->getConfiguration()[ConfigurationInterface::LOGO_URL], PlatformUrlsInterface::PAYMENT_URL => add_query_arg(array('payment_url' => '1'), wc_get_checkout_url()) ); } /** * Get Order Data. * * @param mixed $orderId * * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.ElseExpression) */ public function getOrderData($orderId) { $order = wc_get_order($orderId); // Force a new DB read (and update cache) for meta data. $order->read_meta_data(true); $countries = WC()->countries->countries; // Order Info $info = $this->getOrderInfo($order); // Get order items $items = array(); // Does an order need shipping? $needsShipping = false; foreach ($order->get_items() as $orderItem) { /** @var WC_Order_Item_Product $orderItem */ $price = $order->get_line_subtotal($orderItem, false, false); $priceWithTax = $order->get_line_subtotal($orderItem, true, false); $tax = $priceWithTax - $price; $taxPercent = ($tax > 0) ? round(100 / ($price / $tax)) : 0; $qty = $orderItem->get_quantity(); $image = wp_get_attachment_image_src($orderItem->get_product()->get_image_id(), 'full'); if ($image) { $image = array_shift($image); } else { $image = wc_placeholder_img_src('full'); } if (null === parse_url($image, PHP_URL_SCHEME) && mb_substr($image, 0, mb_strlen(WP_CONTENT_URL), 'UTF-8') === WP_CONTENT_URL ) { $image = wp_guess_url() . $image; } // Get Product Class $productClass = get_post_meta($orderItem->get_product()->get_id(), '_sb_product_class', true); if (empty($productClass)) { $productClass = 'ProductGroup1'; } // Get Product Sku $productReference = trim(str_replace(array(' ', '.', ','), '-', $orderItem->get_product()->get_sku())); if (empty($productReference)) { $productReference = wp_generate_password(12, false); } $productName = trim($orderItem->get_name()); // Check is product shippable $product = $orderItem->get_product(); if ($product && $product->needs_shipping()) { $needsShipping = true; } $items[] = array( // The field Reference must match the regular expression '[\\w-]*' OrderItemInterface::FIELD_REFERENCE => $productReference, OrderItemInterface::FIELD_NAME => !empty($productName) ? $productName : '-', OrderItemInterface::FIELD_TYPE => OrderItemInterface::TYPE_PRODUCT, OrderItemInterface::FIELD_CLASS => $productClass, OrderItemInterface::FIELD_ITEM_URL => $orderItem->get_product()->get_permalink(), OrderItemInterface::FIELD_IMAGE_URL => $image, OrderItemInterface::FIELD_DESCRIPTION => $orderItem->get_name(), OrderItemInterface::FIELD_QTY => $qty, OrderItemInterface::FIELD_QTY_UNIT => 'pcs', OrderItemInterface::FIELD_UNITPRICE => round($priceWithTax / $qty * 100), OrderItemInterface::FIELD_VAT_PERCENT => round($taxPercent * 100), OrderItemInterface::FIELD_AMOUNT => round($priceWithTax * 100), OrderItemInterface::FIELD_VAT_AMOUNT => round($tax * 100), ); } // Add Shipping Line if ((float)$order->get_shipping_total() > 0) { $shipping = $order->get_shipping_total(); $tax = $order->get_shipping_tax(); $shippingWithTax = $shipping + $tax; $taxPercent = ($tax > 0) ? round(100 / ($shipping / $tax)) : 0; $shippingMethod = trim($order->get_shipping_method()); $items[] = array( OrderItemInterface::FIELD_REFERENCE => 'shipping', OrderItemInterface::FIELD_NAME => !empty($shippingMethod) ? $shippingMethod : __( 'Shipping', 'woocommerce' ), OrderItemInterface::FIELD_TYPE => OrderItemInterface::TYPE_SHIPPING, OrderItemInterface::FIELD_CLASS => 'ProductGroup1', OrderItemInterface::FIELD_QTY => 1, OrderItemInterface::FIELD_QTY_UNIT => 'pcs', OrderItemInterface::FIELD_UNITPRICE => round($shippingWithTax * 100), OrderItemInterface::FIELD_VAT_PERCENT => round($taxPercent * 100), OrderItemInterface::FIELD_AMOUNT => round($shippingWithTax * 100), OrderItemInterface::FIELD_VAT_AMOUNT => round($tax * 100), ); } // Add fee lines foreach ($order->get_fees() as $orderFee) { /** @var WC_Order_Item_Fee $orderFee */ $fee = $orderFee->get_total(); $tax = $orderFee->get_total_tax(); $feeWithTax = $fee + $tax; $taxPercent = ($tax > 0) ? round(100 / ($fee / $tax)) : 0; $items[] = array( OrderItemInterface::FIELD_REFERENCE => 'fee', OrderItemInterface::FIELD_NAME => $orderFee->get_name(), OrderItemInterface::FIELD_TYPE => OrderItemInterface::TYPE_OTHER, OrderItemInterface::FIELD_CLASS => 'ProductGroup1', OrderItemInterface::FIELD_QTY => 1, OrderItemInterface::FIELD_QTY_UNIT => 'pcs', OrderItemInterface::FIELD_UNITPRICE => round($feeWithTax * 100), OrderItemInterface::FIELD_VAT_PERCENT => round($taxPercent * 100), OrderItemInterface::FIELD_AMOUNT => round($feeWithTax * 100), OrderItemInterface::FIELD_VAT_AMOUNT => round($tax * 100), ); } // Add discount line if ($order->get_total_discount(false) > 0) { $discount = abs($order->get_total_discount(true)); $discountWithTax = abs($order->get_total_discount(false)); $tax = $discountWithTax - $discount; $taxPercent = ($tax > 0) ? round(100 / ($discount / $tax)) : 0; $items[] = array( OrderItemInterface::FIELD_REFERENCE => 'discount', OrderItemInterface::FIELD_NAME => __('Discount', 'swedbank-pay-woocommerce-payments'), OrderItemInterface::FIELD_TYPE => OrderItemInterface::TYPE_DISCOUNT, OrderItemInterface::FIELD_CLASS => 'ProductGroup1', OrderItemInterface::FIELD_QTY => 1, OrderItemInterface::FIELD_QTY_UNIT => 'pcs', OrderItemInterface::FIELD_UNITPRICE => round(-100 * $discountWithTax), OrderItemInterface::FIELD_VAT_PERCENT => round(100 * $taxPercent), OrderItemInterface::FIELD_AMOUNT => round(-100 * $discountWithTax), OrderItemInterface::FIELD_VAT_AMOUNT => round(-100 * $tax), ); } // Payer reference // Get Customer UUID $userId = $order->get_customer_id(); if ($userId > 0) { $payerReference = get_user_meta($userId, '_payex_customer_uuid', true); if (empty($payerReference)) { $payerReference = $this->getUuid($userId); update_user_meta($userId, '_payex_customer_uuid', $payerReference); } } else { $payerReference = $this->getUuid(uniqid($order->get_billing_email())); } $shippingCountry = isset($countries[$order->get_shipping_country()]) ? $countries[$order->get_shipping_country()] : ''; $billingCountry = isset($countries[$order->get_billing_country()]) ? $countries[$order->get_billing_country()] : ''; $items = apply_filters('swedbank_pay_order_items', $items, $order); return array( OrderInterface::PAYMENT_METHOD => $this->getPaymentMethod($orderId), OrderInterface::ORDER_ID => $order->get_id(), OrderInterface::AMOUNT => apply_filters( 'swedbank_pay_order_amount', $order->get_total(), $items, $order ), OrderInterface::VAT_AMOUNT => apply_filters( 'swedbank_pay_order_vat', $info['vat_amount'], $items, $order ), OrderInterface::VAT_RATE => 0, // Can be different OrderInterface::SHIPPING_AMOUNT => 0, // @todo OrderInterface::SHIPPING_VAT_AMOUNT => 0, // @todo // phpcs:disable OrderInterface::DESCRIPTION => apply_filters( 'swedbank_pay_payment_description', sprintf( /* translators: 1: order id */ __('Order #%1$s', 'swedbank-pay-woocommerce-payments'), $order->get_order_number() ), $order ), // phpcs:enable OrderInterface::CURRENCY => $order->get_currency(), OrderInterface::STATUS => $this->getOrderStatus($orderId), OrderInterface::CREATED_AT => gmdate('Y-m-d H:i:s', $order->get_date_created()->getTimestamp()), OrderInterface::PAYMENT_ID => $order->get_meta('_payex_payment_id'), OrderInterface::PAYMENT_ORDER_ID => $order->get_meta('_payex_paymentorder_id'), OrderInterface::NEEDS_SAVE_TOKEN_FLAG => '1' === $order->get_meta('_payex_generate_token') && 0 === count($order->get_payment_tokens()), OrderInterface::NEEDS_SHIPPING => $needsShipping, OrderInterface::HTTP_ACCEPT => isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null, OrderInterface::HTTP_USER_AGENT => $order->get_customer_user_agent(), OrderInterface::BILLING_COUNTRY => $billingCountry, OrderInterface::BILLING_COUNTRY_CODE => $order->get_billing_country(), OrderInterface::BILLING_ADDRESS1 => $order->get_billing_address_1(), OrderInterface::BILLING_ADDRESS2 => $order->get_billing_address_2(), OrderInterface::BILLING_ADDRESS3 => null, OrderInterface::BILLING_CITY => $order->get_billing_city(), OrderInterface::BILLING_STATE => $order->get_billing_state(), OrderInterface::BILLING_POSTCODE => $order->get_billing_postcode(), OrderInterface::BILLING_PHONE => apply_filters( 'swedbank_pay_order_billing_phone', $order->get_billing_phone(), $order ), OrderInterface::BILLING_EMAIL => $order->get_billing_email(), OrderInterface::BILLING_FIRST_NAME => $order->get_billing_first_name(), OrderInterface::BILLING_LAST_NAME => $order->get_billing_last_name(), OrderInterface::SHIPPING_COUNTRY => $shippingCountry, OrderInterface::SHIPPING_COUNTRY_CODE => $order->get_shipping_country(), OrderInterface::SHIPPING_ADDRESS1 => $order->get_shipping_address_1(), OrderInterface::SHIPPING_ADDRESS2 => $order->get_shipping_address_2(), OrderInterface::SHIPPING_ADDRESS3 => null, OrderInterface::SHIPPING_CITY => $order->get_shipping_city(), OrderInterface::SHIPPING_STATE => $order->get_shipping_state(), OrderInterface::SHIPPING_POSTCODE => $order->get_shipping_postcode(), OrderInterface::SHIPPING_PHONE => apply_filters( 'swedbank_pay_order_billing_phone', $order->get_billing_phone(), $order ), OrderInterface::SHIPPING_EMAIL => $order->get_billing_email(), OrderInterface::SHIPPING_FIRST_NAME => $order->get_shipping_first_name(), OrderInterface::SHIPPING_LAST_NAME => $order->get_shipping_last_name(), OrderInterface::CUSTOMER_ID => (int)$order->get_customer_id(), OrderInterface::CUSTOMER_IP => $order->get_customer_ip_address(), OrderInterface::PAYER_REFERENCE => $payerReference, OrderInterface::ITEMS => $items, OrderInterface::LANGUAGE => $this->getConfiguration()[ConfigurationInterface::LANGUAGE], ); } /** * Get Risk Indicator of Order. * * @param mixed $orderId * * @return array * @SuppressWarnings(PHPMD.ElseExpression) */ public function getRiskIndicator($orderId) { $order = wc_get_order($orderId); $result = array(); // Downloadable if ($order->has_downloadable_item()) { // For electronic delivery, the email address to which the merchandise was delivered $result[RiskIndicatorInterface::DELIVERY_EMAIL_ADDRESS] = $order->get_billing_email(); // Electronic Delivery $result[RiskIndicatorInterface::DELIVERY_TIME_FRAME_INDICATOR] = '01'; // Digital goods, includes online services, electronic giftcards and redemption codes $result[RiskIndicatorInterface::SHIP_INDICATOR] = '05'; } // Shippable if ($order->needs_processing()) { // Two-day or more shipping $result['deliveryTimeFrameIndicator'] = '04'; // Compare billing and shipping addresses $billing = $order->get_address('billing'); $shipping = $order->get_address('shipping'); $diff = array_diff($billing, $shipping); if (0 === count($diff)) { // Ship to cardholder's billing address $result[RiskIndicatorInterface::SHIP_INDICATOR] = '01'; } else { // Ship to address that is different than cardholder's billing address $result[RiskIndicatorInterface::SHIP_INDICATOR] = '03'; } } // Is Gift Card $result[RiskIndicatorInterface::GIFT_CARD_PURCHASE] = false; // @todo Add features of WooThemes Order Delivery and Pre-Orders WooCommerce Extensions return apply_filters('swedbank_pay_risk_indicator', $result, $order, $this); } /** * Get Payee Info of Order. * * @param mixed $orderId * * @return array */ public function getPayeeInfo($orderId) { $order = wc_get_order($orderId); return array( PayeeInfoInterface::ORDER_REFERENCE => $order->get_id(), ); } /** * Check if order status can be updated. * * @param mixed $orderId * @param string $status * @param string|null $transactionNumber * @return bool */ public function canUpdateOrderStatus($orderId, $status, $transactionNumber = null) { if ($transactionNumber) { $order = wc_get_order($orderId); if ($order->get_transaction_id() === $transactionNumber) { $this->log( LogLevel::WARNING, sprintf( 'Unable to update order status of #%s (%s). Transaction #%s has been processed.', $orderId, $status, $transactionNumber ) ); return false; } } return true; } /** * Get Order Status. * * @param $orderId * * @return string * @see wc_get_order_statuses() * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getOrderStatus($orderId) { $order = wc_get_order($orderId); switch ($order->get_status()) { case 'checkout-draft': case 'pending': return OrderInterface::STATUS_PENDING; case 'on-hold': return OrderInterface::STATUS_AUTHORIZED; case 'active': case 'completed': case 'processing': return OrderInterface::STATUS_CAPTURED; case 'cancelled': return OrderInterface::STATUS_CANCELLED; case 'refunded': return OrderInterface::STATUS_REFUNDED; case 'failed': return OrderInterface::STATUS_FAILED; case 'pending-cancel': case 'expired': default: return OrderInterface::STATUS_UNKNOWN; } } /** * Update Order Status. * * @param mixed $orderId * @param string $status * @param string|null $message * @param mixed|null $transactionNumber * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ElseExpression) */ public function updateOrderStatus($orderId, $status, $message = null, $transactionNumber = null) { $order = wc_get_order($orderId); if ($transactionNumber) { $transactions = (array) $order->get_meta('_sb_transactions'); if (in_array($transactionNumber, $transactions)) { $this->log('info', 'Skip order status update', [$orderId, $transactionNumber]); return; } $transactions[] = $transactionNumber; $order->update_meta_data('_transaction_id', $transactions); $order->update_meta_data('_sb_transactions', $transactions); $order->save(); } switch ($status) { case OrderInterface::STATUS_PENDING: $order->update_meta_data('_payex_payment_state', $status); $order->update_status('on-hold', $message); break; case OrderInterface::STATUS_AUTHORIZED: $order->update_meta_data('_payex_payment_state', $status); $order->save(); // Reduce stock $orderStockReduced = $order->get_meta('_order_stock_reduced'); if (!$orderStockReduced) { wc_reduce_stock_levels($order->get_id()); } $order->update_status('on-hold', $message); break; case OrderInterface::STATUS_CAPTURED: $order->update_meta_data('_payex_payment_state', $status); $order->save(); $order->payment_complete($transactionNumber); $order->add_order_note($message); break; case OrderInterface::STATUS_CANCELLED: $order->update_meta_data('_payex_payment_state', $status); $order->save(); if (!$order->has_status('cancelled')) { $order->update_status('cancelled', $message); } else { $order->add_order_note($message); } break; case OrderInterface::STATUS_REFUNDED: // @todo Implement Refunds creation // @see wc_create_refund() $order->update_meta_data('_payex_payment_state', $status); $order->save(); if (!$order->has_status('refunded')) { $order->update_status('refunded', $message); } else { $order->add_order_note($message); } break; case OrderInterface::STATUS_FAILED: $order->update_status('failed', $message); break; } } /** * Set Payment Id to Order. * * @param mixed $orderId * @param string $paymentId * * @return void */ public function setPaymentId($orderId, $paymentId) { $order = wc_get_order($orderId); $order->update_meta_data('_payex_payment_id', $paymentId); $order->save(); clean_post_cache($order->get_id()); } /** * Set Payment Order Id to Order. * * @param mixed $orderId * @param string $paymentOrderId * * @return void */ public function setPaymentOrderId($orderId, $paymentOrderId) { $order = wc_get_order($orderId); $order->update_meta_data('_payex_paymentorder_id', $paymentOrderId); $order->save(); } /** * Add Order Note. * * @param mixed $orderId * @param string $message */ public function addOrderNote($orderId, $message) { $order = wc_get_order($orderId); $order->add_order_note($message); } /** * Get Payment Method. * * @param mixed $orderId * * @return string|null Returns method or null if not exists */ public function getPaymentMethod($orderId) { $order = wc_get_order($orderId); switch ($order->get_payment_method()) { case 'payex_checkout': return PaymentAdapterInterface::METHOD_CHECKOUT; case 'payex_psp_cc': return PaymentAdapterInterface::METHOD_CC; case 'payex_psp_invoice': return PaymentAdapterInterface::METHOD_INVOICE; case 'payex_psp_mobilepay': return PaymentAdapterInterface::METHOD_MOBILEPAY; case 'payex_psp_swish': return PaymentAdapterInterface::METHOD_SWISH; case 'payex_psp_trustly': return PaymentAdapterInterface::METHOD_TRUSTLY; case 'payex_psp_vipps': return PaymentAdapterInterface::METHOD_VIPPS; default: return null; } } /** * Save Transaction data. * * @param mixed $orderId * @param array $transactionData */ public function saveTransaction($orderId, array $transactionData = array()) { $this->gateway->transactions->import($transactionData, $orderId); } /** * Find for Transaction. * * @param $field * @param $value * * @return array */ public function findTransaction($field, $value) { return $this->gateway->transactions->get_by($field, $value, true); } /** * Save Payment Token. * * @param mixed $customerId * @param string $paymentToken * @param string $recurrenceToken * @param string $cardBrand * @param string $maskedPan * @param string $expiryDate * @param mixed|null $orderId */ public function savePaymentToken( $customerId, $paymentToken, $recurrenceToken, $cardBrand, $maskedPan, $expiryDate, $orderId = null ) { if (!property_exists($this->gateway, 'payment_token_class')) { return; } // Create Payment Token if (!is_string($this->gateway->payment_token_class) || !class_exists($this->gateway->payment_token_class, false)) { throw new Exception(__('Payment Token class is undefined.', 'swedbank-pay-woocommerce-payments')); } $expiryDate = explode('/', $expiryDate); $token = new $this->gateway->payment_token_class; $token->set_gateway_id($this->gateway->id); $token->set_token($paymentToken); $token->set_recurrence_token($recurrenceToken); $token->set_last4(substr($maskedPan, -4)); $token->set_expiry_year($expiryDate[1]); $token->set_expiry_month($expiryDate[0]); $token->set_card_type(strtolower($cardBrand)); $token->set_user_id($customerId); $token->set_masked_pan($maskedPan); $token->save(); if (!$token->get_id()) { throw new Exception(__('There was a problem adding the card.', 'swedbank-pay-woocommerce-payments')); } $this->log('info', 'Token has been saved', [$token->get_id()]); // Add payment token if ($orderId) { $order = wc_get_order($orderId); $order->add_payment_token($token); // Activate subscription if this is WC_Subscriptions if (function_exists('wcs_order_contains_subscription') && wcs_order_contains_subscription($order) && abs($order->get_total()) < 0.01 ) { $order->payment_complete(); } } } /** * Get Order Lines * * @param \WC_Order $order * * @return array */ private function getOrderItems($order) { $item = array(); foreach ($order->get_items() as $orderItem) { /** @var WC_Order_Item_Product $orderItem */ $price = $order->get_line_subtotal($orderItem, false, false); $priceWithTax = $order->get_line_subtotal($orderItem, true, false); $tax = $priceWithTax - $price; $taxPercent = ($tax > 0) ? round(100 / ($price / $tax)) : 0; $item[] = array( 'type' => 'product', 'name' => $orderItem->get_name(), 'qty' => $orderItem->get_quantity(), 'price_with_tax' => sprintf('%.2f', $priceWithTax), 'price_without_tax' => sprintf('%.2f', $price), 'tax_price' => sprintf('%.2f', $tax), 'tax_percent' => sprintf('%.2f', $taxPercent), ); }; // Add Shipping Line if ((float)$order->get_shipping_total() > 0) { $shipping = $order->get_shipping_total(); $tax = $order->get_shipping_tax(); $shippingWithTax = $shipping + $tax; $taxPercent = ($tax > 0) ? round(100 / ($shipping / $tax)) : 0; $item[] = array( 'type' => 'shipping', 'name' => $order->get_shipping_method(), 'qty' => 1, 'price_with_tax' => sprintf('%.2f', $shippingWithTax), 'price_without_tax' => sprintf('%.2f', $shipping), 'tax_price' => sprintf('%.2f', $tax), 'tax_percent' => sprintf('%.2f', $taxPercent), ); } // Add fee lines foreach ($order->get_fees() as $orderFee) { /** @var WC_Order_Item_Fee $orderFee */ $fee = $orderFee->get_total(); $tax = $orderFee->get_total_tax(); $feeWithTax = $fee + $tax; $taxPercent = ($tax > 0) ? round(100 / ($fee / $tax)) : 0; $item[] = array( 'type' => 'fee', 'name' => $orderFee->get_name(), 'qty' => 1, 'price_with_tax' => sprintf('%.2f', $feeWithTax), 'price_without_tax' => sprintf('%.2f', $fee), 'tax_price' => sprintf('%.2f', $tax), 'tax_percent' => sprintf('%.2f', $taxPercent), ); } // Add discount line if ($order->get_total_discount(false) > 0) { $discount = $order->get_total_discount(true); $discountWithTax = $order->get_total_discount(false); $tax = $discountWithTax - $discount; $taxPercent = ($tax > 0) ? round(100 / ($discount / $tax)) : 0; $item[] = array( 'type' => 'discount', 'name' => __('Discount', 'swedbank-pay-woocommerce-payments'), 'qty' => 1, 'price_with_tax' => sprintf('%.2f', -1 * $discountWithTax), 'price_without_tax' => sprintf('%.2f', -1 * $discount), 'tax_price' => sprintf('%.2f', -1 * $tax), 'tax_percent' => sprintf('%.2f', $taxPercent), ); } return $item; } /** * Get Order Info * * @param WC_Order $order * * @return array */ private function getOrderInfo($order) { $amount = 0; $vatAmount = 0; $descriptions = array(); $items = $this->getOrderItems($order); foreach ($items as $item) { $amount += $item['price_with_tax']; $vatAmount += $item['tax_price']; $descriptions[] = array( 'amount' => $item['price_with_tax'], 'vatAmount' => $item['tax_price'], // @todo Validate 'itemAmount' => sprintf('%.2f', $item['price_with_tax'] / $item['qty']), 'quantity' => $item['qty'], 'description' => $item['name'], ); } return array( 'amount' => $amount, 'vat_amount' => $vatAmount, 'items' => $descriptions, ); } /** * Generate UUID * * @param $node * * @return string */ private function getUuid($node) { //return \Ramsey\Uuid\Uuid::uuid5( \Ramsey\Uuid\Uuid::NAMESPACE_OID, $node )->toString(); return apply_filters('swedbank_pay_generate_uuid', $node); } }
38.054137
121
0.558261
43a45273985179cfebdb8b51806a2f95e1a8bc0a
287
dart
Dart
plant_monitor_app/flutter_mongodb_realm/lib/auth/credentials/user_password_credentinal.dart
sbis04/plant-monitor
575afa166996b379bf13d72ad5e3293af7df5672
[ "Apache-2.0" ]
12
2022-01-13T04:11:00.000Z
2022-02-10T18:24:29.000Z
plant_monitor_app/flutter_mongodb_realm/lib/auth/credentials/user_password_credentinal.dart
sbis04/plant-monitor
575afa166996b379bf13d72ad5e3293af7df5672
[ "Apache-2.0" ]
null
null
null
plant_monitor_app/flutter_mongodb_realm/lib/auth/credentials/user_password_credentinal.dart
sbis04/plant-monitor
575afa166996b379bf13d72ad5e3293af7df5672
[ "Apache-2.0" ]
1
2022-02-01T12:50:41.000Z
2022-02-01T12:50:41.000Z
import 'package:flutter/foundation.dart'; import 'stitch_credential.dart'; @deprecated class UserPasswordCredential extends StitchCredential { final String username; final String password; UserPasswordCredential({ required this.username, required this.password, }); }
19.133333
55
0.770035
79a1a1675c1f71de41a1969cc52ea9c1e37acdb8
1,725
php
PHP
resources/views/Payment/edit.blade.php
QuanNguyen-851/Project2_Ministry
8c669fccf0e039bf7e864a7efd314279e586d753
[ "MIT" ]
null
null
null
resources/views/Payment/edit.blade.php
QuanNguyen-851/Project2_Ministry
8c669fccf0e039bf7e864a7efd314279e586d753
[ "MIT" ]
null
null
null
resources/views/Payment/edit.blade.php
QuanNguyen-851/Project2_Ministry
8c669fccf0e039bf7e864a7efd314279e586d753
[ "MIT" ]
1
2021-06-23T14:24:50.000Z
2021-06-23T14:24:50.000Z
@extends('layouts.layout') @section('main') <div class="card"> <form action="{{ route('payment.update', $payment->id) }}" method="post" id="updatevalidateform"> @csrf @method("PUT") <div class="header text-center">Updated phương thức đóng</div> <div class="content"> <div class="form-group"> <label class="control-label">phương thức</label> <input class="form-control" name="name" type="text" required="true" value="{{$payment->name}}" /> </div> <div class="form-group"> <label class="control-label">Giảm( %/đợt ) </label> <input class="form-control" name="sale" type="text" required="true" number="true" value="{{$payment->sale}}" /> </div> <div class="form-group"> <label class="control-label">Số đợt/lần đóng</label> <input class="form-control" name="countPer" type="text" required="true" number="true" value="{{$payment->countPer}}" /> </div> <span style=" color: red;font-size: 12px;margin-left: 44px;"> @if (Session::has('err')) {{Session::get('err')}} @endif </span> </div> <div class="footer text-center"> <button type="submit" class="btn btn-info btn-fill btn-wd">Cập Nhật</button> </div> </form> </div> </div> @endsection
26.538462
102
0.443478
dcb258cbe09d6ba9bd4de07238d5075278c2c224
169
lua
Lua
nvim/lua/core/init.lua
UniqueDing/.conf
0afe3486c361dfc37e61b2472e0217d06693ed78
[ "MIT" ]
1
2020-12-24T14:12:37.000Z
2020-12-24T14:12:37.000Z
nvim/lua/core/init.lua
UniqueDing/dotfiles
6d72c849fd9a45bee86dd9852f909ac34940e111
[ "MIT" ]
null
null
null
nvim/lua/core/init.lua
UniqueDing/dotfiles
6d72c849fd9a45bee86dd9852f909ac34940e111
[ "MIT" ]
null
null
null
require("settings") --require("plugins") function load_core() local pack = require("core.pack") pack.ensure_plugins() pack.load_compile() end load_core()
14.083333
37
0.686391
72b23b48234cb1d24dc6532f5d3663244404b448
734
cake
C#
Content/scripts/data/download/cake/repositories.Material.cake
moljac/HolisticWare.DotNetNew.XamarinProjectsStructureTemplate
45f40654b288b26c6bc3e1df3b4071828c1a6644
[ "MIT" ]
1
2021-11-09T06:43:03.000Z
2021-11-09T06:43:03.000Z
scripts/data/download/cake/repositories.Material.cake
Samples-Playgrounds/Samples.MAUI
a11b39e4e61ed3881c3705e0e6cd6dcb04bbfd0d
[ "MIT" ]
31
2020-07-23T21:39:14.000Z
2020-07-23T21:40:44.000Z
scripts/data/download/cake/repositories.Material.cake
Samples-Playgrounds/Samples.MAUI
a11b39e4e61ed3881c3705e0e6cd6dcb04bbfd0d
[ "MIT" ]
1
2020-06-25T12:16:12.000Z
2020-06-25T12:16:12.000Z
Dictionary<string, Dictionary<string, string> > Repositories_Material = null; Repositories_Material = new Dictionary<string, Dictionary<string, string> >() { { "Material-diverse", new Dictionary<string, string>() { { "HackerNewsReader", "https://github.com/hitherejoe/HackerNewsReader" }, { "design-library", "https://github.com/googlecodelabs/android-design-library" }, { "topeka", "https://github.com/googlesamples/android-topeka" } } }, };
30.583333
78
0.446866
976e3d0b9e3e510a82200b67243f64d6b6683aec
5,109
tsx
TypeScript
frontend/app/review-request/component.tsx
brnrdog/please-review
b23babcca62012eff22fa7ff878d26d529a3ddd1
[ "MIT" ]
null
null
null
frontend/app/review-request/component.tsx
brnrdog/please-review
b23babcca62012eff22fa7ff878d26d529a3ddd1
[ "MIT" ]
null
null
null
frontend/app/review-request/component.tsx
brnrdog/please-review
b23babcca62012eff22fa7ff878d26d529a3ddd1
[ "MIT" ]
null
null
null
import * as React from 'react'; import { RepoIcon, GitCommitIcon, DiffAddedIcon, DiffRemovedIcon, EyeIcon } from 'react-octicons' import * as numeral from 'numeral'; import Avatar from '../avatar/component'; import ConfirmButton from '../confirm-button/component'; const styles = require('./styles.module.css'); export interface IProps { reviewRequest: typeof ReviewRequest; onCloseReviewRequest: () => void; } const mapReviewersToLinks = rs => rs.map(r => ( <a key={r.username} target="_blank" className={styles['reviewer-link']} href={r.profileUrl} > {r.username} </a> )); export default ({ reviewRequest, onCloseReviewRequest }: IProps) => ( <div className="card mb-4"> <div className="card-header"> {reviewRequest.title} </div> <ul className="list-group list-group-flush"> <li className="list-group-item"> <div className="row"> <div className="col-4 col-sm-auto mb-2 mb-sm-0"> <div className={styles['data-group']}> <label className={`text-muted`}> <RepoIcon /> Repository </label> <span> <a href={reviewRequest.repositoryUrl} target="_blank"> {reviewRequest.repository} </a> </span> </div> </div> <div className="col-4 col-sm-auto mb-2 mb-sm-0"> <div className={styles['data-group']}> <label className={`text-muted`}> <EyeIcon /> Reviews </label> <span> <strong>{reviewRequest.reviews}</strong> </span> </div> </div> <div className="col-4 col-sm-auto mb-2 mb-sm-0"> <div className={styles['data-group']}> <label className={`text-muted`}> <GitCommitIcon /> Commits </label> <span> <strong>{reviewRequest.commits}</strong> </span> </div> </div> <div className="col-4 col-sm-auto mb-2 mb-sm-0"> <div className={styles['data-group']}> <label className={`text-muted`}> <DiffAddedIcon /> Additions </label> <span> <strong className="text-success"> +{numeral(reviewRequest.additions).format(0,0)} </strong> </span> </div> </div> <div className="col-4 col-sm-auto mb-2 mb-sm-0"> <div className={styles['data-group']}> <label className={`text-muted`}> <DiffRemovedIcon /> Deletions </label> <span> <strong className="text-danger"> -{numeral(reviewRequest.deletions).format(0,0)} </strong> </span> </div> </div> </div> </li> <li className="list-group-item"> <div className="row"> <div className="col-auto"> <div className="row no-gutters"> <div className="col-auto"> <Avatar url={reviewRequest.user.avatarUrl} /> </div> <div className="col-auto"> <div className={styles['data-group']}> <label className={`text-muted`}> Requested by </label> <span> <a href={"https://avatars0.githubusercontent.com/u/670325"} target="_blank"> {reviewRequest.user.username} </a> </span> </div> </div> </div> </div> <div className="col-auto"> <div className={styles['data-group']}> <label className={`text-muted`}> Repository Languages </label> <span> {reviewRequest.languages.split(',').map((language, index) => { const type = index < 3 ? 'primary' : 'secondary' const classes = `badge badge-pill badge-${type}`; return ( <span className={`${styles['language']} ${classes}`}> {language} </span> ); })} </span> </div> </div> </div> </li> </ul> <div className="card-footer border-top-0 text-right"> <ConfirmButton className="btn btn-secondary btn-sm mr-2" confirmMessage="Are you sure you want to close this request?" onConfirm={onCloseReviewRequest} modalKey={`rr-confirm-${reviewRequest.id}`} > Close Review Request </ConfirmButton> <a href={reviewRequest.reviewUrl} target="_blank" className="btn btn-primary btn-sm" > Review Pull Request </a> </div> </div> )
30.963636
96
0.471521
2336c9210e2bfdf284245b5dad1891626ddd9153
184
css
CSS
Hookr/Web/frontend/src/components/Login/Login.css
mrlldd/hookr-rent-service
a9ca9a00b35ce87d82de65bf9b664748bae0c376
[ "Apache-2.0" ]
null
null
null
Hookr/Web/frontend/src/components/Login/Login.css
mrlldd/hookr-rent-service
a9ca9a00b35ce87d82de65bf9b664748bae0c376
[ "Apache-2.0" ]
null
null
null
Hookr/Web/frontend/src/components/Login/Login.css
mrlldd/hookr-rent-service
a9ca9a00b35ce87d82de65bf9b664748bae0c376
[ "Apache-2.0" ]
null
null
null
.Login { display: flex; flex-direction: column; justify-content: space-between; align-items: center; vertical-align: middle; } .Login > h1, .Login > div { margin: 8% 0; }
14.153846
33
0.646739
1aae445fcbf83af4076cc2673e761c619c1bcaad
31,311
py
Python
hubit/tree.py
mrsonne/hub
1705de728dd65c79ff4d87fb12d903c1503be31c
[ "BSD-3-Clause" ]
4
2021-02-19T08:03:31.000Z
2021-03-05T19:01:59.000Z
hubit/tree.py
mrsonne/hub
1705de728dd65c79ff4d87fb12d903c1503be31c
[ "BSD-3-Clause" ]
30
2021-02-08T19:22:57.000Z
2022-03-24T21:37:52.000Z
hubit/tree.py
mrsonne/hubit
1705de728dd65c79ff4d87fb12d903c1503be31c
[ "BSD-3-Clause" ]
null
null
null
from __future__ import annotations import logging import copy import itertools from typing import ( Any, List, Dict, Mapping, Sequence, Tuple, Union, Optional, TYPE_CHECKING, ) from .errors import HubitIndexError, HubitError, HubitModelQueryError from .config import _HubitPath, HubitModelPath, HubitQueryPath, PathIndexRange, Path from .utils import is_digit, get_from_datadict, split_items, traverse if TYPE_CHECKING: from .config import HubitModelComponent IDX_WILDCARD = PathIndexRange.wildcard_chr class LeafNode: """Used for leaves in the LengthTree instead of a LengthNode""" def __init__(self, idx: int): # Stores index in parent's list of children self.index = idx # Not used but mypy likes it self.level = 0 self.parent = None def remove_decendants(self): pass class LengthNode: def __init__(self, nchildren: int): """A node in the length tree i.e. a generalized shape for non-rectagular data. Args: nchildren (int): Number of children. Equivalent to the number of indices for the current node. """ self.level = 0 # Assume bottom level self.children: Sequence[Union[LengthNode, LeafNode]] = [ LeafNode(idx) for idx in range(nchildren) ] self._set_child_for_idx() # Assume top level (parent = None) self.parent: Optional[LengthNode] = None self.tree: LengthTree # Stores index in parent's list of children self.index: int # Is node constrained by pruning self.is_constrained: bool = False def _set_child_for_idx(self): self._child_for_idx = {child.index: child for child in self.children} def nchildren(self) -> int: return len(self.children) def set_children(self, children: Sequence[Union[LengthNode, LeafNode]]): self.children = list(children) for idx, child in enumerate(self.children): child.parent = self child.level = self.level + 1 child.index = idx self._set_child_for_idx() def remove(self): """remove node""" if self.parent is None: raise HubitIndexError self.remove_decendants() self.parent.children.remove(self) del self.parent._child_for_idx[self.index] if self.parent.nchildren() == 0: self.parent.remove() self.tree.nodes_for_level[self.level].remove(self) # for node in self.tree.nodes_for_level[self.level]: # node.is_constrained = False def pop_child_for_idx(self, idx): child = self._child_for_idx[idx] child.remove_decendants() if not isinstance(child, LeafNode): # Not the bottom-most level so safe to access self.level + 1 self.tree.nodes_for_level[self.level + 1].remove(child) self.children.pop(idx) del self._child_for_idx[idx] def remove_decendants(self): for child in self.children: if isinstance(child, LeafNode): continue # Remove child from tree child.tree.nodes_for_level[child.level].remove(child) child.remove_decendants() self.children = [LeafNode(idx) for idx in range(len(self.children))] self._set_child_for_idx() def __str__(self): return f'LengthNode(nchildren={self.nchildren()}, index={self.index}, has parent={"Yes" if self.parent else "No"}, is_constrained={self.is_constrained})' def __repr__(self): return str(self) class DummyLengthTree: """Dummy tree for""" def __init__(self, *args, **kwargs): self.level_names = [] def get_idx_context(self): return "-".join(self.level_names) def prune_from_path( self, _path: _HubitPath = _HubitPath(), inplace: bool = True, ) -> DummyLengthTree: return self if inplace else copy.deepcopy(self) def clip_at_level( self, _level_name: str = "", inplace: bool = True, ) -> DummyLengthTree: return self if inplace else copy.deepcopy(self) def fix_idx_at_level( self, _idx_value: int = 0, _level_idx: int = 0, inplace: bool = True, ): """Don't change the tree""" return self if inplace else copy.deepcopy(self) def expand_path( self, path: HubitModelPath, *args, **kwargs ) -> List[HubitModelPath]: return [path] def none_like(self): return None class LengthTree: """Stores length information for multi-dimensional and non-rectangular data. """ def __init__(self, nodes: List[LengthNode], level_names: Sequence[str]): """A data structure that allows manipulations of connected LengthNodes Args: nodes (List[LengthNode]): Connected length nodes level_names (List[str]): Name of the levels specified on the nodes """ self.nlevels = len(level_names) self.level_names: Sequence[str] = level_names self.nodes_for_level: Sequence[List[LengthNode]] = [ [] for _ in range(self.nlevels) ] for node in nodes: node.tree = self self.nodes_for_level[node.level].append(node) def get_idx_context(self): return "-".join(self.level_names) def clip_at_level(self, level_name: str, inplace: bool = True) -> LengthTree: """Remove levels below 'level_name' Args: level_name (str): Name of deepest level to include. Levels below will be remove inplace (bool, optional): If True the instance itself will be clipped. If False a clipped copy will be created. Defaults to True. Returns: LengthTree: Clipped tree """ obj = self if inplace else copy.deepcopy(self) level_idx = obj.level_names.index(level_name) for node in obj.nodes_for_level[level_idx]: node.remove_decendants() obj.level_names = obj.level_names[: level_idx + 1] obj.nodes_for_level = obj.nodes_for_level[: level_idx + 1] return obj def prune_from_path(self, path: _HubitPath, inplace: bool = True) -> LengthTree: """Prune the length tree based on a path where zero to all indices are already specified. Args: path: A Hubit path with zero to all index IDs replaced by indices inplace (bool, optional): If True the instance itself will be pruned. If False a pruned copy will be created. Defaults to True. Returns: LengthTree: Pruned tree. If inplace=True the instance itself is also pruned. """ obj = self if inplace else copy.deepcopy(self) ranges = path.ranges() if all([range.is_full_range for range in ranges]): return obj # Loop over the index ID levels assert len(ranges) == len( obj.level_names ), f"Path {path} does not math tree with levels {obj.level_names}" for level_idx, range in enumerate(ranges): if range.is_full_range: # No pruning required since all elements are in scope continue if range.is_digit: obj.fix_idx_at_level(int(range), level_idx) return obj def fix_idx_at_level(self, idx_value: int, level_idx: int, inplace: bool = True): """Fix the nodes at level_idx to the value idx Args: idx_value (int): Index value to be set. level_idx (int): Level index inplace (bool, optional): If True the instance itself will be modified. If False a copy will be created. Defaults to True. Raises: HubitIndexError: Raise of the specified idx_value cannot be provided Returns: LengthTree: Fixed tree. If inplace=True the instance itself is also modified. """ obj = self if inplace else copy.deepcopy(self) nodes_to_be_deleted = [] for node in obj.nodes_for_level[level_idx]: # Keep child corresponding to idx remove the rest idx_others = [child.index for child in node.children] node.is_constrained = True if idx_value in idx_others: # idx can be provided idx_others.remove(idx_value) for idx_other in reversed(idx_others): node.pop_child_for_idx(idx_other) else: nodes_to_be_deleted.append(node) for node in nodes_to_be_deleted: try: node.remove() except HubitIndexError: raise HubitIndexError( f"Cannot find index {idx_value} " f"for index ID {obj.level_names[level_idx]} " f"in tree " f"{self}" ) return obj def to_list(self): """Convert length tree to nested lists for testing puposes Returns: List: Nested lists representing the length tree """ idx_vals = [ [node.nchildren() for node in nodes] for nodes in self.nodes_for_level ] size_for_level = [] size_for_level = [idx_vals[0][0]] for idx, vals in enumerate(idx_vals[1:], 1): # Loop over levels above (excluding level 0) and incrementally # divide list into sub-lists for sizes in idx_vals[1:idx][::-1]: # Cast to list in case of an integer if is_digit(sizes): vals = split_items(vals, traverse([sizes])) elif len(sizes) == 1: vals = split_items(vals, traverse(sizes))[0] else: vals = split_items(vals, traverse(sizes)) if len(vals) == 1: vals = vals[0] size_for_level.append(vals) return size_for_level @staticmethod def _nodes_for_iterpaths( connecting_paths: List[str], data: Dict, nodes=None, paths_previous=None, parent: LengthNode = None, ) -> Tuple: """Lengths Args: connecting_paths (List[str]): Sequence of index identification strings between index IDs data (Dict): Input data nodes (List[LengthNode], optional): Cumulative list of nodes. Defaults to None. paths_previous (List, optional): Hubit internal paths found in previous level of recursion with explicit indices. Defaults to None. parent (LengthNode, optional): Parent node Returns: Tuple: Two-tuple list of nodes, paths_previous """ sep = "." paths_previous = paths_previous or [connecting_paths[0]] nodes = nodes or [] # Get node list for paths prepared at the previous recursion level child_nodes = [ LengthNode(len(get_from_datadict(data, path.split(sep)))) for path in paths_previous ] if parent is not None: parent.set_children(child_nodes) nodes.extend(child_nodes) paths_next = paths_previous if len(connecting_paths) > 1: # Prepare paths for next recursive call by appending the # indices (from out_current_level) and the connecting path # to the previously found paths for node, path_previous in zip(child_nodes, paths_previous): paths_next = [ "{}.{}.{}".format(path_previous, curidx, connecting_paths[1]) for curidx in range(node.nchildren()) ] # Call again for next index ID nodes, paths_next = LengthTree._nodes_for_iterpaths( connecting_paths[1:], data, nodes=nodes, parent=node, paths_previous=paths_next, ) elif len(connecting_paths) == 1: for node, path_previous in zip(child_nodes, paths_previous): paths_next = [ "{}.{}".format(path_previous, curidx) for curidx in range(node.nchildren()) ] return nodes, paths_next @classmethod def from_data(cls, path: HubitModelPath, data: dict, prune: bool = False) -> Any: """Infer lengths of lists in 'input_data' that correspond to index IDs in the path. Args: path (str): Hubit model path input_data (Dict): Input data prune (bool): Tree is pruned if True Returns: LengthTree: Element 0 is DummyLengthTree if no index IDs found in 'path' otherwise a LengthTree. """ # Handle no index IDs if len(path.get_index_specifiers()) == 0: return DummyLengthTree() # Handle all IDs are digits if all([range.is_digit for range in path.ranges()]): return DummyLengthTree() connecting_paths = path.paths_between_specifiers() # Exclude leaf attribute (empty string or path following last index specifier) connecting_paths = connecting_paths[:-1] nodes, _ = LengthTree._nodes_for_iterpaths(connecting_paths, data) index_identifiers = path.get_index_identifiers() tree = cls(nodes, index_identifiers) # Some path indices may have specific locations so prune the tree # This does not work when different indices can be provided by # different components since the tress are only stored according to their # index context. When different indices are be provided by # different components the index context are the same but the trees are # different if prune: tree.prune_from_path(path) return tree def reshape(self, items: List, inplace: bool = True) -> Any: """Reshape items according to the shape defined by the tree Args: items (List): Flat list of to be reshaped inplace (bool): If True the specified list will be reshaped. If False a copy will be created and reshaped. Returns: None objects arraged like the tree. """ _items = items if inplace else copy.deepcopy(items) # Always one node at the top of the tree top_node = self.nodes_for_level[0][0] # Used to check if items are ever split. # Use top node since it is not part of the loop as_list = not top_node.is_constrained for nodes in reversed(self.nodes_for_level[1:]): # If 1 node and contrained by pruning do not split # Assures that "segments[0].layers[0].thickness[:]" would result # in a 1D list while "segments[0].layers[:].thickness[:]" would # result in a 2D list even if there were only 1 layer # print("is_constrained", nodes[0].is_constrained) # if len(nodes) == 1 and nodes[0].is_constrained: # continue if all([node.is_constrained for node in nodes]): continue as_list = True nchildren = [node.nchildren() for node in nodes] _items = split_items(_items, nchildren) if as_list: # Reduce dimensionality by 1 if top_node.is_constrained: _items = _items[0] return _items else: # TODO: could check len(items) = 1 at the top assert ( len(items) == 1 ), f"Expected list of length 1, but found {len(items)}." return _items def _node_for_idxs(self, idxs: List[int]): """ Get the node corresponding to a list of indices """ if len(idxs) == 0: node = self.nodes_for_level[0][0] else: node = self.nodes_for_level[0][0]._child_for_idx[idxs[0]] for node_idx in idxs[1:]: node = node._child_for_idx[node_idx] return node def normalize_path(self, qpath: HubitQueryPath) -> HubitQueryPath: """Handle negative indices As stated in "test_normalize_path2" the normalization in general depends on the context """ idxids = qpath.get_index_specifiers() _path = copy.copy(qpath) for idx_level, idxid in enumerate(idxids): if is_digit(idxid) and int(idxid) < 0: # Get index context i.e. indices prior to current level _idx_context = [ int(idx) for idx in _path.get_index_specifiers()[:idx_level] ] node = self._node_for_idxs(_idx_context) _path = HubitQueryPath( _path.replace(idxid, str(node.nchildren() + int(idxid)), 1) ) return _path def expand_path( self, path: Path, flat: bool = False, ) -> List[HubitQueryPath]: """Expand model path with wildcard based on tree Example for a query path: list[:].some_attr.numbers -> [ list[0].some_attr.numbers, list[1].some_attr.numbers, list[2].some_attr.numbers ] Args: path (Path): Any path with wildcards and index IDs flat (bool): Return expansion result as a flat list. Returns: List: Paths from expansion. Arranged in the shape defined by the tree if flat = False. Otherwise a flat list. """ # Get the content of the braces idxspecs = path.get_index_specifiers() ranges = path.ranges() # Manipulate as strings paths = [str(path)] for idx_level, (idxspec, range) in enumerate(zip(idxspecs, ranges)): nodes = self.nodes_for_level[idx_level] paths_current_level = [] for _path, node in zip(paths, nodes): if range.is_digit: # slice is digit so replace index specifier with that digit paths_current_level.append(_path.replace(idxspec, range)) elif range.is_full_range or range.is_empty: # slice is wildcard or not specified so expand from node children paths_current_level.extend( [ _path.replace(idxspec, str(child.index), 1) for child in node.children ] ) elif range.is_limited_range: # Loop over children to see who are included in the range paths_current_level.extend( [ _path.replace(idxspec, str(child.index), 1) for child in node.children if range.contains_index(child.index) ] ) else: raise HubitError( f"Unknown index range '{range}' for path '{path}' of type '{type(path)}'." ) paths = copy.deepcopy(paths_current_level) # Cast strings as paths _paths = [HubitQueryPath(_path) for _path in paths] if flat: return _paths else: return self.reshape(_paths) def _all_nodes_constrained(self): return all( [node.is_constrained for nodes in self.nodes_for_level for node in nodes] ) def number_of_leaves(self): """Number of leaves in the tree""" return sum(self.number_of_children(-1)) def number_of_children(self, idx_level: int) -> List[int]: """Number of children for each node at the specified level""" return [node.nchildren() for node in self.nodes_for_level[idx_level]] def none_like(self) -> Any: """Create data structure in the shape of the tree filled with None Returns: Data structure with None """ # If all node are constrained the result is None. No list to reshape if self._all_nodes_constrained(): return None # Reshape a flat list with all elements set to None. The list has length # like all leaves in the tree return self.reshape([None for _ in range(self.number_of_leaves())]) def __str__(self): lines = ["--------------------", "Tree"] for idx, (name, nodes) in enumerate( zip( self.level_names, self.nodes_for_level, ) ): nparents = len({node.parent for node in nodes if node.parent is not None}) nchildren = sum([node.nchildren() for node in nodes]) children_are_leaves = [ all([isinstance(child, LeafNode) for child in node.children]) for node in nodes ] idx_node = [[child.index for child in node.children] for node in nodes] is_constrained = [node.is_constrained for node in nodes] lines.append( f"level={idx} ({name}), " f"nodes={len(nodes)} (constrained: {is_constrained}), " f"parents={nparents}, " f"children={nchildren}, " f"children are leaves={children_are_leaves}, " f"child idxs={idx_node}" ) lines.append("--------------------") lines.append("Lengths") size_for_level = self.to_list() for idx, (name, size) in enumerate(zip(self.level_names, size_for_level)): lines.append(f"level={idx} ({name}), {size}") return "\n".join(lines) class _QueryExpansion: """A Hubit query expansion. A query can be split into multiple queries Args: path: A [`HubitQueryPath`][hubit.config.HubitQueryPath] representing the original query. decomposed_paths: If a single component can provide results for `path`, `decomposed_paths` has one element of type [`HubitQueryPath`][hubit.config.HubitQueryPath]. If multiple components match the query individual path contributions are the items in the list. expanded_paths_for_decomposed_path: For each element in `decomposed_paths` these are the expanded paths i.e. dotted paths with real indices not wildcards. """ def __init__(self, path: HubitQueryPath, mpaths: List[HubitModelPath]): """ path: the query path mpaths: the model paths that match the query """ self.path = path if len(mpaths) > 1 and not path.has_slice_range(): # Should not be possible to have multiple providers if the query # points to a specific path i.e. has no ranges. # TODO: This check could be more strict e.g. the wildcard is located where # the mpaths vary raise HubitModelQueryError( f"More than one component match the query '{path}'. Matching components provide: {mpaths}." ) # Get the index contexts for doing some tests _idx_contexts = {mpath.get_idx_context() for mpath in mpaths} if len(_idx_contexts) > 1: msg = f"Fatal error. Inconsistent providers for query '{path}': {', '.join(mpaths)}" raise HubitModelQueryError(msg) if len(_idx_contexts) == 0: msg = f"Fatal error. No provider for query path '{path}'." raise HubitModelQueryError(msg) self.decomposed_paths, index_identifiers = _QueryExpansion.decompose_query( path, mpaths ) self.expanded_paths_for_decomposed_path: Dict[ HubitQueryPath, List[HubitQueryPath] ] = {} if index_identifiers is None: self.decomposed_idx_identifier = None else: # Cannot occur since len(_idx_contexts) is 1 # if len(set(index_identifiers)) > 1: # msg = f"Fatal error. Inconsistent decomposition for query '{path}': {', '.join(mpaths)}" # raise HubitModelQueryError(msg) self.decomposed_idx_identifier = index_identifiers[0] self._idx_context = list(_idx_contexts)[0] @property def idx_context(self): """The (one) index context corresponding to the model paths""" return self._idx_context def update_expanded_paths( self, decomposed_path: HubitQueryPath, expanded_paths: List[HubitQueryPath] ): self.expanded_paths_for_decomposed_path[decomposed_path] = expanded_paths def flat_expanded_paths(self): """Returns flat list of expanded paths""" return [ path for paths in self.expanded_paths_for_decomposed_path.values() for path in paths ] def is_decomposed(self): return len(self.decomposed_paths) > 1 def is_expanded(self): if ( not self.is_decomposed() and self.path == self.decomposed_paths[0] and len(self.expanded_paths_for_decomposed_path[self.decomposed_paths[0]]) == 1 and self.path == self.expanded_paths_for_decomposed_path[self.decomposed_paths[0]][0] ): return False else: return True @staticmethod def decompose_query( qpath: HubitQueryPath, mpaths: List[HubitModelPath] ) -> Tuple[List[HubitQueryPath], Union[List[str], None]]: """ If a single component can provide results for `path`, `decomposed_paths` has one element of type [`HubitQueryPath`][hubit.config.HubitQueryPath]. If multiple components are required to provide the query their individual path contributions are the items in the list. index_identifiers are the index identifiers corresponding to the decomposed index """ index_identifiers: Union[List, None] if len(mpaths) > 1: # More than one provider required to match query. Split query into queries # each having a unique provider decomposed_qpaths = [] # Index identifiers corresponding to decomposed field index_identifiers = [] for mpath in mpaths: q_idx_specs = qpath.get_index_specifiers() idxs, ranges = zip( *[ (idx, range) for idx, range in enumerate(mpath.ranges()) if not range.is_empty ] ) if len(ranges) == 1: # Replace the index specifier from the query path with # the range from the model path q_idx_specs[idxs[0]] = ranges[0] # Set the ranges (one comes from model path) on the query path decomposed_qpaths.append(qpath.set_indices(q_idx_specs)) # Save the index identifier corresponding to the replacement index_identifiers.append(mpath.get_index_identifiers()[idxs[0]]) elif len(ranges) >= 1: raise HubitModelQueryError( ( f"Only one index range may be specified as digit for each", f"model path. For model path '{mpath}', '{mpath.ranges()}'", f"were found.", ) ) else: logging.warning( f"No digits found for decomposed model path {mpath}" ) else: decomposed_qpaths = [qpath] index_identifiers = None return decomposed_qpaths, index_identifiers def validate_tree(self, tree: LengthTree): """Validate that we get the expected number of mpaths in the expansion Raises if tree is invalid. TODO: If the tree was pruned I think the test could be more strict using == instead of >=. """ # Don't validate if DummyLengthTree since they can never be decomposed if isinstance(tree, DummyLengthTree): return # Don't validate tree against expansion if path was not decomposed if not self.is_decomposed(): return n_decomposed_paths = len(self.decomposed_paths) tree_level_name = self.decomposed_idx_identifier # Find out which level (index) we are at try: idx_level = tree.level_names.index(tree_level_name) except ValueError as err: print(f"ERROR. Level name '{tree_level_name}' not found in tree") print(tree) print(self) raise HubitError("Query expansion error.") # For each node at the level the number of children should be # greater than or equal to the number for paths in the decomposition results = [n >= n_decomposed_paths for n in tree.number_of_children(idx_level)] if not all(results): print( f"ERROR. " f"Too few children at level {idx_level} with " f"name '{tree_level_name}' of tree. " f"Expected at least {n_decomposed_paths} children " "corresponding to the number of decomposed paths.\n" ) print(tree) print(self) raise HubitError("Query expansion error.") def __str__(self): lines = [f"\nQuery\n {self.path}"] lines.append("Decomposition & expansion") for decomp_path, expanded_paths in itertools.zip_longest( self.decomposed_paths, self.expanded_paths_for_decomposed_path.values(), fillvalue=None, ): lines.append(f" {decomp_path} -> {expanded_paths}") return "\n".join(lines) def tree_for_idxcontext( components: List[HubitModelComponent], data: Dict ) -> Mapping[str, Union[LengthTree, DummyLengthTree]]: """Compute LengthTree for relevant index contexts. Args: components (List[Componet]): List of Hubit components data (Dict): Input data Returns: Dict: LengthTree for relevant index contexts """ out = {"": DummyLengthTree()} for component in components: for binding in component.consumes_input: tree = LengthTree.from_data(binding.path, data) idx_context = binding.path.get_idx_context() if idx_context in out.keys(): continue out[idx_context] = tree # Clip trees to generate trees for (all) shallower index contexts for tree in copy.deepcopy(list(out.values())): for level_name in tree.level_names[:-1]: new_tree = tree.clip_at_level(level_name, inplace=False) idx_context = new_tree.get_idx_context() if idx_context in out.keys(): continue out[idx_context] = new_tree return out
36.239583
161
0.585385
384710fd1615d43cc68c2f0c02a8971176f6e484
2,829
cs
C#
src/Externals/google-api-dotnet-client/Src/GoogleApis.Tests/Apis/Discovery/MediaUploadTest.cs
Dmiri/Xamarin.google-apis
a74bee7ea38af9d24925124ec452488a2e4579ad
[ "Apache-2.0" ]
40
2015-02-03T22:00:17.000Z
2021-06-09T09:36:45.000Z
src/Externals/google-api-dotnet-client/Src/GoogleApis.Tests/Apis/Discovery/MediaUploadTest.cs
Dmiri/Xamarin.google-apis
a74bee7ea38af9d24925124ec452488a2e4579ad
[ "Apache-2.0" ]
3
2015-07-29T21:16:37.000Z
2021-08-04T14:55:39.000Z
src/Externals/google-api-dotnet-client/Src/GoogleApis.Tests/Apis/Discovery/MediaUploadTest.cs
Dmiri/Xamarin.google-apis
a74bee7ea38af9d24925124ec452488a2e4579ad
[ "Apache-2.0" ]
31
2015-03-29T19:24:27.000Z
2021-07-29T19:51:47.000Z
/* Copyright 2011 Google 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 System.Collections.Generic; using System.Linq; using NUnit.Framework; using Google.Apis.Discovery; using Google.Apis.Json; namespace Google.Apis.Tests.Apis.Discovery { /// <summary> /// Tests the "MediaUpload"-class /// </summary> [TestFixture] public class MediaUploadTest { private const string SampleInsertMethod = @" { 'accept': [ 'image/*', 'video/*', 'audio/*' ], 'maxSize': '10GB', 'protocols': { 'simple': { 'multipart': true, 'path': '/upload/test/v4/resources' }, 'resumable': { 'multipart': true, 'path': '/resumable/upload/test/v4/resources' } } }"; /// <summary> /// Tests that the constructor fills in the proper default arguments /// </summary> [Test] public void TestConstructor() { var method = new MediaUpload(JsonReader.Parse(SampleInsertMethod) as JsonDictionary); Assert.That(method.MaxSize, Is.Not.Null); Assert.That(method.MaxSize, Is.EqualTo("10GB")); } [Test] public void TestAccepts() { var method = new MediaUpload(JsonReader.Parse(SampleInsertMethod) as JsonDictionary); Assert.That(method.Accepts, Is.Not.Null); Assert.That(method.Accepts.Length, Is.EqualTo(3)); Assert.That(method.Accepts, Is.EquivalentTo( new string[] { "image/*", "video/*", "audio/*" })); } [Test] public void TestProtocols() { var method = new MediaUpload(JsonReader.Parse(SampleInsertMethod) as JsonDictionary); Assert.That(method.Simple, Is.Not.Null); Assert.That(method.Simple.MultiPart, Is.True); Assert.That(method.Simple.Path, Is.Not.Null); Assert.That(method.Simple.Path, Is.EqualTo("/upload/test/v4/resources")); Assert.That(method.Resumable, Is.Not.Null); Assert.That(method.Resumable.MultiPart, Is.True); Assert.That(method.Resumable.Path, Is.Not.Null); Assert.That(method.Resumable.Path, Is.EqualTo("/resumable/upload/test/v4/resources")); } } }
32.147727
98
0.61824
e1abc85846202871bf2e9271e0a2b0848a14b1f4
1,072
dart
Dart
example/lib/main.dart
astudilloalex/flutter-open-weather-map-client
265460186b02c2e97aca6afed31538b88077a3e9
[ "BSD-2-Clause-FreeBSD" ]
1
2021-08-10T02:54:50.000Z
2021-08-10T02:54:50.000Z
example/lib/main.dart
astudilloalex/flutter-open-weather-map-client
265460186b02c2e97aca6afed31538b88077a3e9
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
example/lib/main.dart
astudilloalex/flutter-open-weather-map-client
265460186b02c2e97aca6afed31538b88077a3e9
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
import 'package:example/src/current_weather/current_weather_view.dart'; import 'package:example/src/home/home_view.dart'; import 'package:example/src/not_found/not_found_view.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter open_weather_map_client example', initialRoute: '/', onGenerateRoute: (settings) { return MaterialPageRoute( builder: (context) { switch (settings.name) { case CurrentWeatherView.routeName: return const CurrentWeatherView(); case HomeView.routeName: return const HomeView(); default: return const NotFoundView(); } }, settings: settings, ); }, ); } }
28.210526
71
0.622201
bb45b1c988d2af19818529c513ab86312cbd3945
46,215
cs
C#
QR Code Generator/User Controls/ReadQRCodePanel.Designer.cs
GAGreatProgrammer/QR-Code-Generator
5cfcf6de5cb0c35c7b5729f38df9ace0ba35e6c0
[ "MIT" ]
null
null
null
QR Code Generator/User Controls/ReadQRCodePanel.Designer.cs
GAGreatProgrammer/QR-Code-Generator
5cfcf6de5cb0c35c7b5729f38df9ace0ba35e6c0
[ "MIT" ]
null
null
null
QR Code Generator/User Controls/ReadQRCodePanel.Designer.cs
GAGreatProgrammer/QR-Code-Generator
5cfcf6de5cb0c35c7b5729f38df9ace0ba35e6c0
[ "MIT" ]
null
null
null
 namespace QR_Code_Generator.User_Controls { partial class ReadQRCodePanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ReadQRCodePanel)); Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges borderEdges1 = new Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges(); Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges borderEdges2 = new Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges(); Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges borderEdges3 = new Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges(); Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges borderEdges4 = new Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges(); Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges borderEdges5 = new Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderEdges(); this.lblQRCode = new System.Windows.Forms.Label(); this.Panel = new Bunifu.UI.WinForms.BunifuPanel(); this.CameraImage = new System.Windows.Forms.PictureBox(); this.btnRead = new Bunifu.UI.WinForms.BunifuButton.BunifuButton(); this.btnClear = new Bunifu.UI.WinForms.BunifuButton.BunifuButton(); this.btnUploadQRCodeImage = new Bunifu.UI.WinForms.BunifuButton.BunifuButton(); this.cboCamera = new Bunifu.UI.WinForms.BunifuDropdown(); this.btnReload = new Bunifu.UI.WinForms.BunifuButton.BunifuButton(); this.timer = new System.Windows.Forms.Timer(this.components); this.btnStop = new Bunifu.UI.WinForms.BunifuButton.BunifuButton(); this.Panel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CameraImage)).BeginInit(); this.SuspendLayout(); // // lblQRCode // this.lblQRCode.AutoSize = true; this.lblQRCode.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblQRCode.Location = new System.Drawing.Point(110, 15); this.lblQRCode.Name = "lblQRCode"; this.lblQRCode.Size = new System.Drawing.Size(190, 29); this.lblQRCode.TabIndex = 1; this.lblQRCode.Text = "Read QR Code"; // // Panel // this.Panel.BackgroundColor = System.Drawing.Color.Transparent; this.Panel.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("Panel.BackgroundImage"))); this.Panel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.Panel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(18)))), ((int)(((byte)(219)))), ((int)(((byte)(135))))); this.Panel.BorderRadius = 30; this.Panel.BorderThickness = 2; this.Panel.Controls.Add(this.CameraImage); this.Panel.Location = new System.Drawing.Point(15, 112); this.Panel.Name = "Panel"; this.Panel.ShowBorders = true; this.Panel.Size = new System.Drawing.Size(405, 310); this.Panel.TabIndex = 5; // // CameraImage // this.CameraImage.Location = new System.Drawing.Point(10, 10); this.CameraImage.Name = "CameraImage"; this.CameraImage.Size = new System.Drawing.Size(385, 290); this.CameraImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.CameraImage.TabIndex = 46; this.CameraImage.TabStop = false; // // btnRead // this.btnRead.AllowAnimations = true; this.btnRead.AllowMouseEffects = true; this.btnRead.AllowToggling = false; this.btnRead.AnimationSpeed = 200; this.btnRead.AutoGenerateColors = false; this.btnRead.AutoRoundBorders = false; this.btnRead.AutoSizeLeftIcon = true; this.btnRead.AutoSizeRightIcon = true; this.btnRead.BackColor = System.Drawing.Color.Transparent; this.btnRead.BackColor1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(122)))), ((int)(((byte)(183))))); this.btnRead.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnRead.BackgroundImage"))); this.btnRead.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnRead.ButtonText = "Read"; this.btnRead.ButtonTextMarginLeft = 0; this.btnRead.ColorContrastOnClick = 45; this.btnRead.ColorContrastOnHover = 45; this.btnRead.Cursor = System.Windows.Forms.Cursors.Default; borderEdges1.BottomLeft = true; borderEdges1.BottomRight = true; borderEdges1.TopLeft = true; borderEdges1.TopRight = true; this.btnRead.CustomizableEdges = borderEdges1; this.btnRead.DialogResult = System.Windows.Forms.DialogResult.None; this.btnRead.DisabledBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnRead.DisabledFillColor = System.Drawing.Color.Empty; this.btnRead.DisabledForecolor = System.Drawing.Color.Empty; this.btnRead.FocusState = Bunifu.UI.WinForms.BunifuButton.BunifuButton.ButtonStates.Pressed; this.btnRead.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnRead.ForeColor = System.Drawing.Color.White; this.btnRead.IconLeft = null; this.btnRead.IconLeftAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnRead.IconLeftCursor = System.Windows.Forms.Cursors.Default; this.btnRead.IconLeftPadding = new System.Windows.Forms.Padding(11, 3, 3, 3); this.btnRead.IconMarginLeft = 11; this.btnRead.IconPadding = 10; this.btnRead.IconRight = null; this.btnRead.IconRightAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnRead.IconRightCursor = System.Windows.Forms.Cursors.Default; this.btnRead.IconRightPadding = new System.Windows.Forms.Padding(3, 3, 7, 3); this.btnRead.IconSize = 25; this.btnRead.IdleBorderColor = System.Drawing.Color.Empty; this.btnRead.IdleBorderRadius = 0; this.btnRead.IdleBorderThickness = 0; this.btnRead.IdleFillColor = System.Drawing.Color.Empty; this.btnRead.IdleIconLeftImage = null; this.btnRead.IdleIconRightImage = null; this.btnRead.IndicateFocus = false; this.btnRead.Location = new System.Drawing.Point(15, 575); this.btnRead.Name = "btnRead"; this.btnRead.OnDisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnRead.OnDisabledState.BorderRadius = 30; this.btnRead.OnDisabledState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnRead.OnDisabledState.BorderThickness = 1; this.btnRead.OnDisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.btnRead.OnDisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(160)))), ((int)(((byte)(168))))); this.btnRead.OnDisabledState.IconLeftImage = null; this.btnRead.OnDisabledState.IconRightImage = null; this.btnRead.onHoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(150)))), ((int)(((byte)(255))))); this.btnRead.onHoverState.BorderRadius = 30; this.btnRead.onHoverState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnRead.onHoverState.BorderThickness = 1; this.btnRead.onHoverState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(150)))), ((int)(((byte)(255))))); this.btnRead.onHoverState.ForeColor = System.Drawing.Color.White; this.btnRead.onHoverState.IconLeftImage = null; this.btnRead.onHoverState.IconRightImage = null; this.btnRead.OnIdleState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnRead.OnIdleState.BorderRadius = 30; this.btnRead.OnIdleState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnRead.OnIdleState.BorderThickness = 1; this.btnRead.OnIdleState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnRead.OnIdleState.ForeColor = System.Drawing.Color.White; this.btnRead.OnIdleState.IconLeftImage = null; this.btnRead.OnIdleState.IconRightImage = null; this.btnRead.OnPressedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnRead.OnPressedState.BorderRadius = 30; this.btnRead.OnPressedState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnRead.OnPressedState.BorderThickness = 1; this.btnRead.OnPressedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnRead.OnPressedState.ForeColor = System.Drawing.Color.White; this.btnRead.OnPressedState.IconLeftImage = null; this.btnRead.OnPressedState.IconRightImage = null; this.btnRead.Size = new System.Drawing.Size(130, 40); this.btnRead.TabIndex = 8; this.btnRead.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnRead.TextAlignment = System.Windows.Forms.HorizontalAlignment.Center; this.btnRead.TextMarginLeft = 0; this.btnRead.TextPadding = new System.Windows.Forms.Padding(0); this.btnRead.UseDefaultRadiusAndThickness = true; this.btnRead.Click += new System.EventHandler(this.btnRead_Click); // // btnClear // this.btnClear.AllowAnimations = true; this.btnClear.AllowMouseEffects = true; this.btnClear.AllowToggling = false; this.btnClear.AnimationSpeed = 200; this.btnClear.AutoGenerateColors = false; this.btnClear.AutoRoundBorders = false; this.btnClear.AutoSizeLeftIcon = true; this.btnClear.AutoSizeRightIcon = true; this.btnClear.BackColor = System.Drawing.Color.Transparent; this.btnClear.BackColor1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(122)))), ((int)(((byte)(183))))); this.btnClear.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnClear.BackgroundImage"))); this.btnClear.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnClear.ButtonText = "Clear"; this.btnClear.ButtonTextMarginLeft = 0; this.btnClear.ColorContrastOnClick = 45; this.btnClear.ColorContrastOnHover = 45; this.btnClear.Cursor = System.Windows.Forms.Cursors.Default; borderEdges2.BottomLeft = true; borderEdges2.BottomRight = true; borderEdges2.TopLeft = true; borderEdges2.TopRight = true; this.btnClear.CustomizableEdges = borderEdges2; this.btnClear.DialogResult = System.Windows.Forms.DialogResult.None; this.btnClear.DisabledBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnClear.DisabledFillColor = System.Drawing.Color.Empty; this.btnClear.DisabledForecolor = System.Drawing.Color.Empty; this.btnClear.FocusState = Bunifu.UI.WinForms.BunifuButton.BunifuButton.ButtonStates.Pressed; this.btnClear.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnClear.ForeColor = System.Drawing.Color.White; this.btnClear.IconLeft = null; this.btnClear.IconLeftAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnClear.IconLeftCursor = System.Windows.Forms.Cursors.Default; this.btnClear.IconLeftPadding = new System.Windows.Forms.Padding(11, 3, 3, 3); this.btnClear.IconMarginLeft = 11; this.btnClear.IconPadding = 10; this.btnClear.IconRight = null; this.btnClear.IconRightAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnClear.IconRightCursor = System.Windows.Forms.Cursors.Default; this.btnClear.IconRightPadding = new System.Windows.Forms.Padding(3, 3, 7, 3); this.btnClear.IconSize = 25; this.btnClear.IdleBorderColor = System.Drawing.Color.Empty; this.btnClear.IdleBorderRadius = 0; this.btnClear.IdleBorderThickness = 0; this.btnClear.IdleFillColor = System.Drawing.Color.Empty; this.btnClear.IdleIconLeftImage = null; this.btnClear.IdleIconRightImage = null; this.btnClear.IndicateFocus = false; this.btnClear.Location = new System.Drawing.Point(290, 575); this.btnClear.Name = "btnClear"; this.btnClear.OnDisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnClear.OnDisabledState.BorderRadius = 30; this.btnClear.OnDisabledState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnClear.OnDisabledState.BorderThickness = 1; this.btnClear.OnDisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.btnClear.OnDisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(160)))), ((int)(((byte)(168))))); this.btnClear.OnDisabledState.IconLeftImage = null; this.btnClear.OnDisabledState.IconRightImage = null; this.btnClear.onHoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(91)))), ((int)(((byte)(91))))); this.btnClear.onHoverState.BorderRadius = 30; this.btnClear.onHoverState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnClear.onHoverState.BorderThickness = 1; this.btnClear.onHoverState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(91)))), ((int)(((byte)(91))))); this.btnClear.onHoverState.ForeColor = System.Drawing.Color.White; this.btnClear.onHoverState.IconLeftImage = null; this.btnClear.onHoverState.IconRightImage = null; this.btnClear.OnIdleState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); this.btnClear.OnIdleState.BorderRadius = 30; this.btnClear.OnIdleState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnClear.OnIdleState.BorderThickness = 1; this.btnClear.OnIdleState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); this.btnClear.OnIdleState.ForeColor = System.Drawing.Color.White; this.btnClear.OnIdleState.IconLeftImage = null; this.btnClear.OnIdleState.IconRightImage = null; this.btnClear.OnPressedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); this.btnClear.OnPressedState.BorderRadius = 30; this.btnClear.OnPressedState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnClear.OnPressedState.BorderThickness = 1; this.btnClear.OnPressedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); this.btnClear.OnPressedState.ForeColor = System.Drawing.Color.White; this.btnClear.OnPressedState.IconLeftImage = null; this.btnClear.OnPressedState.IconRightImage = null; this.btnClear.Size = new System.Drawing.Size(130, 40); this.btnClear.TabIndex = 9; this.btnClear.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnClear.TextAlignment = System.Windows.Forms.HorizontalAlignment.Center; this.btnClear.TextMarginLeft = 0; this.btnClear.TextPadding = new System.Windows.Forms.Padding(0); this.btnClear.UseDefaultRadiusAndThickness = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnUploadQRCodeImage // this.btnUploadQRCodeImage.AllowAnimations = true; this.btnUploadQRCodeImage.AllowMouseEffects = true; this.btnUploadQRCodeImage.AllowToggling = false; this.btnUploadQRCodeImage.AnimationSpeed = 200; this.btnUploadQRCodeImage.AutoGenerateColors = false; this.btnUploadQRCodeImage.AutoRoundBorders = false; this.btnUploadQRCodeImage.AutoSizeLeftIcon = true; this.btnUploadQRCodeImage.AutoSizeRightIcon = true; this.btnUploadQRCodeImage.BackColor = System.Drawing.Color.Transparent; this.btnUploadQRCodeImage.BackColor1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(122)))), ((int)(((byte)(183))))); this.btnUploadQRCodeImage.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnUploadQRCodeImage.BackgroundImage"))); this.btnUploadQRCodeImage.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Dash; this.btnUploadQRCodeImage.ButtonText = ""; this.btnUploadQRCodeImage.ButtonTextMarginLeft = 0; this.btnUploadQRCodeImage.ColorContrastOnClick = 45; this.btnUploadQRCodeImage.ColorContrastOnHover = 45; this.btnUploadQRCodeImage.Cursor = System.Windows.Forms.Cursors.Default; borderEdges3.BottomLeft = true; borderEdges3.BottomRight = true; borderEdges3.TopLeft = true; borderEdges3.TopRight = true; this.btnUploadQRCodeImage.CustomizableEdges = borderEdges3; this.btnUploadQRCodeImage.DialogResult = System.Windows.Forms.DialogResult.None; this.btnUploadQRCodeImage.DisabledBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnUploadQRCodeImage.DisabledFillColor = System.Drawing.Color.Empty; this.btnUploadQRCodeImage.DisabledForecolor = System.Drawing.Color.Empty; this.btnUploadQRCodeImage.FocusState = Bunifu.UI.WinForms.BunifuButton.BunifuButton.ButtonStates.Pressed; this.btnUploadQRCodeImage.Font = new System.Drawing.Font("Segoe UI", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnUploadQRCodeImage.ForeColor = System.Drawing.Color.Black; this.btnUploadQRCodeImage.IconLeft = global::QR_Code_Generator.Properties.Resources.UploadQRCodeImage; this.btnUploadQRCodeImage.IconLeftAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnUploadQRCodeImage.IconLeftCursor = System.Windows.Forms.Cursors.Default; this.btnUploadQRCodeImage.IconLeftPadding = new System.Windows.Forms.Padding(11, 3, 3, 3); this.btnUploadQRCodeImage.IconMarginLeft = 11; this.btnUploadQRCodeImage.IconPadding = 10; this.btnUploadQRCodeImage.IconRight = null; this.btnUploadQRCodeImage.IconRightAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnUploadQRCodeImage.IconRightCursor = System.Windows.Forms.Cursors.Default; this.btnUploadQRCodeImage.IconRightPadding = new System.Windows.Forms.Padding(3, 3, 7, 3); this.btnUploadQRCodeImage.IconSize = 25; this.btnUploadQRCodeImage.IdleBorderColor = System.Drawing.Color.Empty; this.btnUploadQRCodeImage.IdleBorderRadius = 0; this.btnUploadQRCodeImage.IdleBorderThickness = 0; this.btnUploadQRCodeImage.IdleFillColor = System.Drawing.Color.Empty; this.btnUploadQRCodeImage.IdleIconLeftImage = global::QR_Code_Generator.Properties.Resources.UploadQRCodeImage; this.btnUploadQRCodeImage.IdleIconRightImage = null; this.btnUploadQRCodeImage.IndicateFocus = false; this.btnUploadQRCodeImage.Location = new System.Drawing.Point(15, 445); this.btnUploadQRCodeImage.Name = "btnUploadQRCodeImage"; this.btnUploadQRCodeImage.OnDisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnUploadQRCodeImage.OnDisabledState.BorderRadius = 30; this.btnUploadQRCodeImage.OnDisabledState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnUploadQRCodeImage.OnDisabledState.BorderThickness = 2; this.btnUploadQRCodeImage.OnDisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.btnUploadQRCodeImage.OnDisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(160)))), ((int)(((byte)(168))))); this.btnUploadQRCodeImage.OnDisabledState.IconLeftImage = null; this.btnUploadQRCodeImage.OnDisabledState.IconRightImage = null; this.btnUploadQRCodeImage.onHoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(18)))), ((int)(((byte)(219)))), ((int)(((byte)(135))))); this.btnUploadQRCodeImage.onHoverState.BorderRadius = 30; this.btnUploadQRCodeImage.onHoverState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Dash; this.btnUploadQRCodeImage.onHoverState.BorderThickness = 2; this.btnUploadQRCodeImage.onHoverState.FillColor = System.Drawing.Color.White; this.btnUploadQRCodeImage.onHoverState.ForeColor = System.Drawing.Color.White; this.btnUploadQRCodeImage.onHoverState.IconLeftImage = null; this.btnUploadQRCodeImage.onHoverState.IconRightImage = null; this.btnUploadQRCodeImage.OnIdleState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(18)))), ((int)(((byte)(219)))), ((int)(((byte)(135))))); this.btnUploadQRCodeImage.OnIdleState.BorderRadius = 30; this.btnUploadQRCodeImage.OnIdleState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Dash; this.btnUploadQRCodeImage.OnIdleState.BorderThickness = 2; this.btnUploadQRCodeImage.OnIdleState.FillColor = System.Drawing.Color.White; this.btnUploadQRCodeImage.OnIdleState.ForeColor = System.Drawing.Color.Black; this.btnUploadQRCodeImage.OnIdleState.IconLeftImage = global::QR_Code_Generator.Properties.Resources.UploadQRCodeImage; this.btnUploadQRCodeImage.OnIdleState.IconRightImage = null; this.btnUploadQRCodeImage.OnPressedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(18)))), ((int)(((byte)(219)))), ((int)(((byte)(135))))); this.btnUploadQRCodeImage.OnPressedState.BorderRadius = 30; this.btnUploadQRCodeImage.OnPressedState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Dash; this.btnUploadQRCodeImage.OnPressedState.BorderThickness = 2; this.btnUploadQRCodeImage.OnPressedState.FillColor = System.Drawing.Color.White; this.btnUploadQRCodeImage.OnPressedState.ForeColor = System.Drawing.Color.White; this.btnUploadQRCodeImage.OnPressedState.IconLeftImage = null; this.btnUploadQRCodeImage.OnPressedState.IconRightImage = null; this.btnUploadQRCodeImage.Size = new System.Drawing.Size(405, 100); this.btnUploadQRCodeImage.TabIndex = 10; this.btnUploadQRCodeImage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnUploadQRCodeImage.TextAlignment = System.Windows.Forms.HorizontalAlignment.Center; this.btnUploadQRCodeImage.TextMarginLeft = 0; this.btnUploadQRCodeImage.TextPadding = new System.Windows.Forms.Padding(0); this.btnUploadQRCodeImage.UseDefaultRadiusAndThickness = true; this.btnUploadQRCodeImage.Click += new System.EventHandler(this.btnUploadQRCodeImage_Click); // // cboCamera // this.cboCamera.BackColor = System.Drawing.Color.Transparent; this.cboCamera.BackgroundColor = System.Drawing.Color.White; this.cboCamera.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.cboCamera.BorderRadius = 17; this.cboCamera.Color = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.cboCamera.Direction = Bunifu.UI.WinForms.BunifuDropdown.Directions.Down; this.cboCamera.DisabledBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240))))); this.cboCamera.DisabledBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.cboCamera.DisabledColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240))))); this.cboCamera.DisabledForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(109)))), ((int)(((byte)(109)))), ((int)(((byte)(109))))); this.cboCamera.DisabledIndicatorColor = System.Drawing.Color.DarkGray; this.cboCamera.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.cboCamera.DropdownBorderThickness = Bunifu.UI.WinForms.BunifuDropdown.BorderThickness.Thick; this.cboCamera.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboCamera.DropDownTextAlign = Bunifu.UI.WinForms.BunifuDropdown.TextAlign.Left; this.cboCamera.FillDropDown = true; this.cboCamera.FillIndicator = false; this.cboCamera.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cboCamera.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboCamera.ForeColor = System.Drawing.Color.Black; this.cboCamera.FormattingEnabled = true; this.cboCamera.Icon = null; this.cboCamera.IndicatorAlignment = Bunifu.UI.WinForms.BunifuDropdown.Indicator.Right; this.cboCamera.IndicatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.cboCamera.IndicatorLocation = Bunifu.UI.WinForms.BunifuDropdown.Indicator.Right; this.cboCamera.IndicatorThickness = 2; this.cboCamera.IsDropdownOpened = false; this.cboCamera.ItemBackColor = System.Drawing.Color.White; this.cboCamera.ItemBorderColor = System.Drawing.Color.White; this.cboCamera.ItemForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.cboCamera.ItemHeight = 34; this.cboCamera.ItemHighLightColor = System.Drawing.Color.DodgerBlue; this.cboCamera.ItemHighLightForeColor = System.Drawing.Color.White; this.cboCamera.ItemTopMargin = 3; this.cboCamera.Location = new System.Drawing.Point(15, 53); this.cboCamera.Name = "cboCamera"; this.cboCamera.Size = new System.Drawing.Size(335, 40); this.cboCamera.TabIndex = 45; this.cboCamera.Text = null; this.cboCamera.TextAlignment = Bunifu.UI.WinForms.BunifuDropdown.TextAlign.Left; this.cboCamera.TextLeftMargin = 5; // // btnReload // this.btnReload.AllowAnimations = true; this.btnReload.AllowMouseEffects = true; this.btnReload.AllowToggling = false; this.btnReload.AnimationSpeed = 200; this.btnReload.AutoGenerateColors = false; this.btnReload.AutoRoundBorders = false; this.btnReload.AutoSizeLeftIcon = true; this.btnReload.AutoSizeRightIcon = true; this.btnReload.BackColor = System.Drawing.Color.Transparent; this.btnReload.BackColor1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(122)))), ((int)(((byte)(183))))); this.btnReload.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnReload.BackgroundImage"))); this.btnReload.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnReload.ButtonText = ""; this.btnReload.ButtonTextMarginLeft = 0; this.btnReload.ColorContrastOnClick = 45; this.btnReload.ColorContrastOnHover = 45; this.btnReload.Cursor = System.Windows.Forms.Cursors.Default; borderEdges4.BottomLeft = true; borderEdges4.BottomRight = true; borderEdges4.TopLeft = true; borderEdges4.TopRight = true; this.btnReload.CustomizableEdges = borderEdges4; this.btnReload.DialogResult = System.Windows.Forms.DialogResult.None; this.btnReload.DisabledBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnReload.DisabledFillColor = System.Drawing.Color.Empty; this.btnReload.DisabledForecolor = System.Drawing.Color.Empty; this.btnReload.FocusState = Bunifu.UI.WinForms.BunifuButton.BunifuButton.ButtonStates.Pressed; this.btnReload.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnReload.ForeColor = System.Drawing.Color.White; this.btnReload.IconLeft = global::QR_Code_Generator.Properties.Resources.ReloadCamera; this.btnReload.IconLeftAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnReload.IconLeftCursor = System.Windows.Forms.Cursors.Default; this.btnReload.IconLeftPadding = new System.Windows.Forms.Padding(11, 3, 3, 3); this.btnReload.IconMarginLeft = 11; this.btnReload.IconPadding = 8; this.btnReload.IconRight = null; this.btnReload.IconRightAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnReload.IconRightCursor = System.Windows.Forms.Cursors.Default; this.btnReload.IconRightPadding = new System.Windows.Forms.Padding(3, 3, 7, 3); this.btnReload.IconSize = 25; this.btnReload.IdleBorderColor = System.Drawing.Color.Empty; this.btnReload.IdleBorderRadius = 0; this.btnReload.IdleBorderThickness = 0; this.btnReload.IdleFillColor = System.Drawing.Color.Empty; this.btnReload.IdleIconLeftImage = global::QR_Code_Generator.Properties.Resources.ReloadCamera; this.btnReload.IdleIconRightImage = null; this.btnReload.IndicateFocus = false; this.btnReload.Location = new System.Drawing.Point(360, 53); this.btnReload.Name = "btnReload"; this.btnReload.OnDisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnReload.OnDisabledState.BorderRadius = 30; this.btnReload.OnDisabledState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnReload.OnDisabledState.BorderThickness = 1; this.btnReload.OnDisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.btnReload.OnDisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(160)))), ((int)(((byte)(168))))); this.btnReload.OnDisabledState.IconLeftImage = null; this.btnReload.OnDisabledState.IconRightImage = null; this.btnReload.onHoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(150)))), ((int)(((byte)(255))))); this.btnReload.onHoverState.BorderRadius = 30; this.btnReload.onHoverState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnReload.onHoverState.BorderThickness = 1; this.btnReload.onHoverState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(150)))), ((int)(((byte)(255))))); this.btnReload.onHoverState.ForeColor = System.Drawing.Color.White; this.btnReload.onHoverState.IconLeftImage = null; this.btnReload.onHoverState.IconRightImage = null; this.btnReload.OnIdleState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnReload.OnIdleState.BorderRadius = 30; this.btnReload.OnIdleState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnReload.OnIdleState.BorderThickness = 1; this.btnReload.OnIdleState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnReload.OnIdleState.ForeColor = System.Drawing.Color.White; this.btnReload.OnIdleState.IconLeftImage = global::QR_Code_Generator.Properties.Resources.ReloadCamera; this.btnReload.OnIdleState.IconRightImage = null; this.btnReload.OnPressedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnReload.OnPressedState.BorderRadius = 30; this.btnReload.OnPressedState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnReload.OnPressedState.BorderThickness = 1; this.btnReload.OnPressedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnReload.OnPressedState.ForeColor = System.Drawing.Color.White; this.btnReload.OnPressedState.IconLeftImage = null; this.btnReload.OnPressedState.IconRightImage = null; this.btnReload.Size = new System.Drawing.Size(60, 40); this.btnReload.TabIndex = 46; this.btnReload.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnReload.TextAlignment = System.Windows.Forms.HorizontalAlignment.Center; this.btnReload.TextMarginLeft = 0; this.btnReload.TextPadding = new System.Windows.Forms.Padding(0); this.btnReload.UseDefaultRadiusAndThickness = true; this.btnReload.Click += new System.EventHandler(this.btnReload_Click); // // timer // this.timer.Tick += new System.EventHandler(this.timer_Tick); // // btnStop // this.btnStop.AllowAnimations = true; this.btnStop.AllowMouseEffects = true; this.btnStop.AllowToggling = false; this.btnStop.AnimationSpeed = 200; this.btnStop.AutoGenerateColors = false; this.btnStop.AutoRoundBorders = false; this.btnStop.AutoSizeLeftIcon = true; this.btnStop.AutoSizeRightIcon = true; this.btnStop.BackColor = System.Drawing.Color.Transparent; this.btnStop.BackColor1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(122)))), ((int)(((byte)(183))))); this.btnStop.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnStop.BackgroundImage"))); this.btnStop.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnStop.ButtonText = "Stop"; this.btnStop.ButtonTextMarginLeft = 0; this.btnStop.ColorContrastOnClick = 45; this.btnStop.ColorContrastOnHover = 45; this.btnStop.Cursor = System.Windows.Forms.Cursors.Default; borderEdges5.BottomLeft = true; borderEdges5.BottomRight = true; borderEdges5.TopLeft = true; borderEdges5.TopRight = true; this.btnStop.CustomizableEdges = borderEdges5; this.btnStop.DialogResult = System.Windows.Forms.DialogResult.None; this.btnStop.DisabledBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnStop.DisabledFillColor = System.Drawing.Color.Empty; this.btnStop.DisabledForecolor = System.Drawing.Color.Empty; this.btnStop.FocusState = Bunifu.UI.WinForms.BunifuButton.BunifuButton.ButtonStates.Pressed; this.btnStop.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnStop.ForeColor = System.Drawing.Color.White; this.btnStop.IconLeft = null; this.btnStop.IconLeftAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnStop.IconLeftCursor = System.Windows.Forms.Cursors.Default; this.btnStop.IconLeftPadding = new System.Windows.Forms.Padding(11, 3, 3, 3); this.btnStop.IconMarginLeft = 11; this.btnStop.IconPadding = 10; this.btnStop.IconRight = null; this.btnStop.IconRightAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnStop.IconRightCursor = System.Windows.Forms.Cursors.Default; this.btnStop.IconRightPadding = new System.Windows.Forms.Padding(3, 3, 7, 3); this.btnStop.IconSize = 25; this.btnStop.IdleBorderColor = System.Drawing.Color.Empty; this.btnStop.IdleBorderRadius = 0; this.btnStop.IdleBorderThickness = 0; this.btnStop.IdleFillColor = System.Drawing.Color.Empty; this.btnStop.IdleIconLeftImage = null; this.btnStop.IdleIconRightImage = null; this.btnStop.IndicateFocus = false; this.btnStop.Location = new System.Drawing.Point(153, 575); this.btnStop.Name = "btnStop"; this.btnStop.OnDisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.btnStop.OnDisabledState.BorderRadius = 30; this.btnStop.OnDisabledState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnStop.OnDisabledState.BorderThickness = 1; this.btnStop.OnDisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.btnStop.OnDisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(160)))), ((int)(((byte)(168))))); this.btnStop.OnDisabledState.IconLeftImage = null; this.btnStop.OnDisabledState.IconRightImage = null; this.btnStop.onHoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(150)))), ((int)(((byte)(255))))); this.btnStop.onHoverState.BorderRadius = 30; this.btnStop.onHoverState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnStop.onHoverState.BorderThickness = 1; this.btnStop.onHoverState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(150)))), ((int)(((byte)(255))))); this.btnStop.onHoverState.ForeColor = System.Drawing.Color.White; this.btnStop.onHoverState.IconLeftImage = null; this.btnStop.onHoverState.IconRightImage = null; this.btnStop.OnIdleState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnStop.OnIdleState.BorderRadius = 30; this.btnStop.OnIdleState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnStop.OnIdleState.BorderThickness = 1; this.btnStop.OnIdleState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnStop.OnIdleState.ForeColor = System.Drawing.Color.White; this.btnStop.OnIdleState.IconLeftImage = null; this.btnStop.OnIdleState.IconRightImage = null; this.btnStop.OnPressedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnStop.OnPressedState.BorderRadius = 30; this.btnStop.OnPressedState.BorderStyle = Bunifu.UI.WinForms.BunifuButton.BunifuButton.BorderStyles.Solid; this.btnStop.OnPressedState.BorderThickness = 1; this.btnStop.OnPressedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(9)))), ((int)(((byte)(132)))), ((int)(((byte)(227))))); this.btnStop.OnPressedState.ForeColor = System.Drawing.Color.White; this.btnStop.OnPressedState.IconLeftImage = null; this.btnStop.OnPressedState.IconRightImage = null; this.btnStop.Size = new System.Drawing.Size(130, 40); this.btnStop.TabIndex = 47; this.btnStop.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.btnStop.TextAlignment = System.Windows.Forms.HorizontalAlignment.Center; this.btnStop.TextMarginLeft = 0; this.btnStop.TextPadding = new System.Windows.Forms.Padding(0); this.btnStop.UseDefaultRadiusAndThickness = true; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // ReadQRCodePanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.Controls.Add(this.btnStop); this.Controls.Add(this.btnReload); this.Controls.Add(this.cboCamera); this.Controls.Add(this.btnUploadQRCodeImage); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnRead); this.Controls.Add(this.Panel); this.Controls.Add(this.lblQRCode); this.Name = "ReadQRCodePanel"; this.Size = new System.Drawing.Size(445, 645); this.Load += new System.EventHandler(this.ReadQRCodePanel_Load); this.Panel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CameraImage)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblQRCode; private Bunifu.UI.WinForms.BunifuPanel Panel; private Bunifu.UI.WinForms.BunifuButton.BunifuButton btnRead; private Bunifu.UI.WinForms.BunifuButton.BunifuButton btnClear; private Bunifu.UI.WinForms.BunifuButton.BunifuButton btnUploadQRCodeImage; private Bunifu.UI.WinForms.BunifuDropdown cboCamera; private System.Windows.Forms.PictureBox CameraImage; private Bunifu.UI.WinForms.BunifuButton.BunifuButton btnReload; private System.Windows.Forms.Timer timer; private Bunifu.UI.WinForms.BunifuButton.BunifuButton btnStop; } }
73.125
170
0.657557
755e4477c7ea9bb768d388b0848a7ce1d2fbb0cc
3,206
css
CSS
css/style.css
MarishaHoza/chocolate-pizza
d37b7dbfd2742edd3c4ab8e0856c32c6d3e7f185
[ "MIT" ]
null
null
null
css/style.css
MarishaHoza/chocolate-pizza
d37b7dbfd2742edd3c4ab8e0856c32c6d3e7f185
[ "MIT" ]
null
null
null
css/style.css
MarishaHoza/chocolate-pizza
d37b7dbfd2742edd3c4ab8e0856c32c6d3e7f185
[ "MIT" ]
1
2019-06-14T20:43:09.000Z
2019-06-14T20:43:09.000Z
@import url('https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Yellowtail&display=swap'); @import url('https://fonts.googleapis.com/css?family=Oswald:700&display=swap'); @import url('https://fonts.googleapis.com/css?family=Amiri&display=swap'); @import url('https://fonts.googleapis.com/css?family=Patrick+Hand&display=swap'); /* font-family: 'Yellowtail', cursive; font-family: 'Open Sans Condensed', sans-serif; */ * { box-sizing: border-box; } body { padding: 50px 150px; } header { overflow: hidden; } header > img { float: left; } header > div { float: left; display: block; width: 200px; font-family: 'Yellowtail', cursive; } header > div > h1 { font-size: 2.2em; } header > img:not(:first-child) { float: right; margin: 1px; height: 24px; width: 24px; } header > img:nth-child(4) { margin-left: 8px; } header > div > h4 { font-family: 'Open Sans Condensed', sans-serif; text-transform: uppercase; font-size: 0.7em; margin-left: 5px; } header > div:last-child { float: left; clear: both; height: 10px; width: 100%; overflow: hidden; background-image: url('../images/hr-img.png'); margin-top: 30px; margin-bottom: 50px; } main > h1 { font-size: 3em; font-family: 'Oswald', sans-serif; } main > h2 { font-family: 'Open Sans Condensed', sans-serif; text-transform: uppercase; width: 300px; display: inline-block; color: #bbb; } main > h3 { float: right; font-family: 'Open Sans Condensed', sans-serif; text-transform: uppercase; color: #bbb; } main > img { float: right; } main > section > img { margin-top: 30px; width: 100%; margin-bottom: 30px; } article > p { margin-bottom: 30px; font-family: 'Amiri', serif; text-indent: 2em; line-height: 1.5em; } article > img { width: 100%; } article > form { position: absolute; margin: 50px 70px; width: 1000px; height: 250px; } form ul { list-style-position: outside; } form li { font-size: 2em; float: left; width: 50%; font-family: 'Patrick Hand', cursive; line-height: 1.2em; } footer { font-family: 'Amiri', serif; } footer > div:first-child { height: 10px; width: 100%; background-image: url('../images/hr-img.png'); margin-top: 30px; margin-bottom: 20px; } footer > section:nth-child(2) > div { float: left; margin-left: 10px; font-size: 1.3em; } footer > section:nth-child(2) > div > h3 { margin-bottom: 10px; font-size: 1.4em; font-weight: bold; } footer button { width: 180px; height: 50px; font-size: 1.4em; font-family: 'Open Sans Condensed', sans-serif; text-transform: uppercase; background-color: #d37d61; border: 1px solid transparent; color: #fff; float: right; margin-top: 10px; } footer > section:nth-child(2) > img { float: left; } footer > section { overflow: hidden; margin-bottom: 50px; } footer > section:last-child { margin-bottom: 25px; } footer > section:last-child > div { border: 1px solid #ddd; width: 48.2%; margin-top: 18px; margin-bottom: 25px; float: left; } footer > section:last-child > img { margin: 5px; float: left; } footer > section:last-child > p { text-align: center; color: #bbb; }
16.441026
103
0.648472
e7170dea52d5e8ad9042a0dbd9bc8b86b9527afe
4,234
php
PHP
resources/views/seller/form/form-addcustomers.blade.php
RichardFuentes369/Inventario
512e57f3880a0f24734af7688070600de31f6ca2
[ "MIT" ]
null
null
null
resources/views/seller/form/form-addcustomers.blade.php
RichardFuentes369/Inventario
512e57f3880a0f24734af7688070600de31f6ca2
[ "MIT" ]
null
null
null
resources/views/seller/form/form-addcustomers.blade.php
RichardFuentes369/Inventario
512e57f3880a0f24734af7688070600de31f6ca2
[ "MIT" ]
null
null
null
<form action="{{ url('vendedor') }}/{{ 'clientesC' }}" method="post"> {{ csrf_field() }} <center> <div class="col-sm-12"><br> <div class="row"> <div class="col-sm-12"> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Nombres</span> </div> <input type="text" name="name" class="form-control inputcenter"> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Apellidos</span> </div> <input type="text" name="lastname" class="form-control inputcenter"> </div> </div> <div class="col-sm-6"> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Tipo Documento</span> </div> <select name="td" id="sexo" class="form-control inputcenter"> <option value="" selected="selected">--Seleccione--</option> <option value="cc">Cedula de Ciudadania</option> <option value="ti">Tarjeta de Identidad</option> <option value="pasaporte">Pasaporte</option> </select> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">DNI</span> </div> <input type="text" name="dni" class="form-control inputcenter"> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Fecha Nacimiento</span> </div> <input type="date" name="fn" class="form-control inputcenter"> </div> </div> <div class="col-sm-6"> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Sexo</span> </div> <select name="sexo" id="sexo" class="form-control inputcenter"> <option value="" selected="selected">--Seleccione--</option> <option value="M">Masculino</option> <option value="F">Femenino</option> </select> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Fijo</span> </div> <input type="text" name="phone" class="form-control inputcenter"> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Celular</span> </div> <input type="text" name="cellphone" class="form-control inputcenter"> </div> </div> <div class="col-sm-12"> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Dirección</span> </div> <input type="text" name="address" class="form-control inputcenter"> </div> </div> <div class="col-sm-6"> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Departamento</span> </div> <input type="text" name="department" class="form-control inputcenter"> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Ciudad</span> </div> <input type="text" name="county" class="form-control inputcenter"> </div> </div> <div class="col-sm-6"> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Barrio</span> </div> <input type="text" name="neighborhood" class="form-control inputcenter"> </div> <div class="texarea-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">@</span> </div> <input type="text" name="email" class="form-control inputcenter"> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-success botonejecutarfuncion">Crear</button> </div> </div> </center> </form>
38.144144
82
0.591639
413781a62a6c0d9a56cd0f4e9ee7d47cdf54aea9
708
rs
Rust
examples/bulk.rs
mrxiaozhuox/dorea
46c79b9f8ba6040f6f934e6bea0bf7f01085cbe7
[ "MIT" ]
83
2021-07-21T14:06:30.000Z
2022-03-30T03:37:25.000Z
examples/bulk.rs
mrxiaozhuox/Dorea
561bcd4990bca7a3787b25bbbf2af72def9c5569
[ "MIT" ]
5
2021-08-11T04:04:29.000Z
2022-01-18T13:26:45.000Z
examples/bulk.rs
mrxiaozhuox/Dorea
561bcd4990bca7a3787b25bbbf2af72def9c5569
[ "MIT" ]
10
2021-06-29T00:33:17.000Z
2022-03-30T03:37:26.000Z
/// 在你运行这个 Demo 之前,请确保 Dorea 服务已经正常启动! /// dorea.examples.bulk /// 对于数据进行批量上传: /// 本 Demo 将对 数据库循环插入 1024 次。 use dorea::{client::DoreaClient, value::DataValue}; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut db = DoreaClient::connect(("127.0.0.1", 3450), "").await?; // db.select("bulk").await; // 循环 1024 次: for i in 1..100721 { // 将 {i} Key 设置为一个 Number 数据:{i} match db .setex(&i.to_string(), DataValue::Number(i as f64), 0) .await { Ok(_) => { println!("SUCCESS: {:?}", i); } Err(err) => { panic!("{}", err); } }; } Ok(()) }
22.83871
70
0.45904
45d83074a6a311e52e10397d84bfed014e9507fd
272
py
Python
src/io/__init__.py
jonathan-scholbach/jargon
1bc49efb4002b4f348b1449ca5bad32bc416dab7
[ "MIT" ]
null
null
null
src/io/__init__.py
jonathan-scholbach/jargon
1bc49efb4002b4f348b1449ca5bad32bc416dab7
[ "MIT" ]
null
null
null
src/io/__init__.py
jonathan-scholbach/jargon
1bc49efb4002b4f348b1449ca5bad32bc416dab7
[ "MIT" ]
null
null
null
"""Module for all i/o functionality.""" from .string_manipulation import title_from_path, pluralize, mask from .clear import clear from .colorprint import cprint from .argument_parser import argument_parser from .print_table import Table from .date_diff import date_diff
30.222222
65
0.823529
8de1a1dda6edbb4e539d1af31fbeb8c98f9ef299
223
js
JavaScript
SpiceApplication.App/wwwroot/js/vue/components/menuFooter.js
AnnabellFlem/SpiceApplication
49399e5355408f57b8563cc4b9d719dec9c545b1
[ "Apache-2.0" ]
1
2019-04-18T16:56:27.000Z
2019-04-18T16:56:27.000Z
SpiceApplication.App/wwwroot/js/vue/components/menuFooter.js
AnnabellFlem/SpiceApplication
49399e5355408f57b8563cc4b9d719dec9c545b1
[ "Apache-2.0" ]
null
null
null
SpiceApplication.App/wwwroot/js/vue/components/menuFooter.js
AnnabellFlem/SpiceApplication
49399e5355408f57b8563cc4b9d719dec9c545b1
[ "Apache-2.0" ]
1
2019-04-18T16:56:28.000Z
2019-04-18T16:56:28.000Z
const menuFooter = Vue.component('menu-footer', { template: ` <div class="footer"> <p>&copy; 2019 Spice&amp;Herbs, <br /> All Rights Reserved.</p> </div> ` }); export default menuFooter;
24.777778
75
0.569507
6649734c512f1111bf33424b92c096d9c2ae4a3d
8,876
py
Python
buildscripts/tests/resmokelib/run/test_list_tags.py
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
buildscripts/tests/resmokelib/run/test_list_tags.py
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
buildscripts/tests/resmokelib/run/test_list_tags.py
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
"""Unit tests for buildscripts/resmokelib/run/list_tags.py.""" # pylint: disable=missing-docstring import unittest from buildscripts.resmokelib.run import list_tags def _get_suite(tags_blocks): block = "" for tags_block in tags_blocks: block = f"{block} {tags_block}" + "\n" return (("test_kind: js_test\n" "\n" "selector:\n" " roots: []\n") + block + ("\n" "executor:\n" " config: {}\n" " fixture:\n" " class: MongoDFixture\n" " mongod_options:\n" " set_parameters:\n" " enableTestCommands: 1\n")) class TestParseTagsBlocks(unittest.TestCase): def test_no_tags_blocks(self): suite = _get_suite([]) result = list_tags.parse_tags_blocks(suite) self.assertCountEqual([], result) def test_empty_tags_block(self): tags_blocks = ["exclude_with_any_tags:\n"] suite = _get_suite(tags_blocks) result = list_tags.parse_tags_blocks(suite) self.assertCountEqual(tags_blocks, result) def test_two_tags_blocks(self): tags_blocks = [("exclude_with_any_tags:\n" " - dummy_tag_1\n" " - dummy_tag_2\n" " - dummy_tag_3"), ("include_with_any_tags:\n" " - dummy_tag_4\n" " - dummy_tag_5\n" " - dummy_tag_6")] suite = _get_suite(tags_blocks) result = list_tags.parse_tags_blocks(suite) self.assertCountEqual(tags_blocks, result) def test_tags_block_with_tags_and_above_comments(self): tags_blocks = [("exclude_with_any_tags:\n" " # comment\n" " - dummy_tag_1\n" " # comment line 1\n" " # comment line 2\n" " - dummy_tag_2\n" " #################\n" " # fancy comment #\n" " #################\n" " - dummy_tag_3")] suite = _get_suite(tags_blocks) result = list_tags.parse_tags_blocks(suite) self.assertCountEqual(tags_blocks, result) def test_tags_block_with_tags_and_inline_comments(self): tags_blocks = [("exclude_with_any_tags:\n" " - dummy_tag_1 # inline comment\n" " - dummy_tag_2 # another one\n" " - dummy_tag_3 # and another one")] suite = _get_suite(tags_blocks) result = list_tags.parse_tags_blocks(suite) self.assertCountEqual(tags_blocks, result) def test_tags_block_with_tags_and_both_comments(self): tags_blocks = [("exclude_with_any_tags:\n" " # above comment\n" " - dummy_tag_1 # inline comment\n" " # above comment line 1\n" " # above comment line 2\n" " - dummy_tag_2 # another one inline\n" " #######################\n" " # above fancy comment #\n" " #######################\n" " - dummy_tag_3 # and another one inline")] suite = _get_suite(tags_blocks) result = list_tags.parse_tags_blocks(suite) self.assertCountEqual(tags_blocks, result) class TestSplitIntoTags(unittest.TestCase): def test_empty_block(self): result = list_tags.split_into_tags("") self.assertCountEqual([], result) def test_block_with_no_tags(self): block = "exclude_with_any_tags:\n" result = list_tags.split_into_tags(block) self.assertCountEqual([[""]], result) def test_block_with_tags_no_comments(self): block = ("exclude_with_any_tags:\n" " - dummy_tag_1\n" " - dummy_tag_2\n" " - dummy_tag_3") expected = [ ["- dummy_tag_1"], ["- dummy_tag_2"], ["- dummy_tag_3"], ] result = list_tags.split_into_tags(block) self.assertCountEqual(expected, result) def test_block_with_tags_and_above_comments(self): block = ("exclude_with_any_tags:\n" " # comment\n" " - dummy_tag_1\n" " # comment line 1\n" " # comment line 2\n" " - dummy_tag_2\n" " #################\n" " # fancy comment #\n" " #################\n" " - dummy_tag_3") expected = [ [ "# comment", "- dummy_tag_1", ], [ "# comment line 1", "# comment line 2", "- dummy_tag_2", ], [ "#################", "# fancy comment #", "#################", "- dummy_tag_3", ], ] result = list_tags.split_into_tags(block) self.assertCountEqual(expected, result) def test_block_with_tags_and_inline_comments(self): block = (("exclude_with_any_tags:\n" " - dummy_tag_1 # inline comment\n" " - dummy_tag_2 # another one\n" " - dummy_tag_3 # and another one")) expected = [ ["- dummy_tag_1 # inline comment"], ["- dummy_tag_2 # another one"], ["- dummy_tag_3 # and another one"], ] result = list_tags.split_into_tags(block) self.assertCountEqual(expected, result) def test_block_with_tags_and_both_comments(self): block = ("exclude_with_any_tags:\n" " # above comment\n" " - dummy_tag_1 # inline comment\n" " # above comment line 1\n" " # above comment line 2\n" " - dummy_tag_2 # another one inline\n" " #######################\n" " # above fancy comment #\n" " #######################\n" " - dummy_tag_3 # and another one inline") expected = [ [ "# above comment", "- dummy_tag_1 # inline comment", ], [ "# above comment line 1", "# above comment line 2", "- dummy_tag_2 # another one inline", ], [ "#######################", "# above fancy comment #", "#######################", "- dummy_tag_3 # and another one inline", ], ] result = list_tags.split_into_tags(block) self.assertCountEqual(expected, result) class TestGetTagDoc(unittest.TestCase): def test_empty_tag_block(self): expected = ("", "") result = list_tags.get_tag_doc("") self.assertEqual(expected, result) def test_tag_no_comment(self): tag_block = ["- dummy_tag"] expected = ("dummy_tag", "") result = list_tags.get_tag_doc(tag_block) self.assertEqual(expected, result) def test_tag_with_above_comment(self): tag_block = [ "# comment", "- dummy_tag", ] expected = ("dummy_tag", "comment") result = list_tags.get_tag_doc(tag_block) self.assertEqual(expected, result) def test_tag_with_multiline_above_comment(self): tag_block = [ "# comment line 1", "# comment line 2", "- dummy_tag", ] expected = ("dummy_tag", ("comment line 1\ncomment line 2")) result = list_tags.get_tag_doc(tag_block) self.assertEqual(expected, result) def test_tag_with_inline_comment(self): tag_block = ["- dummy_tag # comment"] expected = ("dummy_tag", "comment") result = list_tags.get_tag_doc(tag_block) self.assertEqual(expected, result) def test_tag_with_both_comment(self): tag_block = [ "# above comment line 1", "# above comment line 2", "- dummy_tag # inline comment", ] expected = ("dummy_tag", ("above comment line 1\n" "above comment line 2\n" "inline comment")) result = list_tags.get_tag_doc(tag_block) self.assertEqual(expected, result)
37.451477
76
0.475665
2cac1fc48761863e734b537bbf128eb8f99c3313
2,071
py
Python
puml-graphs/test/Test_Puml_dudes_experiments.py
StevenJV/Book_Generation_Z_Developer
7e2ff829faff41b1ce2f1f2f9cb88d712ebbc9ee
[ "Apache-2.0" ]
36
2018-02-20T18:52:40.000Z
2022-01-05T08:36:42.000Z
puml-graphs/test/Test_Puml_dudes_experiments.py
StevenJV/Book_Generation_Z_Developer
7e2ff829faff41b1ce2f1f2f9cb88d712ebbc9ee
[ "Apache-2.0" ]
57
2018-02-22T00:57:13.000Z
2020-04-03T16:30:33.000Z
puml-graphs/test/Test_Puml_dudes_experiments.py
StevenJV/Book_Generation_Z_Developer
7e2ff829faff41b1ce2f1f2f9cb88d712ebbc9ee
[ "Apache-2.0" ]
25
2018-02-19T22:42:13.000Z
2021-08-02T15:47:41.000Z
from unittest import TestCase from plantuml.API_Plant_UML import API_Plant_UML from utils.Dev import Dev from utils.Files import Files from utils.Show_Img import Show_Img from utils.aws.Lambdas import Lambdas class Test_Puml_dudes_experiments(TestCase): def setUp(self): self.plantuml = API_Plant_UML() def create_local_png(self, puml_file): png_file = '/tmp/{0}.png'.format(Files.file_name(puml_file)) puml = Files.contents(puml_file) img_url = 'https://github.com/DinisCruz/Book_Generation_Z_Developer/raw/dudes-test/puml-graphs/dudes/puml/' puml = puml.replace("<img:", "<img:{0}".format(img_url)) return self.plantuml.puml_to_png_using_lambda_function(puml, png_file) def test_create_puml____reader_sends_feedback(self): png_file = self.create_local_png('../diagrams/reader-sends-feedback.puml') # puml_file = '../diagrams/reader-sends-feedback.puml' # png_file = '/tmp/{0}.png'.format(Files.file_name(puml_file)) # puml = Files.contents(puml_file) # img_url = 'https://github.com/DinisCruz/Book_Generation_Z_Developer/raw/dudes-test/puml-graphs/dudes/puml/' # puml = puml.replace("<img:","<img:{0}".format(img_url)) # self.plantuml.puml_to_png_using_lambda_function(puml, png_file) def test_create_puml_use_content_from_book(self): png_file = self.create_local_png('../dudes/diagrams/use-content-from-book.puml') Dev.pprint(png_file) def test_create_puml_use_content_from_book(self): png_file = self.create_local_png('../puml/STEM-tech-stack.puml') Dev.pprint(png_file) # dudes def test_puml___dudes_creation(self): target_file = '/tmp/dudes-puml.png' puml = Files.contents('../dudes/puml/first-test.puml') #Dev.pprint(puml) #self.plantuml.puml_to_png_via_local_server(puml, target_file) self.plantuml.puml_to_png_using_lambda_function(puml,target_file) #Show_Img.from_path(png_file) #Dev.pprint(png_file)
37.654545
119
0.700145
c9ea159087966e57826e9359923305af0c1bf69d
565
ts
TypeScript
src/products/applications/delete.product.application.ts
eryzerz/nestjs-ddd
16bd1dfc7c1c368dec1b99788c07aeffe365f0f7
[ "MIT" ]
3
2022-01-14T20:01:10.000Z
2022-03-23T22:03:59.000Z
src/products/applications/delete.product.application.ts
eryzerz/nestjs-ddd
16bd1dfc7c1c368dec1b99788c07aeffe365f0f7
[ "MIT" ]
null
null
null
src/products/applications/delete.product.application.ts
eryzerz/nestjs-ddd
16bd1dfc7c1c368dec1b99788c07aeffe365f0f7
[ "MIT" ]
1
2022-02-23T15:12:53.000Z
2022-02-23T15:12:53.000Z
import { Inject, Injectable } from "@nestjs/common"; import { IDeleteProductApplication } from "../interfaces/applications/delete.product.application.interface"; import { PRODUCT_TYPES } from "../interfaces/types"; @Injectable() export class DeleteProductApplication implements IDeleteProductApplication { constructor( @Inject(PRODUCT_TYPES.services.IDeleteProductService) private productService: IDeleteProductApplication ){} async remove(id: string): Promise<{deleted: boolean}> { return await this.productService.remove(id) } }
37.666667
111
0.757522
459603db6ddc057350cd74440771c94e61afe547
368
py
Python
Estudos/Desafio021.py
boaventura16/Boaventura16
c8eca113d38d539c0eecdce358799f65787dcb72
[ "MIT" ]
2
2020-11-04T18:07:40.000Z
2020-11-21T03:50:33.000Z
Estudos/Desafio021.py
boaventura16/Boaventura16
c8eca113d38d539c0eecdce358799f65787dcb72
[ "MIT" ]
null
null
null
Estudos/Desafio021.py
boaventura16/Boaventura16
c8eca113d38d539c0eecdce358799f65787dcb72
[ "MIT" ]
null
null
null
ex = input('Digite uma expressão matematica:\n') lista = [] for simb in ex: if simb == '(': lista.append('(') elif simb == ')': if len(lista) > 0: lista.pop() else: lista.append(')') break if len(lista) == 0: print('Sua expressão está correta.') else: print('Sua expressão está errada.')
23
48
0.505435
961bc98c55f095b84d18aac43bb4a62028fdf3f9
408
sql
SQL
resources/sql/query-hours-by-day.sql
lshift/timetracker
d3dc770268da1219dbab4223649a53a2740ea9f9
[ "MIT" ]
null
null
null
resources/sql/query-hours-by-day.sql
lshift/timetracker
d3dc770268da1219dbab4223649a53a2740ea9f9
[ "MIT" ]
1
2017-07-17T14:00:28.000Z
2017-07-17T14:02:19.000Z
resources/sql/query-hours-by-day.sql
lshift/timetracker
d3dc770268da1219dbab4223649a53a2740ea9f9
[ "MIT" ]
null
null
null
SELECT start_time :: date :: text as day, u.name AS user_name, SUM(date_part('epoch', tt.end_time - tt.start_time) :: float / 3600) AS hours FROM task_time tt INNER JOIN users u ON u.id = tt.user_id WHERE u.name = :user_name AND tt.start_time >= :start_date :: date AND tt.start_time < :end_date :: date GROUP BY start_time :: date, u.name ORDER BY start_time :: date, u.name
40.8
85
0.664216
d040ad32d8e9a8dd8265530692d9ab8983b35d8c
3,410
cpp
C++
library/Java/Lang/ArithmeticException/ArithmeticExceptionTest.cpp
VietAnh14/native
8f9f23c2ff21ac14c69745556e04aaec36dbcd13
[ "Zlib" ]
1
2018-12-12T13:04:09.000Z
2018-12-12T13:04:09.000Z
library/Java/Lang/ArithmeticException/ArithmeticExceptionTest.cpp
vothaosontlu/native
2b8d062ce6db66dfdaa8b17087ba32455c9531e8
[ "Zlib" ]
null
null
null
library/Java/Lang/ArithmeticException/ArithmeticExceptionTest.cpp
vothaosontlu/native
2b8d062ce6db66dfdaa8b17087ba32455c9531e8
[ "Zlib" ]
null
null
null
/** * Copyright (c) 2016 Food Tiny Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../../../Test.hpp" #include "ArithmeticException.hpp" using namespace Java::Lang; TEST (JavaLangArithmeticException, Constructor) { // Constructs a new ArithmeticException with null as its detail message. InterruptedException arithmeticExceptionWithNullMessage; assertEquals("", arithmeticExceptionWithNullMessage.getMessage()); // Constructs a new ArithmeticException with the specified detail message. InterruptedException arithmeticExceptionWithMessage = InterruptedException( "ArithmeticException with the specified message"); assertEquals("ArithmeticException with the specified message", arithmeticExceptionWithMessage.getMessage()); // Constructs a new ArithmeticException with the specified detail message and cause. InterruptedException arithmeticExceptionWithMessageAndCause = InterruptedException( "ArithmeticException with the specified message and cause", &arithmeticExceptionWithMessage); assertEquals("ArithmeticException with the specified message and cause", arithmeticExceptionWithMessageAndCause.getMessage()); assertEquals("ArithmeticException with the specified message", arithmeticExceptionWithMessageAndCause.getCause()->getMessage()); // Constructs a new ArithmeticException with the specified cause. InterruptedException arithmeticExceptionWithCause = InterruptedException( &arithmeticExceptionWithMessageAndCause); assertEquals("ArithmeticException with the specified message and cause", arithmeticExceptionWithCause.getCause()->getMessage()); assertEquals("ArithmeticException with the specified message", arithmeticExceptionWithCause.getCause()->getCause()->getMessage()); } TEST (JavaLangArithmeticException, TryCatch) { try { throw InterruptedException("Throw ArithmeticException"); } catch (InterruptedException e) { assertEquals("Throw ArithmeticException", e.getMessage()); } }
50.147059
88
0.758651
143ff77c66a5452c14a6d6b32763955c26c16b39
47
ts
TypeScript
src/app/components/node/browse/display/index.ts
userlea/BatchExplorer
e826b88487c8dab82e12038f37bee7322d898b15
[ "MIT" ]
111
2018-07-17T14:42:58.000Z
2022-03-14T22:15:07.000Z
src/app/components/node/browse/display/index.ts
userlea/BatchExplorer
e826b88487c8dab82e12038f37bee7322d898b15
[ "MIT" ]
951
2018-07-16T23:45:05.000Z
2022-03-29T22:01:05.000Z
src/app/components/node/browse/display/index.ts
userlea/BatchExplorer
e826b88487c8dab82e12038f37bee7322d898b15
[ "MIT" ]
51
2018-08-03T17:27:19.000Z
2022-03-01T16:48:57.000Z
export * from "./node-list-display.component";
23.5
46
0.723404
b5fcec75141100437fac6db05418da529884b163
1,356
rb
Ruby
lib/rubyrati/base.rb
apostlion/rubyra
5b5ac2368423d907b5e003e4540beeddc1e68051
[ "Unlicense", "MIT" ]
1
2016-05-08T14:27:15.000Z
2016-05-08T14:27:15.000Z
lib/rubyrati/base.rb
apostlion/rubyra
5b5ac2368423d907b5e003e4540beeddc1e68051
[ "Unlicense", "MIT" ]
null
null
null
lib/rubyrati/base.rb
apostlion/rubyra
5b5ac2368423d907b5e003e4540beeddc1e68051
[ "Unlicense", "MIT" ]
1
2021-02-10T08:08:04.000Z
2021-02-10T08:08:04.000Z
require 'rubyrati' require 'rubygems' require 'net/http' require 'cgi' require 'hpricot' module Hpricot class Elem def get_html(xpath) search(xpath).inner_html end end end class String def tr_time_to_datetime DateTime.strptime(self, "%F %H:%M:%S %Z") end end ## # This module holds every class and every method that handles Technorati API. # It contains classes for every logical entity that exists in the realm of # Technorati datasets - Blog, Tag, Query, etc — and the Base class that all of # them extend to handle the query functionality. module Rubyrati class Base def initialize(args) end def fetch(path, key, *args) url = URI.parse("http://api.technorati.com/" + path) @complete_url = url.path + key(key) + args.collect{|x| set_arguments(x)}.join response = Net::HTTP.start(url.host, url.port) do |http| http.get @complete_url, 'User-Agent' => key, 'Accept' => 'text/xml' end result = Hpricot.XML(response.body.to_s) result end def key(key) "?key=#{CGI::escape key}" end def set_arguments(args) arguments = [] args.each do |key, value| arguments << "&#{key.to_s}=#{CGI::escape value.to_s}" end arguments.join end end class Blog < Base def initialize(url) @url = url end end end
21.870968
83
0.643805