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
sequencelengths
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
sequencelengths
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
sequencelengths
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
5d6de6ff03ea4e48c23109b4857d7e6d2a989d08
50
sql
SQL
resources/migrations/201911180000164-create-index-idx_form_template_prompt_sort.down.sql
jaydeesimon/vetd-app
d431e9e71de649102ce8a17a30a1041f90496787
[ "MIT" ]
98
2020-02-05T21:17:40.000Z
2022-03-03T19:40:24.000Z
resources/migrations/201911180000164-create-index-idx_form_template_prompt_sort.down.sql
jaydeesimon/vetd-app
d431e9e71de649102ce8a17a30a1041f90496787
[ "MIT" ]
2
2020-02-06T19:15:38.000Z
2020-02-09T17:45:00.000Z
resources/migrations/201911180000164-create-index-idx_form_template_prompt_sort.down.sql
jaydeesimon/vetd-app
d431e9e71de649102ce8a17a30a1041f90496787
[ "MIT" ]
19
2020-02-06T02:26:12.000Z
2022-02-11T19:43:16.000Z
DROP INDEX IF EXISTS idx_form_template_prompt_sort
50
50
0.92
fc8014ed4b9355c17a2cd5c2c556318da9052c46
5,603
dart
Dart
lib/views/booking/components/slot_list.dart
RyzAnugrah/parking_u
b6d1f3727cb975613992096c5d4564ef905d8e3c
[ "MIT" ]
null
null
null
lib/views/booking/components/slot_list.dart
RyzAnugrah/parking_u
b6d1f3727cb975613992096c5d4564ef905d8e3c
[ "MIT" ]
null
null
null
lib/views/booking/components/slot_list.dart
RyzAnugrah/parking_u
b6d1f3727cb975613992096c5d4564ef905d8e3c
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:parking_u/models/parkir_model.dart'; import 'package:sizer/sizer.dart'; import 'package:parking_u/constants.dart'; import 'package:parking_u/size_config.dart'; class SlotList extends StatefulWidget { final ParkirModel item; const SlotList({Key key, this.item}) : super(key: key); @override _SlotListState createState() => _SlotListState(); } class _SlotListState extends State<SlotList> { @override Widget build(BuildContext context) { return Column( children: [ SingleChildScrollView( scrollDirection: Axis.vertical, child: GridView.builder( itemCount: widget.item.lahanTersedia ~/ 2, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 4.0, ), primary: false, padding: const EdgeInsets.all(10.0), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return SlotListCard( number: ++index, available: true, press: () {}, ); }, ), ), SingleChildScrollView( scrollDirection: Axis.vertical, child: GridView.builder( itemCount: widget.item.lahanTidakTersedia, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 4.0, ), primary: false, padding: const EdgeInsets.all(10.0), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return SlotListCard( number: ++index + (widget.item.lahanTersedia ~/ 2), available: false, press: () {}, ); }, ), ), SingleChildScrollView( scrollDirection: Axis.vertical, child: GridView.builder( itemCount: widget.item.lahanTersedia ~/ 2, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 4.0, ), primary: false, padding: const EdgeInsets.all(10.0), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return SlotListCard( number: ++index + (widget.item.lahanTersedia ~/ 2) + (widget.item.lahanTidakTersedia), available: true, press: () {}, ); }, ), ), ], ); } } class SlotListCard extends StatefulWidget { const SlotListCard({ Key key, @required this.number, @required this.press, @required this.available, }) : super(key: key); final int number; final GestureTapCallback press; final bool available; @override _SlotListCardState createState() => _SlotListCardState(); } class _SlotListCardState extends State<SlotListCard> { bool availableColor; bool _colorTap = false; @override void initState() { super.initState(); availableColor = widget.available; } @override Widget build(BuildContext context) { return InkWell( child: GestureDetector( onTap: () => { }, onDoubleTap: widget.press, child: SizedBox( width: getProportionateScreenWidth(150), height: getProportionateScreenWidth(150), child: Padding( padding: EdgeInsets.symmetric( horizontal: getProportionateScreenWidth(10), vertical: getProportionateScreenWidth(20), ), child: Stack( children: [ Container( decoration: BoxDecoration( color: (availableColor ? (_colorTap ? infoColor : successColor) : pendingColor), border: Border.all(color: secondaryTextColor), borderRadius: borderRadius, ), ), Container( margin: EdgeInsets.symmetric( horizontal: 35.0, vertical: 25.0, ), decoration: BoxDecoration( color: primaryBackgroundColor, border: Border.all(color: secondaryTextColor), borderRadius: BorderRadius.circular(50.0), ), ), Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: Text( '${widget.number}', style: TextStyle( color: secondaryTextColor, fontSize: bodyText2.sp, fontWeight: FontWeight.w700, ), overflow: TextOverflow.ellipsis, maxLines: 2, textAlign: TextAlign.center, ), ), ], ), ), ], ), ), ), ), ); } }
30.785714
68
0.499732
f41a6268d0f10c0ade8e5df2406623c6d124c9e0
1,192
dart
Dart
lib/cryptography.dart
itMcdull/gl_cryptography
1bd3f97229ca9ba1f5fa83f29fc89f87f5ef02b3
[ "Apache-2.0" ]
null
null
null
lib/cryptography.dart
itMcdull/gl_cryptography
1bd3f97229ca9ba1f5fa83f29fc89f87f5ef02b3
[ "Apache-2.0" ]
null
null
null
lib/cryptography.dart
itMcdull/gl_cryptography
1bd3f97229ca9ba1f5fa83f29fc89f87f5ef02b3
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Gohilla ([email protected]). // // 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. /// A collection of cryptographic algorithms. library cryptography; export 'src/algorithms/chacha20.dart'; export 'src/algorithms/curve25519.dart'; export 'src/algorithms/hmac.dart'; export 'src/algorithms/sha2.dart'; export 'src/cryptography/cipher.dart'; export 'src/cryptography/hash_algorithm.dart'; export 'src/cryptography/key_exchange_algorithm.dart'; export 'src/cryptography/key_pair.dart'; export 'src/cryptography/mac_algorithm.dart'; export 'src/cryptography/public_key.dart'; export 'src/cryptography/secret_key.dart'; export 'src/cryptography/signature_algorithm.dart';
39.733333
75
0.78104
3a3069240fee96d573aba309e145ba64777d0faa
2,347
lua
Lua
Themes/_fallback/BGAnimations/ScreenPlayerOptions overlay.lua
kangalioo/etterna
11630aa1c23bad46b2da993602b06f8b659a4961
[ "MIT" ]
1
2020-11-09T21:58:28.000Z
2020-11-09T21:58:28.000Z
Themes/_fallback/BGAnimations/ScreenPlayerOptions overlay.lua
kangalioo/etterna
11630aa1c23bad46b2da993602b06f8b659a4961
[ "MIT" ]
null
null
null
Themes/_fallback/BGAnimations/ScreenPlayerOptions overlay.lua
kangalioo/etterna
11630aa1c23bad46b2da993602b06f8b659a4961
[ "MIT" ]
null
null
null
local t = Def.ActorFrame {} local NSPreviewSize = 0.5 local NSPreviewX = 35 local NSPreviewY = 125 local NSPreviewXSpan = 35 local NSPreviewReceptorY = -30 local OptionRowHeight = 35 local NoteskinRow = 0 function NSkinPreviewWrapper(dir, ele) return Def.ActorFrame { InitCommand = function(self) self:zoom(NSPreviewSize) end, LoadNSkinPreview("Get", dir, ele, PLAYER_1) } end t[#t + 1] = Def.ActorFrame { OnCommand = function(self) self:xy(NSPreviewX, NSPreviewY) for i = 0, SCREENMAN:GetTopScreen():GetNumRows() - 1 do if SCREENMAN:GetTopScreen():GetOptionRow(i) and SCREENMAN:GetTopScreen():GetOptionRow(i):GetName() == "NoteSkins" then NoteskinRow = i end end self:SetUpdateFunction( function(self) local row = SCREENMAN:GetTopScreen():GetCurrentRowIndex(PLAYER_1) local pos = 0 if row > 4 then pos = NSPreviewY + NoteskinRow * OptionRowHeight - (SCREENMAN:GetTopScreen():GetCurrentRowIndex(PLAYER_1) - 4) * OptionRowHeight else pos = NSPreviewY + NoteskinRow * OptionRowHeight end self:y(pos) self:visible(NoteskinRow - row > -5 and NoteskinRow - row < 7) end ) end, Def.ActorFrame { NSkinPreviewWrapper("Down", "Tap Note") }, Def.ActorFrame { InitCommand = function(self) self:y(NSPreviewReceptorY) end, NSkinPreviewWrapper("Down", "Receptor") } } if GetScreenAspectRatio() > 1.7 then t[#t][#(t[#t]) + 1] = Def.ActorFrame { Def.ActorFrame { InitCommand = function(self) self:x(NSPreviewXSpan * 1) end, NSkinPreviewWrapper("Left", "Tap Note") }, Def.ActorFrame { InitCommand = function(self) self:x(NSPreviewXSpan * 1):y(NSPreviewReceptorY) end, NSkinPreviewWrapper("Left", "Receptor") }, Def.ActorFrame { InitCommand = function(self) self:x(NSPreviewXSpan * 2) end, NSkinPreviewWrapper("Up", "Tap Note") }, Def.ActorFrame { InitCommand = function(self) self:x(NSPreviewXSpan * 2):y(NSPreviewReceptorY) end, NSkinPreviewWrapper("Up", "Receptor") }, Def.ActorFrame { InitCommand = function(self) self:x(NSPreviewXSpan * 3) end, NSkinPreviewWrapper("Right", "Tap Note") }, Def.ActorFrame { InitCommand = function(self) self:x(NSPreviewXSpan * 3):y(NSPreviewReceptorY) end, NSkinPreviewWrapper("Right", "Receptor") } } end return t
24.447917
121
0.683426
6d3f24f7fcc18a388802cfa833f0e2e247098ecd
1,681
ts
TypeScript
src/app/services/supabase.service.ts
flozim/cosTask
09d32e3487e8132d1dac99669450f34b6ead4eda
[ "MIT" ]
null
null
null
src/app/services/supabase.service.ts
flozim/cosTask
09d32e3487e8132d1dac99669450f34b6ead4eda
[ "MIT" ]
null
null
null
src/app/services/supabase.service.ts
flozim/cosTask
09d32e3487e8132d1dac99669450f34b6ead4eda
[ "MIT" ]
null
null
null
import { createClient, SupabaseClient } from "@supabase/supabase-js"; import { from } from "rxjs/internal/observable/from"; import { environment } from "src/environments/environment"; import { map, tap } from "rxjs/operators"; import { Observable } from "rxjs"; import { Injectable } from "@angular/core"; import { AppImg } from "../model/appImg"; @Injectable({ providedIn: 'root' }) export class SupabaseService { private supabase: SupabaseClient; constructor() { this.supabase = createClient(environment.supabaseUrl, environment.supbaseKey); } /** * * @returns Object[] with field id:number */ getAllAppImgIds(): Observable<any> { const query = this.supabase.from('appImg').select('id'); return from(query).pipe( map(res => res['body']) ); } getAppImgById(id: number): Observable<any> { const query = this.supabase.from('appImg').select('*').filter('id', 'eq', id); return from(query).pipe( map(res => res['body']) ); } /** * * @param tags * @param url * @returns AppImg[] */ postAppImg(tags: string[], url: string): Observable<any> { let tagsInString: string = ""; tags.forEach(tag => { tagsInString = tagsInString + tag + ','; }) if (tagsInString.charAt(tagsInString.length - 1) === ',') { tagsInString = tagsInString.slice(0, tagsInString.length - 1) } const query = this.supabase.from('appImg').insert({ data: url, tags: tagsInString }); return from(query).pipe( map(res => res['body']) ); } }
27.112903
93
0.577037
fa1d427f4907498834b2f85ae3fa22c683432fd1
7,916
cpp
C++
CodeSnippets/rotateMatrix.cpp
Teabeans/CPP_Learn
a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a
[ "MIT" ]
1
2019-01-31T23:42:59.000Z
2019-01-31T23:42:59.000Z
CodeSnippets/rotateMatrix.cpp
Teabeans/CPP_Learn
a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a
[ "MIT" ]
null
null
null
CodeSnippets/rotateMatrix.cpp
Teabeans/CPP_Learn
a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a
[ "MIT" ]
1
2020-03-04T18:09:15.000Z
2020-03-04T18:09:15.000Z
//-----------------------------------------------------------------------------| // Authorship //-----------------------------------------------------------------------------| // // Tim Lum // [email protected] // Created: 2018.07.15 // Modified: 2018.08.22 // /* 1.7 - RotateMatrix() - P.91 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? //-----------------------------------------------------------------------------| // PROBLEM SETUP AND ASSUMPTIONS //-----------------------------------------------------------------------------| A left rotation may be performed by calling a right rotation 3 times. Only the right (clockwise) rotation shall be handled The nature of the pixel is immaterial; we may handle the pixel as a 32-bit int Since the problem specifies an N x N matrix, we address a square aspect ratio To move a pixel 0 1 X 0 1 X +---+---+ +---+---+ ([0][0] becomes [1][0]) 0 | 1 | 2 | 0 | 4 | 1 | ([1][0] becomes [1][1]) +---+---+ +---+---+ 1 | 4 | 3 | 1 | 3 | 2 | +---+---+ +---+---+ Y Y Output format is ambiguous, though it is implied that the data itself should be rotated. However, displaying the "image" and its rotated result may also be acceptable. //-----------------------------------------------------------------------------| // NAIVE APPROACH //-----------------------------------------------------------------------------| Iterate across every pixel within a quadrant and for (4) times Identify the 4 sister-pixels And swap them in turn 0 1 2 X [X][Y] is sister to +---+---+---+ [XMax - X][Y] which is sister to 0 | 1 | 2 | 3 | [XMax - X][YMax - Y] which is sister to +---+---+---+ [X][YMax-Y] 1 | 8 | 9 | 4 | +---+---+---+ 2 | 7 | 6 | 5 | +---+---+---+ The global behavioral rule may be defined as: The 90 degree rotational position of any pixel in a square matrix with coordinates: X, Y Is (XMax - Y), X 0 1 2 X +---+---+---+ 0 | X | O | X | 0, 0 rotates 90 degrees to +---+---+---+ 2, 0 which rotates 90 degrees to 1 | O | O | O | 2, 2 which rotates 90 degrees to +---+---+---+ 0, 2 2 | X | O | X | +---+---+---+ //-----------------------------------------------------------------------------| // OPTIMIZATIONS //-----------------------------------------------------------------------------| 1) The orientation of the image may be stored as a separate value from 0 to 3. This may then be used to interpret the N, E, S, W orientation of the image without modifying the image itself. Effectively, we may interject an orientation filter which appropriately redirects array access based upon the rotational state of the image. This has the added benefit of functioning on non-square arrays, and also facilitates easy addition of -90 and 180 degree rotations. From an image editing standpoint, interpretation rather than alteration of the base data will also better preserve image information. //-----------------------------------------------------------------------------| // TIME COMPLEXITY //-----------------------------------------------------------------------------| Any solution which modifies the original body of data may not complete faster than in a time complexity of: O( n^2 ) A filter solution, however, only adds a constant time alteration to the random access lookup of the parent data. As a "rotation" is merely the toggling of a rotation byte, the filter may complete in a time complexity of: O( 1 ) //-----------------------------------------------------------------------------| // PSEUDOLOGIC //-----------------------------------------------------------------------------| Compare string lengths for equality Declare alphabet table charCounts For each character in string1 Add 1 to the appropriate table in charCounts For each character in string2 Subtract 1 from the appropriate table in charCounts If the result is <0 Return false //-----------------------------------------------------------------------------| // CODE (C++) //-----------------------------------------------------------------------------| */ // Compile with: // $ g++ --std=c++11 01_07_RotateMatrix.cpp -o RotateMatrix // Run with: // $ ./RotateMatrix #include <string> #include <iostream> #include <iomanip> #define WIDTH 3 #define HEIGHT 7 // Rotation control: // 0 == Base image // 1 == 90 degree clockwise rotation // 2 == 180 degree rotation // 3 == 270 degree rotation int ROTATION = 0; int IMAGE[ WIDTH ][ HEIGHT ]; // (+) --------------------------------| // #printMatrix( ) // ------------------------------------| // Desc: Print a matrix // Params: None // PreCons: None // PosCons: None // RetVal: None void printMatrix( ) { int xDim = WIDTH; int yDim = HEIGHT; if( ROTATION == 0 ) { // For rows 0 to MAX... for( int row = 0 ; row < yDim ; row++ ) { // Print column 0 to MAX for( int col = 0 ; col < xDim; col++ ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } else if( ROTATION == 1 ) { for( int col = 0 ; col < xDim ; col++ ) { for( int row = ( yDim - 1 ) ; row >= 0; row-- ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } else if ( ROTATION == 2 ) { for( int row = yDim-1 ; row >= 0 ; row-- ) { for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } else if ( ROTATION == 3 ) { for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) { for( int row = 0 ; row < yDim ; row++ ) { std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " "; } std::cout << std::endl << std::endl; } } } // (+) --------------------------------| // #rotateMatrix( ) // ------------------------------------| // Desc: Rotates a matrix // Params: None // PreCons: None // PosCons: None // RetVal: None void rotateMatrix( ) { ROTATION = ( ROTATION + 1 ) % 4; } //-----------------------------------------------------------------------------| // DRIVER //-----------------------------------------------------------------------------| // (+) --------------------------------| // #main( int, char* ) // ------------------------------------| // Desc: Code driver // Params: int arg1 - The number of command line arguments passed in // char* arg2 - The content of the command line arguments // PreCons: None // PosCons: None // RetVal: int - The exit code (0 for normal, -1 for error) int main( int argc, char* argv[ ] ) { std::cout << "Test of rotateMatrix( )" << std::endl; int xDim = WIDTH; int yDim = HEIGHT; // For row 0 to MAX for( int row = 0 ; row < yDim ; row++ ) { for( int col = 0 ; col < xDim ; col++ ) { IMAGE[ col ][ row ] = ( xDim * row ) + col; } } printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); std::cout << std::endl; std::cout << "Rotating..." << std::endl << std::endl; rotateMatrix( ); printMatrix( ); return( 0 ); } // Closing main( int, char* ) // End of file 01_07_RotateMatrix.cpp
28.681159
84
0.457302
fcb283a0a809671056f8f52d259da81c9f5b8372
1,180
dart
Dart
lib/main.dart
Clashkid155/Dspace
91029af7bfb74336524a53c9a6adb1524a79b2b2
[ "MIT" ]
null
null
null
lib/main.dart
Clashkid155/Dspace
91029af7bfb74336524a53c9a6adb1524a79b2b2
[ "MIT" ]
null
null
null
lib/main.dart
Clashkid155/Dspace
91029af7bfb74336524a53c9a6adb1524a79b2b2
[ "MIT" ]
null
null
null
import 'package:dspace/widgets/tab.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'function/functions.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { /// Use normal scaffold and use pageview(Might not be possible) in base scaffold /// Don' include empty dir /// use isolate on stream for the listing of dir /// List dir = []; @override void initState() { _(); super.initState(); // Future.microtask(() => null) } void _() async { //compute(await dirs(), '/'); dir = await compute(dirs, (await home()).toString()); setState(() {}); } @override Widget build(BuildContext context) { return MaterialApp( // showPerformanceOverlay: true, //initialRoute: 'Table', title: 'Dspace', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: Tabletest( datasource: dir, )); } }
22.264151
82
0.621186
ec6cf7fef367cce3a79d91a341e17037e6731435
327
sql
SQL
tests/feature/db_backup.sql
muzk6/sparrow
7c92f9b6ec065a7dd1994ba0793fe10dd8c6b2df
[ "MIT" ]
5
2020-01-14T17:40:11.000Z
2020-10-12T01:41:52.000Z
tests/feature/db_backup.sql
muzk6/sparrow
7c92f9b6ec065a7dd1994ba0793fe10dd8c6b2df
[ "MIT" ]
null
null
null
tests/feature/db_backup.sql
muzk6/sparrow
7c92f9b6ec065a7dd1994ba0793fe10dd8c6b2df
[ "MIT" ]
null
null
null
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `test`; DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL DEFAULT '', `order` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
32.7
79
0.697248
e2940544dc8f10bcf94059e7b62a94a157f6a4b9
698
js
JavaScript
src/App.js
Formalibus/bochaper
1f6d9b7f78355438dfa1d6fc931c1c369cf87e6a
[ "CC0-1.0" ]
null
null
null
src/App.js
Formalibus/bochaper
1f6d9b7f78355438dfa1d6fc931c1c369cf87e6a
[ "CC0-1.0" ]
null
null
null
src/App.js
Formalibus/bochaper
1f6d9b7f78355438dfa1d6fc931c1c369cf87e6a
[ "CC0-1.0" ]
null
null
null
import { BrowserRouter, HashRouter, Route, Switch } from "react-router-dom"; import Navbar from "./bochaper/Navbar"; import Footer from "./bochaper/Footer"; import Main from "./pages/Main"; import Tabs from "./pages/Tabs"; import Music from "./pages/Music"; function App() { return ( <BrowserRouter> <HashRouter basename="/"> <Navbar /> <Switch> <Route exact path="/"> <Main /> </Route> <Route path="/tabs"> <Tabs /> </Route> <Route path="/music"> <Music /> </Route> </Switch> <Footer /> </HashRouter> </BrowserRouter> ); } export default App;
22.516129
76
0.528653
00429ccac0c2eb21aacba9fa655f94e1021a5389
6,055
sql
SQL
toko.sql
arvitlp/ecom_arvita
9f760ef024321c21dc5ef5316626d15949d22da6
[ "MIT" ]
null
null
null
toko.sql
arvitlp/ecom_arvita
9f760ef024321c21dc5ef5316626d15949d22da6
[ "MIT" ]
null
null
null
toko.sql
arvitlp/ecom_arvita
9f760ef024321c21dc5ef5316626d15949d22da6
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Waktu pembuatan: 09 Apr 2020 pada 15.54 -- Versi server: 10.1.37-MariaDB -- Versi PHP: 5.6.40 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: `toko` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `tb_barang` -- CREATE TABLE `tb_barang` ( `id_brg` int(11) NOT NULL, `nama_brg` varchar(200) NOT NULL, `keterangan` varchar(300) NOT NULL, `kategori` varchar(100) NOT NULL, `harga` int(11) NOT NULL, `stok` int(4) NOT NULL, `gambar` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tb_barang` -- INSERT INTO `tb_barang` (`id_brg`, `nama_brg`, `keterangan`, `kategori`, `harga`, `stok`, `gambar`) VALUES (2, 'Handphone', 'Iphone 11 Pro ', 'hp', 19000000, 4, 'hp1.jpg'), (5, 'Kamera', 'Kamera Fujifilm X-A01', 'Kamera', 12000000, 4, 'kamera1.jpg'), (8, 'Laptop', 'Laptop Asus VivoBook', 'Elektronik', 8000000, 14, 'laptop1.jpg'), (11, 'Kamera Canon', 'Kamera DSLR Canon', 'Kamera', 5000000, 9, 'canon1.jpg'), (12, 'Tongsis ', 'Tongsis Gurita', 'Aksesoris', 50000, 10, 'tongsis1.jpg'), (13, 'Mixer', 'Mixer Portable', 'Elektronik', 4500000, 9, 'mixer2.jpg'), (14, 'HP ', 'HP Samsung A50', 'Hp', 3500000, 5, 'hpsamsung1.jpg'), (15, 'HP ', 'HP Xiaomi Redmi Note 7', 'Hp', 1850000, 15, 'hp21.jpg'), (16, 'TV Panasonic', 'TV LED Panasonnic', 'Elektronik', 4500000, 5, 'tvpanasonic1.jpg'), (17, 'Blender', 'Blender Pink Cantik', 'Elektronik', 350000, 4, 'blender1.jpg'); -- -------------------------------------------------------- -- -- Struktur dari tabel `tb_invoice` -- CREATE TABLE `tb_invoice` ( `id` int(11) NOT NULL, `nama` varchar(100) NOT NULL, `alamat` varchar(250) NOT NULL, `tgl_pesan` datetime NOT NULL, `batas_bayar` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tb_invoice` -- INSERT INTO `tb_invoice` (`id`, `nama`, `alamat`, `tgl_pesan`, `batas_bayar`) VALUES (1, 'Arvita', 'Semarang', '2020-04-03 11:00:53', '2020-04-04 11:00:53'), (3, 'bambang', 'Semarang', '2020-04-03 11:42:59', '2020-04-04 11:42:59'), (4, '', '', '2020-04-04 20:24:29', '2020-04-05 20:24:29'), (5, '', '', '2020-04-04 20:24:55', '2020-04-05 20:24:55'), (6, 'Arvita', 'Jakarta Barat', '2020-04-08 01:41:28', '2020-04-09 01:41:28'), (7, 'Arvita', 'Jakarta Barat', '2020-04-08 01:42:06', '2020-04-09 01:42:06'), (8, 'Arvita', 'Jakarta Barat', '2020-04-08 01:43:39', '2020-04-09 01:43:39'), (9, 'Arvita', 'Jakarta Barat', '2020-04-08 01:44:06', '2020-04-09 01:44:06'), (10, 'Arvita', 'Jakarta Barat', '2020-04-08 01:44:27', '2020-04-09 01:44:27'), (11, '', '', '2020-04-08 01:49:54', '2020-04-09 01:49:54'), (12, '', '', '2020-04-08 01:49:55', '2020-04-09 01:49:55'), (13, '', '', '2020-04-08 01:49:55', '2020-04-09 01:49:55'), (14, '', '', '2020-04-08 01:56:21', '2020-04-09 01:56:21'); -- -------------------------------------------------------- -- -- Struktur dari tabel `tb_pesanan` -- CREATE TABLE `tb_pesanan` ( `id` int(11) NOT NULL, `id_invoice` int(11) NOT NULL, `id_brg` int(11) NOT NULL, `nama_brg` varchar(200) NOT NULL, `jumlah` int(3) NOT NULL, `harga` int(10) NOT NULL, `pilihan` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tb_pesanan` -- INSERT INTO `tb_pesanan` (`id`, `id_invoice`, `id_brg`, `nama_brg`, `jumlah`, `harga`, `pilihan`) VALUES (2, 1, 3, 'Jam', 1, 15000000, ''), (3, 0, 3, 'Jam', 1, 15000000, ''), (4, 3, 5, 'Kamera', 1, 12000000, ''), (5, 4, 2, 'Handphone', 1, 19000000, ''), (6, 4, 13, 'Mixer', 1, 4500000, ''), (7, 5, 2, 'Handphone', 1, 19000000, ''), (8, 6, 8, 'Laptop', 1, 8000000, ''), (9, 11, 11, 'Kamera Canon', 1, 5000000, ''), (10, 14, 5, 'Kamera', 1, 12000000, ''); -- -- Trigger `tb_pesanan` -- DELIMITER $$ CREATE TRIGGER `pesanan_penjualan` AFTER INSERT ON `tb_pesanan` FOR EACH ROW BEGIN UPDATE tb_barang SET stok = stok-NEW.jumlah WHERE id_brg =NEW.id_brg; END $$ DELIMITER ; -- -------------------------------------------------------- -- -- Struktur dari tabel `tb_user` -- CREATE TABLE `tb_user` ( `id` int(11) NOT NULL, `nama` varchar(100) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(50) NOT NULL, `role_id` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tb_user` -- INSERT INTO `tb_user` (`id`, `nama`, `username`, `password`, `role_id`) VALUES (1, 'admin', 'admin', '123', 1), (2, 'user', 'user', '123', 2); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `tb_barang` -- ALTER TABLE `tb_barang` ADD PRIMARY KEY (`id_brg`); -- -- Indeks untuk tabel `tb_invoice` -- ALTER TABLE `tb_invoice` ADD PRIMARY KEY (`id`); -- -- Indeks untuk tabel `tb_pesanan` -- ALTER TABLE `tb_pesanan` ADD PRIMARY KEY (`id`); -- -- Indeks untuk tabel `tb_user` -- ALTER TABLE `tb_user` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT untuk tabel yang dibuang -- -- -- AUTO_INCREMENT untuk tabel `tb_barang` -- ALTER TABLE `tb_barang` MODIFY `id_brg` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT untuk tabel `tb_invoice` -- ALTER TABLE `tb_invoice` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT untuk tabel `tb_pesanan` -- ALTER TABLE `tb_pesanan` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT untuk tabel `tb_user` -- ALTER TABLE `tb_user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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 */;
28.294393
106
0.623947
e747bdc1bec4ffd07afbbc0ee3f23d9192f5c010
1,002
php
PHP
app/Http/Controllers/Admin/ProductImageController.php
Dejan1990/E-Commerce-App
939ce6401c20fae9cbb44c1099cbda9159a3c4be
[ "MIT" ]
null
null
null
app/Http/Controllers/Admin/ProductImageController.php
Dejan1990/E-Commerce-App
939ce6401c20fae9cbb44c1099cbda9159a3c4be
[ "MIT" ]
null
null
null
app/Http/Controllers/Admin/ProductImageController.php
Dejan1990/E-Commerce-App
939ce6401c20fae9cbb44c1099cbda9159a3c4be
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Product; use App\Models\ProductImage; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; class ProductImageController extends Controller { public function upload(Request $request) { $request->validate([ 'image' => ['required', 'image', 'mimes:jpg,png,jpeg', 'max:2048'] ]); if ($request->file('image')) { $request->image = $request->file('image')->store('product'); } $product = Product::find($request->product_id); $product->images()->create([ 'image' => $request->image ]); return response()->json(['status' => 'Success']); } public function delete($id) { $image = ProductImage::find($id); if (Storage::exists($image->image)) { Storage::delete($image->image); } $image->delete(); return back(); } }
22.266667
78
0.572854
057b730a2f2ed588317f3ad487c59eae9d7949b6
3,287
lua
Lua
lua/prosesitter/linter/lintreq.lua
dvdsk/prosesitter.nvim
fc8b34e6f60ef212bfe7b6e98b64b818d472f36c
[ "MIT" ]
6
2021-11-08T23:43:47.000Z
2022-03-13T12:43:21.000Z
lua/prosesitter/linter/lintreq.lua
dskleingeld/prosesitter
fc8b34e6f60ef212bfe7b6e98b64b818d472f36c
[ "MIT" ]
21
2021-07-09T16:32:32.000Z
2021-09-19T17:01:25.000Z
lua/prosesitter/linter/lintreq.lua
dvdsk/prosesitter.nvim
fc8b34e6f60ef212bfe7b6e98b64b818d472f36c
[ "MIT" ]
null
null
null
local log = require("prosesitter/log") local util = require("prosesitter/util") local state = require("prosesitter/state") local api = vim.api local ns = state.ns_placeholders local M = {} M.__index = M -- failed table lookups on the instances should fallback to the class table, to get methods function M.new() local self = setmetatable({}, M) -- an array self.text = {} -- key: placeholder_id, -- value: arrays of tables of buf, id(same as key), row_col, idx self.meta_by_mark = {} -- key: index of corrosponding text in self.text (idx) -- value: table of buf, id, row_col, idx(same as key) self.meta_by_idx = {} return self end -- text can be empty list -- needs to be passed 1 based start_col function M:add_range(buf, lines, start_row, start_col) for i, text in ipairs(lines) do local row = start_row - 1 + i self:add(buf, text, row, start_col) start_col = 1 end end function M:append(buf, id, text, start_col) local meta_list = self.meta_by_mark[id] local meta = { buf = buf, id = id, row_col = start_col, idx = #self.text + 1, } meta_list[#meta_list + 1] = meta self.meta_by_idx[meta.idx] = meta self.text[meta.idx] = text end function M:add(buf, text, row, start_col) local id = nil local marks = api.nvim_buf_get_extmarks(buf, ns, { row, 0 }, { row, 0 }, {}) if #marks > 0 then id = marks[1][1] -- there can be a max of 1 placeholder per line if self.meta_by_mark[id] ~= nil then self:append(buf, id, text, start_col) return end else id = api.nvim_buf_set_extmark(buf, ns, row, 0, { end_col = 0 }) end local meta = { buf = buf, id = id, row_col = start_col, idx = #self.text + 1 } self.meta_by_mark[id] = { meta } self.meta_by_idx[meta.idx] = meta self.text[meta.idx] = text end local function delete_by_idx(deleted_meta, array, map) for i = #deleted_meta, 1, -1 do local idx = deleted_meta[i].idx table.remove(array, idx) table.remove(map, idx) end end function M:clear_lines(buf, start, stop) local marks = api.nvim_buf_get_extmarks(buf, ns, { start, 0 }, { stop, 0 }, {}) for i = #marks, 1, -1 do local mark = marks[i] local id = mark[1] local deleted = self.meta_by_mark[id] if deleted ~= nil then self.meta_by_mark[id] = {} delete_by_idx(deleted, self.text, self.meta_by_idx) end end end function M:is_empty() local empty = next(self.text) == nil return empty end -- returns a request with members: function M:build() local req = {} req.text = table.concat(self.text, " ") req.areas = {} -- TODO hide check under debug flag local meta_seen = {} for _, meta in ipairs(self.meta_by_idx) do local hash = table.concat({meta.buf,meta.id,meta.row_col},",") if meta_seen[hash] ~= nil then assert(false, "lintreq contains duplicates!") end meta_seen[hash] = true end local col = 0 for i = 1, #self.text do local meta = self.meta_by_idx[i] local area = { col = col, -- column in text passed to linter row_col = meta.row_col, -- column in buffer row_id = meta.id, -- extmark at the start of the row buf_id = meta.buf, } req.areas[#req.areas + 1] = area col = col + #self.text[i] + 1 -- plus one for the line end end self:reset() return req end function M:reset() self.text = {} self.meta_by_mark = {} self.meta_by_idx = {} end return M
25.091603
105
0.672041
2c8491766b0000c5fc83a77dc8c63fa70a598ad8
503
py
Python
src/vaulthelpers/management/commands/revoke_vault_leases.py
ArroyoDev-LLC/django-vault-helpers
14777c7a50dc52d5a6be95c094f3b2105488b5db
[ "0BSD" ]
null
null
null
src/vaulthelpers/management/commands/revoke_vault_leases.py
ArroyoDev-LLC/django-vault-helpers
14777c7a50dc52d5a6be95c094f3b2105488b5db
[ "0BSD" ]
null
null
null
src/vaulthelpers/management/commands/revoke_vault_leases.py
ArroyoDev-LLC/django-vault-helpers
14777c7a50dc52d5a6be95c094f3b2105488b5db
[ "0BSD" ]
null
null
null
from django.core.management.base import BaseCommand from vaulthelpers import common class Command(BaseCommand): help = 'Revoke the active Vault token and any associated secret leases' def handle(self, *args, **options): authenticator = common.get_vault_auth() if authenticator is None: return client = authenticator.authenticated_client() client.revoke_self_token() self.stdout.write('Revoked Vault token and all associated secret leases')
33.533333
81
0.713718
c5775c7db57a26d09a7c690d54ae1257a7a9f10e
116
css
CSS
BetterTouchToolDocs/styles/website.css
idjevm/BetterTouchTool
7a53a8401de46b6c7c98f7069a6d08c71f31110b
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
BetterTouchToolDocs/styles/website.css
idjevm/BetterTouchTool
7a53a8401de46b6c7c98f7069a6d08c71f31110b
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
BetterTouchToolDocs/styles/website.css
idjevm/BetterTouchTool
7a53a8401de46b6c7c98f7069a6d08c71f31110b
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
.page-inner { position: relative; max-width: 1000px; margin: 0 auto; padding: 20px 15px 40px 15px; }
19.333333
33
0.62931
78f58952c461a5a4bbaf44d5fe59277b0dae4b93
2,760
lua
Lua
Interface/AddOns/Prat-3.0/services/links.lua
swgloomy/Wow-plugin
187e1e27f2cc3fbe7962d1a0ab00e30b8b06f0da
[ "MIT" ]
null
null
null
Interface/AddOns/Prat-3.0/services/links.lua
swgloomy/Wow-plugin
187e1e27f2cc3fbe7962d1a0ab00e30b8b06f0da
[ "MIT" ]
null
null
null
Interface/AddOns/Prat-3.0/services/links.lua
swgloomy/Wow-plugin
187e1e27f2cc3fbe7962d1a0ab00e30b8b06f0da
[ "MIT" ]
null
null
null
--------------------------------------------------------------------------------- -- -- Prat - A framework for World of Warcraft chat mods -- -- Copyright (C) 2006-2018 Prat Development Team -- -- This program 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. -- -- This program 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 this program; if not, write to: -- -- Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- -- ------------------------------------------------------------------------------- --[[ BEGIN STANDARD HEADER ]] -- -- Imports local _G = _G local LibStub = LibStub local pairs, ipairs = pairs, ipairs local tinsert, tremove, tconcat = table.insert, table.remove, table.concat -- Isolate the environment setfenv(1, select(2, ...)) --[[ END STANDARD HEADER ]] -- local function debug(...) -- _G.ChatFrame1:print(...) end function BuildLink(linktype, data, text, color, link_start, link_end) return "|cff" .. (color or "ffffff") .. "|H" .. linktype .. ":" .. data .. "|h" .. (link_start or "[") .. text .. (link_end or "]") .. "|h|r" end do LinkRegistry = {} local LinkOwners = {} -- linktype = { linkid, linkfunc, handler } function RegisterLinkType(linktype, who) if linktype and linktype.linkid and linktype.linkfunc then tinsert(LinkRegistry, linktype) local idx = #LinkRegistry debug([[DBG_LINK("RegisterLinkType", who, linktype.linkid, idx)]]) if idx then LinkOwners[idx] = who end return idx end end function UnregisterAllLinkTypes(who) debug([[DBG_LINK("UnregisterAllLinkTypes", who)]]) for k,owner in pairs(LinkOwners) do if owner == who then UnregisterLinkType(k) end end end function UnregisterLinkType(idx) tremove(LinkRegistry, idx) end function SetHyperlinkHook(hooks, frame, link, ...) debug("SetItemRef ", link, ...) for i,reg_link in ipairs(LinkRegistry) do if reg_link.linkid == link:sub(1, (reg_link.linkid):len()) then if (reg_link.linkfunc(reg_link.handler, link, ...) == false) then debug([[DUMP_LINK("SetItemRef ", "Link Handled Internally")]]) return false end end end hooks.SetHyperlink(frame, link, ...) end end
26.285714
143
0.625725
da8fd77ab3b627c2473e97d8a92ba1d7cc465b80
9,367
php
PHP
src/Resources/views/Web/Cart/cargo_select.html.php
cagatayy94/symfonyshop.tk
28027995f773bd88692582826ae84534a0053314
[ "MIT" ]
null
null
null
src/Resources/views/Web/Cart/cargo_select.html.php
cagatayy94/symfonyshop.tk
28027995f773bd88692582826ae84534a0053314
[ "MIT" ]
null
null
null
src/Resources/views/Web/Cart/cargo_select.html.php
cagatayy94/symfonyshop.tk
28027995f773bd88692582826ae84534a0053314
[ "MIT" ]
null
null
null
<?php $view->extend('Web/default.html.php'); ?> <?php $view['slots']->start('body'); ?> <div role="main" class="main"> <section class="page-header"> <div class="container"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb"> <li><a href="/">Anasayfa</a></li> <li class="active">Adres Seçimi</li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1 class="font-weight-bold">Adres Seçimi</h1> </div> </div> </div> </section> <section class="section" style="padding-top: 0"> <div class="container"> <div class="row"> <div class="col"> <form id="address_selection" action="<?php echo $this->get('router')->path('cart_update_address_and_cargo') ?>" method="post"> <div class="row"> <div class="col-md-12"> <button type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#add_address_modal">Yeni Adres Ekle</button> </div> </div> <div class="row"> <div class="col-md-6"> <div class="row d-flex justify-content-center"> <h2 class="font-weight-bold mb-3">Fatura Adresi</h2> </div> <div class="row"> <div class="col-md-12 billing_address_holder"> </div> </div> </div> <div class="col-md-6"> <div class="row row d-flex justify-content-center"> <h2 class="font-weight-bold mb-3">Kargo Adresi</h2> </div> <div class="row"> <div class="col-md-12 shipping_address_holder"> Lütfen Adres Ekleyin </div> </div> </div> </div> <div class="form-row"> <div class="form-group col"> <label class="text-color-dark font-weight-semibold" for="shipping_company">KARGO FIRMASI:</label> <select class="form-control line-height-1 bg-light-5 required" name="shipping_company_id" id="shipping_company" required=""> <option value="">Seçiniz</option> <?php foreach ($cargoCompany as $value): ?> <option value="<?php echo $value['id'] ?>"><?php echo $value['name'] ?></option> <?php endforeach ?> </select> </div> </div> <div class="row"> <div class="col text-right"> <button class="btn btn-primary btn-rounded font-weight-bold btn-h-2 btn-v-3" type="submit">ÖDEME ADIMINA GEÇ</button> </div> </div> </form> </div> </div> </div> </section> </div> <div class="modal fade" id="add_address_modal" tabindex="-1" role="dialog" aria-labelledby="add_address_modal" aria-hidden="true"> <div class="modal-dialog text-left" role="document"> <div class="modal-content"> <form action="<?php echo $this->get('router')->path('add_user_addresses') ?>" method="post" class="contact-form form-style-2" id="add_address_form"> <div class="modal-header"> <h5 class="modal-title">Yeni adres ekleyin</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label for="adres-ismi" class="form-control-label">*Adres başlığı (Ev, İş)</label> <input type="text" name="address_name" class="form-control required"> <label for="adres-ismi" class="form-control-label">*Adresteki isim</label> <input type="text" name="full_name" class="form-control required"> <label for="adres" class="form-control-label">*Adres</label> <input type="text" name="address" class="form-control required"> <label for="ilce" class="form-control-label">*İlçe</label> <input type="text" name="county" class="form-control required"> <label for="sehir" class="form-control-label">*Şehir</label> <input type="text" name="city" class="form-control required"> <label for="telefon" class="form-control-label">*Telefon</label> <input type="text" name="mobile" class="form-control mobile-mask required"> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">Kaydet</button> <button type="button" class="btn" data-dismiss="modal">Kapat</button> </div> </form> </div> </div> </div> <div class="modal fade" id="update_address_modal_in_cart" tabindex="-1" role="dialog" aria-labelledby="update_address_modal_in_cart" aria-hidden="true"> <div class="modal-dialog text-left" role="document"> <div class="modal-content"> <form action="<?php echo $this->get('router')->path('update_user_addresses') ?>" method="post" class="contact-form form-style-2" id="update_address_form_in_cart"> <input type="hidden" name="address_id"> <div class="modal-header"> <h5 class="modal-title" id="exampleModal4Label">Adres Güncelle</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label for="address_name" class="form-control-label">*Adres başlığı (Ev, İş)</label> <input type="text" name="address_name" class="form-control required"> <label for="adres-ismi" class="form-control-label">*Adresteki isim</label> <input type="text" name="full_name" class="form-control required"> <label for="adres" class="form-control-label">*Adres</label> <input type="text" name="address" class="form-control required"> <label for="ilce" class="form-control-label">*İlçe</label> <input type="text" name="county" class="form-control required"> <label for="sehir" class="form-control-label">*Şehir</label> <input type="text" name="city" class="form-control required"> <label for="telefon" class="form-control-label">*Telefon</label> <input type="tel" name="mobile" class="form-control mobile-mask required"> </div> </div> <div class="modal-footer"> <input align="right" class="btn btn-primary" value="Güncelle" type="Submit" class="form-control"> <button type="button" class="btn" data-dismiss="modal">Kapat</button> </div> </form> </div> </div> </div> <script type="text/javascript"> function defer(method) { if (window.jQuery) { method(); } else { setTimeout(function() { defer(method) }, 50); } } defer(function () { $(document).ready(function() { updateAddressesInCart(); }); }); </script> <?php $view['slots']->stop(); ?>
55.755952
178
0.430874
30a3f0dee4314b70c7c0d1fb712a87fbc79af188
725
lua
Lua
MMOCoreORB/bin/scripts/mobile/lair/creature_lair/yavin4_tybis_male_neutral_medium_boss_01.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/mobile/lair/creature_lair/yavin4_tybis_male_neutral_medium_boss_01.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/mobile/lair/creature_lair/yavin4_tybis_male_neutral_medium_boss_01.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
yavin4_tybis_male_neutral_medium_boss_01 = Lair:new { mobiles = {{"male_tybis", 1},{"female_tybis", 1}}, bossMobiles = {{"grand_tybis",1}}, spawnLimit = 15, buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_dead_log_large_fog_green.iff"}, buildingsEasy = {"object/tangible/lair/base/poi_all_lair_dead_log_large_fog_green.iff"}, buildingsMedium = {"object/tangible/lair/base/poi_all_lair_dead_log_large_fog_green.iff"}, buildingsHard = {"object/tangible/lair/base/poi_all_lair_dead_log_large_fog_green.iff"}, buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_dead_log_large_fog_green.iff"}, } addLairTemplate("yavin4_tybis_male_neutral_medium_boss_01", yavin4_tybis_male_neutral_medium_boss_01)
55.769231
101
0.817931
18625e60946914d4e97bc4d51a5a56e54b26bf84
1,464
swift
Swift
ChowTown/Models/Meal.swift
jordainfg/ChowTown
6e05598d53746e83f1669e46fab985d89813f53e
[ "MIT" ]
null
null
null
ChowTown/Models/Meal.swift
jordainfg/ChowTown
6e05598d53746e83f1669e46fab985d89813f53e
[ "MIT" ]
null
null
null
ChowTown/Models/Meal.swift
jordainfg/ChowTown
6e05598d53746e83f1669e46fab985d89813f53e
[ "MIT" ]
null
null
null
// // Meal.swift // ChowTown // // Created by Jordain Gijsbertha on 21/11/2019. // Copyright © 2019 Jordain Gijsbertha. All rights reserved. // import Foundation public struct Meal{ var companyID : String var name: String var detail : String var price : Double var about : Array<Int> var allergens: Array<Any> var calories : String var protein : String var fat : String var carbs : String var additions: Array<String> var isPopular : Bool var imageRef : String init?(dictionary: [String: Any]) { guard let companyID = dictionary["companyID"] as? String else { return nil } self.companyID = companyID self.name = dictionary["name"] as! String self.detail = dictionary["detail"] as! String self.price = dictionary["price"] as! Double self.about = dictionary["about"] as! Array<Int> self.allergens = dictionary["allergens"] as! Array<Any> self.protein = dictionary["protein"] as! String self.calories = dictionary["calories"] as! String self.fat = dictionary["fat"] as! String self.carbs = dictionary["carbs"] as! String self.additions = dictionary["additions"] as! Array<String> self.isPopular = dictionary["isPopular"] as! Bool self.imageRef = dictionary["imageRef"] as! String } }
31.826087
88
0.595628
b0594ae49374433f3aa1f3742afab1c61b1b7b74
444
py
Python
py_code/test_0.py
marcoromanelli-github/GreedyFeatureSelection
d8fcba2701422c689e526b6a0f70bb121cca323c
[ "MIT" ]
null
null
null
py_code/test_0.py
marcoromanelli-github/GreedyFeatureSelection
d8fcba2701422c689e526b6a0f70bb121cca323c
[ "MIT" ]
null
null
null
py_code/test_0.py
marcoromanelli-github/GreedyFeatureSelection
d8fcba2701422c689e526b6a0f70bb121cca323c
[ "MIT" ]
null
null
null
import numpy as np from gfs import PygfsManager def test0(): feat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 1, 1]]) labels = [1, 3, 4, 5] gfsMan = PygfsManager(feat, labels, "shannon".encode()) print("Selected features ---> ", gfsMan.greedyAlgorithm(2)) gfsMan = PygfsManager(feat, labels, "renyi".encode()) print("Selected features ---> ", gfsMan.greedyAlgorithm(2)) if __name__ == '__main__': test0()
24.666667
65
0.608108
4576de23e37082e2dea8e638cef12f85c2f2f63b
5,442
py
Python
test/unit2/usersignup/validation_test.py
cdoremus/udacity-python_web_development-cs253
87cf5dd5d0e06ee745d3aba058d96fa46f2aeb6b
[ "Apache-2.0" ]
null
null
null
test/unit2/usersignup/validation_test.py
cdoremus/udacity-python_web_development-cs253
87cf5dd5d0e06ee745d3aba058d96fa46f2aeb6b
[ "Apache-2.0" ]
null
null
null
test/unit2/usersignup/validation_test.py
cdoremus/udacity-python_web_development-cs253
87cf5dd5d0e06ee745d3aba058d96fa46f2aeb6b
[ "Apache-2.0" ]
null
null
null
''' Created on Apr 25, 2012 @author: h87966 ''' import unittest from unit2.usersignup.validation import UserSignupValidation from unit2.usersignup.validation import VERIFICATION_MESSAGES from unit2.usersignup.validation import VERIFICATION_MESSAGES_KEYS from unit2.usersignup.validation import MISMATCHED_PASSWORDS_MESSAGE class Test(unittest.TestCase): def setUp(self): self.validation = UserSignupValidation() pass def tearDown(self): pass def testIsValidUsername(self): self.assertTrue(self.validation.is_valid_username("Crag")) self.assertTrue(self.validation.is_valid_username("Crag-Doremus")) self.assertTrue(self.validation.is_valid_username("Crag_Doremus")) self.assertTrue(self.validation.is_valid_username("Cra")) self.assertFalse(self.validation.is_valid_username("ca")) self.assertFalse(self.validation.is_valid_username("cat!")) self.assertTrue(self.validation.is_valid_username("abcdefghijklmnopqrst")) self.assertFalse(self.validation.is_valid_username("abcdefghijklmnopqrstu")) pass def testIsValidPassword(self): self.assertTrue(self.validation.is_valid_password("Craig")) self.assertTrue(self.validation.is_valid_password("abcdefghijklmnopqrst")) self.assertFalse(self.validation.is_valid_password("abcdefghijklmnopqrstu")) pass def testIsValidEmail(self): self.assertTrue(self.validation.is_valid_email("[email protected]")) self.assertTrue(self.validation.is_valid_email("[email protected]")) self.assertFalse(self.validation.is_valid_email("Craigfoocom")) pass def testValid(self): username = "Craig" password = "craig1" verify = "craig1" email = "[email protected]" validMsgs, isValid = self.validation.validate(username, password, verify, email) self.assertTrue(isValid) self.assertEmptyMessage([VERIFICATION_MESSAGES_KEYS[0],VERIFICATION_MESSAGES_KEYS[1],VERIFICATION_MESSAGES_KEYS[2],VERIFICATION_MESSAGES_KEYS[3]], validMsgs) def testValid_BadUsername(self): username = "Craigasdfasdfasdfasdfadfadfs" password = "craig1" verify = "craig1" email = "[email protected]" validMsgs, isValid = self.validation.validate(username, password, verify, email) self.assertFalse(isValid) self.assertEquals(VERIFICATION_MESSAGES[VERIFICATION_MESSAGES_KEYS[0]], validMsgs[VERIFICATION_MESSAGES_KEYS[0]]) self.assertEmptyMessage([VERIFICATION_MESSAGES_KEYS[1],VERIFICATION_MESSAGES_KEYS[2],VERIFICATION_MESSAGES_KEYS[3]], validMsgs) def testValid_BadPassword(self): username = "Craig" password = "c1" verify = "c1" email = "[email protected]" validMsgs, isValid = self.validation.validate(username, password, verify, email) self.assertFalse(isValid) self.assertEquals(VERIFICATION_MESSAGES[VERIFICATION_MESSAGES_KEYS[1]], validMsgs[VERIFICATION_MESSAGES_KEYS[1]]) self.assertEquals(VERIFICATION_MESSAGES[VERIFICATION_MESSAGES_KEYS[2]], validMsgs[VERIFICATION_MESSAGES_KEYS[2]]) self.assertEmptyMessage([VERIFICATION_MESSAGES_KEYS[0],VERIFICATION_MESSAGES_KEYS[3]], validMsgs) # def testValid_BadVerifyPassword(self): # username = "Craig" # password = "c1" # verify = "c1" # email = "[email protected]" # validMsgs, isValid = self.validation.validate(username, password, verify, email) # self.assertFalse(isValid) # self.assertEquals(VERIFICATION_MESSAGES[VERIFICATION_MESSAGES_KEYS[2]], validMsgs[VERIFICATION_MESSAGES_KEYS[2]]) # self.assertEmptyMessage([VERIFICATION_MESSAGES_KEYS[0],VERIFICATION_MESSAGES_KEYS[1],VERIFICATION_MESSAGES_KEYS[3]], validMsgs) def testValid_BadEmail(self): username = "Craig" password = "craig1" verify = "craig1" email = "craigfoo.com" validMsgs, isValid = self.validation.validate(username, password, verify, email) self.assertFalse(isValid) self.assertEquals(VERIFICATION_MESSAGES[VERIFICATION_MESSAGES_KEYS[3]], validMsgs[VERIFICATION_MESSAGES_KEYS[3]]) self.assertEmptyMessage([VERIFICATION_MESSAGES_KEYS[0],VERIFICATION_MESSAGES_KEYS[2],VERIFICATION_MESSAGES_KEYS[1]], validMsgs) def testValid_PasswordsDontMatch(self): username = "Craig" password = "craig1" verify = "craig" email = "[email protected]" validMsgs, isValid = self.validation.validate(username, password, verify, email) self.assertFalse(isValid) self.assertEquals(MISMATCHED_PASSWORDS_MESSAGE, validMsgs[VERIFICATION_MESSAGES_KEYS[1]]) self.assertEquals(MISMATCHED_PASSWORDS_MESSAGE, validMsgs[VERIFICATION_MESSAGES_KEYS[2]]) self.assertEmptyMessage([VERIFICATION_MESSAGES_KEYS[0],VERIFICATION_MESSAGES_KEYS[3]], validMsgs) def test_is_password_and_verify_equals(self): self.assertTrue(self.validation.is_password_and_verify_equals("craig", "craig")) self.assertFalse(self.validation.is_password_and_verify_equals("craig", "craig1")) def assertEmptyMessage(self, key_list, messages): for key in key_list: self.assertEquals('', messages[key], "Message with key " + key + " is not empty") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testValidateUsername'] unittest.main()
45.35
165
0.722161
cb73f4fefac266ce48b01257841b58df1d8971d8
8,637
h
C
kernel/daoClass.h
kunal/dao
a9b71620cf0e5214f39e6c4b4bdbffbfc65a7348
[ "BSD-2-Clause" ]
165
2015-01-23T02:09:29.000Z
2022-02-05T06:20:45.000Z
kernel/daoClass.h
kunal/dao
a9b71620cf0e5214f39e6c4b4bdbffbfc65a7348
[ "BSD-2-Clause" ]
220
2015-01-01T12:26:07.000Z
2021-05-31T19:07:50.000Z
kernel/daoClass.h
kunal/dao
a9b71620cf0e5214f39e6c4b4bdbffbfc65a7348
[ "BSD-2-Clause" ]
19
2015-02-17T19:14:15.000Z
2021-06-24T09:19:47.000Z
/* // Dao Virtual Machine // http://daoscript.org // // Copyright (c) 2006-2017, Limin Fu // 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 HOLDER 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. */ #ifndef DAO_CLASS_H #define DAO_CLASS_H #include"daoType.h" #define DAO_CLASS_CONST_CSTOR 1 /* // The DaoClass structure contains all the information for a Dao class. // // In the Dao type system, Dao class is represented by two DaoType objects: // -- DaoClass::clsType: for the class object itself; // -- DaoClass::objType: for the instance objects of the class; // // The class members can be looked up by DaoClass::lookupTable, which maps // the member names to lookup indices. // // Bit structure for the lookup indices: EEPPSSSSUUUUUUUUIIIIIIIIIIIIIIII. // Where: // -- EE: 2 bits reserved for encoding error; // -- PP: 2 bits to encode permission; // -- SSSS: 4 bits to encode storage type; // -- UUUUUUUU: 8 bits to encode up index; // -- IIIIIIIIIIIIIIII: 16 bits to encode the actual index in field arrays; // // The permission bits will encode the following values: // -- DAO_PERM_PRIVATE; // -- DAO_PERM_PROTECTED; // -- DAO_PERM_PUBLIC; // // The storage bits will encode the following values: // -- DAO_CLASS_CONSTANT: for constants; // -- DAO_CLASS_VARIABLE: for static variables; // -- DAO_OBJECT_VARIABLE: for instance variables; // // The up-index bits will encode the following values: // -- Zero: for members from the current class; // -- One: for members from the direct base class; // -- Two and above: for members from the indirect base classes; // // Class constant layout in DaoClass:constants: // -- Single Index (0): the class object itself, with its name ("X") as the lookup name; // -- Single Index (1): the class constructor (implicit/explicit), with lookup name "X::X"; // -- Multiple Indices: the constants from the mixin component classes; // -- Mulitple Indices: the constants from the base class; // -- Mulitple Indices: the constants defined in the current class; // // Class instance variable information layout in DaoClass::instvars; // -- Single Index (0): information for the self object with type DaoClass::objType; // -- Multiple Indices: the "instvars" from the mixin component classes; // -- Multiple Indices: the "instvars" from the base class; // -- Mulitple Indices: the instance variables defined in the current class; // // Class static variable information layout in DaoClass::instvars; // -- Multiple Indices: the static variables from the mixin component classes; // -- Multiple Indices: the static variables from the base class; // -- Mulitple Indices: the static variables defined in the current class; // // Index ranges for the constants and variables from mixin component and base classes: // -- [ DaoClass::cstMixinStart, DaoClass::cstMixinEnd ) : // Constants from mixin components; // -- [ DaoClass::cstMixinStart, DaoClass::cstMixinEnd2 ) : // Constants from mixin components, plus extra constants created for method overloading; // -- [ DaoClass::glbMixinStart, DaoClass::glbMixinEnd ) : // Static variables from mixin components; // -- [ DaoClass::objMixinStart, DaoClass::objMixinEnd ) : // Instance variables from mixin components; // -- [ DaoClass::cstParentStart, DaoClass::cstParentEnd ) : // Constants from base/parent classes; // -- [ DaoClass::glbParentStart, DaoClass::glbParentEnd ) : // Static variables from base/parent classes; // Index ranges for individual mixin components are stored in DaoClass::ranges; */ struct DaoClass { DAO_VALUE_COMMON; DString *className; DaoNamespace *nameSpace; /* Definition namespace; */ DaoType *clsType; DaoType *objType; /* GC handled in constants; */ DHash_(DString*,size_t) *lookupTable; /* member lookup table; */ DList_(DaoConstant*) *constants; /* constants; */ DList_(DaoVariable*) *variables; /* static variables (types and init values); */ DList_(DaoVariable*) *instvars; /* instance variable (types and default values); */ DList_(DString*) *cstDataName; /* keep track field declaration order; */ DList_(DString*) *glbDataName; /* keep track field declaration order; */ DList_(DString*) *objDataName; /* keep tracking field declaration order; */ DaoValue *parent; /* DaoClass or DaoCData; */ DList_(DaoClass*) *mixinBases; /* direct mixin classes; */ DList_(DaoClass*|DaoCData*) *allBases; /* mixin or parent classes; */ DList_(DaoClass*) *mixins; /* mixin classes; */ DArray_(ushort_t) *ranges; /* ranges of the fields of the mixin classes; */ ushort_t cstMixinStart, cstMixinEnd, cstMixinEnd2; ushort_t glbMixinStart, glbMixinEnd; ushort_t objMixinStart, objMixinEnd; ushort_t cstParentStart, cstParentEnd; ushort_t glbParentStart, glbParentEnd; ushort_t objParentStart, objParentEnd; /* // Routines with overloading signatures: // They are inserted into constants, no refCount updating for this. */ DMap_(DString*,DaoRoutine*) *methSignatures; DMap_(DaoRoutine*,DaoRoutine*) *interMethods; DaoRoutine *initRoutine; /* Default class constructor. */ DaoRoutine *initRoutines; /* All explicit constructors; GC handled in constants; */ DList_(DaoValue*) *references; /* for GC */ uint_t attribs; ushort_t objDefCount; ushort_t derived; }; DAO_DLL DaoClass* DaoClass_New( DaoNamespace *nspace ); DAO_DLL void DaoClass_Delete( DaoClass *self ); DAO_DLL void DaoClass_PrintCode( DaoClass *self, DaoStream *stream ); DAO_DLL void DaoClass_AddReference( DaoClass *self, void *reference ); DAO_DLL void DaoClass_SetName( DaoClass *self, DString *name, DaoNamespace *ns ); DAO_DLL int DaoClass_BaseConstructorOffset( DaoClass *self, DaoClass *base, int idx ); DAO_DLL int DaoClass_CopyField( DaoClass *self, DaoClass *other, DMap *deftypes ); DAO_DLL int DaoClass_DeriveClassData( DaoClass *self ); DAO_DLL void DaoClass_DeriveObjectData( DaoClass *self ); DAO_DLL void DaoClass_UpdateMixinConstructors( DaoClass *self ); DAO_DLL void DaoClass_UpdateAttributes( DaoClass *self ); DAO_DLL void DaoClass_UpdateVirtualMethods( DaoClass *self ); DAO_DLL void DaoClass_CastingMethod( DaoClass *self, DaoRoutine *routine ); DAO_DLL int DaoClass_ChildOf( DaoClass *self, DaoValue *base ); DAO_DLL void DaoClass_AddMixinClass( DaoClass *self, DaoClass *mixin ); DAO_DLL void DaoClass_AddBaseClass( DaoClass *self, DaoValue *base ); DAO_DLL DaoValue* DaoClass_CastToBase( DaoClass *self, DaoType *parent ); DAO_DLL int DaoClass_FindConst( DaoClass *self, DString *name ); DAO_DLL DaoValue* DaoClass_GetConst( DaoClass *self, int id ); DAO_DLL void DaoClass_SetConst( DaoClass *self, int id, DaoValue *value ); DAO_DLL DaoValue* DaoClass_GetData( DaoClass *self, DString *name, DaoClass *thisClass ); DAO_DLL int DaoClass_GetDataIndex( DaoClass *self, DString *name ); DAO_DLL int DaoClass_AddConst( DaoClass *self, DString *name, DaoValue *value, int pm ); DAO_DLL int DaoClass_AddGlobalVar( DaoClass *self, DString *name, DaoValue *val, DaoType *tp, int pm ); DAO_DLL int DaoClass_AddObjectVar( DaoClass *self, DString *name, DaoValue *val, DaoType *tp, int pm ); DAO_DLL void DaoClass_AddOverloadedRoutine( DaoClass *self, DString *signature, DaoRoutine *rout ); DAO_DLL DaoRoutine* DaoClass_GetOverloadedRoutine( DaoClass *self, DString *signature ); DAO_DLL DaoRoutine* DaoClass_FindMethod( DaoClass *self, const char *name, DaoClass *scoped ); #endif
44.066327
103
0.745977
2743032a694c23dbd33561abc63f62bb66670628
80
rb
Ruby
app/models/special_event.rb
Slavkata/hoteldb101
3e227224b3e78e53a4aed51cbaa70c50d998531f
[ "MIT" ]
null
null
null
app/models/special_event.rb
Slavkata/hoteldb101
3e227224b3e78e53a4aed51cbaa70c50d998531f
[ "MIT" ]
null
null
null
app/models/special_event.rb
Slavkata/hoteldb101
3e227224b3e78e53a4aed51cbaa70c50d998531f
[ "MIT" ]
null
null
null
class SpecialEvent < ApplicationRecord self.table_name = "Special_events" end
20
38
0.8125
8125707948e40e60a21f924207772a55943bff34
7,924
dart
Dart
lib/HomePage.dart
Murali-jha/cpu-scheduler
d12fa41ab56699a49b3a562a830fd00865f784c7
[ "MIT" ]
null
null
null
lib/HomePage.dart
Murali-jha/cpu-scheduler
d12fa41ab56699a49b3a562a830fd00865f784c7
[ "MIT" ]
null
null
null
lib/HomePage.dart
Murali-jha/cpu-scheduler
d12fa41ab56699a49b3a562a830fd00865f784c7
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:scheduling/drawer.dart'; import 'AlgoApp.dart'; import 'help.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { // Add your onPressed code here! Navigator.of(context) .push(MaterialPageRoute(builder: (context) => AlgoApp())); }, child: Icon(Icons.point_of_sale,color: Colors.white,), backgroundColor: Colors.blue, ), appBar: AppBar( shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical( bottom: Radius.circular(20.0) ), ), title: Text("Schedulo",style: TextStyle(fontSize: 25.0),), centerTitle: true, actions: [ IconButton(icon: Icon(Icons.help_outline), onPressed: (){ Navigator.push(context, MaterialPageRoute(builder: (context)=>HelpApp())); }) ], ), drawer: DrawerAppBar(), body: Container( margin: EdgeInsets.all(15.0), padding: EdgeInsets.all(6.0), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: OutlineButton( onPressed: null, color: Colors.white, child: Text("What is Schedulo ?",style: TextStyle(color: Colors.white,fontSize: 20.0),), shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)) ), ), ListTile( title: Text("Back in the day, primitive operating systems only allowed to execute a process at a time. The running process alternated time in CPU and time in I/O. The OS provided the process with the basic I/O routines, as these must be protected. Processes started and ended in CPU time. The time that a process spends in CPU is called burst.", style: TextStyle(fontSize: 18.0), ), ), ListTile( title: Text("In any case, the I/O system is much slower than the CPU, so, if we have only one process, the CPU will be idle most of the time. It was decided that several processes could be executed at a time, alternating in the use of CPU and I/O system. This idea not only required changes in the OS, but also in the hardware. Dividing the memory in several parts, putting a process in each part and making the CPU commute from process to process is what we call multi-programming.", style: TextStyle(fontSize: 18.0), ), ), ListTile( title: Text("The goal of multi-programming is to improve the performance by using the CPU more efficiently. A shared-time OS needs to change the running process every now and then, letting all the processes use both the CPU and the I/O system. The problem now is to decide which process should be running in each moment. In the simplest case, a process can be sent out of the CPU when it finishes or it needs to use the I/O system. However, the OS may decide to replace the running process in other occasions. Choosing the processes that are candidate for CPU execution and choosing which candidate should take the CPU is called CPU Scheduling.", style: TextStyle(fontSize: 18.0), ), ), SizedBox(height: 10.0,), Divider(color: Colors.white,), SizedBox(height: 15.0,), Center( child: OutlineButton( onPressed: null, color: Colors.white, child: Text("The Scheduler",style: TextStyle(color: Colors.white,fontSize: 20.0),), shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)) ), ), ListTile( title: Text("Old operating systems had three schedulers:\n\n\nThe long-term scheduler, which decides which processes have the right to exist.\n\nThe mid-term scheduler, which decides which processes can stay in main memory and which are sent to the swap (disk).\n\nThe short-term scheduler or CPU scheduler, which decides which process in memory has the right to use the CPU.\n\nHowever, in modern operating systems, the long-term scheduler is practically absent, and the mid-term scheduler has practically been replaced by virtual memory.", style: TextStyle(fontSize: 18.0), ), ), SizedBox(height: 10.0,), Divider(color: Colors.white,), SizedBox(height: 15.0,), Center( child: OutlineButton( onPressed: null, color: Colors.white, child: Text("The CPU Scheduler",style: TextStyle(color: Colors.white,fontSize: 20.0),), shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)) ), ), ListTile( title: Text("The OS moves from a process to another by saving the state of the process that is in CPU in the PCB of that process and loading the state of the new process from its PCB. This operation is called context switch and takes some time. If the CPU time was short, the process would not really execute, as time would be practically spent in doing context switch.\n\nOld operating systems such as MS-DOS could remove processes from the CPU only if they finished or if they needed to use the I/O system. Other processes could not use the CPU if the current process did not leave. This kind of scheduling is called non-preemptive or co-operative. Not only this type of scheduling was unfair, but also it could block the computer if the process in CPU had a problem. In modern systems, the OS can remove processes from the CPU when they decide. This type of scheduling is called preemptive.\n\n\nIn this app we will study several scheduling algorithms, some preemptive and some non-preemptive:", style: TextStyle(fontSize: 18.0), ), ), ListTile( title: Text("First Come First Serve(FCFS)", style: TextStyle(fontSize: 18.0), ), leading: Icon(Icons.arrow_forward_ios_outlined), ), ListTile( title: Text("Shortest Job First(SJF)", style: TextStyle(fontSize: 18.0), ), leading: Icon(Icons.arrow_forward_ios_outlined), ), ListTile( title: Text("Round Robin(RR)", style: TextStyle(fontSize: 18.0), ), leading: Icon(Icons.arrow_forward_ios_outlined), ), ListTile( title: Text("Random Scheduling(Random)", style: TextStyle(fontSize: 18.0), ), leading: Icon(Icons.arrow_forward_ios_outlined), ), ListTile( title: Text("Nevertheless, modern operating systems may apply a combination of some of them in a Multiple Queue scheduling system.", style: TextStyle(fontSize: 18.0), ), ), ListTile( title: Text("Send your question at [email protected]", style: TextStyle(fontSize: 18.0), ), ), Divider(color: Colors.white,), ], ), ), ), ); } }
56.6
1,014
0.602726
1a74c9294166e6d2c868dddf706d31d842ce797a
3,038
py
Python
engine/src/juliabox/plugins/vol_defcfg/defcfg.py
karthiganesh/juliabox
761d39c7f8f481bdb5bf1dc4011d4e267158e551
[ "MIT" ]
50
2016-09-09T02:17:09.000Z
2022-03-15T17:16:20.000Z
engine/src/juliabox/plugins/vol_defcfg/defcfg.py
wsshin/JuliaBox
395df7654834f9671ab132cd29c02fb05ce42c27
[ "MIT" ]
58
2016-08-29T19:19:28.000Z
2018-11-14T01:49:16.000Z
engine/src/juliabox/plugins/vol_defcfg/defcfg.py
wsshin/JuliaBox
395df7654834f9671ab132cd29c02fb05ce42c27
[ "MIT" ]
24
2016-09-27T18:20:54.000Z
2022-01-02T09:37:44.000Z
import os from juliabox.jbox_util import ensure_delete, make_sure_path_exists, unique_sessname, JBoxCfg from juliabox.vol import JBoxVol class JBoxDefaultConfigVol(JBoxVol): provides = [JBoxVol.JBP_CONFIG] FS_LOC = None @staticmethod def configure(): cfg_location = os.path.expanduser(JBoxCfg.get('cfg_location')) make_sure_path_exists(cfg_location) JBoxDefaultConfigVol.FS_LOC = cfg_location @staticmethod def _get_config_mounts_used(cid): used = [] props = JBoxDefaultConfigVol.dckr().inspect_container(cid) try: for _cpath, hpath in JBoxVol.extract_mounts(props): if hpath.startswith(JBoxDefaultConfigVol.FS_LOC): used.append(hpath.split('/')[-1]) except: JBoxDefaultConfigVol.log_error("error finding config mount points used in " + cid) return [] return used @staticmethod def refresh_disk_use_status(container_id_list=None): pass @staticmethod def get_disk_for_user(user_email): JBoxDefaultConfigVol.log_debug("creating configs disk for %s", user_email) if JBoxDefaultConfigVol.FS_LOC is None: JBoxDefaultConfigVol.configure() disk_path = os.path.join(JBoxDefaultConfigVol.FS_LOC, unique_sessname(user_email)) cfgvol = JBoxDefaultConfigVol(disk_path, user_email=user_email) cfgvol._unpack_config() return cfgvol @staticmethod def is_mount_path(fs_path): return fs_path.startswith(JBoxDefaultConfigVol.FS_LOC) @staticmethod def get_disk_from_container(cid): mounts_used = JBoxDefaultConfigVol._get_config_mounts_used(cid) if len(mounts_used) == 0: return None mount_used = mounts_used[0] disk_path = os.path.join(JBoxDefaultConfigVol.FS_LOC, str(mount_used)) container_name = JBoxVol.get_cname(cid) sessname = container_name[1:] return JBoxDefaultConfigVol(disk_path, sessname=sessname) @staticmethod def refresh_user_home_image(): pass def release(self, backup=False): ensure_delete(self.disk_path, include_itself=True) @staticmethod def disk_ids_used_pct(): return 0 def _unpack_config(self): if os.path.exists(self.disk_path): JBoxDefaultConfigVol.log_debug("Config folder exists %s. Deleting...", self.disk_path) ensure_delete(self.disk_path, include_itself=True) JBoxDefaultConfigVol.log_debug("Config folder deleted %s", self.disk_path) JBoxDefaultConfigVol.log_debug("Will unpack config to %s", self.disk_path) os.mkdir(self.disk_path) JBoxDefaultConfigVol.log_debug("Created config folder %s", self.disk_path) self.restore_user_home(True) JBoxDefaultConfigVol.log_debug("Restored config files to %s", self.disk_path) self.setup_instance_config() JBoxDefaultConfigVol.log_debug("Setup instance config at %s", self.disk_path)
35.325581
98
0.691244
b057f7c52f6c617ec26be274861241fa5f76df6c
1,003
py
Python
run_glm.py
ys7yoo/npglm
98cc040fff8a861e2d7e210fef049207f1714b2a
[ "MIT" ]
9
2020-11-20T17:43:36.000Z
2021-02-26T22:18:59.000Z
run_glm.py
ys7yoo/npglm
98cc040fff8a861e2d7e210fef049207f1714b2a
[ "MIT" ]
1
2021-02-04T13:51:17.000Z
2021-02-04T23:56:07.000Z
run_glm.py
ys7yoo/npglm
98cc040fff8a861e2d7e210fef049207f1714b2a
[ "MIT" ]
1
2020-11-22T19:36:35.000Z
2020-11-22T19:36:35.000Z
from GLM.GLM_Model.Model_Runner import Model_Runner from Utils import utils, SpikeGen import torch def main(): expt = 'expt_supp' params = utils.Params('GLM/GLM_Params/params.json') params.torch_d_type = torch.float64 params.gp_filter_plot_path = f"Results_Data/{expt}/data/gp_filter_plot" params.basis_filter_plot_path = f"Results_Data/{expt}/data/basis_filter_plot" params.gp_ev_path = f"Results_Data/{expt}/data/neuron_gp_ev" params.basis_ev_path = f"Results_Data/{expt}/data/neuron_map_ev" if params.inference_type == 'basis': params.inference_type = 'basis' gp = Model_Runner(params) gp.initialize_design_matrices() gp.create_map_covariates() gp.train_map() elif params.inference_type == 'gp': params.inference_type = 'gp' gp = Model_Runner(params) gp.initialize_design_matrices() gp.create_variational_covariates() gp.train_variational() if __name__ == '__main__': main()
32.354839
81
0.702891
ef7c8154f6171fac1b8f012260d43a854279d2eb
24,082
c
C
xfit/obFileSelect.c
scattering-central/CCP13
e78440d34d0ac80d2294b131ca17dddcf7505b01
[ "BSD-3-Clause" ]
null
null
null
xfit/obFileSelect.c
scattering-central/CCP13
e78440d34d0ac80d2294b131ca17dddcf7505b01
[ "BSD-3-Clause" ]
null
null
null
xfit/obFileSelect.c
scattering-central/CCP13
e78440d34d0ac80d2294b131ca17dddcf7505b01
[ "BSD-3-Clause" ]
3
2017-09-05T15:15:22.000Z
2021-01-15T11:13:45.000Z
/******************************************************************************* obFileSelect.c Associated Header file: obFileSelect.h *******************************************************************************/ #include <stdio.h> #ifdef MOTIF #include <Xm/Xm.h> #include <Xm/MwmUtil.h> #include <Xm/DialogS.h> #include <Xm/MenuShell.h> #endif /* MOTIF */ #include "UxXt.h" #include <Xm/PushB.h> #include <Xm/RowColumn.h> #include <Xm/TextF.h> #include <Xm/Label.h> #include <Xm/Form.h> #include <Xm/FileSB.h> /******************************************************************************* Includes, Defines, and Global variables from the Declarations Editor: *******************************************************************************/ #include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <X11/Xlib.h> #ifndef DESIGN_TIME typedef void (*vfptr)(); #endif #define FILTER "*000.*" static void do_selection (Widget wgt, XtPointer cd, XtPointer cb); static int _UxIfClassId; int UxobFileSelect_readHeader_Id = -1; char* UxobFileSelect_readHeader_Name = "readHeader"; int UxobFileSelect_OKfunction_Id = -1; char* UxobFileSelect_OKfunction_Name = "OKfunction"; int UxobFileSelect_show_Id = -1; char* UxobFileSelect_show_Name = "show"; int UxobFileSelect_defaults_Id = -1; char* UxobFileSelect_defaults_Name = "defaults"; /******************************************************************************* The following header file defines the context structure. *******************************************************************************/ #ifndef XKLOADDS #define XKLOADDS #endif /* XKLOADDS */ #define CONTEXT_MACRO_ACCESS 1 #include "obFileSelect.h" #undef CONTEXT_MACRO_ACCESS /******************************************************************************* Declarations of methods *******************************************************************************/ static int _obFileSelect_readHeader( swidget UxThis, Environment * pEnv, char *file, int mem, int *np, int *nr, int *nf ); static void _obFileSelect_OKfunction( swidget UxThis, Environment * pEnv, vfptr okfunc ); static void _obFileSelect_show( swidget UxThis, Environment * pEnv, int found ); static void _obFileSelect_defaults( swidget UxThis, Environment * pEnv ); /******************************************************************************* Auxiliary code from the Declarations Editor: *******************************************************************************/ /* * Extra call backs for internal widgets. */ static void do_selection (Widget wgt, XtPointer cd, XtPointer cb) { struct stat stbuf; char *text; int found; text = XmTextFieldGetString (wgt); if ((stat (text, &stbuf) != -1) && (stbuf.st_mode & S_IFMT) != S_IFDIR && ((found = obFileSelect_readHeader (XtParent (wgt), &UxEnv, text, filenum, &npix, &nrast, &nframe)) > 0)) { ilfr = nframe; if (filename) free (filename); filename = (char *) strdup (text); obFileSelect_show (XtParent(wgt), &UxEnv, found); } else { filename = (char *) NULL; } free (text); } /******************************************************************************* The following are method functions. *******************************************************************************/ static int Ux_readHeader( swidget UxThis, Environment * pEnv, char *file, int mem, int *np, int *nr, int *nf ) { } static int _obFileSelect_readHeader( swidget UxThis, Environment * pEnv, char *file, int mem, int *np, int *nr, int *nf ) { int _Uxrtrn; _UxCobFileSelect *UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = (_UxCobFileSelect *) UxGetContext( UxThis ); if (pEnv) pEnv->_major = NO_EXCEPTION; _Uxrtrn = Ux_readHeader( UxThis, pEnv, file, mem, np, nr, nf ); UxObFileSelectContext = UxSaveCtx; return ( _Uxrtrn ); } static void Ux_OKfunction( swidget UxThis, Environment * pEnv, vfptr okfunc ) { ok_function = okfunc; } static void _obFileSelect_OKfunction( swidget UxThis, Environment * pEnv, vfptr okfunc ) { _UxCobFileSelect *UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = (_UxCobFileSelect *) UxGetContext( UxThis ); if (pEnv) pEnv->_major = NO_EXCEPTION; Ux_OKfunction( UxThis, pEnv, okfunc ); UxObFileSelectContext = UxSaveCtx; } static void Ux_show( swidget UxThis, Environment * pEnv, int found ) { char buff[10]; if (ilfr != 1) { XtSetSensitive (textField1, TRUE); XtSetSensitive (textField2, TRUE); XtSetSensitive (textField3, TRUE); } XtSetSensitive (menu1, TRUE); if (found < 3) XtSetSensitive (menu1_p1_b2, FALSE); if (found < 2) XtSetSensitive (menu1_p1_b3, FALSE); sprintf (buff, "%d", ilfr); XmTextFieldSetString (textField2, buff); } static void _obFileSelect_show( swidget UxThis, Environment * pEnv, int found ) { _UxCobFileSelect *UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = (_UxCobFileSelect *) UxGetContext( UxThis ); if (pEnv) pEnv->_major = NO_EXCEPTION; Ux_show( UxThis, pEnv, found ); UxObFileSelectContext = UxSaveCtx; } static void Ux_defaults( swidget UxThis, Environment * pEnv ) { XmTextFieldSetString (textField1, "1"); XmTextFieldSetString (textField2, "1"); XmTextFieldSetString (textField3, "1"); filenum = 1; XtVaSetValues (menu1, XmNmenuHistory, menu1_p1_b1, NULL); XtSetSensitive (textField1, FALSE); XtSetSensitive (textField2, FALSE); XtSetSensitive (textField3, FALSE); XtSetSensitive (menu1, FALSE); } static void _obFileSelect_defaults( swidget UxThis, Environment * pEnv ) { _UxCobFileSelect *UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = (_UxCobFileSelect *) UxGetContext( UxThis ); if (pEnv) pEnv->_major = NO_EXCEPTION; Ux_defaults( UxThis, pEnv ); UxObFileSelectContext = UxSaveCtx; } /******************************************************************************* The following are callback functions. *******************************************************************************/ static void mapCB_obFileSelect( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { obFileSelect_defaults (UxWidget, &UxEnv); } UxObFileSelectContext = UxSaveCtx; } static void cancelCB_obFileSelect( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { UxPopdownInterface (UxThisWidget); } UxObFileSelectContext = UxSaveCtx; } static void okCallback_obFileSelect( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { XEvent *event; event = (((XmFileSelectionBoxCallbackStruct *) UxCallbackArg)->event); if ((XtWindow (filelist) == event->xbutton.window) || (event->type == KeyPress)) obFileSelect_defaults (UxWidget, &UxEnv); if (((XmFileSelectionBoxCallbackStruct *) UxCallbackArg)->reason != XmCR_NO_MATCH) { UxPopdownInterface (UxThisWidget); ok_function (filename, npix, nrast, iffr, ilfr, ifinc, filenum); } } UxObFileSelectContext = UxSaveCtx; } static void applyCB_obFileSelect( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { char *text, *cptr, dir[256]; int len; text = XmTextFieldGetString (filtertxt); cptr = strrchr (text, '/'); if (strcmp (cptr+1, FILTER) != 0) { len = cptr-text+1; strncpy (dir, text, len); dir[len] = '\0'; strcat (dir, FILTER); XmFileSelectionDoSearch (UxWidget, XmStringCreateLtoR (dir, XmSTRING_DEFAULT_CHARSET)); } free (text); } UxObFileSelectContext = UxSaveCtx; } static void noMatchCB_obFileSelect( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { XBell (UxDisplay, 50); } UxObFileSelectContext = UxSaveCtx; } static void valueChangedCB_textField1( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { char *text, *text2, buff[10]; text = XmTextFieldGetString (UxWidget); if (*text != '\0') { sscanf (text, "%d", &iffr); if (iffr < 1) XmTextFieldSetString (UxWidget, "1"); else if (iffr > nframe) { sprintf (buff, "%d", nframe); XmTextFieldSetString (UxWidget, buff); } if ((iffr > ilfr && ifinc > 0) || (iffr < ilfr && ifinc < 0)) { text2 = XmTextFieldGetString (textField3); if (*text2 != '\0') { sscanf (text2, "%d", &ifinc); sprintf (buff, "%d", -ifinc); XmTextFieldSetString (textField3, buff); } free (text2); } } free (text); } UxObFileSelectContext = UxSaveCtx; } static void valueChangedCB_textField2( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { char *text, *text2, buff[10]; text = XmTextFieldGetString (UxWidget); if (*text != '\0') { sscanf (text, "%d", &ilfr); if (ilfr < 1) XmTextFieldSetString (UxWidget, "1"); else if (ilfr > nframe) { sprintf (buff, "%d", nframe); XmTextFieldSetString (UxWidget, buff); } if ((iffr > ilfr && ifinc > 0) || (iffr < ilfr && ifinc < 0)) { text2 = XmTextFieldGetString (textField3); if (*text2 != '\0') { sscanf (text2, "%d", &ifinc); sprintf (buff, "%d", -ifinc); XmTextFieldSetString (textField3, buff); } free (text2); } } free (text); } UxObFileSelectContext = UxSaveCtx; } static void valueChangedCB_textField3( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { char *text, buff[10]; text = XmTextFieldGetString (UxWidget); if (*text != '\0') { sscanf (text, "%d", &ifinc); if (ifinc < -nframe) { sprintf (buff, "%d", -nframe); XmTextFieldSetString (UxWidget, buff); } else if (ifinc > nframe) { sprintf (buff, "%d", nframe); XmTextFieldSetString (UxWidget, buff); } } free (text); } UxObFileSelectContext = UxSaveCtx; } static void activateCB_menu1_p1_b1( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { filenum = (int) UxClientData; do_selection (selection, NULL, NULL); } UxObFileSelectContext = UxSaveCtx; } static void activateCB_menu1_p1_b2( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { filenum = (int) UxClientData; do_selection (selection, NULL, NULL); } UxObFileSelectContext = UxSaveCtx; } static void activateCB_menu1_p1_b3( Widget wgt, XtPointer cd, XtPointer cb) { _UxCobFileSelect *UxSaveCtx, *UxContext; Widget UxWidget = wgt; XtPointer UxClientData = cd; XtPointer UxCallbackArg = cb; UxSaveCtx = UxObFileSelectContext; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxGetContext( UxWidget ); { filenum = (int) UxClientData; do_selection (selection, NULL, NULL); } UxObFileSelectContext = UxSaveCtx; } /******************************************************************************* The 'build_' function creates all the widgets using the resource values specified in the Property Editor. *******************************************************************************/ static Widget _Uxbuild_obFileSelect() { Widget _UxParent; Widget data1_shell; /* Creation of obFileSelect */ _UxParent = UxParent; if ( _UxParent == NULL ) { _UxParent = UxTopLevel; } _UxParent = XtVaCreatePopupShell( "obFileSelect_shell", xmDialogShellWidgetClass, _UxParent, XmNx, 245, XmNy, 190, XmNwidth, 400, XmNheight, 400, XmNshellUnitType, XmPIXELS, XmNtitle, "obFileSelect", NULL ); obFileSelect = XtVaCreateWidget( "obFileSelect", xmFileSelectionBoxWidgetClass, _UxParent, XmNresizePolicy, XmRESIZE_NONE, XmNunitType, XmPIXELS, XmNwidth, 400, XmNheight, 400, XmNdialogType, XmDIALOG_FILE_SELECTION, RES_CONVERT( XmNchildPlacement, "place_below_selection" ), RES_CONVERT( XmNdirMask, FILTER ), XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL, RES_CONVERT( XmNdialogTitle, "File Selection" ), XmNautoUnmanage, FALSE, RES_CONVERT( XmNdirSpec, "" ), RES_CONVERT( XmNdirectory, "" ), XmNmustMatch, TRUE, NULL ); XtAddCallback( obFileSelect, XmNmapCallback, (XtCallbackProc) mapCB_obFileSelect, (XtPointer) UxObFileSelectContext ); XtAddCallback( obFileSelect, XmNcancelCallback, (XtCallbackProc) cancelCB_obFileSelect, (XtPointer) UxObFileSelectContext ); XtAddCallback( obFileSelect, XmNokCallback, (XtCallbackProc) okCallback_obFileSelect, (XtPointer) UxObFileSelectContext ); XtAddCallback( obFileSelect, XmNapplyCallback, (XtCallbackProc) applyCB_obFileSelect, (XtPointer) UxObFileSelectContext ); XtAddCallback( obFileSelect, XmNnoMatchCallback, (XtCallbackProc) noMatchCB_obFileSelect, (XtPointer) UxObFileSelectContext ); UxPutContext( obFileSelect, (char *) UxObFileSelectContext ); UxPutClassCode( obFileSelect, _UxIfClassId ); /* Creation of form1 */ form1 = XtVaCreateManagedWidget( "form1", xmFormWidgetClass, obFileSelect, XmNresizePolicy, XmRESIZE_NONE, XmNunitType, XmPIXELS, XmNwidth, 427, XmNheight, 65, NULL ); UxPutContext( form1, (char *) UxObFileSelectContext ); /* Creation of label2 */ label2 = XtVaCreateManagedWidget( "label2", xmLabelWidgetClass, form1, XmNx, -350, XmNy, -1, XmNwidth, 90, XmNheight, 25, RES_CONVERT( XmNlabelString, "Last Frame" ), XmNalignment, XmALIGNMENT_BEGINNING, XmNleftOffset, 90, XmNleftAttachment, XmATTACH_FORM, XmNtopOffset, 10, XmNfontList, UxConvertFontList("7x14" ), NULL ); UxPutContext( label2, (char *) UxObFileSelectContext ); /* Creation of label3 */ label3 = XtVaCreateManagedWidget( "label3", xmLabelWidgetClass, form1, XmNx, -3, XmNy, -1, XmNwidth, 90, XmNheight, 25, RES_CONVERT( XmNlabelString, "Increment" ), XmNalignment, XmALIGNMENT_BEGINNING, XmNleftOffset, 180, XmNleftAttachment, XmATTACH_FORM, XmNtopOffset, 10, XmNfontList, UxConvertFontList("7x14" ), NULL ); UxPutContext( label3, (char *) UxObFileSelectContext ); /* Creation of label4 */ label4 = XtVaCreateManagedWidget( "label4", xmLabelWidgetClass, form1, XmNx, 365, XmNy, -1, XmNwidth, 90, XmNheight, 25, RES_CONVERT( XmNlabelString, "Binary Data" ), XmNalignment, XmALIGNMENT_BEGINNING, XmNtopOffset, 10, XmNleftAttachment, XmATTACH_NONE, XmNrightAttachment, XmATTACH_FORM, XmNrightOffset, 14, XmNfontList, UxConvertFontList("7x14" ), NULL ); UxPutContext( label4, (char *) UxObFileSelectContext ); /* Creation of textField1 */ textField1 = XtVaCreateManagedWidget( "textField1", xmTextFieldWidgetClass, form1, XmNwidth, 70, XmNheight, 30, XmNvalue, "1", XmNsensitive, TRUE, XmNleftOffset, 0, XmNleftAttachment, XmATTACH_FORM, XmNtopOffset, 28, XmNtopAttachment, XmATTACH_FORM, XmNfontList, UxConvertFontList("7x14" ), NULL ); XtAddCallback( textField1, XmNvalueChangedCallback, (XtCallbackProc) valueChangedCB_textField1, (XtPointer) UxObFileSelectContext ); UxPutContext( textField1, (char *) UxObFileSelectContext ); /* Creation of textField2 */ textField2 = XtVaCreateManagedWidget( "textField2", xmTextFieldWidgetClass, form1, XmNwidth, 70, XmNheight, 30, XmNvalue, "1", XmNleftOffset, 90, XmNleftAttachment, XmATTACH_FORM, XmNtopOffset, 28, XmNtopAttachment, XmATTACH_FORM, XmNfontList, UxConvertFontList("7x14" ), NULL ); XtAddCallback( textField2, XmNvalueChangedCallback, (XtCallbackProc) valueChangedCB_textField2, (XtPointer) UxObFileSelectContext ); UxPutContext( textField2, (char *) UxObFileSelectContext ); /* Creation of textField3 */ textField3 = XtVaCreateManagedWidget( "textField3", xmTextFieldWidgetClass, form1, XmNwidth, 70, XmNheight, 30, XmNvalue, "1", XmNleftOffset, 180, XmNleftAttachment, XmATTACH_FORM, XmNtopOffset, 28, XmNtopAttachment, XmATTACH_FORM, XmNfontList, UxConvertFontList("7x14" ), NULL ); XtAddCallback( textField3, XmNvalueChangedCallback, (XtCallbackProc) valueChangedCB_textField3, (XtPointer) UxObFileSelectContext ); UxPutContext( textField3, (char *) UxObFileSelectContext ); /* Creation of data1 */ data1_shell = XtVaCreatePopupShell ("data1_shell", xmMenuShellWidgetClass, form1, XmNwidth, 1, XmNheight, 1, XmNallowShellResize, TRUE, XmNoverrideRedirect, TRUE, NULL ); data1 = XtVaCreateWidget( "data1", xmRowColumnWidgetClass, data1_shell, XmNrowColumnType, XmMENU_PULLDOWN, NULL ); UxPutContext( data1, (char *) UxObFileSelectContext ); /* Creation of menu1_p1_b1 */ menu1_p1_b1 = XtVaCreateManagedWidget( "menu1_p1_b1", xmPushButtonWidgetClass, data1, RES_CONVERT( XmNlabelString, "SAXS" ), XmNfontList, UxConvertFontList("7x14" ), NULL ); XtAddCallback( menu1_p1_b1, XmNactivateCallback, (XtCallbackProc) activateCB_menu1_p1_b1, (XtPointer) 0x1 ); UxPutContext( menu1_p1_b1, (char *) UxObFileSelectContext ); /* Creation of menu1_p1_b2 */ menu1_p1_b2 = XtVaCreateManagedWidget( "menu1_p1_b2", xmPushButtonWidgetClass, data1, RES_CONVERT( XmNlabelString, "WAXS" ), XmNfontList, UxConvertFontList("7x14" ), NULL ); XtAddCallback( menu1_p1_b2, XmNactivateCallback, (XtCallbackProc) activateCB_menu1_p1_b2, (XtPointer) 0x3 ); UxPutContext( menu1_p1_b2, (char *) UxObFileSelectContext ); /* Creation of menu1_p1_b3 */ menu1_p1_b3 = XtVaCreateManagedWidget( "menu1_p1_b3", xmPushButtonWidgetClass, data1, RES_CONVERT( XmNlabelString, "Calibration" ), XmNfontList, UxConvertFontList("7x14" ), NULL ); XtAddCallback( menu1_p1_b3, XmNactivateCallback, (XtCallbackProc) activateCB_menu1_p1_b3, (XtPointer) 0x2 ); UxPutContext( menu1_p1_b3, (char *) UxObFileSelectContext ); /* Creation of menu1 */ menu1 = XtVaCreateManagedWidget( "menu1", xmRowColumnWidgetClass, form1, XmNrowColumnType, XmMENU_OPTION, XmNsubMenuId, data1, XmNleftAttachment, XmATTACH_NONE, XmNtopOffset, 25, XmNresizeHeight, TRUE, XmNresizeWidth, TRUE, XmNpacking, XmPACK_TIGHT, XmNrightAttachment, XmATTACH_FORM, XmNrightOffset, -2, XmNtopAttachment, XmATTACH_FORM, XmNheight, 30, XmNwidth, 130, XmNresizable, FALSE, NULL ); UxPutContext( menu1, (char *) UxObFileSelectContext ); /* Creation of label1 */ label1 = XtVaCreateManagedWidget( "label1", xmLabelWidgetClass, form1, XmNx, 224, XmNy, -1, XmNwidth, 90, XmNheight, 25, RES_CONVERT( XmNlabelString, "First Frame" ), XmNalignment, XmALIGNMENT_BEGINNING, XmNbottomAttachment, XmATTACH_NONE, XmNbottomWidget, NULL, XmNleftOffset, 0, XmNleftAttachment, XmATTACH_FORM, XmNtopOffset, 10, XmNfontList, UxConvertFontList("7x14" ), NULL ); UxPutContext( label1, (char *) UxObFileSelectContext ); XtAddCallback( obFileSelect, XmNdestroyCallback, (XtCallbackProc) UxDestroyContextCB, (XtPointer) UxObFileSelectContext); return ( obFileSelect ); } /******************************************************************************* The following is the 'Interface function' which is the external entry point for creating this interface. This function should be called from your application or from a callback function. *******************************************************************************/ Widget create_obFileSelect( swidget _UxUxParent ) { Widget rtrn; _UxCobFileSelect *UxContext; static int _Uxinit = 0; UxObFileSelectContext = UxContext = (_UxCobFileSelect *) UxNewContext( sizeof(_UxCobFileSelect), False ); UxParent = _UxUxParent; if ( ! _Uxinit ) { _UxIfClassId = UxNewInterfaceClassId(); UxobFileSelect_readHeader_Id = UxMethodRegister( _UxIfClassId, UxobFileSelect_readHeader_Name, (void (*)()) _obFileSelect_readHeader ); UxobFileSelect_OKfunction_Id = UxMethodRegister( _UxIfClassId, UxobFileSelect_OKfunction_Name, (void (*)()) _obFileSelect_OKfunction ); UxobFileSelect_show_Id = UxMethodRegister( _UxIfClassId, UxobFileSelect_show_Name, (void (*)()) _obFileSelect_show ); UxobFileSelect_defaults_Id = UxMethodRegister( _UxIfClassId, UxobFileSelect_defaults_Name, (void (*)()) _obFileSelect_defaults ); _Uxinit = 1; } { filename = (char *) NULL; filenum = 1; iffr = 1; ilfr = 1; ifinc = 1; nframe = 1; rtrn = _Uxbuild_obFileSelect(); selection = XmFileSelectionBoxGetChild (UxGetWidget (rtrn), XmDIALOG_TEXT); filelist = XmFileSelectionBoxGetChild (UxGetWidget (rtrn), XmDIALOG_LIST); filtertxt = XmFileSelectionBoxGetChild (UxGetWidget (rtrn), XmDIALOG_FILTER_TEXT); XtAddCallback (selection, XmNvalueChangedCallback, (XtCallbackProc) do_selection, (XtPointer) UxObFileSelectContext ); return(rtrn); } } /******************************************************************************* END OF FILE *******************************************************************************/
27.397042
122
0.641309
aff1c0eb8b7dc63fa464f39be82ae8945e56c68b
14,075
py
Python
tests/test_fpack_field.py
frankurcrazy/fpack
ce2369ec3018b20d79f101ed0b439fd312681472
[ "BSD-3-Clause" ]
2
2020-08-26T14:16:39.000Z
2021-01-11T08:43:36.000Z
tests/test_fpack_field.py
frankurcrazy/fpack
ce2369ec3018b20d79f101ed0b439fd312681472
[ "BSD-3-Clause" ]
17
2021-04-28T06:02:45.000Z
2022-03-29T18:05:56.000Z
tests/test_fpack_field.py
frankurcrazy/fpack
ce2369ec3018b20d79f101ed0b439fd312681472
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python import struct import unittest try: from fpack import * except ImportError: import os import sys sys.path.append(os.path.abspath(os.path.join(".", ".."))) from fpack import * class TestField(unittest.TestCase): def test_not_implemented_methods(self): field = Field() with self.assertRaises(NotImplementedError): field.pack() with self.assertRaises(NotImplementedError): field.unpack(b"12345") with self.assertRaises(NotImplementedError): field.size with self.assertRaises(NotImplementedError): field = Field.from_bytes(b"12345") def test_str_representation(self): self.assertEqual(str(Field()), "None") self.assertEqual(str(Field(1234)), "1234") class TestPrimitiveFieldPack(unittest.TestCase): def test_uint8_pack(self): s = struct.Struct("B") val = 255 f = Uint8(val) p = f.pack() self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_uint16_pack(self): s = struct.Struct("!H") val = 65535 f = Uint16(val) p = f.pack() self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_uint32_pack(self): s = struct.Struct("!I") val = 12345789 f = Uint32(val) p = f.pack() self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_uint64_pack(self): s = struct.Struct("!Q") val = 2555555555 f = Uint64(val) p = f.pack() self.assertEqual(f.size, s.size) self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_int8_pack(self): s = struct.Struct("b") val = -128 f = Int8(val) p = f.pack() self.assertEqual(f.size, s.size) self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_int16_pack(self): s = struct.Struct("!h") val = -32767 f = Int16(val) p = f.pack() self.assertEqual(f.size, s.size) self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_int32_pack(self): s = struct.Struct("!i") val = -12345789 f = Int32(val) p = f.pack() self.assertEqual(f.size, s.size) self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) def test_int64_pack(self): s = struct.Struct("!q") val = -2055555555 f = Int64(val) p = f.pack() self.assertEqual(f.size, s.size) self.assertEqual(len(p), s.size) self.assertEqual(p, s.pack(val)) class TestPrimitiveFieldUnpack(unittest.TestCase): def test_uint8_unpack(self): s = struct.Struct("B") val = 255 f = Uint8() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Uint8.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Uint8)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_uint16_unpack(self): s = struct.Struct("!H") val = 65535 f = Uint16() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Uint16.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Uint16)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_uint32_unpack(self): s = struct.Struct("!I") val = 12345789 f = Uint32() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Uint32.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Uint32)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_uint64_unpack(self): s = struct.Struct("!Q") val = 2555555555 f = Uint64() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Uint64.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Uint64)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_int8_unpack(self): s = struct.Struct("b") val = -128 f = Int8() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Int8.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Int8)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_int16_unpack(self): s = struct.Struct("!h") val = -32767 f = Int16() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Int16.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Int16)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_int32_unpack(self): s = struct.Struct("!i") val = -12345789 f = Int32() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Int32.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Int32)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_int64_unpack(self): s = struct.Struct("!q") val = -2055555555 f = Int64() p = f.unpack(s.pack(val)) self.assertEqual(p, s.size) self.assertEqual(f.val, val) p, length = Int64.from_bytes(s.pack(val)) self.assertTrue(isinstance(p, Int64)) self.assertEqual(length, s.size) self.assertEqual(p.val, val) def test_uint8_unpack_undersize(self): s = struct.Struct("B") val = 255 f = Uint8() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:0]) def test_uint16_unpack_undersize(self): s = struct.Struct("!H") val = 65535 f = Uint16() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:0]) def test_uint32_unpack_undersize(self): s = struct.Struct("!I") val = 12345789 f = Uint32() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:0]) def test_uint64_unpack_undersize(self): s = struct.Struct("!Q") val = 2555555555 f = Uint64() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:0]) def test_int8_unpack_undersize(self): s = struct.Struct("b") val = -128 f = Int8() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:0]) def test_int16_unpack_undersize(self): s = struct.Struct("!h") val = -32767 f = Int16() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:1]) def test_int32_unpack_undersize(self): s = struct.Struct("!i") val = -12345789 f = Int32() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:3]) def test_int64_unpack_undersize(self): s = struct.Struct("!q") val = -2055555555 f = Int64() with self.assertRaises(ValueError): f.unpack(s.pack(val)[:5]) class TestStringField(unittest.TestCase): def test_pack_string(self): val = "helloworld!" field = String(val) packed = field.pack() test_packed = struct.pack("!H", len(val)) + val.encode("utf-8") self.assertEqual(packed, test_packed) self.assertEqual(field.size, len(test_packed)) def test_pack_string_empty(self): val = "" field = String(val) packed = field.pack() test_packed = struct.pack("!H", len(val)) + val.encode("utf-8") self.assertEqual(packed, test_packed) self.assertEqual(field.size, len(test_packed)) def test_pack_string_none(self): val = None field = String(val) packed = field.pack() self.assertEqual(str(field), "None") self.assertEqual(packed, b"\x00" * 2) def test_unpack_string(self): val = "helloworld!" test_packed = struct.pack("!H", len(val)) + val.encode("utf-8") unpacked, length = String.from_bytes(test_packed) self.assertEqual(unpacked.val, val) self.assertEqual(unpacked.size, len(test_packed)) self.assertEqual(str(unpacked), f'"{val}"') def test_unpack_string_undersized(self): val = "helloworld!" test_packed = struct.pack("!H", len(val)) + val.encode("utf-8") with self.assertRaises(ValueError): unpacked, length = String.from_bytes(test_packed[:-1]) with self.assertRaises(ValueError): unpacked, length = String.from_bytes(test_packed[:1]) def test_unpack_string_oversized(self): val = "helloworld!" test_packed = struct.pack("!H", len(val)) + val.encode("utf-8") sth = b"testdata123" unpacked, length = String.from_bytes(test_packed + sth) self.assertEqual(unpacked.val, val) self.assertEqual(unpacked.size, len(test_packed)) class TestBytesField(unittest.TestCase): def test_pack_bytes(self): val = b"helloworld!" field = Bytes(val) packed = field.pack() test_packed = struct.pack("!H", len(val)) + val self.assertEqual(packed, test_packed) self.assertEqual(field.size, len(test_packed)) def test_pack_bytes_empty(self): val = b"" field = Bytes(val) packed = field.pack() test_packed = struct.pack("!H", len(val)) + val self.assertEqual(packed, test_packed) self.assertEqual(field.size, len(test_packed)) def test_pack_bytes_none(self): val = None field = Bytes(val) packed = field.pack() self.assertEqual(str(field), "None") self.assertEqual(packed, b"\x00" * 2) def test_unpack_bytes(self): val = b"helloworld!" test_packed = struct.pack("!H", len(val)) + val unpacked, length = Bytes.from_bytes(test_packed) self.assertEqual(unpacked.val, val) self.assertEqual(unpacked.size, len(test_packed)) self.assertEqual(str(unpacked), f"{val}") def test_unpack_bytes_undersized(self): val = b"helloworld!" test_packed = struct.pack("!H", len(val)) + val with self.assertRaises(ValueError): unpacked, length = Bytes.from_bytes(test_packed[:-1]) with self.assertRaises(ValueError): unpacked, length = Bytes.from_bytes(test_packed[:1]) def test_unpack_bytes_oversized(self): val = b"helloworld!" test_packed = struct.pack("!H", len(val)) + val sth = b"testdata123" unpacked, length = Bytes.from_bytes(test_packed + sth) self.assertEqual(unpacked.val, val) self.assertEqual(unpacked.size, len(test_packed)) class TestArrayField(unittest.TestCase): def test_pack_string_array(self): array_of_string = [ String("this"), String("is"), String("an"), String("array"), String("of"), String("strings."), ] StringArray = array_field_factory("StringArray", String) array = StringArray(array_of_string) item_strings = f"[{','.join(str(x) for x in array_of_string)}]" packed = b"\x00\x06" for s in array_of_string: packed += s.pack() self.assertEqual(len(array), len(array_of_string)) self.assertEqual(array.size, 37) self.assertEqual( str(array), f"<StringArray length={len(array_of_string)} items={item_strings}>", ) self.assertEqual(array.pack(), packed) def test_pack_string_array_incompatible_size(self): array_of_string = [ String("this"), String("is"), String("an"), String("array"), String("of"), Bytes(b"strings."), ] StringArray = array_field_factory("StringArray", String) with self.assertRaises(TypeError): array = StringArray(array_of_string) array.pack() def test_unpack_string_array(self): StringArray = array_field_factory("StringArray", String) raw = b"\x00\x06\x00\x04this\x00\x02is\x00\x02an\x00\x05array\x00\x02of\x00\x08strings." unpacked, s = StringArray.from_bytes(raw) self.assertTrue(unpacked.size, len(raw)) self.assertEqual(s, len(raw)) self.assertTrue(len(unpacked), 6) def test_unpack_string_array_undersized(self): StringArray = array_field_factory("StringArray", String) raw = b"\x00\x06\x00\x04this\x00\x02is\x00\x02an\x00\x05array\x00\x02of\x00\x08strings." with self.assertRaises(ValueError): unpacked, s = StringArray.from_bytes(raw[:0]) def test_unpack_string_array_incomplete(self): StringArray = array_field_factory("StringArray", String) raw = b"\x00\x06\x00\x04this\x00\x02is\x00\x02an\x00\x05array\x00\x02of\x00\x08strings." with self.assertRaises(ValueError): unpacked, s = StringArray.from_bytes(raw[:-1]) class TestFieldFactory(unittest.TestCase): def test_field_factory(self): fieldClass = field_factory("Test", Uint8) self.assertEqual(fieldClass.__name__, "Test") self.assertTrue(issubclass(fieldClass, Uint8)) def test_array_field_factory(self): fieldClass = array_field_factory("TestArray", Uint8) self.assertEqual(fieldClass.__name__, "TestArray") self.assertTrue(issubclass(fieldClass, Array)) if __name__ == "__main__": unittest.main()
28.783231
96
0.590764
9762cc19812d32230e130044b3d2ceffb8a48927
98
sql
SQL
pgAdmin/pgadmin4/web/pgadmin/browser/server_groups/servers/pgagent/templates/pga_job/sql/pre3.4/run_now.sql
WeilerWebServices/PostgreSQL
ae594ed077bebbad1be3c1d95c38b7c2c2683e8c
[ "PostgreSQL" ]
4
2019-10-03T21:58:22.000Z
2021-02-12T13:33:32.000Z
openresty-win32-build/thirdparty/x86/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/pgagent/templates/pga_job/sql/pre3.4/run_now.sql
nneesshh/openresty-oss
bfbb9d7526020eda1788a0ed24f2be3c8be5c1c3
[ "MIT" ]
10
2020-06-05T19:42:26.000Z
2022-03-11T23:38:35.000Z
openresty-win32-build/thirdparty/x86/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/pgagent/templates/pga_job/sql/pre3.4/run_now.sql
nneesshh/openresty-oss
bfbb9d7526020eda1788a0ed24f2be3c8be5c1c3
[ "MIT" ]
1
2021-01-13T09:30:29.000Z
2021-01-13T09:30:29.000Z
UPDATE pgagent.pga_job SET jobnextrun=now()::timestamptz WHERE jobid={{ jid|qtLiteral }}::integer
24.5
40
0.77551
14a0ee4b321cc9c246952841c7f108efaccdf1fd
2,895
ts
TypeScript
index.d.ts
Rocket1184/ncm-releases
63267488419f7ce238e584226a575a5d7fe2987e
[ "MIT" ]
null
null
null
index.d.ts
Rocket1184/ncm-releases
63267488419f7ce238e584226a575a5d7fe2987e
[ "MIT" ]
1
2020-04-12T06:54:01.000Z
2020-04-12T06:54:01.000Z
index.d.ts
Rocket1184/ncm-releases
63267488419f7ce238e584226a575a5d7fe2987e
[ "MIT" ]
null
null
null
// from `@octokit/rest` type ReposListCommitsResponseItemParentsItem = { url: string; sha: string }; type ReposListCommitsResponseItemCommitter = { login: string; id: number; node_id: string; avatar_url: string; gravatar_id: string; url: string; html_url: string; followers_url: string; following_url: string; gists_url: string; starred_url: string; subscriptions_url: string; organizations_url: string; repos_url: string; events_url: string; received_events_url: string; type: string; site_admin: boolean; }; type ReposListCommitsResponseItemAuthor = { login: string; id: number; node_id: string; avatar_url: string; gravatar_id: string; url: string; html_url: string; followers_url: string; following_url: string; gists_url: string; starred_url: string; subscriptions_url: string; organizations_url: string; repos_url: string; events_url: string; received_events_url: string; type: string; site_admin: boolean; }; type ReposListCommitsResponseItemCommitVerification = { verified: boolean; reason: string; signature: null; payload: null; }; type ReposListCommitsResponseItemCommitTree = { url: string; sha: string }; type ReposListCommitsResponseItemCommitCommitter = { name: string; email: string; date: string; }; type ReposListCommitsResponseItemCommitAuthor = { name: string; email: string; date: string; }; type ReposListCommitsResponseItemCommit = { url: string; author: ReposListCommitsResponseItemCommitAuthor; committer: ReposListCommitsResponseItemCommitCommitter; message: string; tree: ReposListCommitsResponseItemCommitTree; comment_count: number; verification: ReposListCommitsResponseItemCommitVerification; }; type ReposListCommitsResponseItem = { url: string; sha: string; node_id: string; html_url: string; comments_url: string; commit: ReposListCommitsResponseItemCommit; author: ReposListCommitsResponseItemAuthor; committer: ReposListCommitsResponseItemCommitter; parents: Array<ReposListCommitsResponseItemParentsItem>; }; namespace Gh { type ReposListCommitsResponse = Array<ReposListCommitsResponseItem>; } namespace Qn { interface File { key: string; hash: string; fsize: number; mimeType: string; putTime: number; type: number; status: number; } } namespace Ncm { interface Pkg { name: string; size: string; url: string; } interface Commit { sha?: string; commit: { message: string; } } interface Build { hash: string; timestamp: number; commits?: Commit[]; pkgs: { [key: string]: Pkg }; } } expors as namespace;
24.327731
76
0.672884
33edfda8b13257b4179bba3935cbda0ae0916474
2,767
h
C
include/materials/RandomMix_t.h
guillaumetousignant/another_path_tracer
2738b32f91443ce15d1e7ab8ab77903bdfca695b
[ "MIT" ]
1
2019-08-08T12:19:45.000Z
2019-08-08T12:19:45.000Z
include/materials/RandomMix_t.h
guillaumetousignant/another_path_tracer
2738b32f91443ce15d1e7ab8ab77903bdfca695b
[ "MIT" ]
38
2019-07-11T16:18:00.000Z
2021-09-16T14:54:36.000Z
include/materials/RandomMix_t.h
guillaumetousignant/another_path_tracer
2738b32f91443ce15d1e7ab8ab77903bdfca695b
[ "MIT" ]
null
null
null
#ifndef APTRACER_RANDOMMIX_T_H #define APTRACER_RANDOMMIX_T_H #include "entities/Material_t.h" #include "entities/Ray_t.h" #include <random> namespace APTracer { namespace Entities { class Shape_t; }} using APTracer::Entities::Ray_t; using APTracer::Entities::Shape_t; using APTracer::Entities::Material_t; namespace APTracer { namespace Materials { /** * @brief The random mix material describes a mix of two materials, with the material being chosen randomly on bounce according to a ratio. * * This material will bounce rays on either of its material randomly according to a ratio. The * ratio is the proportion of light bounced on the refracted material. * This material models surfaces that are a mix of two materials, like dusty surfaces or surfaces * that partly emit light. */ class RandomMix_t final : public Material_t { public: /** * @brief Construct a new RandomMix_t object from two materials and a ratio. * * @param first_material First material, that will be randomly bounced according to the ratio. * @param second_material Second material, that will be randomly bounced according to the (1 - ratio). * @param ratio Proportion of the light bounced by the first material, from 0 to 1. */ RandomMix_t(Material_t* first_material, Material_t* second_material, double ratio); Material_t* first_material_; /**< @brief Material that will be bounced in proportion to the ratio.*/ Material_t* second_material_; /**< @brief Material that will be bounced in proportion to (1 - ratio).*/ double ratio_; /**< @brief Proportion of the light bounced by the first, "refracted", material.*/ std::uniform_real_distribution<double> unif_; /**< @brief Uniform random distribution used for generating random numbers.*/ /** * @brief Bounces a ray of light on the material. * * The ray is bounced randomly on either the reflected or refracted material according * to a ratio, which if the proportion of light bounced by the refracted material. * * @param uv Object space coordinates of the hit point. Used to query the shape for values at coordinates on it. Two components, u, and v, that can change meaning depending on the shape. * @param hit_obj Pointer to the shape that was hit by the ray. * @param ray Ray that has intersected the shape. */ virtual auto bounce(std::array<double, 2> uv, const Shape_t* hit_obj, Ray_t &ray) -> void final; }; }} #endif
50.309091
199
0.654138
c3d0a76a1dbccde73b5ea2ca6b1f1febe26a1186
1,062
swift
Swift
animation/Transition/Transition.swift
MChainZhou/animation
d6cd6875bfd783b7af01e983046aa7ab3fa0ba55
[ "MIT" ]
null
null
null
animation/Transition/Transition.swift
MChainZhou/animation
d6cd6875bfd783b7af01e983046aa7ab3fa0ba55
[ "MIT" ]
null
null
null
animation/Transition/Transition.swift
MChainZhou/animation
d6cd6875bfd783b7af01e983046aa7ab3fa0ba55
[ "MIT" ]
null
null
null
// // Transition.swift // animation // // Created by USER on 2018/10/23. // Copyright © 2018年 USER. All rights reserved. // import UIKit class Transition: NSObject { } extension Transition: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AniObjct() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AniObjct() } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return nil } // iOS 8 func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return OverlayPresentationController(presentedViewController: presented, presenting: presenting) } }
31.235294
170
0.757062
af85339abcf9cdc6c1c0d4d49be5260fdb385720
5,877
py
Python
aos/util/trapezoid_profile.py
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
39
2021-06-18T03:22:30.000Z
2022-03-21T15:23:43.000Z
aos/util/trapezoid_profile.py
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
10
2021-06-18T03:22:19.000Z
2022-03-18T22:14:15.000Z
aos/util/trapezoid_profile.py
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
4
2021-08-19T19:20:04.000Z
2022-03-08T07:33:18.000Z
#!/usr/bin/python3 import numpy class TrapezoidProfile(object): """Computes a trapezoidal motion profile Attributes: _acceleration_time: the amount of time the robot will travel at the specified acceleration (s) _acceleration: the acceleration the robot will use to get to the target (unit/s^2) _constant_time: amount of time to travel at a constant velocity to reach target (s) _deceleration_time: amount of time to decelerate (at specified deceleration) to target (s) _deceleration: decceleration the robot needs to get to goal velocity (units/s^2) _maximum_acceleration: the maximum acceleration (units/s^2) _maximum_velocity: the maximum velocity (unit/s) _timestep: time between calls to Update (delta_time) _output: output array containing distance to goal and velocity """ def __init__(self, delta_time): """Constructs a TrapezoidProfile. Args: delta_time: time between calls to Update (seconds) """ self._acceleration_time = 0 self._acceleration = 0 self._constant_time = 0 self._deceleration_time = 0 self._deceleration = 0 self._maximum_acceleration = 0 self._maximum_velocity = 0 self._timestep = delta_time self._output = numpy.array(numpy.zeros((2,1))) # Updates the state def Update(self, goal_position, goal_velocity): self._CalculateTimes(goal_position - self._output[0], goal_velocity) next_timestep = self._timestep # We now have the amount of time we need to accelerate to follow the # profile, the amount of time we need to move at constant velocity # to follow the profile, and the amount of time we need to decelerate to # follow the profile. Do as much of that as we have time left in dt. if self._acceleration_time > next_timestep: self._UpdateVals(self._acceleration, next_timestep) else: self._UpdateVals(self._acceleration, self._acceleration_time) next_timestep -= self._acceleration_time if self._constant_time > next_timestep: self._UpdateVals(0, next_timestep) else: self._UpdateVals(0, self._constant_time) next_timestep -= self._constant_time; if self._deceleration_time > next_timestep: self._UpdateVals(self._deceleration, next_timestep) else: self._UpdateVals(self._deceleration, self._deceleration_time) next_timestep -= self._deceleration_time self._UpdateVals(0, next_timestep) return self._output # Useful for preventing windup etc. def MoveCurrentState(self, current): self._output = current # Useful for preventing windup etc. def MoveGoal(self, dx): self._output[0] += dx def SetGoal(self, x): self._output[0] = x def set_maximum_acceleration(self, maximum_acceleration): self._maximum_acceleration = maximum_acceleration def set_maximum_velocity(self, maximum_velocity): self._maximum_velocity = maximum_velocity def _UpdateVals(self, acceleration, delta_time): self._output[0, 0] += (self._output[1, 0] * delta_time + 0.5 * acceleration * delta_time * delta_time) self._output[1, 0] += acceleration * delta_time def _CalculateTimes(self, distance_to_target, goal_velocity): if distance_to_target == 0: self._acceleration_time = 0 self._acceleration = 0 self._constant_time = 0 self._deceleration_time = 0 self._deceleration = 0 return elif distance_to_target < 0: # Recurse with everything inverted. self._output[1] *= -1 self._CalculateTimes(-distance_to_target, -goal_velocity) self._output[1] *= -1 self._acceleration *= -1 self._deceleration *= -1 return self._constant_time = 0 self._acceleration = self._maximum_acceleration maximum_acceleration_velocity = ( distance_to_target * 2 * numpy.abs(self._acceleration) + self._output[1] * self._output[1]) if maximum_acceleration_velocity > 0: maximum_acceleration_velocity = numpy.sqrt(maximum_acceleration_velocity) else: maximum_acceleration_velocity = -numpy.sqrt(-maximum_acceleration_velocity) # Since we know what we'd have to do if we kept after it to decelerate, we # know the sign of the acceleration. if maximum_acceleration_velocity > goal_velocity: self._deceleration = -self._maximum_acceleration else: self._deceleration = self._maximum_acceleration # We now know the top velocity we can get to. top_velocity = numpy.sqrt((distance_to_target + (self._output[1] * self._output[1]) / (2.0 * self._acceleration) + (goal_velocity * goal_velocity) / (2.0 * self._deceleration)) / (-1.0 / (2.0 * self._deceleration) + 1.0 / (2.0 * self._acceleration))) # If it can go too fast, we now know how long we get to accelerate for and # how long to go at constant velocity. if top_velocity > self._maximum_velocity: self._acceleration_time = ((self._maximum_velocity - self._output[1]) / self._maximum_acceleration) self._constant_time = (distance_to_target + (goal_velocity * goal_velocity - self._maximum_velocity * self._maximum_velocity) / (2.0 * self._maximum_acceleration)) / self._maximum_velocity else: self._acceleration_time = ( (top_velocity - self._output[1]) / self._acceleration) if self._output[1] > self._maximum_velocity: self._constant_time = 0 self._acceleration_time = 0 self._deceleration_time = ( (goal_velocity - top_velocity) / self._deceleration)
37.433121
84
0.671261
fd007fd86515bdb4a1cd29cfbf2d65e840d6bf17
66
sql
SQL
src/test/resources/sql/select/20497a66.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/select/20497a66.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/select/20497a66.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:regex.sql ln:65 expect:true select 'xyy' ~ '(?<=[xy])yy+'
22
35
0.590909
8dadeca8517870a3842b21bdd82a2bc906692675
3,728
js
JavaScript
screens/wizzard/WizzardScreen.js
aenniw/esp-mdns-lights
d2df7860c2662bc4a0057819984fff04d0904466
[ "MIT" ]
1
2019-04-19T16:12:49.000Z
2019-04-19T16:12:49.000Z
screens/wizzard/WizzardScreen.js
aenniw/esp-mdns-lights
d2df7860c2662bc4a0057819984fff04d0904466
[ "MIT" ]
1
2019-07-01T12:14:33.000Z
2019-12-24T18:41:39.000Z
screens/wizzard/WizzardScreen.js
aenniw/esp-mdns-lights
d2df7860c2662bc4a0057819984fff04d0904466
[ "MIT" ]
null
null
null
import React from "react"; import { Platform, StyleSheet, View } from "react-native"; import * as Permissions from "expo-permissions"; import { BarCodeScanner } from "expo-barcode-scanner"; import WizzardModal from "./WizzardModal"; import { IconButton } from "../../components/Buttons"; import { MonoText, LocaleText } from "../../components/Texts"; export default class HomeScreen extends React.Component { static navigationOptions = { headerTitle: () => ( <MonoText label="wizzard.label" style={{ fontSize: 18, paddingHorizontal: 20 }} /> ) }; state = { cameraPermission: Permissions.PermissionStatus.UNDETERMINED, scanned: true }; async componentDidMount() { this.getPermissionsAsync(); } getPermissionsAsync = async () => { const { status } = await Permissions.askAsync(Permissions.CAMERA); this.setState({ cameraPermission: status }); }; handleBarCodeScanned = ({ data }) => { const match = data.match("WIFI:S:(.*);T:(WPA|WEP);P:(.*);;"); if (match) { this.setState({ ssid: match[1], type: match[2], password: match[3] }); } this.setState({ scanned: true }); }; reScan = () => { this.setState( { ssid: undefined, type: undefined, password: undefined, scanned: false }, () => { if (Platform.OS === "web") { this.handleBarCodeScanned({ data: "WIFI:S:SSID;T:WPA;P:password;;" }); } } ); }; clearScan = () => { this.setState({ ssid: undefined, type: undefined, password: undefined }); }; render() { const { cameraPermission, scanned, ssid, type, password } = this.state; return ( <View style={styles.container}> <View style={[ styles.containerContent, { backgroundColor: cameraPermission === Permissions.PermissionStatus.GRANTED ? "black" : "lightgray" } ]} > {cameraPermission === Permissions.PermissionStatus.UNDETERMINED && ( <LocaleText style={styles.sectionWarning} label="camera.permission" /> )} {cameraPermission === Permissions.PermissionStatus.GRANTED && ( <BarCodeScanner style={StyleSheet.absoluteFillObject} barCodeTypes={[BarCodeScanner.Constants.BarCodeType.qr]} onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned} /> )} {cameraPermission === Permissions.PermissionStatus.DENIED && ( <LocaleText style={styles.sectionWarning} label="camera.none" /> )} </View> <View style={styles.scanButton}> <IconButton style={{ borderRadius: 20, position: "absolute", bottom: 30 }} name="qr-scanner" size={50} onPress={this.reScan} /> </View> {ssid && ( <WizzardModal ssid={ssid} type={type} password={password} onClose={this.clearScan} /> )} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, containerContent: { flex: 1, display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }, scanButton: { display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center" }, sectionWarning: { fontSize: 20, fontFamily: "space-mono", textAlign: "center", paddingHorizontal: 15 } });
25.360544
80
0.546674
aca84deda1b0b6d77ad779a3a9a699cac1a540a9
1,276
lua
Lua
wyx/event/EntityPositionEvent.lua
scottcs/wyx
554324cf36faf28da437d4af52fe392e9507cf62
[ "MIT" ]
null
null
null
wyx/event/EntityPositionEvent.lua
scottcs/wyx
554324cf36faf28da437d4af52fe392e9507cf62
[ "MIT" ]
null
null
null
wyx/event/EntityPositionEvent.lua
scottcs/wyx
554324cf36faf28da437d4af52fe392e9507cf62
[ "MIT" ]
null
null
null
local Class = require 'lib.hump.class' local Event = getClass 'wyx.event.Event' -- EntityPositionEvent -- local EntityPositionEvent = Class{name='EntityPositionEvent', inherits=Event, function(self, entityID, toX, toY, fromX, fromY) if type(entityID) ~= 'string' then entityID = entityID:getID() end verify('string', entityID) verify('number', toX, toY, fromX, fromY) assert(EntityRegistry:exists(entityID), 'EntityPositionEvent: entityID %q does not exist', entityID) Event.construct(self, 'Entity Position Event') self._debugLevel = 2 self._entityID = entityID self._toX = toX self._toY = toY self._fromX = fromX self._fromY = fromY end } -- destructor function EntityPositionEvent:destroy() self._entityID = nil self._toX = nil self._toY = nil self._fromX = nil self._fromY = nil Event.destroy(self) end function EntityPositionEvent:getEntity() return self._entityID end function EntityPositionEvent:getDestination() return self._toX, self._toY end function EntityPositionEvent:getOrigin() return self._fromX, self._fromY end function EntityPositionEvent:__tostring() return self:_msg('{%08s} from: (%d,%d) to: (%d,%d)', self._entityID, self._fromX, self._fromY, self._toX, self._toY) end -- the class return EntityPositionEvent
27.148936
77
0.746082
c6a265a39c9e43189485eaec90c7b91a01bff007
575
css
CSS
src/routes/EditEventPage/EditEventPage.css
JizongL/stressTrac
9bf051e8ebc667121a64115484c6e2c7ce4ce9e4
[ "MIT" ]
null
null
null
src/routes/EditEventPage/EditEventPage.css
JizongL/stressTrac
9bf051e8ebc667121a64115484c6e2c7ce4ce9e4
[ "MIT" ]
4
2020-09-04T20:35:17.000Z
2021-05-08T16:28:40.000Z
src/routes/EditEventPage/EditEventPage.css
JizongL/stressTrac-client
9bf051e8ebc667121a64115484c6e2c7ce4ce9e4
[ "MIT" ]
null
null
null
.edit_event_form{ display: flex; justify-content: center; color:white; font-size: 15px; } .edit_event_form input{ width:500px; } .edit_event_form select{ margin-bottom: 10px; } .edit_event_page{ display:flex; flex-direction: column; background-color: #049c41; font-family:'Roboto',sans-serif; } .edit_event_title{ font-size: 40px; color: white; text-align: center; } @media(max-width:600px){ .edit_event_title{ font-size: 20px; } .edit_event_form select{ width:100%; } .edit_event_form input{ width:100%; } }
14.02439
36
0.664348
728597fcab696c9d5089f3ebfba13afe8e14a92a
11,160
cs
C#
Stepon.FaceRecognization/FaceDemo/Main.cs
maxjove/FaceRecognization
d14e6a995ba5ceb3437a3ab5e98cab2e7694aa9b
[ "Apache-2.0" ]
242
2017-09-29T02:24:04.000Z
2021-11-09T12:09:45.000Z
Stepon.FaceRecognization/FaceDemo/Main.cs
maxjove/FaceRecognization
d14e6a995ba5ceb3437a3ab5e98cab2e7694aa9b
[ "Apache-2.0" ]
14
2017-10-10T06:30:25.000Z
2019-04-07T08:16:21.000Z
Stepon.FaceRecognization/FaceDemo/Main.cs
maxjove/FaceRecognization
d14e6a995ba5ceb3437a3ab5e98cab2e7694aa9b
[ "Apache-2.0" ]
95
2017-10-10T05:42:21.000Z
2022-02-19T09:00:34.000Z
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using NReco.VideoConverter; using Stepon.FaceRecognization; using Stepon.FaceRecognization.Age; using Stepon.FaceRecognization.Common; using Stepon.FaceRecognization.Detection; using Stepon.FaceRecognization.Gender; using Stepon.FaceRecognization.Recognization; using Stepon.FaceRecognization.Tracking; namespace FaceDemo { public partial class Main : Form { private const string AppId = ""; private const string FtKey = ""; private const string FdKey = ""; private const string FrKey = ""; private const string AgeKey = ""; private const string GenderKey = ""; private const string FaceLibraryPath = "faces"; private static readonly object _imageLock = new object(); private readonly Dictionary<string, byte[]> _cache = new Dictionary<string, byte[]>(); private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim(); private FaceDetection _detection; //用于静态图片抽取特征 private Bitmap _image; private IntPtr _pImage; private FaceProcessor _processor; private FaceRecognize _recognize; private bool _renderRunning = true; private Task _renderTask; private bool _shouldShot; private FaceTracking _traking; //用于视频流检测人脸 private MemoryStream outputStream; private ConvertLiveMediaTask task; //视频图形信息 private int width = 1920; private int height = 1080; private int pixelSize = 3; private int stride; private int bufferSize; //性别和年龄 private FaceAge _age; private FaceGender _gender; public Main() { InitializeComponent(); Init(); } private void Init() { _age = new FaceAge(AppId, AgeKey); _gender = new FaceGender(AppId, GenderKey); _traking = LocatorFactory.GetTrackingLocator(AppId, FtKey, _age, _gender) as FaceTracking; _detection = LocatorFactory.GetDetectionLocator(AppId, FdKey) as FaceDetection; _recognize = new FaceRecognize(AppId, FrKey); _processor = new FaceProcessor(_traking, _recognize); //init cache if (Directory.Exists(FaceLibraryPath)) { var files = Directory.GetFiles(FaceLibraryPath); foreach (var file in files) { var info = new FileInfo(file); _cache.Add(info.Name.Replace(info.Extension, ""), File.ReadAllBytes(file)); } } stride = width * pixelSize; bufferSize = stride * height; _pImage = Marshal.AllocHGlobal(bufferSize); _image = new Bitmap(width, height, stride, PixelFormat.Format24bppRgb, _pImage); var ffmpeg = new FFMpegConverter(); outputStream = new MemoryStream(); var setting = new ConvertSettings { CustomOutputArgs = "-an -r 15 -pix_fmt bgr24 -updatefirst 1" //根据业务需求-r参数可以调整,取决于摄像机的FPS }; //-s 1920x1080 -q:v 2 -b:v 64k task = ffmpeg.ConvertLiveMedia("rtsp://user:[email protected]:554/h264/ch1/main/av_stream", null, outputStream, Format.raw_video, setting); /* * USB摄像头捕获 * 通过ffmpeg可以捕获USB摄像,如下代码所示。 * 首先通过:ffmpeg -list_devices true -f dshow -i dummy命令,可以列出系统中存在的USB摄像设备(或通过控制面板的设备管理工具查看设备名称),例如在我电脑中叫USB2.0 PC CAMERA。 * 然后根据捕获的分辨率,修改视频图形信息,包括width和height,一般像素大小不用修改,如果要参考设备支持的分辨率,可以使用: * ffmpeg -list_options true -f dshow -i video="USB2.0 PC CAMERA"命令 */ //task = ffmpeg.ConvertLiveMedia("video=USB2.0 PC CAMERA", "dshow", // outputStream, Format.raw_video, setting); task.OutputDataReceived += DataReceived; task.Start(); _renderTask = new Task(Render); _renderTask.Start(); } private void DataReceived(object sender, EventArgs e) { if (outputStream.Position == bufferSize) //1920*1080*3,stride * width,取决于图片的大小和像素格式 lock (_imageLock) { var data = outputStream.ToArray(); Marshal.Copy(data, 0, _pImage, data.Length);//直接替换在内存中的位图数据,以提升处理效率 outputStream.Seek(0, SeekOrigin.Begin); } } private void Render() { while (_renderRunning) { if (_image == null) continue; Bitmap image; lock (_imageLock) { image = (Bitmap)_image.Clone(); } if (_shouldShot) { WriteFeature(image); _shouldShot = false; } Verify(image); if (videoImage.InvokeRequired) videoImage.Invoke(new Action(() => { videoImage.Image = image; })); else videoImage.Image = image; } } private void Verify(Bitmap bitmap) { var features = _processor.LocateExtract(bitmap); //var features = _processor.LocateExtract(bitmap, LocateOperation.IncludeAge | LocateOperation.IncludeGender); //采用此方式抽取的特征,将包含性别和年龄信息 if (features != null) { var names = MatchAll(features); var index = 0; using (var g = Graphics.FromImage(bitmap)) { foreach (var feature in features) { g.DrawRectangle(new Pen(Color.Crimson, 2), feature.FaceLoaction); g.DrawString(names[index], new Font(new FontFamily("SimSun"), 12), new SolidBrush(Color.Crimson), feature.FaceLoaction.Right, feature.FaceLoaction.Bottom); feature.Dispose(); //feature中的特征数据从托管内存复制到非托管,必须释放,否则内存泄露 index++; } } } } private string[] MatchAll(Feature[] features) { var result = Enumerable.Repeat("陌生人", features.Length).ToArray(); if (_cache.Count == 0) return result; //依次处理找到的人脸 var max = new float[features.Length]; try { _cacheLock.EnterReadLock(); foreach (var single in _cache) for (var i = 0; i < features.Length; i++) { var sim = _processor.Match(features[i].FeatureData, single.Value); //此方法默认保留采集到的特征(非托管内存),并自动释放被比较(特征库)的特征数据,所以无需担心内存泄露 if (sim > 0.5) if (sim > max[i]) { max[i] = sim; result[i] = single.Key; } } } finally { _cacheLock.ExitReadLock(); } return result; } protected override void OnClosing(CancelEventArgs e) { _renderRunning = false; task.Stop(true); _traking.Dispose(); _detection.Dispose(); _recognize.Dispose(); _age.Dispose(); _gender.Dispose(); Marshal.FreeHGlobal(_pImage); base.OnClosing(e); } private void WriteFeature(Bitmap bitmap) { var code = _detection.Detect(bitmap, out var locate); try { if (code == ErrorCode.Ok) { if (locate.HasFace) { if (locate.FaceCount > 1) { MessageBox.Show("选定的图片检测到多余一张的人脸,请重新选择"); return; } var name = userIdentity.Text; using (var feature = _recognize.ExtractFeature(locate.OffInput, locate.Faces[0], locate.FacesOrient[0])) { if (!Directory.Exists(FaceLibraryPath)) Directory.CreateDirectory(FaceLibraryPath); File.WriteAllBytes(Path.Combine(FaceLibraryPath, $"{name}.dat"), feature.FeatureData); try { _cacheLock.EnterWriteLock(); _cache.Add(name, feature.FeatureData); } finally { _cacheLock.ExitWriteLock(); } } if (userIdentity.InvokeRequired) userIdentity.Invoke(new Action(() => { userIdentity.Text = ""; })); else userIdentity.Text = ""; } } else { MessageBox.Show(code.ToString()); } } catch (Exception error) { MessageBox.Show(error.Message); } finally { locate.Dispose(); } MessageBox.Show("建立特征成功"); } /// <summary> /// 选择静态照片进行特征抽取 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnImageExtractClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(userIdentity.Text)) { MessageBox.Show("请先输入用户标识"); return; } var openFile = new OpenFileDialog { Multiselect = false }; var result = openFile.ShowDialog(); if (result == DialogResult.OK) { var file = openFile.FileName; WriteFeature(new Bitmap(Image.FromFile(file))); } } /// <summary> /// 从视频流中抓取照片进行特征抽取 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnShotExtractClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(userIdentity.Text)) { MessageBox.Show("请先输入用户标识"); return; } _shouldShot = true; } } }
32.347826
146
0.495251
da56872f8ffc75b959896a9bb1ab9c3e22a74cc3
6,737
php
PHP
src/Component/Cache/Redis/RedisAttendant.php
src-run/teavee-object-cache-bundle
66f7f82706ddb4e38cc3b77bbfd69e2d5fcaf8d4
[ "MIT" ]
null
null
null
src/Component/Cache/Redis/RedisAttendant.php
src-run/teavee-object-cache-bundle
66f7f82706ddb4e38cc3b77bbfd69e2d5fcaf8d4
[ "MIT" ]
1
2015-03-01T10:09:40.000Z
2015-03-22T18:02:52.000Z
src/Component/Cache/Redis/RedisAttendant.php
src-run/teavee-object-cache-bundle
66f7f82706ddb4e38cc3b77bbfd69e2d5fcaf8d4
[ "MIT" ]
null
null
null
<?php /* * This file is part of the Teavee Block Manager Bundle. * * (c) Scribe Inc. <[email protected]> * (c) Rob Frawley 2nd <[email protected]> * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ namespace Scribe\Teavee\ObjectCacheBundle\Component\Cache\Redis; use Redis; use Scribe\Teavee\ObjectCacheBundle\Component\Cache\AbstractCacheAttendant; use Scribe\Wonka\Exception\InvalidArgumentException; use Scribe\Wonka\Exception\LogicException; use Scribe\Wonka\Utility\Extension; use Scribe\Wonka\Utility\Filter\StringFilter; /** * Class RedisAttendant. */ class RedisAttendant extends AbstractCacheAttendant implements RedisAttendantInterface { /** * Options defined by DI; normalized and loaded upon lazy initialization, {@see setUp()}. * * @var string[] */ protected $optionCollection = []; /** * Server defined by DI; normalized and loaded upon lazy initialization, {@see setUp()}. * * @var mixed[] */ protected $server = []; /** * Redis object instance. * * @var Redis */ protected $r; /** * Set server options. * * @param string[] $options * * @return $this */ public function setOptions(array $options = []) { $this->optionCollection = (array) $options; return $this; } /** * Get server options. * * @return string[] */ public function getOptions() { return $this->optionCollection; } /** * @param mixed[] $server * * @return $this */ public function setServer(array $server = []) { $this->server = (array) $server; return $this; } /** * @return mixed[] */ public function getServer() { return (array) $this->server; } /** * {@inheritdoc} */ public function isSupported(...$by) { return (bool) (Extension::isEnabled('redis')); } /** * {@inheritdoc} */ protected function setUp() { $this ->setUpInstance() ->setUpServers() ->setUpOptions(); } /** * Instantiate redis object instance. * * @return $this */ protected function setUpInstance() { $this->r = new Redis(); return $this; } /** * Normalize passed option list and apply. * * @return $this */ protected function setUpOptions() { foreach ($this->optionCollection as $type => $state) { $this->r->setOption(...$this->normalizeOption($type, $state)); } return $this; } /** * Normalize human-readable options to correct Memcache constants for type and state. * * @param string $type * @param mixed $state * * @return mixed[] */ protected function normalizeOption($type, $state) { return [ $this->normalizeOptionType($type), $this->normalizeOptionState($state) ]; } /** * Normalize option type. * * @param string $type * * @return mixed */ protected function normalizeOptionType($type) { return $this->resolveConstant($type, 'OPT_'); } /** * Normalize option type state. * * @param mixed $state * * @return bool|int */ protected function normalizeOptionState($state) { return $this->resolveConstant($state); } /** * Resolve value of Redis constant. * * @param string $name * @param string $prefix * @param string $class * * @throws InvalidArgumentException If constant cannot be resolved. * * @return mixed */ protected function resolveConstant($name, $prefix = '', $class = 'Redis') { $constant = sprintf('%s::%s%s', $class, $prefix, strtoupper($name)); if (!defined($constant)) { throw new InvalidArgumentException('Provided name "%s" unresolvable to constant "%s".', $name, $constant); } return constant($constant); } /** * Normalize passed server list and apply. * * @return $this */ protected function setUpServers() { if (true !== $this->r->connect(...$this->normalizeServerOptions($this->server))) { throw new InvalidArgumentException('Could not connect to server with keys "%s" and values "%s".', null, null, implode(',', array_keys($this->server)), implode(',', array_values($this->server))); } return $this; } /** * Normalize server options. * * @param mixed[] $options * * @return mixed[] */ protected function normalizeServerOptions(array $options = []) { $normalized = []; foreach (['host', 'port', 'timeout', 'reserved', 'retry_interval'] as $o) { $normalized[] = $this->normalizeServerOptionValue($options, $o); } return $normalized; } /** * @param mixed[] $options * @param string $name * * @return mixed */ protected function normalizeServerOptionValue(array $options, $name) { if (array_key_exists($name, $options)) { return $options[$name]; } return $this->resolveConstant(strtoupper($name), 'DEFAULT_', get_called_class()); } /** * Get cache entry. * * @param string $key * * @return null|string */ protected function getCacheEntry($key) { if (false === ($data = $this->r->get($key))) { return null; } return $data; } /** * Set cache entry. * * @param string $key * @param mixed $data * * @return bool */ protected function setCacheEntry($key, $data) { return (bool) $this->r->set($key, $data, $this->ttl); } /** * Check for cache entry. * * @param string $key * * @return bool */ protected function hasCacheEntry($key) { return (bool) $this->r->exists($key); } /** * Delete cache entry. * * @param string $key * * @return bool */ protected function delCacheEntry($key) { return (bool) $this->r->del($key); } /** * Flush all cache entries. * * @return bool */ protected function flushCacheEntries() { return (bool) $this->r->flushAll(); } /** * @return string[] */ protected function listCacheKeys() { return (array) $this->r->keys('*'); } } /* EOF */
21.119122
206
0.541339
38b7b691e1aac03e024ad38cecb2a8617ddf82da
110
php
PHP
vendor/pagerfanta/pagerfanta/src/Exception/LogicException.php
linhcatcat/wcf
9823a3db37f8157337e81f1e92363d129c83f13a
[ "MIT" ]
5
2021-09-29T06:55:24.000Z
2022-03-02T02:47:00.000Z
vendor/pagerfanta/pagerfanta/src/Exception/LogicException.php
linhcatcat/wcf
9823a3db37f8157337e81f1e92363d129c83f13a
[ "MIT" ]
1
2021-05-09T23:38:59.000Z
2021-05-09T23:38:59.000Z
vendor/pagerfanta/pagerfanta/src/Exception/LogicException.php
linhcatcat/wcf
9823a3db37f8157337e81f1e92363d129c83f13a
[ "MIT" ]
null
null
null
<?php namespace Pagerfanta\Exception; class LogicException extends \LogicException implements Exception { }
13.75
65
0.818182
0dc0e7a7a8194ab1ce36f1e3098b19042bfad3d9
337
rb
Ruby
test/test_helper.rb
tech-angels/annotator
ad8f203635633eb3428105be7c39b80694184a2b
[ "MIT" ]
8
2015-06-29T10:34:59.000Z
2019-08-29T07:39:28.000Z
test/test_helper.rb
tech-angels/annotator
ad8f203635633eb3428105be7c39b80694184a2b
[ "MIT" ]
null
null
null
test/test_helper.rb
tech-angels/annotator
ad8f203635633eb3428105be7c39b80694184a2b
[ "MIT" ]
null
null
null
require 'fileutils' # Configure Rails Environment ENV["RAILS_ENV"] = "test" # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } TestApp.prepare! require File.expand_path("#{TestApp.path}/config/environment.rb", __FILE__) require "rails/test_help" Rails.backtrace_cleaner.remove_silencers!
21.0625
76
0.74184
2c847d6ed812e04e3e82982325c29e59d9aa8aee
1,346
py
Python
SedOperations.py
p10rahulm/brandyz-reco
95d5e3f291cdb5b951e0c7d83ff30c59f8a3797f
[ "MIT" ]
null
null
null
SedOperations.py
p10rahulm/brandyz-reco
95d5e3f291cdb5b951e0c7d83ff30c59f8a3797f
[ "MIT" ]
null
null
null
SedOperations.py
p10rahulm/brandyz-reco
95d5e3f291cdb5b951e0c7d83ff30c59f8a3797f
[ "MIT" ]
null
null
null
# for windows download sed from here: http://gnuwin32.sourceforge.net/packages/sed.htm # on second thoughts: https://stackoverflow.com/questions/1823591/sed-creates-un-deleteable-files-in-windows/25407238 # Use the following: https://github.com/mbuilov/sed-windows/blob/master/sed-4.4-x64.exe import subprocess def tail(filename, numlines): # get last line from tail subprocess # - note for windows had to download gnu unixutils from https://sourceforge.net/projects/unxutils/reviews/ # - add it to path, etc numlines_str = '-'+str(numlines) # object returned is bytes-like. Need to convert to str. return str(subprocess.check_output(['tail', numlines_str, filename]))[1:] def replace_line_number(filename,linenumber,newline_string): # below is a sample conversion which targets the first line on file.txt # sed - i "1s/.*/$var/" file.txt sed_command = str(linenumber) + "s/.*/" + newline_string + "/" # calling subprocess function to oursource replacement to sed. This is much faster than any python based solution subprocess.call(["sed", "-i", sed_command, filename]) if __name__=="__main__": print(tail("SedOperations.py",1)) with open("test/some_sed_test.txt") as f: new_first_line = str(int(f.readline())+1) replace_line_number("test/some_sed_test.txt",1,new_first_line)
48.071429
117
0.725854
1f2d7525bf1813f9928bb71de41246e5eafba6f7
416
sql
SQL
Views/vinyl_info.sql
KamranDjourshari24/Vinyl-Record-Database
fd8154c1a4ef056fe035335efd107c8485a8d54a
[ "MIT" ]
2
2021-01-10T20:11:44.000Z
2021-01-10T23:26:21.000Z
Views/vinyl_info.sql
KamranDjourshari24/Vinyl-Record-Database
fd8154c1a4ef056fe035335efd107c8485a8d54a
[ "MIT" ]
null
null
null
Views/vinyl_info.sql
KamranDjourshari24/Vinyl-Record-Database
fd8154c1a4ef056fe035335efd107c8485a8d54a
[ "MIT" ]
2
2021-04-22T20:39:52.000Z
2021-04-22T21:00:03.000Z
USE project; CREATE OR REPLACE VIEW vinyl_info AS SELECT artist_name AS "Artist Name", album_name AS "Album Name", genre AS "Genre", track_amount "Number of Songs", runtime AS "Runtime", first_available AS "Date when First Available", IF(is_explicit, "True", "False") AS "Is Explicit?" FROM vinyl JOIN singers USING(singer_id) ORDER BY artist_name, album_name; SELECT * FROM vinyl_info
32
101
0.71875
540ce22d1dfacf7247ef098bdde4bb677e972232
1,083
lua
Lua
gatherer.lua
shagu/delvermd
946709d5b75c8df29b7ac106bb5181573c476dd9
[ "MIT" ]
1
2021-04-17T06:14:11.000Z
2021-04-17T06:14:11.000Z
gatherer.lua
shagu/delvermd
946709d5b75c8df29b7ac106bb5181573c476dd9
[ "MIT" ]
null
null
null
gatherer.lua
shagu/delvermd
946709d5b75c8df29b7ac106bb5181573c476dd9
[ "MIT" ]
null
null
null
-- download gatherer images local gatherer = {} function gatherer:Fetch(collection, images) local https = require("ssl.https") local id = 0 for i, card in pairs(collection) do id = id + 1 io.write("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b") io.write("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b") io.write(" - Downloading Gatherer Artwork ("..id..")") io.flush() local cache = io.open("cache/images/" .. card.scryfall .. ".jpg") if card.multiverse and card.imgurl and not cache then local image = fetchlang and https.request(card.imgurl_lang) image = image or https.request(card.imgurl) if image then images[i]["stock"] = image local file = io.open("cache/images/" .. card.scryfall .. ".jpg", "w") file:write(image) file:close() else print(string.format(" WARNING: No Image for '%s' (%s)", card.name, card.multiverse)) end elseif cache then cache:close() end end print() return images end return gatherer
29.27027
92
0.601108
14e7511a3dcb031cdfc7f54d1bdf1d1681127298
7,356
ts
TypeScript
packages/cli/src/question/question.ts
swatDong/TeamsFx
393402bce7831e171332fc26e82ab35b52af8270
[ "MIT" ]
null
null
null
packages/cli/src/question/question.ts
swatDong/TeamsFx
393402bce7831e171332fc26e82ab35b52af8270
[ "MIT" ]
null
null
null
packages/cli/src/question/question.ts
swatDong/TeamsFx
393402bce7831e171332fc26e82ab35b52af8270
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. "use strict"; import inquirer, { DistinctQuestion } from "inquirer"; import { NodeType, QTreeNode, OptionItem, Question, ConfigMap, getValidationFunction, RemoteFuncExecutor, isAutoSkipSelect, getSingleOption, SingleSelectQuestion, MultiSelectQuestion, getCallFuncValue, StaticOption, DymanicOption } from "@microsoft/teamsfx-api"; import CLILogProvider from "../commonlib/log"; import * as constants from "../constants"; import { flattenNodes, getChoicesFromQTNodeQuestion, toConfigMap } from "../utils"; import { QTNConditionNotSupport, QTNQuestionTypeNotSupport, NotValidInputValue, NotValidOptionValue } from "../error"; export async function validateAndUpdateAnswers( root: QTreeNode | undefined, answers: ConfigMap, remoteFuncValidator?: RemoteFuncExecutor ): Promise<void> { if (!root) { return; } const nodes = flattenNodes(root); for (const node of nodes) { if (node.data.type === NodeType.group) { continue; } const ans: any = answers.get(node.data.name); if (!ans) { continue; } if ("validation" in node.data && node.data.validation) { const validateFunc = getValidationFunction(node.data.validation, toConfigMap(answers), remoteFuncValidator); const result = await validateFunc(ans); if (typeof result === "string") { throw NotValidInputValue(node.data.name, result); } } // if it is a select question if (node.data.type === NodeType.multiSelect || node.data.type === NodeType.singleSelect) { const question = node.data as SingleSelectQuestion | MultiSelectQuestion; let option = question.option; if (!(option instanceof Array)) { option = await getCallFuncValue(answers, false, node.data.option as DymanicOption) as StaticOption; } // if the option is the object, need to find the object first. if (typeof option[0] !== "string") { // for multi-select question if (ans instanceof Array) { const items = []; for (const one of ans) { const item = (option as OptionItem[]).filter(op => op.cliName === one || op.id === one)[0]; if (item) { if (question.returnObject) { items.push(item); } else { items.push(item.id); } } else { throw NotValidOptionValue(question, option); } } answers.set(node.data.name, items); } // for single-select question else { const item = (option as OptionItem[]).filter(op => op.cliName === ans || op.id === ans)[0]; if (!item) { throw NotValidOptionValue(question, option); } if (question.returnObject) { answers.set(node.data.name, item); } else { answers.set(node.data.name, item.id); } } } } } } export async function visitInteractively( node: QTreeNode, answers?: any, parentNodeAnswer?: any, remoteFuncValidator?: RemoteFuncExecutor ): Promise<{ [_: string]: any }> { if (!answers) { answers = {}; } let shouldVisitChildren = false; if (node.condition) { if (node.condition.target) { throw QTNConditionNotSupport(node); } if (node.condition.equals) { if (node.condition.equals === parentNodeAnswer) { shouldVisitChildren = true; } else { return answers; } } if ("minItems" in node.condition && node.condition.minItems) { if (parentNodeAnswer instanceof Array && parentNodeAnswer.length >= node.condition.minItems) { shouldVisitChildren = true; } else { return answers; } } if ("contains" in node.condition && node.condition.contains) { if (parentNodeAnswer instanceof Array && parentNodeAnswer.includes(node.condition.contains)) { shouldVisitChildren = true; } else { return answers; } } if ("containsAny" in node.condition && node.condition.containsAny) { if (parentNodeAnswer instanceof Array && node.condition.containsAny.map(item => parentNodeAnswer.includes(item)).includes(true)) { shouldVisitChildren = true; } else { return answers; } } if (!shouldVisitChildren) { throw QTNConditionNotSupport(node); } } else { shouldVisitChildren = true; } let answer: any = undefined; if (node.data.type !== NodeType.group) { if (node.data.type === NodeType.localFunc) { const res = await node.data.func(answers); answers[node.data.name] = res; } else if (!isAutoSkipSelect(node.data)) { answers = await inquirer.prompt([toInquirerQuestion(node.data, answers, remoteFuncValidator)], answers); // convert the option.label to option.id if ("option" in node.data) { const option = node.data.option; if (option instanceof Array && option.length > 0 && typeof option[0] !== "string") { const tmpAns = answers[node.data.name]; if (tmpAns instanceof Array) { answers[node.data.name] = tmpAns.map(label => (option as OptionItem[]).find(op => label === op.label)?.id); } else { answers[node.data.name] = (option as OptionItem[]).find(op => tmpAns === op.label)?.id; } } } } else { answers[node.data.name] = getSingleOption(node.data as (SingleSelectQuestion | MultiSelectQuestion)); } answer = answers[node.data.name]; } if (shouldVisitChildren && node.children) { for (const child of node.children) { answers = await visitInteractively(child, answers, answer, remoteFuncValidator); } } return answers!; } export function toInquirerQuestion(data: Question, answers: { [_: string]: any }, remoteFuncValidator?: RemoteFuncExecutor): DistinctQuestion { let type: "input" | "number" | "password" | "list" | "checkbox"; let defaultValue = data.default; switch (data.type) { case NodeType.file: case NodeType.folder: defaultValue = defaultValue || "./"; case NodeType.text: type = "input"; break; case NodeType.number: type = "number"; break; case NodeType.password: type = "password"; break; case NodeType.singleSelect: type = "list"; break; case NodeType.multiSelect: type = "checkbox"; break; case NodeType.func: case NodeType.localFunc: throw QTNQuestionTypeNotSupport(data); } let choices = undefined; if (answers["host-type"] === "SPFx" && data.name === "programming-language"){ choices = ["TypeScript"]; } return { type, name: data.name, message: data.description || data.title || "", choices: choices ? choices : getChoicesFromQTNodeQuestion(data, true), default: defaultValue, validate: async (input: any) => { if ("validation" in data && data.validation) { const validateFunc = getValidationFunction(data.validation, toConfigMap(answers), remoteFuncValidator); const result = await validateFunc(input); if (typeof result === "string") { return result; } } return true; } }; }
30.147541
143
0.617047
e049170d6449887e8ac1d2ff9c2f310b8c656e11
37,647
h
C
code/qcommon/qcommon.h
raynorpat/xreal
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
[ "BSD-3-Clause" ]
11
2016-06-03T07:46:15.000Z
2021-09-09T19:35:32.000Z
code/qcommon/qcommon.h
raynorpat/xreal
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
[ "BSD-3-Clause" ]
1
2016-10-14T23:06:19.000Z
2016-10-14T23:06:19.000Z
code/qcommon/qcommon.h
raynorpat/xreal
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
[ "BSD-3-Clause" ]
5
2016-10-13T04:43:58.000Z
2019-08-24T14:03:35.000Z
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. Copyright (C) 2006-2008 Robert Beckebans <[email protected]> This file is part of XreaL source code. XreaL 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. XreaL 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 XreaL source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // qcommon.h -- definitions common between client and server, but not game.or ref modules #ifndef _QCOMMON_H_ #define _QCOMMON_H_ #include "../game/q_shared.h" #include "../qcommon/cm_public.h" //Ignore __attribute__ on non-gcc platforms #ifndef __GNUC__ #ifndef __attribute__ #define __attribute__(x) #endif #endif //#define PRE_RELEASE_DEMO //============================================================================ // // msg.c // typedef struct { qboolean allowoverflow; // if false, do a Com_Error qboolean overflowed; // set to true if the buffer size failed (with allowoverflow set) qboolean oob; // set to true if the buffer size failed (with allowoverflow set) byte *data; int maxsize; int cursize; int readcount; int bit; // for bitwise reads and writes } msg_t; void MSG_Init(msg_t * buf, byte * data, int length); void MSG_InitOOB(msg_t * buf, byte * data, int length); void MSG_Clear(msg_t * buf); void MSG_WriteData(msg_t * buf, const void *data, int length); void MSG_Bitstream(msg_t * buf); // TTimo // copy a msg_t in case we need to store it as is for a bit // (as I needed this to keep an msg_t from a static var for later use) // sets data buffer as MSG_Init does prior to do the copy void MSG_Copy(msg_t * buf, byte * data, int length, msg_t * src); struct usercmd_s; struct entityState_s; struct playerState_s; void MSG_WriteBits(msg_t * msg, int value, int bits); void MSG_WriteChar(msg_t * sb, int c); void MSG_WriteByte(msg_t * sb, int c); void MSG_WriteShort(msg_t * sb, int c); void MSG_WriteLong(msg_t * sb, int c); void MSG_WriteFloat(msg_t * sb, float f); void MSG_WriteString(msg_t * sb, const char *s); void MSG_WriteBigString(msg_t * sb, const char *s); void MSG_WriteAngle16(msg_t * sb, float f); void MSG_BeginReading(msg_t * sb); void MSG_BeginReadingOOB(msg_t * sb); int MSG_ReadBits(msg_t * msg, int bits); int MSG_ReadChar(msg_t * sb); int MSG_ReadByte(msg_t * sb); int MSG_ReadShort(msg_t * sb); int MSG_ReadLong(msg_t * sb); float MSG_ReadFloat(msg_t * sb); char *MSG_ReadString(msg_t * sb); char *MSG_ReadBigString(msg_t * sb); char *MSG_ReadStringLine(msg_t * sb); float MSG_ReadAngle16(msg_t * sb); void MSG_ReadData(msg_t * sb, void *buffer, int size); int MSG_LookaheadByte(msg_t * msg); void MSG_WriteDeltaUsercmd(msg_t * msg, struct usercmd_s *from, struct usercmd_s *to); void MSG_ReadDeltaUsercmd(msg_t * msg, struct usercmd_s *from, struct usercmd_s *to); void MSG_WriteDeltaUsercmdKey(msg_t * msg, int key, usercmd_t * from, usercmd_t * to); void MSG_ReadDeltaUsercmdKey(msg_t * msg, int key, usercmd_t * from, usercmd_t * to); void MSG_WriteDeltaEntity(msg_t * msg, struct entityState_s *from, struct entityState_s *to, qboolean force); void MSG_ReadDeltaEntity(msg_t * msg, entityState_t * from, entityState_t * to, int number); void MSG_WriteDeltaPlayerstate(msg_t * msg, struct playerState_s *from, struct playerState_s *to); void MSG_ReadDeltaPlayerstate(msg_t * msg, struct playerState_s *from, struct playerState_s *to); void MSG_ReportChangeVectors_f(void); //============================================================================ /* ============================================================== NET ============================================================== */ #define PACKET_BACKUP 32 // number of old messages that must be kept on client and // server for delta comrpession and ping estimation #define PACKET_MASK (PACKET_BACKUP-1) #define MAX_PACKET_USERCMDS 32 // max number of usercmd_t in a packet #define PORT_ANY -1 #define MAX_RELIABLE_COMMANDS 64 // max string commands buffered for restransmit typedef enum { NA_BOT, NA_BAD, // an address lookup failed NA_LOOPBACK, NA_BROADCAST, NA_IP, NA_IP6, NA_MULTICAST6, NA_UNSPEC } netadrtype_t; typedef enum { NS_CLIENT, NS_SERVER } netsrc_t; #define NET_ADDRSTRMAXLEN 48 // maximum length of an IPv6 address string including trailing '\0' typedef struct { netadrtype_t type; byte ip[4]; byte ip6[16]; unsigned short port; } netadr_t; void NET_Init(void); void NET_Shutdown(void); void NET_Restart(void); void NET_Config(qboolean enableNetworking); void NET_FlushPacketQueue(void); void NET_SendPacket(netsrc_t sock, int length, const void *data, netadr_t to); void QDECL NET_OutOfBandPrint(netsrc_t net_socket, netadr_t adr, const char *format, ...) __attribute__ ((format(printf, 3, 4))); void QDECL NET_OutOfBandData(netsrc_t sock, netadr_t adr, byte * format, int len); qboolean NET_CompareAdr(netadr_t a, netadr_t b); qboolean NET_CompareBaseAdr(netadr_t a, netadr_t b); qboolean NET_IsLocalAddress(netadr_t adr); const char *NET_AdrToString(netadr_t a); const char *NET_AdrToStringwPort(netadr_t a); int NET_StringToAdr(const char *s, netadr_t * a, netadrtype_t family); qboolean NET_GetLoopPacket(netsrc_t sock, netadr_t * net_from, msg_t * net_message); void NET_JoinMulticast6(void); void NET_LeaveMulticast6(void); void NET_Sleep(int msec); #define MAX_MSGLEN 16384 // max length of a message, which may // be fragmented into multiple packets #define MAX_DOWNLOAD_WINDOW 8 // max of eight download frames #define MAX_DOWNLOAD_BLKSIZE 2048 // 2048 byte block chunks /* Netchan handles packet fragmentation and out of order / duplicate suppression */ typedef struct { netsrc_t sock; int dropped; // between last packet and previous netadr_t remoteAddress; int qport; // qport value to write when transmitting // sequencing variables int incomingSequence; int outgoingSequence; // incoming fragment assembly buffer int fragmentSequence; int fragmentLength; byte fragmentBuffer[MAX_MSGLEN]; // outgoing fragment buffer // we need to space out the sending of large fragmented messages qboolean unsentFragments; int unsentFragmentStart; int unsentLength; byte unsentBuffer[MAX_MSGLEN]; } netchan_t; void Netchan_Init(int qport); void Netchan_Setup(netsrc_t sock, netchan_t * chan, netadr_t adr, int qport); void Netchan_Transmit(netchan_t * chan, int length, const byte * data); void Netchan_TransmitNextFragment(netchan_t * chan); qboolean Netchan_Process(netchan_t * chan, msg_t * msg); /* ============================================================== PROTOCOL ============================================================== */ #define PROTOCOL_VERSION 72 // maintain a list of compatible protocols for demo playing // NOTE: that stuff only works with two digits protocols extern int demo_protocols[]; #ifndef MASTER_SERVER_NAME #define MASTER_SERVER_NAME "master.varcache.org" #endif #ifndef STANDALONE #ifndef AUTHORIZE_SERVER_NAME #define AUTHORIZE_SERVER_NAME "authorize.quake3arena.com" #endif #ifndef PORT_AUTHORIZE #define PORT_AUTHORIZE 27952 #endif #endif #define PORT_MASTER 27950 #define PORT_SERVER 27960 #define NUM_SERVER_PORTS 4 // broadcast scan this many ports after // PORT_SERVER so a single machine can // run multiple servers // the svc_strings[] array in cl_parse.c should mirror this // // server to client // enum svc_ops_e { svc_bad, svc_nop, svc_gamestate, svc_configstring, // [short] [string] only in gamestate messages svc_baseline, // only in gamestate messages svc_serverCommand, // [string] to be executed by client game module svc_download, // [short] size [size bytes] svc_snapshot, svc_EOF, // svc_extension follows a svc_EOF, followed by another svc_* ... // this keeps legacy clients compatible. svc_extension, svc_voip, // not wrapped in USE_VOIP, so this value is reserved. }; // // client to server // enum clc_ops_e { clc_bad, clc_nop, clc_move, // [[usercmd_t] clc_moveNoDelta, // [[usercmd_t] clc_clientCommand, // [string] message clc_EOF, // clc_extension follows a clc_EOF, followed by another clc_* ... // this keeps legacy servers compatible. clc_extension, clc_voip, // not wrapped in USE_VOIP, so this value is reserved. }; /* ============================================================== VIRTUAL MACHINE ============================================================== */ typedef struct { intptr_t(*systemCall) (intptr_t * parms); intptr_t(QDECL * entryPoint) (int callNum, ...); char name[MAX_QPATH]; void *dllHandle; byte *dataBase; // fqpath member added 7/20/02 by T.Ray char fqpath[MAX_QPATH + 1]; } vm_t; extern vm_t *currentVM; typedef enum { TRAP_MEMSET = 100, TRAP_MEMCPY, TRAP_STRNCPY, TRAP_SIN, TRAP_COS, TRAP_ATAN2, TRAP_SQRT, TRAP_MATRIXMULTIPLY, TRAP_ANGLEVECTORS, TRAP_PERPENDICULARVECTOR, TRAP_FLOOR, TRAP_CEIL } sharedTraps_t; void VM_Init(void); vm_t *VM_Create(const char *module, intptr_t(*systemCalls) (intptr_t *)); void VM_Free(vm_t * vm); void VM_Clear(void); vm_t *VM_Restart(vm_t * vm); intptr_t QDECL VM_Call(vm_t * vm, int callNum, ...); intptr_t QDECL VM_DllSyscall(intptr_t arg, ...); void *VM_ArgPtr(intptr_t intValue); void *VM_ExplicitArgPtr(vm_t * vm, intptr_t intValue); #define VMA(x) VM_ArgPtr(args[x]) static ID_INLINE float _vmf(intptr_t x) { union { intptr_t l; float fh, fl; } t; t.l = x; return t.fl; } #define VMF(x) _vmf(args[x]) /* ============================================================== CMD Command text buffering and command execution ============================================================== */ /* Any number of commands can be added in a frame, from several different sources. Most commands come from either keybindings or console line input, but entire text files can be execed. */ void Cbuf_Init(void); // allocates an initial text buffer that will grow as needed void Cbuf_AddText(const char *text); // Adds command text at the end of the buffer, does NOT add a final \n void Cbuf_ExecuteText(int exec_when, const char *text); // this can be used in place of either Cbuf_AddText or Cbuf_InsertText void Cbuf_Execute(void); // Pulls off \n terminated lines of text from the command buffer and sends // them through Cmd_ExecuteString. Stops when the buffer is empty. // Normally called once per frame, but may be explicitly invoked. // Do not call inside a command function, or current args will be destroyed. //=========================================================================== /* Command execution takes a null terminated string, breaks it into tokens, then searches for a command or variable that matches the first token. */ typedef void (*xcommand_t) (void); void Cmd_Init(void); void Cmd_AddCommand(const char *cmd_name, xcommand_t function); // called by the init functions of other parts of the program to // register commands and functions to call for them. // The cmd_name is referenced later, so it should not be in temp memory // if function is NULL, the command will be forwarded to the server // as a clc_clientCommand instead of executed locally void Cmd_RemoveCommand(const char *cmd_name); void Cmd_CommandCompletion(void (*callback) (const char *s)); // callback with each valid string int Cmd_Argc(void); char *Cmd_Argv(int arg); void Cmd_ArgvBuffer(int arg, char *buffer, int bufferLength); char *Cmd_Args(void); char *Cmd_ArgsFrom(int arg); void Cmd_ArgsBuffer(char *buffer, int bufferLength); char *Cmd_Cmd(void); // The functions that execute commands get their parameters with these // functions. Cmd_Argv () will return an empty string, not a NULL // if arg > argc, so string operations are allways safe. void Cmd_TokenizeString(const char *text); void Cmd_TokenizeStringIgnoreQuotes(const char *text_in); // Takes a null terminated string. Does not need to be /n terminated. // breaks the string up into arg tokens. void Cmd_ExecuteString(const char *text); // Parses a single line of text into arguments and tries to execute it // as if it was typed at the console /* ============================================================== CVAR ============================================================== */ /* cvar_t variables are used to hold scalar or string variables that can be changed or displayed at the console or prog code as well as accessed directly in C code. The user can access cvars from the console in three ways: r_draworder prints the current value r_draworder 0 sets the current value to 0 set r_draworder 0 as above, but creates the cvar if not present Cvars are restricted from having the same names as commands to keep this interface from being ambiguous. The are also occasionally used to communicated information between different modules of the program. */ cvar_t *Cvar_Get(const char *var_name, const char *value, int flags); // creates the variable if it doesn't exist, or returns the existing one // if it exists, the value will not be changed, but flags will be ORed in // that allows variables to be unarchived without needing bitflags // if value is "", the value will not override a previously set value. void Cvar_Register(vmCvar_t * vmCvar, const char *varName, const char *defaultValue, int flags); // basically a slightly modified Cvar_Get for the interpreted modules void Cvar_Update(vmCvar_t * vmCvar); // updates an interpreted modules' version of a cvar void Cvar_Set(const char *var_name, const char *value); // will create the variable with no flags if it doesn't exist void Cvar_SetLatched(const char *var_name, const char *value); // don't set the cvar immediately void Cvar_SetValue(const char *var_name, float value); // expands value to a string and calls Cvar_Set float Cvar_VariableValue(const char *var_name); int Cvar_VariableIntegerValue(const char *var_name); // returns 0 if not defined or non numeric char *Cvar_VariableString(const char *var_name); void Cvar_VariableStringBuffer(const char *var_name, char *buffer, int bufsize); // returns an empty string if not defined int Cvar_Flags(const char *var_name); // returns CVAR_NONEXISTENT if cvar doesn't exist or the flags of that particular CVAR. void Cvar_CommandCompletion(void (*callback) (const char *s)); // callback with each valid string void Cvar_Reset(const char *var_name); void Cvar_ForceReset(const char *var_name); void Cvar_SetCheatState(void); // reset all testing vars to a safe value qboolean Cvar_Command(void); // called by Cmd_ExecuteString when Cmd_Argv(0) doesn't match a known // command. Returns true if the command was a variable reference that // was handled. (print or change) void Cvar_WriteVariables(fileHandle_t f); // writes lines containing "set variable value" for all variables // with the archive flag set to true. void Cvar_Init(void); char *Cvar_InfoString(int bit); char *Cvar_InfoString_Big(int bit); // returns an info string containing all the cvars that have the given bit set // in their flags ( CVAR_USERINFO, CVAR_SERVERINFO, CVAR_SYSTEMINFO, etc ) void Cvar_InfoStringBuffer(int bit, char *buff, int buffsize); void Cvar_CheckRange(cvar_t * cv, float minVal, float maxVal, qboolean shouldBeIntegral); void Cvar_Restart_f(void); extern int cvar_modifiedFlags; // whenever a cvar is modifed, its flags will be OR'd into this, so // a single check can determine if any CVAR_USERINFO, CVAR_SERVERINFO, // etc, variables have been modified since the last check. The bit // can then be cleared to allow another change detection. /* ============================================================== FILESYSTEM No stdio calls should be used by any part of the game, because we need to deal with all sorts of directory and seperator char issues. ============================================================== */ // referenced flags // these are in loop specific order so don't change the order #define FS_GENERAL_REF 0x01 #define FS_UI_REF 0x02 #define FS_CGAME_REF 0x04 #define FS_QAGAME_REF 0x08 // number of id paks that will never be autodownloaded from baseq3 #define NUM_ID_PAKS 9 #define MAX_FILE_HANDLES 64 #ifdef DEDICATED # define Q3CONFIG_CFG "xreal_server.cfg" #else # define Q3CONFIG_CFG "xreal.cfg" #endif qboolean FS_Initialized(void); void FS_InitFilesystem(void); void FS_Shutdown(qboolean closemfp); qboolean FS_ConditionalRestart(int checksumFeed); void FS_Restart(int checksumFeed); // shutdown and restart the filesystem so changes to fs_gamedir can take effect void FS_AddGameDirectory(const char *path, const char *dir); char **FS_ListFiles(const char *directory, const char *extension, int *numfiles); // directory should not have either a leading or trailing / // if extension is "/", only subdirectories will be returned // the returned files will not include any directories or / void FS_FreeFileList(char **list); qboolean FS_FileExists(const char *file); char *FS_BuildOSPath(const char *base, const char *game, const char *qpath); int FS_LoadStack(void); int FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize); int FS_GetModList(char *listbuf, int bufsize); fileHandle_t FS_FOpenFileWrite(const char *qpath); fileHandle_t FS_FOpenFileAppend(const char *filename); // will properly create any needed paths and deal with seperater character issues int FS_filelength(fileHandle_t f); fileHandle_t FS_SV_FOpenFileWrite(const char *filename); int FS_SV_FOpenFileRead(const char *filename, fileHandle_t * fp); void FS_SV_Rename(const char *from, const char *to); int FS_FOpenFileRead(const char *qpath, fileHandle_t * file, qboolean uniqueFILE); // if uniqueFILE is true, then a new FILE will be fopened even if the file // is found in an already open pak file. If uniqueFILE is false, you must call // FS_FCloseFile instead of fclose, otherwise the pak FILE would be improperly closed // It is generally safe to always set uniqueFILE to true, because the majority of // file IO goes through FS_ReadFile, which Does The Right Thing already. int FS_FileIsInPAK(const char *filename, int *pChecksum); // returns 1 if a file is in the PAK file, otherwise -1 int FS_Write(const void *buffer, int len, fileHandle_t f); int FS_Read2(void *buffer, int len, fileHandle_t f); int FS_Read(void *buffer, int len, fileHandle_t f); // properly handles partial reads and reads from other dlls void FS_FCloseFile(fileHandle_t f); // note: you can't just fclose from another DLL, due to MS libc issues int FS_ReadFile(const char *qpath, void **buffer); // returns the length of the file // a null buffer will just return the file length without loading // as a quick check for existance. -1 length == not present // A 0 byte will always be appended at the end, so string ops are safe. // the buffer should be considered read-only, because it may be cached // for other uses. void FS_ForceFlush(fileHandle_t f); // forces flush on files we're writing to. void FS_FreeFile(void *buffer); // frees the memory returned by FS_ReadFile void FS_WriteFile(const char *qpath, const void *buffer, int size); // writes a complete file, creating any subdirectories needed int FS_filelength(fileHandle_t f); // doesn't work for files that are opened from a pack file int FS_FTell(fileHandle_t f); // where are we? void FS_Flush(fileHandle_t f); void QDECL FS_Printf(fileHandle_t f, const char *fmt, ...) __attribute__ ((format(printf, 2, 3))); // like fprintf int FS_FOpenFileByMode(const char *qpath, fileHandle_t * f, fsMode_t mode); // opens a file for reading, writing, or appending depending on the value of mode int FS_Seek(fileHandle_t f, long offset, int origin); // seek on a file (doesn't work for zip files!!!!!!!!) qboolean FS_FilenameCompare(const char *s1, const char *s2); const char *FS_GamePureChecksum(void); // Returns the checksum of the pk3 from which the server loaded the qagame.qvm const char *FS_LoadedPakNames(void); const char *FS_LoadedPakChecksums(void); const char *FS_LoadedPakPureChecksums(void); // Returns a space separated string containing the checksums of all loaded pk3 files. // Servers with sv_pure set will get this string and pass it to clients. const char *FS_ReferencedPakNames(void); const char *FS_ReferencedPakChecksums(void); const char *FS_ReferencedPakPureChecksums(void); // Returns a space separated string containing the checksums of all loaded // AND referenced pk3 files. Servers with sv_pure set will get this string // back from clients for pure validation void FS_ClearPakReferences(int flags); // clears referenced booleans on loaded pk3s void FS_PureServerSetReferencedPaks(const char *pakSums, const char *pakNames); void FS_PureServerSetLoadedPaks(const char *pakSums, const char *pakNames); // If the string is empty, all data sources will be allowed. // If not empty, only pk3 files that match one of the space // separated checksums will be checked for files, with the // sole exception of .cfg files. qboolean FS_CheckDirTraversal(const char *checkdir); qboolean FS_ComparePaks(char *neededpaks, int len, qboolean dlstring); void FS_Rename(const char *from, const char *to); void FS_Remove(const char *osPath); void FS_HomeRemove(const char *homePath); void FS_FilenameCompletion(const char *dir, const char *ext, qboolean stripExt, void (*callback) (const char *s)); /* ============================================================== Edit fields and command line history/completion ============================================================== */ #define MAX_EDIT_LINE 256 typedef struct { int cursor; int scroll; int widthInChars; char buffer[MAX_EDIT_LINE]; } field_t; void Field_Clear(field_t * edit); void Field_AutoComplete(field_t * edit); /* ============================================================== MISC ============================================================== */ // centralizing the declarations for cl_cdkey // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=470 extern char cl_cdkey[34]; // returned by Sys_GetProcessorFeatures typedef enum { CF_RDTSC = 1 << 0, CF_MMX = 1 << 1, CF_MMX_EXT = 1 << 2, CF_3DNOW = 1 << 3, CF_3DNOW_EXT = 1 << 4, CF_SSE = 1 << 5, CF_SSE2 = 1 << 6, CF_ALTIVEC = 1 << 7 } cpuFeatures_t; // centralized and cleaned, that's the max string you can send to a Com_Printf / Com_DPrintf (above gets truncated) #define MAXPRINTMSG 4096 typedef enum { // SE_NONE must be zero SE_NONE = 0, // evTime is still valid SE_KEY, // evValue is a key code, evValue2 is the down flag SE_CHAR, // evValue is an ascii char SE_MOUSE, // evValue and evValue2 are reletive signed x / y moves SE_JOYSTICK_AXIS, // evValue is an axis number and evValue2 is the current state (-127 to 127) SE_CONSOLE, // evPtr is a char* SE_PACKET // evPtr is a netadr_t followed by data bytes to evPtrLength } sysEventType_t; typedef struct { int evTime; sysEventType_t evType; int evValue, evValue2; int evPtrLength; // bytes of data pointed to by evPtr, for journaling void *evPtr; // this must be manually freed if not NULL } sysEvent_t; void Com_QueueEvent(int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr); int Com_EventLoop(void); sysEvent_t Com_GetSystemEvent(void); char *CopyString(const char *in); void Info_Print(const char *s); void Com_BeginRedirect(char *buffer, int buffersize, void (*flush) (char *)); void Com_EndRedirect(void); void QDECL Com_Printf(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))); void QDECL Com_DPrintf(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))); void QDECL Com_Error(int code, const char *fmt, ...) __attribute__ ((format(printf, 2, 3))); void Com_Quit_f(void); int Com_Milliseconds(void); // will be journaled properly unsigned Com_BlockChecksum(const void *buffer, int length); char *Com_MD5File(const char *filename, int length, const char *prefix, int prefix_len); int Com_HashKey(char *string, int maxlen); int Com_Filter(char *filter, char *name, int casesensitive); int Com_FilterPath(char *filter, char *name, int casesensitive); int Com_RealTime(qtime_t * qtime); qboolean Com_SafeMode(void); void Com_StartupVariable(const char *match); // checks for and removes command line "+set var arg" constructs // if match is NULL, all set commands will be executed, otherwise // only a set with the exact name. Only used during startup. extern cvar_t *com_developer; extern cvar_t *com_dedicated; extern cvar_t *com_speeds; extern cvar_t *com_timescale; extern cvar_t *com_sv_running; extern cvar_t *com_cl_running; extern cvar_t *com_version; extern cvar_t *com_blood; extern cvar_t *com_buildScript; // for building release pak files extern cvar_t *com_journal; extern cvar_t *com_cameraMode; extern cvar_t *com_ansiColor; extern cvar_t *com_unfocused; extern cvar_t *com_maxfpsUnfocused; extern cvar_t *com_minimized; extern cvar_t *com_maxfpsMinimized; extern cvar_t *com_altivec; // both client and server must agree to pause extern cvar_t *cl_paused; extern cvar_t *sv_paused; extern cvar_t *cl_packetdelay; extern cvar_t *sv_packetdelay; // com_speeds times extern int time_game; extern int time_frontend; extern int time_backend; // renderer backend time extern int com_frameTime; extern int com_frameMsec; extern qboolean com_errorEntered; extern fileHandle_t com_journalFile; extern fileHandle_t com_journalDataFile; typedef enum { TAG_FREE, TAG_GENERAL, TAG_BOTLIB, TAG_RENDERER, TAG_SMALL, TAG_STATIC } memtag_t; /* --- low memory ---- server vm server clipmap ---mark--- renderer initialization (shaders, etc) UI vm cgame vm renderer map renderer models ---free--- temp file loading --- high memory --- */ #if defined(_DEBUG) #define ZONE_DEBUG #endif #ifdef ZONE_DEBUG #define Z_TagMalloc(size, tag) Z_TagMallocDebug(size, tag, #size, __FILE__, __LINE__) #define Z_Malloc(size) Z_MallocDebug(size, #size, __FILE__, __LINE__) #define S_Malloc(size) S_MallocDebug(size, #size, __FILE__, __LINE__) void *Z_TagMallocDebug(int size, int tag, char *label, char *file, int line); // NOT 0 filled memory void *Z_MallocDebug(int size, char *label, char *file, int line); // returns 0 filled memory void *S_MallocDebug(int size, char *label, char *file, int line); // returns 0 filled memory #else void *Z_TagMalloc(int size, int tag); // NOT 0 filled memory void *Z_Malloc(int size); // returns 0 filled memory void *S_Malloc(int size); // NOT 0 filled memory only for small allocations #endif void Z_Free(void *ptr); void Z_FreeTags(int tag); int Z_AvailableMemory(void); void Z_LogHeap(void); void Hunk_Clear(void); void Hunk_ClearToMark(void); void Hunk_SetMark(void); qboolean Hunk_CheckMark(void); void Hunk_ClearTempMemory(void); void *Hunk_AllocateTempMemory(int size); void Hunk_FreeTempMemory(void *buf); int Hunk_MemoryRemaining(void); void Hunk_Log(void); void Hunk_Trash(void); void Com_TouchMemory(void); // commandLine should not include the executable name (argv[0]) void Com_Init(char *commandLine); void Com_Frame(void); void Com_Shutdown(void); /* ============================================================== CLIENT / SERVER SYSTEMS ============================================================== */ // // client interface // void CL_InitKeyCommands(void); // the keyboard binding interface must be setup before execing // config files, but the rest of client startup will happen later void CL_Init(void); void CL_Disconnect(qboolean showMainMenu); void CL_Shutdown(void); void CL_Frame(int msec); qboolean CL_GameCommand(void); void CL_KeyEvent(int key, qboolean down, unsigned time); void CL_CharEvent(int key); // char events are for field typing, not game control void CL_MouseEvent(int dx, int dy, int time); void CL_JoystickEvent(int axis, int value, int time); void CL_PacketEvent(netadr_t from, msg_t * msg); void CL_ConsolePrint(char *text); void CL_MapLoading(void); // do a screen update before starting to load a map // when the server is going to load a new map, the entire hunk // will be cleared, so the client must shutdown cgame, ui, and // the renderer void CL_ForwardCommandToServer(const char *string); // adds the current command line as a clc_clientCommand to the client message. // things like godmode, noclip, etc, are commands directed to the server, // so when they are typed in at the console, they will need to be forwarded. void CL_CDDialog(void); // bring up the "need a cd to play" dialog void CL_ShutdownAll(void); // shutdown all the client stuff void CL_FlushMemory(void); // dump all memory on an error void CL_StartHunkUsers(qboolean rendererOnly); // start all the client stuff using the hunk void Key_KeynameCompletion(void (*callback) (const char *s)); // for keyname autocompletion void Key_WriteBindings(fileHandle_t f); // for writing the config files void S_ClearSoundBuffer(void); // call before filesystem access void SCR_DebugGraph(float value, int color); // FIXME: move logging to common? // // server interface // void SV_Init(void); void SV_Shutdown(char *finalmsg); void SV_Frame(int msec); void SV_PacketEvent(netadr_t from, msg_t * msg); qboolean SV_GameCommand(void); // // UI interface // qboolean UI_GameCommand(void); qboolean UI_usesUniqueCDKey(void); /* ============================================================== NON-PORTABLE SYSTEM SERVICES ============================================================== */ typedef enum { AXIS_SIDE, AXIS_FORWARD, AXIS_UP, AXIS_ROLL, AXIS_YAW, AXIS_PITCH, MAX_JOYSTICK_AXIS } joystickAxis_t; void Sys_Init(void); // general development dll loading for virtual machine testing void *QDECL Sys_LoadDll(const char *name, char *fqpath, intptr_t(QDECL ** entryPoint) (int, ...), intptr_t(QDECL * systemcalls) (intptr_t, ...)); void Sys_UnloadDll(void *dllHandle); void Sys_UnloadGame(void); void *Sys_GetGameAPI(void *parms); void Sys_UnloadCGame(void); void *Sys_GetCGameAPI(void); void Sys_UnloadUI(void); void *Sys_GetUIAPI(void); //bot libraries void Sys_UnloadBotLib(void); void *Sys_GetBotLibAPI(void *parms); char *Sys_GetCurrentUser(void); void QDECL Sys_Error(const char *error, ...) __attribute__ ((format(printf, 1, 2))); void Sys_Quit(void); char *Sys_GetClipboardData(void); // note that this isn't journaled... void Sys_Print(const char *msg); // Sys_Milliseconds should only be used for profiling purposes, // any game related timing information should come from event timestamps int Sys_Milliseconds(void); qboolean Sys_RandomBytes(byte * string, int len); // the system console is shown when a dedicated server is running void Sys_DisplaySystemConsole(qboolean show); cpuFeatures_t Sys_GetProcessorFeatures(void); void Sys_SetErrorText(const char *text); void Sys_SendPacket(int length, const void *data, netadr_t to); qboolean Sys_GetPacket(netadr_t * net_from, msg_t * net_message); qboolean Sys_StringToAdr(const char *s, netadr_t * a, netadrtype_t family); //Does NOT parse port numbers, only base addresses. qboolean Sys_IsLANAddress(netadr_t adr); void Sys_ShowIP(void); void Sys_Mkdir(const char *path); char *Sys_Cwd(void); void Sys_SetDefaultInstallPath(const char *path); char *Sys_DefaultInstallPath(void); #ifdef MACOS_X char *Sys_DefaultAppPath(void); #endif void Sys_SetDefaultHomePath(const char *path); char *Sys_DefaultHomePath(void); const char *Sys_Dirname(char *path); const char *Sys_Basename(char *path); char *Sys_ConsoleInput(void); char **Sys_ListFiles(const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs); void Sys_FreeFileList(char **list); void Sys_Sleep(int msec); qboolean Sys_LowPhysicalMemory(void); /* This is based on the Adaptive Huffman algorithm described in Sayood's Data * Compression book. The ranks are not actually stored, but implicitly defined * by the location of a node within a doubly-linked list */ #define NYT HMAX /* NYT = Not Yet Transmitted */ #define INTERNAL_NODE (HMAX+1) typedef struct nodetype { struct nodetype *left, *right, *parent; /* tree structure */ struct nodetype *next, *prev; /* doubly-linked list */ struct nodetype **head; /* highest ranked node in block */ int weight; int symbol; } node_t; #define HMAX 256 /* Maximum symbol */ typedef struct { int blocNode; int blocPtrs; node_t *tree; node_t *lhead; node_t *ltail; node_t *loc[HMAX + 1]; node_t **freelist; node_t nodeList[768]; node_t *nodePtrs[768]; } huff_t; typedef struct { huff_t compressor; huff_t decompressor; } huffman_t; void Huff_Compress(msg_t * buf, int offset); void Huff_Decompress(msg_t * buf, int offset); void Huff_Init(huffman_t * huff); void Huff_addRef(huff_t * huff, byte ch); int Huff_Receive(node_t * node, int *ch, byte * fin); void Huff_transmit(huff_t * huff, int ch, byte * fout); void Huff_offsetReceive(node_t * node, int *ch, byte * fin, int *offset); void Huff_offsetTransmit(huff_t * huff, int ch, byte * fout, int *offset); void Huff_putBit(int bit, byte * fout, int *offset); int Huff_getBit(byte * fout, int *offset); // don't use if you don't know what you're doing. int Huff_getBloc(void); void Huff_setBloc(int _bloc); extern huffman_t clientHuffTables; #define SV_ENCODE_START 4 #define SV_DECODE_START 12 #define CL_ENCODE_START 12 #define CL_DECODE_START 4 // flags for sv_allowDownload and cl_allowDownload #define DLF_ENABLE 1 #define DLF_NO_REDIRECT 2 #define DLF_NO_UDP 4 #define DLF_NO_DISCONNECT 8 #endif // _QCOMMON_H_
31.138958
125
0.656467
cd3a1f10c14c803c27fff695cd1f60851660107b
2,926
rs
Rust
src/reader/types.rs
tiffany352/wasm-rs
373e9857a440ee64abcab84023561b5e6be67b16
[ "Apache-2.0", "MIT" ]
2
2016-10-30T03:29:41.000Z
2016-11-02T00:18:03.000Z
src/reader/types.rs
tiffany352/wasm-rs
373e9857a440ee64abcab84023561b5e6be67b16
[ "Apache-2.0", "MIT" ]
null
null
null
src/reader/types.rs
tiffany352/wasm-rs
373e9857a440ee64abcab84023561b5e6be67b16
[ "Apache-2.0", "MIT" ]
null
null
null
use super::*; use std::io; pub struct TypeSection<'a>(pub &'a [u8], pub usize); pub struct TypeEntryIterator<'a>(&'a [u8], usize); pub enum TypeEntry<'a> { Function(FunctionType<'a>), } pub struct FunctionType<'a> { pub form: LanguageType, params_count: usize, params_raw: &'a [u8], pub return_type: Option<ValueType>, } pub struct ParamsIterator<'a>(&'a [u8], usize); impl<'a> TypeSection<'a> { pub fn entries(&self) -> TypeEntryIterator<'a> { TypeEntryIterator(self.0, self.1) } } impl<'a> Iterator for TypeEntryIterator<'a> { type Item = Result<TypeEntry<'a>, Error>; fn next(&mut self) -> Option<Result<TypeEntry<'a>, Error>> { if self.1 == 0 { return None } self.1 -= 1; let form = try_opt!(read_varuint(&mut self.0)); let form = try_opt!(LanguageType::from_int(form as u8).ok_or( Error::UnknownVariant("type entry form") )); let param_count = try_opt!(read_varuint(&mut self.0)); let params = if param_count > self.0.len() as u64 { return Some(Err(Error::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "param_count is larger than remaining space" )))) } else { let res = &self.0[..param_count as usize]; self.0 = &self.0[param_count as usize..]; res }; let return_count = try_opt!(read_varuint(&mut self.0)); let return_ty = if return_count > 0 { if self.0.len() < 1 { return Some(Err(Error::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "return_count is larger than remaining space" )))) } let res = self.0[0]; self.0 = &self.0[1..]; Some(try_opt!(ValueType::from_int(res).ok_or(Error::UnknownVariant("value type")))) } else { None }; Some(Ok(TypeEntry::Function(FunctionType { form: form, params_count: param_count as usize, params_raw: params, return_type: return_ty }))) } } impl<'a> FunctionType<'a> { pub fn params(&self) -> ParamsIterator<'a> { ParamsIterator(self.params_raw, self.params_count) } } impl<'a> Iterator for ParamsIterator<'a> { type Item = Result<ValueType, Error>; fn next(&mut self) -> Option<Result<ValueType, Error>> { if self.1 == 0 { return None } self.1 -= 1; if self.0.len() < 1 { return Some(Err(Error::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "number of params is larger than available space" )))) } let res = self.0[0]; self.0 = &self.0[1..]; Some(Ok(try_opt!(ValueType::from_int(res).ok_or(Error::UnknownVariant("value type"))))) } }
30.164948
95
0.543062
8bdf68efa32961b587042c8e9a636d234dad0a26
285
sql
SQL
db/geonames/countries/YT.sql
IsiRoca/Geodata-Importer
b2cc65d6d561d1a80205b1ab2ceab73da68aa451
[ "MIT" ]
null
null
null
db/geonames/countries/YT.sql
IsiRoca/Geodata-Importer
b2cc65d6d561d1a80205b1ab2ceab73da68aa451
[ "MIT" ]
null
null
null
db/geonames/countries/YT.sql
IsiRoca/Geodata-Importer
b2cc65d6d561d1a80205b1ab2ceab73da68aa451
[ "MIT" ]
null
null
null
LOAD DATA LOCAL INFILE './././download/geonames/countries/YT.txt' INTO TABLE geoname CHARACTER SET 'UTF8' (geonameid, name, asciiname, alternatenames, latitude, longitude, fclass, fcode, country, cc2, admin1, admin2, admin3, admin4, population, elevation, gtopo30, timezone, moddate);
142.5
284
0.77193
535e480adddb002700850e3556db9caf8d77b713
2,955
rb
Ruby
spec/switch/plugins/aws_alb_spec.rb
lscheidler/switch
9b8a122166bcd25f52c34cd637cea234f44bc54a
[ "Apache-2.0" ]
null
null
null
spec/switch/plugins/aws_alb_spec.rb
lscheidler/switch
9b8a122166bcd25f52c34cd637cea234f44bc54a
[ "Apache-2.0" ]
null
null
null
spec/switch/plugins/aws_alb_spec.rb
lscheidler/switch
9b8a122166bcd25f52c34cd637cea234f44bc54a
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 Lars Eric Scheidler # # 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. require "spec_helper" require 'webmock/rspec' class StubSocket def close end end class Aws::Waiters::Waiter def trigger_before_attempt(attempts) throw :success end end describe Switch::Plugins::AwsALB do let(:stub_resource) { Aws::ElasticLoadBalancingV2::Resource.new(stub_responses: true, region: 'eu-central-1') } before(:all) do initialize_test_data @config.dryrun = true @config.aws_region = 'eu-central-1' @config.alb_target_group = "arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id>" @instance_id = "i-0123456789abcdef0" @pm = PluginManager.instance end after(:all) do cleanup end before do stub_request(:get, "http://169.254.169.254/latest/meta-data/instance-id"). to_return(body: @instance_id) end it 'should deregister' do expect(Aws::ElasticLoadBalancingV2::Resource).to receive(:new).and_return(stub_resource) expect(stub_resource.client).to receive(:deregister_targets).with({:target_group_arn=>"arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id>", :targets=>[{:id=>"i-0123456789abcdef0"}]}) {true} @plugin = @pm['Switch::Plugins::AwsALB'].new(@config) expect{@plugin.pre}.to output( "deregister i-0123456789abcdef0 from arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id> wait for deregistration of i-0123456789abcdef0 from arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id>\n" ).to_stdout end it 'should register' do expect(Aws::ElasticLoadBalancingV2::Resource).to receive(:new).and_return(stub_resource) expect(stub_resource.client).to receive(:register_targets).with({:target_group_arn=>"arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id>", :targets=>[{:id=>"i-0123456789abcdef0"}]}) {true} @plugin = @pm['Switch::Plugins::AwsALB'].new(@config) expect{@plugin.post}.to output( "register i-0123456789abcdef0 to arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id> wait for registration of i-0123456789abcdef0 to arn:aws:elasticloadbalancing:<region>:<account-id>:targetgroup/<target-group-name>/<target-group-id>\n" ).to_stdout end end
42.826087
243
0.745516
0f9f909609c4b1a612380954f45da311b8bc89ac
3,334
swift
Swift
Tests/RelayTests/PokemonListQuery.swift
Astrocoders/Relay.swift
d38835f19405812587d185040dc6bb6765e6078a
[ "MIT" ]
51
2020-08-28T19:24:41.000Z
2022-03-08T23:14:41.000Z
Tests/RelayTests/PokemonListQuery.swift
Astrocoders/Relay.swift
d38835f19405812587d185040dc6bb6765e6078a
[ "MIT" ]
33
2020-12-28T08:12:00.000Z
2021-11-02T14:49:23.000Z
Tests/RelayTests/PokemonListQuery.swift
Astrocoders/Relay.swift
d38835f19405812587d185040dc6bb6765e6078a
[ "MIT" ]
2
2021-08-30T12:49:51.000Z
2021-10-11T03:56:42.000Z
// Auto-generated by relay-compiler. Do not edit. import Relay struct PokemonListQuery { var variables: Variables init(variables: Variables) { self.variables = variables } static var node: ConcreteRequest { ConcreteRequest( fragment: ReaderFragment( name: "PokemonListQuery", type: "Query", selections: [ .field(ReaderLinkedField( name: "pokemons", args: [ LiteralArgument(name: "first", value: 50) ], concreteType: "Pokemon", plural: true, selections: [ .field(ReaderScalarField( name: "__typename" )), .field(ReaderScalarField( name: "id" )), .field(ReaderScalarField( name: "name" )), .fragmentSpread(ReaderFragmentSpread( name: "PokemonListRow_pokemon" )) ] )) ]), operation: NormalizationOperation( name: "PokemonListQuery", selections: [ .field(NormalizationLinkedField( name: "pokemons", args: [ LiteralArgument(name: "first", value: 50) ], storageKey: "pokemons(first:50)", concreteType: "Pokemon", plural: true, selections: [ .field(NormalizationScalarField( name: "__typename" )), .field(NormalizationScalarField( name: "id" )), .field(NormalizationScalarField( name: "name" )), .field(NormalizationScalarField( name: "number" )) ] )) ]), params: RequestParameters( name: "PokemonListQuery", operationKind: .query, text: """ query PokemonListQuery { pokemons(first: 50) { __typename id name ...PokemonListRow_pokemon } } fragment PokemonListRow_pokemon on Pokemon { name number } """)) } } extension PokemonListQuery { typealias Variables = EmptyVariables } extension PokemonListQuery { struct Data: Decodable { var pokemons: [Pokemon_pokemons?]? struct Pokemon_pokemons: Decodable, PokemonListRow_pokemon_Key { var __typename: String var id: String var name: String? var fragment_PokemonListRow_pokemon: FragmentPointer } } } extension PokemonListQuery: Relay.Operation {}
30.87037
72
0.407918
beaf9f55d9c6f48d5928ad2312409258de2440bd
380
sh
Shell
ci/linux/build.sh
lodrantl/reversi
8d579e72fdf689f56e7ebbbe16fb9135420573cc
[ "Apache-2.0" ]
1
2017-05-02T09:50:49.000Z
2017-05-02T09:50:49.000Z
ci/linux/build.sh
lodrantl/reversi
8d579e72fdf689f56e7ebbbe16fb9135420573cc
[ "Apache-2.0" ]
1
2017-02-24T11:49:32.000Z
2017-03-28T13:58:31.000Z
ci/linux/build.sh
lodrantl/reversi
8d579e72fdf689f56e7ebbbe16fb9135420573cc
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env bash set -ev #echo on python -m pytest # Build executables with pyinstaller python -m PyInstaller -y reversi.spec # Move to final dir mkdir dist/final mv dist/reversi dist/final/reversi-${VERSION}-${TRAVIS_OS_NAME} # Run tests ls -la dist/ ls -la dist/final #Workaround for https://github.com/travis-ci/travis-ci/issues/6522 #Turn off exit on failure. set +ev
19
66
0.744737
b72ba37b25e9a84db429d533e2a07e383b2cabfb
8,714
cpp
C++
dblsqd/feed.cpp
Mudlet/dblsqd-sdk-qt
80f0da767c24e9c1a89e58aac913dd86e22d4c06
[ "Apache-2.0" ]
1
2021-06-02T06:33:52.000Z
2021-06-02T06:33:52.000Z
dblsqd/feed.cpp
Mudlet/dblsqd-sdk-qt
80f0da767c24e9c1a89e58aac913dd86e22d4c06
[ "Apache-2.0" ]
2
2020-11-12T11:46:45.000Z
2021-11-17T23:53:35.000Z
dblsqd/feed.cpp
Mudlet/dblsqd-sdk-qt
80f0da767c24e9c1a89e58aac913dd86e22d4c06
[ "Apache-2.0" ]
null
null
null
#include "dblsqd/feed.h" namespace dblsqd { /*! \class Feed * \brief The Feed class provides methods for accessing DBLSQD Feeds and downloading Releases. * * A Feed is a representation of an Application’s Releases. * This class can retrieve Feeds via HTTP(S) and offers convenience methods for * * \section3 Loading Feeds * * Before a Feed can be loaded with load(), it needs to be initialized with setUrl(). * * \section3 Downloading Updates * This class also allows downloading updates through the downloadRelease() method. */ /*! * \brief Constructs a new Feed object. * * \sa setUrl() */ Feed::Feed(QString baseUrl, QString channel, QString os, QString arch, QString type) : feedReply(NULL), downloadReply(NULL), downloadFile(NULL), redirects(0), _ready(false) { if (!baseUrl.isEmpty()) { this->setUrl(baseUrl, channel, os, arch, type); } } /*! * \brief Sets the Feed URL. * * This method can be used to manually set the Feed URL. */ void Feed::setUrl(QUrl url) { this->url = url; } /*! * \brief Sets the Feed URL by specifying its components. * * The only required component is baseUrl which must be the base URL for an Application * provided by the DBSLQD CLI Tool. It should include the full schema and does not require * a trailing "/". */ void Feed::setUrl(QString baseUrl, QString channel, QString os, QString arch, QString type) { QStringList urlParts; urlParts << baseUrl; urlParts << channel; if (!os.isEmpty()) { urlParts << os; } else { QString autoOs = QSysInfo::productType().toLower(); if (autoOs == "windows") { autoOs = "win"; } else if (autoOs == "osx" || autoOs == "macos") { autoOs = "mac"; } else { autoOs = QSysInfo::kernelType(); } urlParts << autoOs; } if (!arch.isEmpty()) { urlParts << arch; } else { QString autoArch = QSysInfo::buildCpuArchitecture(); if (autoArch== "i386" || autoArch == "i586" || autoArch == "i586") { autoArch = "x86"; } urlParts << autoArch; } if (!type.isEmpty()) { urlParts << "?t=" + type; } this->url = QUrl(urlParts.join("/")); } /*! * \brief Returns the Feed URL. */ QUrl Feed::getUrl() { return QUrl(url); } /*! * \brief Returns a list of all Releases in the Feed. * * The list is sorted in descending order by version number/release date. * If called before ready() was emitted, an empty list is returned. * \sa getReleases() */ QList<Release> Feed::getReleases() { return releases; } /*! * \brief Returns a list of all Releases in the Feed that are newer than the given Release. * * The list is sorted in descending order by version number/release date. * If called before ready() was emitted, an empty list is returned. * \sa getReleases() */ QList<Release> Feed::getUpdates(Release currentRelease) { QList<Release> updates; for (const auto& release: releases) { if (currentRelease.getVersion().toLower() != release.getVersion().toLower() && currentRelease < release) { updates << release; } } return updates; } /*! * \brief Returns the pointer to a QTemporaryFile for a downloaded file. * * If called before downloadFinished() was emitted, this might return a NULL * pointer. */ QTemporaryFile* Feed::getDownloadFile() { return downloadFile; } /*! * \brief Returns true if Feed information has been retrieved successfully. * * A ready Feed might not contain any release information. * If downloading the Feed failed, false is returned. */ bool Feed::isReady() { return _ready; } /* * Async API functions */ /*! * \brief Retrieves and parses data from the Feed. * * A Feed URL must have been set before with setUrl(). Emits ready() or loadError() on completion. */ void Feed::load() { if (feedReply != NULL && !feedReply->isFinished()) { return; } QNetworkRequest request(getUrl()); feedReply = nam.get(request); connect(feedReply, SIGNAL(finished()), this, SLOT(handleFeedFinished())); } /*! * \brief Starts the download of a given Release. * \sa downloadFinished() downloadError() downloadProgress() */ void Feed::downloadRelease(Release release) { redirects = 0; makeDownloadRequest(release.getDownloadUrl()); this->release = release; } /* * Private methods */ void Feed::makeDownloadRequest(QUrl url) { if (downloadReply != NULL && !downloadReply->isFinished()) { disconnect(downloadReply); downloadReply->abort(); downloadReply->deleteLater(); } if (downloadFile != NULL) { disconnect(downloadFile); downloadFile->close(); downloadFile->deleteLater(); downloadFile = NULL; } QNetworkRequest request(url); downloadReply= nam.get(request); connect(downloadReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(handleDownloadProgress(qint64,qint64))); connect(downloadReply, SIGNAL(readyRead()), this, SLOT(handleDownloadReadyRead())); connect(downloadReply, SIGNAL(finished()), this, SLOT(handleDownloadFinished())); } /* * Signals */ /*! \fn void Feed::ready() * This signal is emitted when a Feed has been successfully downloaded and parsed. * \sa loadError() load() */ /*! \fn void Feed::loadError(QString message) * This signal is emitted when a Feed could not be downloaded. * When loadError() is emitted, ready() is not emitted. * \sa ready() load() */ /*! \fn void Feed::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) * This signal is emitted during the download of a Release through downloadRelease(). * \sa downloadRelease() */ /*! \fn void Feed::downloadFinished() * This signal is emitted when the download of a Release was successful. * A QTemporaryFile* of the downloaded file can then be retrieved with getDownloadFile(). * \sa downloadRelease() */ /*! \fn void Feed::downloadError() * This signal is emitted when there was an error downloading or verifying a Release. * When downloadError() is emitted, downloadFinished() is not emitted. * \sa downloadFinished() downloadRelease() */ /* * Private Slots */ void Feed::handleFeedFinished() { if (feedReply->error() != QNetworkReply::NoError) { emit loadError(feedReply->errorString()); return; } releases.clear(); QByteArray json = feedReply->readAll(); QJsonDocument doc = QJsonDocument::fromJson(json); QJsonArray releasesInfo = doc.object().value("releases").toArray(); for (int i = 0; i < releasesInfo.size(); i++) { releases << Release(releasesInfo.at(i).toObject()); } std::sort(releases.begin(), releases.end()); std::reverse(releases.begin(), releases.end()); _ready = true; emit ready(); } void Feed::handleDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) { emit downloadProgress(bytesReceived, bytesTotal); } void Feed::handleDownloadReadyRead() { if (downloadFile == NULL) { QString fileName = downloadReply->url().fileName(); int extensionPos = fileName.indexOf(QRegExp("(?:\\.tar)?\\.[a-zA-Z0-9]+$")); if (extensionPos > -1) { fileName.insert(extensionPos, "-XXXXXX"); } downloadFile = new QTemporaryFile(QDir::tempPath() + "/" + fileName); downloadFile->open(); } downloadFile->write(downloadReply->readAll()); } void Feed::handleDownloadFinished() { if (downloadReply->error() != QNetworkReply::NoError) { emit downloadError(downloadReply->errorString()); return; } else if (!downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) { if (redirects >= 8) { emit downloadError(tr("Too many redirects.")); return; } QUrl redirectionTarget = downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); QUrl redirectedUrl = downloadReply->url().resolved(redirectionTarget); redirects ++; makeDownloadRequest(redirectedUrl); return; } else if (downloadFile == NULL) { emit downloadError(tr("No data received from server")); return; } downloadFile->flush(); downloadFile->seek(0); QCryptographicHash fileHash(QCryptographicHash::Sha256); fileHash.addData(downloadFile->readAll()); QString hashResult = fileHash.result().toHex(); if (hashResult.toLower() != release.getDownloadSHA256().toLower()) { emit downloadError(tr("Could not verify download integrity.")); return; } emit downloadFinished(); } } // namespace dblsqd
28.759076
119
0.653661
79ded1de805d55f15da03dc7d376a0167f2bf00c
1,954
php
PHP
frontend/views/notification/_item.php
baoguok/getyii
f8a0f5cd7b545f773d61074e93ffbcdd97e31abd
[ "BSD-3-Clause" ]
1
2019-11-04T09:22:42.000Z
2019-11-04T09:22:42.000Z
frontend/views/notification/_item.php
baoguok/getyii
f8a0f5cd7b545f773d61074e93ffbcdd97e31abd
[ "BSD-3-Clause" ]
null
null
null
frontend/views/notification/_item.php
baoguok/getyii
f8a0f5cd7b545f773d61074e93ffbcdd97e31abd
[ "BSD-3-Clause" ]
null
null
null
<?php /** * author : forecho <[email protected]> * createTime : 2015/4/23 14:52 * description: */ use yii\helpers\Html; use yii\helpers\HtmlPurifier; ?> <?php if ($model->status && $model->post): ?> <div class="media-left"> <?= Html::a(Html::img($model->fromUser->userAvatar, ['class' => 'media-object img-circle']), ['/user/default/show', 'username' => $model->fromUser['username']] ); ?> </div> <div class="media-body"> <div class="media-heading"> <?= Html::tag('span', Html::a($model->fromUser['username'], ['/user/default/show', 'username' => $model->fromUser['username']])); ?> <span class="info"><?= $model->getlable($model->type) ?> <?= Html::a(Html::encode($model->post->title), ['/topic/default/view', 'id' => $model->post_id], ['title' => $model->post->title]); ?> <span class="date pull-right"> <i class="fa fa-clock-o"></i> <?= Html::tag('abbr', Yii::$app->formatter->asRelativeTime($model->created_at), ['title' => Yii::$app->formatter->asDatetime($model->created_at)]) ?> </span> <?php if ($index < $notifyCount) { echo Html::tag('span', Yii::t('app', 'New'), ['class' => 'new label label-warning']); } ?> </div> <div class="summary markdown"> <?= HtmlPurifier::process(\yii\helpers\Markdown::process($model->data, 'gfm')) ?> </div> </div> <?php else: ?> <div class="media-body"> <?= Yii::t('app', 'Data Deleted'); ?> </div> <?php endif ?> <div class="media-right opts"> <?= Html::a( Html::tag('i', '', ['class' => 'fa fa-trash']), ['/notification/delete', 'id' => $model->id], [ 'data' => [ 'method' => 'post', ], ] ) ?> </div>
34.892857
113
0.477482
26f4944917347895933e258a51d23a145da50357
5,497
kts
Kotlin
game/src/main/kotlin/world/gregs/voidps/world/community/chat/QuickChat.kts
jarryd229/void
890a1a7467309503737325ee3d25e6fb0cd2e197
[ "BSD-3-Clause" ]
null
null
null
game/src/main/kotlin/world/gregs/voidps/world/community/chat/QuickChat.kts
jarryd229/void
890a1a7467309503737325ee3d25e6fb0cd2e197
[ "BSD-3-Clause" ]
null
null
null
game/src/main/kotlin/world/gregs/voidps/world/community/chat/QuickChat.kts
jarryd229/void
890a1a7467309503737325ee3d25e6fb0cd2e197
[ "BSD-3-Clause" ]
null
null
null
package world.gregs.voidps.world.community.chat import world.gregs.voidps.cache.definition.data.QuickChatType import world.gregs.voidps.engine.client.message import world.gregs.voidps.engine.client.update.view.Viewport.Companion.VIEW_RADIUS import world.gregs.voidps.engine.client.variable.getVar import world.gregs.voidps.engine.entity.character.player.* import world.gregs.voidps.engine.entity.character.player.chat.* import world.gregs.voidps.engine.entity.character.player.skill.Skill import world.gregs.voidps.engine.entity.definition.EnumDefinitions import world.gregs.voidps.engine.entity.definition.ItemDefinitions import world.gregs.voidps.engine.entity.definition.QuickChatPhraseDefinitions import world.gregs.voidps.engine.entity.definition.VariableDefinitions import world.gregs.voidps.engine.event.on import world.gregs.voidps.engine.utility.inject import world.gregs.voidps.network.encode.clanQuickChat import world.gregs.voidps.network.encode.privateQuickChatFrom import world.gregs.voidps.network.encode.privateQuickChatTo import world.gregs.voidps.network.encode.publicQuickChat import world.gregs.voidps.world.community.clan.clan import world.gregs.voidps.world.community.ignore.ignores val players: Players by inject() val phrases: QuickChatPhraseDefinitions by inject() val variables: VariableDefinitions by inject() val enums: EnumDefinitions by inject() val items: ItemDefinitions by inject() on<PrivateQuickChat> { player: Player -> val target = players.get(friend) if (target == null || target.ignores(player)) { player.message("Unable to send message - player unavailable.") return@on } val definition = phrases.get(file) val data = generateData(player, file, data) player.client?.privateQuickChatTo(target.name, file, data) val text = definition.buildString(enums.definitions, items.definitions, data) val message = PrivateQuickChatMessage(player, file, text, data) target.events.emit(message) } on<PrivateQuickChatMessage>({ it.networked }) { player: Player -> player.client?.privateQuickChatFrom(source.name, source.rights.ordinal, file, data) } on<PublicQuickChat>({ chatType == 0 }) { player: Player -> val definition = phrases.get(file) val data = generateData(player, file, data) val text = definition.buildString(enums.definitions, items.definitions, data) val message = PublicQuickChatMessage(player, chatType, file, text, data) players.filter { it.tile.within(player.tile, VIEW_RADIUS) && !it.ignores(player) }.forEach { it.events.emit(message) } } on<PublicQuickChatMessage>({ it.networked }) { player: Player -> player.client?.publicQuickChat(source.index, 0x8000, source.rights.ordinal, file, data) } on<PublicQuickChat>({ chatType == 1 }) { player: Player -> val clan = player.clan if (clan == null) { player.message("You must be in a clan chat to talk.", ChatType.ClanChat) return@on } if (!clan.hasRank(player, clan.talkRank) || !clan.members.contains(player)) { player.message("You are not allowed to talk in this clan chat channel.", ChatType.ClanChat) return@on } val definition = phrases.get(file) val data = generateData(player, file, data) val text = definition.buildString(enums.definitions, items.definitions, data) val message = ClanQuickChatMessage(player, chatType, file, text, data) clan.members.filterNot { it.ignores(player) }.forEach { it.events.emit(message) } } on<ClanQuickChatMessage>({ it.networked }) { player: Player -> player.client?.clanQuickChat(source.name, player.clan!!.name, source.rights.ordinal, file, data) } fun generateData(player: Player, file: Int, data: ByteArray): ByteArray { val definition = phrases.get(file) val types = definition.types ?: return data if (types.size == 1) { when (definition.getType(0)) { QuickChatType.SkillLevel -> { val skill = Skill.all[definition.ids!!.first().first()] val level = player.levels.getMax(skill) return byteArrayOf(level.toByte()) } QuickChatType.Varp -> { val variable = definition.ids!!.first().first() val key = variables.getKey(variable)!! return int(player.getVar(key)) } QuickChatType.Varbit -> { val variable = definition.ids!!.first().first() val key = variables.getKey(variable)!! return int(player.getVar(key)) } QuickChatType.CombatLevel -> return byteArrayOf(player.combatLevel.toByte()) QuickChatType.SlayerAssignment, QuickChatType.ClanRank, QuickChatType.AverageCombatLevel, QuickChatType.SoulWars -> return byteArrayOf(0) else -> return data } } else { val list = mutableListOf<Int>() for (index in types.indices) { when (definition.getType(index)) { QuickChatType.SkillLevel, QuickChatType.SkillExperience -> { val skill = Skill.all[definition.ids!![index].last()] list.add(player.levels.getMax(skill)) } else -> return data } } return list.map { it.toByte() }.toByteArray() } } fun int(value: Int) = byteArrayOf((value shr 24).toByte(), (value shr 16).toByte(), (value shr 8).toByte(), value.toByte())
43.283465
123
0.686192
e1aa9d9b86ddb38a58967b4f1ff0c6fe2d7791d5
3,222
kt
Kotlin
src/main/kotlin/org/nexial/core/SystemVariables.kt
nexiality/nexial-incubate
ee16530ba5b223d943790f9c7ba36b5db9676e19
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/org/nexial/core/SystemVariables.kt
nexiality/nexial-incubate
ee16530ba5b223d943790f9c7ba36b5db9676e19
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/org/nexial/core/SystemVariables.kt
nexiality/nexial-incubate
ee16530ba5b223d943790f9c7ba36b5db9676e19
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nexial.core import org.apache.commons.lang3.BooleanUtils import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.math.NumberUtils import kotlin.streams.toList /** * constants repo. to manage/track system variables */ object SystemVariables { // global defaults, to be registered from the definition of each default values private val SYSVARS = mutableMapOf<String, Any?>() private val SYSVARGROUPS = mutableListOf<String>() @JvmStatic fun registerSysVar(name: String): String { if (StringUtils.isNotBlank(name)) SYSVARS[name] = null return name } @JvmStatic fun <T> registerSysVar(name: String, value: T): String { if (StringUtils.isNotBlank(name)) SYSVARS[name] = value return name } @JvmStatic fun registerSysVarGroup(group: String): String { if (StringUtils.isNotBlank(group) && !SYSVARGROUPS.contains(group)) SYSVARGROUPS.add(group) return group } @JvmStatic fun getDefault(name: String): String? = if (SYSVARS.containsKey(name)) if (SYSVARS[name] == null) null else SYSVARS[name].toString() else null @JvmStatic fun getDefaultBool(name: String): Boolean { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return BooleanUtils.toBoolean(SYSVARS[name].toString()) } @JvmStatic fun getDefaultInt(name: String): Int { require(SYSVARS.containsKey(name)) { "No default value configured for '$name'" } return NumberUtils.toInt(SYSVARS[name].toString()) } @JvmStatic fun getDefaultLong(name: String): Long { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return NumberUtils.toLong(SYSVARS[name].toString()) } @JvmStatic fun getDefaultFloat(name: String): Double { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return NumberUtils.toFloat(SYSVARS[name].toString()).toDouble() } @JvmStatic fun getDefaultDouble(name: String): Double { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return NumberUtils.toDouble(SYSVARS[name].toString()) } @JvmStatic fun isRegisteredSysVar(name: String): Boolean { if (SYSVARS.containsKey(name)) return true for (group in SYSVARGROUPS) { if (StringUtils.startsWith(name, group)) return true } return false } @JvmStatic fun listSysVars(): List<String> = SYSVARS.keys.stream().sorted().toList() }
33.216495
114
0.682806
a9fe6795e57574e5791b9a2efdd1e926247e4a1e
1,652
php
PHP
vendor/ZF2/library/Zend/ZendPdf/library/ZendPdf/Resource/Font/Simple/Parsed/TrueType.php
ngmautri/nhungttk
70c5aadcad11b9975cd926bf03eba95501ce7841
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-09-28T03:04:16.000Z
2020-09-28T03:04:16.000Z
vendor/ZF2/library/Zend/ZendPdf/library/ZendPdf/Resource/Font/Simple/Parsed/TrueType.php
ngmautri/nhungttk
70c5aadcad11b9975cd926bf03eba95501ce7841
[ "Apache-2.0", "BSD-3-Clause" ]
3
2020-08-31T06:17:58.000Z
2021-10-02T01:11:57.000Z
vendor/ZF2/library/Zend/ZendPdf/library/ZendPdf/Resource/Font/Simple/Parsed/TrueType.php
ngmautri/nhungttk
70c5aadcad11b9975cd926bf03eba95501ce7841
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Pdf */ namespace ZendPdf\Resource\Font\Simple\Parsed; use ZendPdf as Pdf; use ZendPdf\BinaryParser\Font\OpenType as OpenTypeFontParser; use ZendPdf\InternalType; use ZendPdf\Resource\Font as FontResource; /** * TrueType fonts implementation * * Font objects should be normally be obtained from the factory methods * {@link \ZendPdf\Font::fontWithName} and {@link \ZendPdf\Font::fontWithPath}. * * @package Zend_PDF * @subpackage Zend_PDF_Fonts */ class TrueType extends AbstractParsed { /** * Object constructor * * @param \ZendPdf\BinaryParser\Font\OpenType\TrueType $fontParser * Font parser * object containing parsed TrueType file. * @param integer $embeddingOptions * Options for font embedding. * @throws \ZendPdf\Exception\ExceptionInterface */ public function __construct(OpenTypeFontParser\TrueType $fontParser, $embeddingOptions) { parent::__construct ( $fontParser, $embeddingOptions ); $this->_fontType = Pdf\Font::TYPE_TRUETYPE; $this->_resource->Subtype = new InternalType\NameObject ( 'TrueType' ); $fontDescriptor = FontResource\FontDescriptor::factory ( $this, $fontParser, $embeddingOptions ); $this->_resource->FontDescriptor = $this->_objectFactory->newObject ( $fontDescriptor ); } }
33.714286
100
0.708232
0d7220e2a6da8d1ae15b986f80f63c31592c0aed
4,984
rb
Ruby
lib/rhouse.rb
derailed/rhouse
2c1c45077d58586a3101191f885c57aaa4361301
[ "Unlicense", "MIT" ]
10
2015-03-18T13:08:54.000Z
2021-07-31T02:29:16.000Z
lib/rhouse.rb
derailed/rhouse
2c1c45077d58586a3101191f885c57aaa4361301
[ "Unlicense", "MIT" ]
null
null
null
lib/rhouse.rb
derailed/rhouse
2c1c45077d58586a3101191f885c57aaa4361301
[ "Unlicense", "MIT" ]
3
2016-02-01T16:49:45.000Z
2021-07-31T02:29:45.000Z
# Sets up the Rhouse gem environment. # Configures logging, database connection and various paths module Rhouse # Gem version VERSION = '0.0.3' # Root path of rhouse PATH = ::File.expand_path(::File.join(::File.dirname(__FILE__), *%w[..])) # Lib path LIBPATH = ::File.join( PATH, "lib" ) # Configuration path CONFPATH = ::File.join( PATH, "config" ) class << self # Holds the rhouse configuration hash attr_reader :config # Holds the environment the gem is running under attr_reader :environment # The version string for the library. def version() VERSION; end # Helper to find file from the root path def path( *args ) args.empty? ? PATH : ::File.join( PATH, args.flatten ) end # Helper to locate a file in lib directory def libpath( *args ) args.empty? ? LIBPATH : ::File.join( LIBPATH, args.flatten ) end # Helper to locate a configuration file in the config dir def confpath( *args ) args.empty? ? CONFPATH : ::File.join( CONFPATH, args.flatten ) end # Initializes the gem. Sets up logging and database connections if required def initialize( opts={} ) @config = default_config.merge( opts ) @environment = (config[:environment] || ENV['RH_ENV'] || :test).to_s establish_db_connection if @config[:requires_db] @initialized = true end public :initialize # For testing only ! def reset @logger = nil @config = nil @environment = nil @initialized = false end public :reset # Is rhouse initialized def initialized?() @initialized; end # Is the gem running in production env? def production_env?() environment == 'production'; end # Is the gem running in test env? def test_env?() environment == 'test' ; end # Connects to the pluto database def establish_db_connection return if ActiveRecord::Base.connected? || !@environment require 'active_record' database = YAML.load_file( conf_path( "database.yml" ) ) ActiveRecord::Base.colorize_logging = true ActiveRecord::Base.logger = logger # set up the AR logger before connecting logger.debug "--- Establishing database connection in '#{@environment.upcase}' environment" ActiveRecord::Base.establish_connection( database[@environment] ) end # Helper to locate a configuration file def conf_path( *args ) @conf_path ||= CONFPATH args.empty? ? @confpath : File.join( @conf_path, *args ) end # Sets up the default configuration env. # By default test env, no db connection and stdout logging def default_config { :environment => :test, :requires_db => false, :log_level => :info, :log_file => $stdout, :email_alert_level => :error } end # Helper to require all files from a given location def require_all_libs_relative_to( fname, dir = nil ) dir ||= ::File.basename(fname, '.*') search_me = ::File.expand_path( ::File.join(::File.dirname(fname), dir, '**', '*.rb')) Dir.glob(search_me).sort.each do |rb| # puts "[REQ] #{rb}" require rb end end # Sets up the rhouse logger. Using the logging gem def logger return @logger if @logger # the logger is initialized before anything else, including the database, so include it here. require "logger" @logger = Rhouse::Logger.new( { :log_file => config[:log_file], :log_level => config[:log_level], :email_alerts_to => config[:email_alerts_to], :email_alert_level => config[:email_alert_level], :additive => false } ) end # For debuging def dump logger << "-" * 22 + " RHouse configuration " + "-" * 76 + "\n" config.keys.sort{ |a,b| a.to_s <=> b.to_s }.each do |k| key = k.to_s.rjust(20) value = config[k] if value.blank? logger << "#{key} : #{value.inspect.rjust(97," ")}\n" # shows an empty hashes/arrays, nils, etc. else case value when Hash logger << "#{key} : #{(value.keys.first.to_s + ": " + value[value.keys.first].inspect).rjust(97,' ')}\n" value.keys[1..-1].each { |k| logger << " "*23 + (k.to_s + " : " + value[k].inspect).rjust(97," ") + "\n" } else logger << "#{key} : #{value.to_s.rjust(97," ")}\n" end end end logger << "-" * 120 + "\n" end end require Rhouse.libpath(*%w[core_ext active_record base]) require Rhouse.libpath(*%w[core_ext active_record connection_adapter]) require_all_libs_relative_to( File.join( File.dirname(__FILE__), %w[rhouse] ) ) end
33.675676
120
0.582865
cd2e086e950dfaeee67854944e64b1e1846f58c6
1,237
cs
C#
Concepts/ViewModels/SliderViewModel.cs
MaciekSwiszczowski/DebuggingAndProfilingExamples
da3977bf684d5d08f466c73c6f9e2caa5b142482
[ "MIT" ]
null
null
null
Concepts/ViewModels/SliderViewModel.cs
MaciekSwiszczowski/DebuggingAndProfilingExamples
da3977bf684d5d08f466c73c6f9e2caa5b142482
[ "MIT" ]
null
null
null
Concepts/ViewModels/SliderViewModel.cs
MaciekSwiszczowski/DebuggingAndProfilingExamples
da3977bf684d5d08f466c73c6f9e2caa5b142482
[ "MIT" ]
null
null
null
using System; using System.ComponentModel.Composition; using System.Windows.Input; using Prism.Commands; using Prism.Mvvm; namespace Concepts.ViewModels { [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class SliderViewModel : BindableBase { private double _rangeStart; private double _rangeEnd; public event Action GenerateNewData; public ICommand GenerateNewDataCommand { get; } public double Minimum { get; set; } public double Maximum { get; set; } public double RangeStart { get => _rangeStart; set { _rangeStart = value; RaisePropertyChanged(); } } public double RangeEnd { get => _rangeEnd; set { _rangeEnd = value; RaisePropertyChanged(); } } [ImportingConstructor] public SliderViewModel() { Minimum = 0; Maximum = 100; RangeStart = 10; RangeEnd = 90; GenerateNewDataCommand = new DelegateCommand(() => GenerateNewData?.Invoke()); } } }
21.701754
90
0.536783
2fd72d125f5346054e3757f9a48f62bf0af118ee
565
py
Python
ADA_KING.py
myid13221/CODECHEF-PYTHON
849532482f1ede127b299ab2d6000f27b99ee7b9
[ "MIT" ]
null
null
null
ADA_KING.py
myid13221/CODECHEF-PYTHON
849532482f1ede127b299ab2d6000f27b99ee7b9
[ "MIT" ]
4
2020-10-04T07:49:30.000Z
2021-10-02T05:24:40.000Z
ADA_KING.py
myid13221/CODECHEF-PYTHON
849532482f1ede127b299ab2d6000f27b99ee7b9
[ "MIT" ]
7
2020-10-04T07:46:55.000Z
2021-11-05T14:30:00.000Z
# cook your dish here try: t = int(input()) for _ in range(t): r, c, k = map(int, input().rstrip().split(' ')) if r <= k: start_row = 1 else: start_row = r-k if c <= k: start_col = 1 else: start_col = c-k if r+k >= 8: end_row = 8 else: end_row = r+k if c+k >= 8: end_col = 8 else: end_col = c+k print((end_row - start_row + 1)*(end_col - start_col + 1)) except: pass
20.925926
66
0.39646
b51e1360a4b238a2d297ecacd230e425d7278201
912
js
JavaScript
API_Gateways/Customer.js
radishj/FreshVcitoriaServer
3e835babdae3dd6e3449b10006d4d293aa1d3932
[ "Apache-2.0" ]
null
null
null
API_Gateways/Customer.js
radishj/FreshVcitoriaServer
3e835babdae3dd6e3449b10006d4d293aa1d3932
[ "Apache-2.0" ]
null
null
null
API_Gateways/Customer.js
radishj/FreshVcitoriaServer
3e835babdae3dd6e3449b10006d4d293aa1d3932
[ "Apache-2.0" ]
null
null
null
const express = require('express'); const router = express.Router(); //const asyncHandler = require('../Helpers/asyncHandler'); //const validate = require('validate.js'); const C = require('../DBServices/Customer'); router.get("/:phone_number",async function(req, res, next) { var phone = req.params.phone_number; C.GetCustomer(phone, res); }); router.post("/",async function(req, res, next) { //var phone = req.params.phone_number; var phone = req.body.phone; var address = req.body.address; await C.UpdateAddress(phone, address, res, next); }) router.post("/new",async function(req, res) { //var phone = req.params.phone; //var address = req.params.address; //var cityID = req.params.cityID; var phone = req.body.phone; var address = req.body.address; var cityID = req.body.cityID; await C.Create(phone, address, cityID, res); }) module.exports = router;
31.448276
60
0.672149
3905b5a759cf16385fad603df3999be49ecaf31d
2,184
py
Python
Bank.py
sahgh313/Bank_project
9a24ff9fd4946b8dd84e77bc5f9e2e03527b2f26
[ "MIT" ]
null
null
null
Bank.py
sahgh313/Bank_project
9a24ff9fd4946b8dd84e77bc5f9e2e03527b2f26
[ "MIT" ]
null
null
null
Bank.py
sahgh313/Bank_project
9a24ff9fd4946b8dd84e77bc5f9e2e03527b2f26
[ "MIT" ]
null
null
null
#پروژه بانک #نوشته شده توسط امیر حسین غرقی class Bank: def Create(self): self.first_name = input( 'Enter first name : ') self.last_name = input("Enter your last name : ") self.phone_number = input("Enter your phone number, sample : 0912*****54 :") self.value = float(input("Enter your start value : ")) while self.value < 0 : print("First value can not be negative !") self.value = float(input("Enter your start value : ")) def Add(self): self.to_add = float(input("How much do you want to add? ")) while self.to_add < 0 : print("Can't be negative! try again ") self.to_add = float(input("How much do you want to add? ")) self.value += self.to_add print ("your balance is :", self.value) def Sub(self): self.sub_from = float(input("how much do you want to take? ")) while self.sub_from < 0 and self.sub_from > self.value: print("Cant be negative! try again ") self.sub_from = float(input("how much do you want to take? ")) self.value -= self.sub_from print ("your balance is :", self.value) def Show(self): print(self.first_name, self.last_name,"phone number", self.phone_number,"account balance", self.value) #------main--------------------------------- print(""" Wellcome here are your choices:) press 1 to create an account; press 2 to deposit to your account; press 3 to withdraw from the account press 4 to show your info; press 0 to exit; """) customer = Bank() while True : print(""" Wellcome here are your choices:) press 1 to create an account; press 2 to deposit to your account; press 3 to withdraw from the account press 4 to show your info; press 0 to exit; """) menu = int(input("")) if menu == 1: customer.Create() elif menu == 2 : customer.Add() elif menu == 3 : customer.Sub() elif menu == 4 : customer.Show() elif menu == 0 : break
24.539326
110
0.553114
2af2ae06377e1a2a73db29f5ab35e11e69f19af6
81
sql
SQL
administrator/components/com_admin/sql/updates/mysql/2.5.0-2012-01-10.sql
ElectricEasel/posrgnew
a9e2d244a3cf29f4620de4705171d4cdbdc579b4
[ "PostgreSQL" ]
null
null
null
administrator/components/com_admin/sql/updates/mysql/2.5.0-2012-01-10.sql
ElectricEasel/posrgnew
a9e2d244a3cf29f4620de4705171d4cdbdc579b4
[ "PostgreSQL" ]
null
null
null
administrator/components/com_admin/sql/updates/mysql/2.5.0-2012-01-10.sql
ElectricEasel/posrgnew
a9e2d244a3cf29f4620de4705171d4cdbdc579b4
[ "PostgreSQL" ]
null
null
null
ALTER TABLE `#__updates` ADD COLUMN `infourl` text NOT NULL AFTER `detailsurl`;
40.5
80
0.753086
051dcfe87e4e0cbbe1f37fc4ca5c51fa1b82cfbb
20,525
sql
SQL
project3.sql
Maahi5656/Laravel-Admin-Template
a697c83170cda77e2edd5cbf412db6d2001cb483
[ "MIT" ]
null
null
null
project3.sql
Maahi5656/Laravel-Admin-Template
a697c83170cda77e2edd5cbf412db6d2001cb483
[ "MIT" ]
null
null
null
project3.sql
Maahi5656/Laravel-Admin-Template
a697c83170cda77e2edd5cbf412db6d2001cb483
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Apr 01, 2021 at 02:09 PM -- Server version: 10.4.18-MariaDB -- PHP Version: 7.4.16 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `project3` -- -- -------------------------------------------------------- -- -- Table structure for table `blogs` -- CREATE TABLE `blogs` ( `id` bigint(20) UNSIGNED NOT NULL, `image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `details` text COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `blogs` -- INSERT INTO `blogs` (`id`, `image`, `title`, `details`, `created_at`, `updated_at`) VALUES (1, '605729fe1e713.jpg', 'We Can Ensure Your Comfortable Life', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n\r\ntypesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\r\n\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\r\n\r\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum', '2021-03-21 05:11:58', '2021-03-21 05:11:58'), (2, '60572b0456a16.jpg', 'We Can Ensure Your Comfortable Life', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n\r\ntypesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\r\n\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\r\n\r\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.', '2021-03-21 05:16:20', '2021-03-21 05:16:20'), (3, '60572b239f9ba.jpg', 'We Can Ensure Your Comfortable Life', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n\r\ntypesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\r\n\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\r\n\r\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.', '2021-03-21 05:16:51', '2021-03-21 05:16:51'); -- -------------------------------------------------------- -- -- Table structure for table `brands` -- CREATE TABLE `brands` ( `id` bigint(20) UNSIGNED NOT NULL, `image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `brands` -- INSERT INTO `brands` (`id`, `image`, `name`, `created_at`, `updated_at`) VALUES (1, '60531511a8748.jpg', 'Bata', '2021-03-18 02:53:37', '2021-03-18 03:01:42'), (2, '6053152fb1082.jpg', 'Walton', '2021-03-18 02:54:07', '2021-03-18 02:54:07'), (3, '605315667bb5a.png', 'Pepsi', '2021-03-18 02:55:02', '2021-03-18 02:55:02'), (4, '6053157e532c2.png', 'Sony', '2021-03-18 02:55:26', '2021-03-18 02:55:26'), (5, '60531638eadc5.png', 'Le Reve', '2021-03-18 02:58:33', '2021-03-18 02:58:33'), (7, '60533e27e4720.png', 'Fanta', '2021-03-18 05:48:55', '2021-03-18 05:48:55'), (8, '60533e472ba2a.png', 'Hewlett-Packard', '2021-03-18 05:49:27', '2021-03-18 05:49:27'), (9, '60533e5fb40a2.jpg', 'Apple', '2021-03-18 05:49:51', '2021-03-18 05:49:51'), (10, '6053417e5e952.jpg', 'North Star', '2021-03-18 06:03:10', '2021-03-18 06:03:10'), (11, '605341d2e4edb.png', 'Coca-Cola', '2021-03-18 06:04:34', '2021-03-18 06:04:34'), (12, '605342547b8f0.jpeg', 'Nokia', '2021-03-18 06:06:44', '2021-03-18 06:06:44'), (13, '605344b0eb77e.png', 'Lifebuoy', '2021-03-18 06:16:49', '2021-03-18 06:16:49'), (14, '605344f355092.png', 'Savlon', '2021-03-18 06:17:55', '2021-03-18 06:17:55'), (15, '605345b13f3e7.jpeg', 'Pran', '2021-03-18 06:19:55', '2021-03-18 06:21:05'), (16, '605345f941e42.jpg', 'Milk Vita', '2021-03-18 06:22:17', '2021-03-18 06:22:17'), (17, '6055c61f14545.jpg', '7 Up', '2021-03-20 03:53:35', '2021-03-20 03:53:35'); -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE `categories` ( `id` bigint(20) UNSIGNED NOT NULL, `image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`id`, `image`, `name`, `created_at`, `updated_at`) VALUES (1, '6053227730702.png', 'Fruit', '2021-03-18 03:50:47', '2021-03-18 04:20:43'), (2, '6053229742dfc.png', 'Drink', '2021-03-18 03:51:19', '2021-03-18 04:20:49'), (3, '605322a15230e.jpg', 'Dessert', '2021-03-18 03:51:29', '2021-03-18 03:51:29'), (4, '6053299ca11a1.jpg', 'Vegetable', '2021-03-18 04:21:16', '2021-03-18 04:21:16'), (5, '60558ffb4fe0a.png', 'Clothing & Accessories', '2021-03-20 00:02:35', '2021-03-20 00:02:35'), (6, '605591d4a9a97.jpg', 'Consumer Products', '2021-03-20 00:10:28', '2021-03-20 00:10:28'), (7, '6055c4958c3dc.png', 'Gadgets & Electronics Appliances', '2021-03-20 03:47:01', '2021-03-20 03:47:32'); -- -------------------------------------------------------- -- -- Table structure for table `comments` -- CREATE TABLE `comments` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `details` text COLLATE utf8mb4_unicode_ci NOT NULL, `blog_id` bigint(20) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `comments` -- INSERT INTO `comments` (`id`, `name`, `email`, `details`, `blog_id`, `created_at`, `updated_at`) VALUES (1, 'John Doe', '[email protected]', 'simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when', 2, '2021-03-22 01:47:54', '2021-03-22 01:47:54'), (2, 'Jack Ma', '[email protected]', 'rjwrhwrdfof dwrp;rr ldm;lkd', 1, '2021-03-22 02:21:52', '2021-03-22 02:21:52'), (3, 'Ajwad Maahi', '[email protected]', 'text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when', 2, '2021-03-22 02:26:06', '2021-03-22 02:26:06'); -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1), (4, '2021_03_18_072208_create_brands_table', 2), (5, '2021_03_18_073758_create_categories_table', 2), (6, '2021_03_20_045136_create_products_table', 3), (7, '2021_03_21_091626_create_blogs_table', 4), (8, '2021_03_21_092256_create_comments_table', 4), (9, '2021_03_22_065853_create_people_table', 5), (10, '2021_04_01_103541_create_orders_table', 6), (11, '2021_04_01_105113_create_order_products_table', 6); -- -------------------------------------------------------- -- -- Table structure for table `orders` -- CREATE TABLE `orders` ( `id` bigint(20) UNSIGNED NOT NULL, `user_id` bigint(20) NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `phone` double NOT NULL, `payment_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `payment_status` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `city` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `discount` double NOT NULL, `total` double NOT NULL, `subtotal` double NOT NULL, `status` tinyint(1) NOT NULL DEFAULT 0, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `order_products` -- CREATE TABLE `order_products` ( `id` bigint(20) UNSIGNED NOT NULL, `order_id` bigint(20) NOT NULL, `product_id` bigint(20) NOT NULL, `price` double(8,2) NOT NULL, `quantity` int(11) NOT NULL, `total` double(8,2) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `brand_id` int(11) NOT NULL, `category_id` int(11) NOT NULL, `quantity` int(11) NOT NULL, `price` double(12,2) NOT NULL, `picture` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `products` -- INSERT INTO `products` (`id`, `name`, `brand_id`, `category_id`, `quantity`, `price`, `picture`, `description`, `created_at`, `updated_at`) VALUES (1, '1 Liter Cold Drink', 7, 2, 1, 15.00, '605583fc70d92.jpg', 'fruit-flavored carbonated soft drinks', '2021-03-19 23:11:24', '2021-03-19 23:11:24'), (2, 'Harold Boot-style Brown', 1, 5, 2, 200.00, '605590710301b.jpg', 'Get on-trend with unsurpassed style & signature comfort of these boot-style casual shoes by Red Label. These are casual by nature', '2021-03-20 00:04:33', '2021-03-20 00:04:33'), (3, 'Lifebuoy Soap', 13, 6, 5, 25.00, '6055921a6c80a.jpg', 'Product details of Lifebuoy Soap Bar Care 100g, Product Type: Soap Bar, Capacity: 100g, Brand: Lifebuoy', '2021-03-20 00:11:38', '2021-03-20 00:11:38'), (4, 'Walton Refrigerator 1', 2, 7, 5, 12000.00, '6055c52d79108.jpg', '- Type: Direct Cool\r\n - Door: Glass door\r\n - Gross Volume: 380 Ltr\r\n - Net Volume: 365 Ltr\r\n - Refrigerant: R600a\r\n - Using Latest Intelligent INVERTER technology\r\n - Do not use Voltage stabilizer, if use warranty will be voided. \r\n​', '2021-03-20 03:49:33', '2021-03-20 03:49:33'), (5, 'Walton Refrigerator Red', 2, 7, 10, 12000.00, '6055c5750723e.jpg', '- Type: Direct Cool\r\n - Door: Glass door\r\n - Gross Volume: 380 Ltr\r\n - Net Volume: 365 Ltr\r\n - Refrigerant: R600a\r\n - Using Latest Intelligent INVERTER technology\r\n - Do not use Voltage stabilizer, if use warranty will be voided. \r\n​', '2021-03-20 03:50:45', '2021-03-20 03:50:45'), (6, '7 UP can', 17, 2, 25, 5.00, '6055c65d0f967.jpg', 'can of carbonated drink', '2021-03-20 03:54:37', '2021-03-20 03:54:37'), (7, '1 Litre &-UP drink', 17, 2, 15, 10.00, '6055c6e9b2c83.jpg', 'One Liter Bottle Of Carbonated Drink', '2021-03-20 03:56:57', '2021-03-20 03:56:57'), (8, 'Full Sleeve Light Blue T-Shirt', 5, 5, 30, 15.00, '6055c7ed7a372.jpg', 'comfortable to wear', '2021-03-20 04:01:17', '2021-03-20 04:01:17'), (9, 'Pepsi Can', 3, 2, 20, 15.00, '6056dc5d61d4f.jpg', 'Pepsi is a carbonated soft drink manufactured by PepsiCo', '2021-03-20 23:40:45', '2021-03-20 23:40:45'), (10, '250 ml Pepsi', 3, 2, 10, 18.00, '6056dcd668710.jpg', 'Pepsi is a carbonated soft drink manufactured by PepsiCo', '2021-03-20 23:42:46', '2021-03-20 23:42:46'), (11, '2 Litre Pepsi Drink', 3, 2, 35, 80.00, '6056dd441af83.jpg', 'Pepsi is a carbonated soft drink manufactured by PepsiCo', '2021-03-20 23:44:36', '2021-03-20 23:44:36'), (12, 'Pepsi Black Can', 3, 2, 25, 10.00, '6056dd9a4d30f.jpg', 'Pepsi is a carbonated soft drink manufactured by PepsiCo', '2021-03-20 23:46:02', '2021-03-20 23:46:02'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `user_type` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT 'customer', `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `user_type`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'Ajwad Maahi', '[email protected]', NULL, '$2y$10$nVknfnorU.s7t6BsLL/kIeldFaOWYqaQZDalRUwwcOHL9KcdW1MYG', 'admin', NULL, '2021-03-18 00:04:40', '2021-03-18 00:04:40'), (2, 'maahi', '[email protected]', NULL, '$2y$10$nVknfnorU.s7t6BsLL/kIeldFaOWYqaQZDalRUwwcOHL9KcdW1MYG', 'customer', NULL, NULL, NULL); -- -- Indexes for dumped tables -- -- -- Indexes for table `blogs` -- ALTER TABLE `blogs` ADD PRIMARY KEY (`id`); -- -- Indexes for table `brands` -- ALTER TABLE `brands` ADD PRIMARY KEY (`id`); -- -- Indexes for table `categories` -- ALTER TABLE `categories` ADD PRIMARY KEY (`id`); -- -- Indexes for table `comments` -- ALTER TABLE `comments` ADD PRIMARY KEY (`id`); -- -- Indexes for table `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `orders` -- ALTER TABLE `orders` ADD PRIMARY KEY (`id`); -- -- Indexes for table `order_products` -- ALTER TABLE `order_products` ADD PRIMARY KEY (`id`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- 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 `blogs` -- ALTER TABLE `blogs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `brands` -- ALTER TABLE `brands` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT for table `categories` -- ALTER TABLE `categories` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `comments` -- ALTER TABLE `comments` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `orders` -- ALTER TABLE `orders` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `order_products` -- ALTER TABLE `order_products` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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 */;
47.075688
1,455
0.706358
ddb6a92175a3dc8477bd7c1af55541ea0908d55a
1,173
java
Java
DAP/library/api/fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/dap_transaction/common/exceptions/RecordsNotFoundException.java
jorgeejgonzalez/fermat
d5f0f7c98510f19f485ac908501df46f24444190
[ "MIT" ]
3
2016-03-23T05:26:51.000Z
2016-03-24T14:33:05.000Z
DAP/library/api/fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/dap_transaction/common/exceptions/RecordsNotFoundException.java
yalayn/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
17
2015-11-20T20:43:17.000Z
2016-07-25T20:35:49.000Z
DAP/library/api/fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/dap_transaction/common/exceptions/RecordsNotFoundException.java
yalayn/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
26
2015-11-20T13:20:23.000Z
2022-03-11T07:50:06.000Z
package com.bitdubai.fermat_dap_api.layer.dap_transaction.common.exceptions; import com.bitdubai.fermat_dap_api.layer.all_definition.exceptions.DAPException; /** * Created by Víctor A. Mars M. ([email protected]) on 26/10/15. */ public class RecordsNotFoundException extends DAPException { //VARIABLE DECLARATION public static final String DEFAULT_MESSAGE = "Couldn't find any record in database to update or delete."; //CONSTRUCTORS public RecordsNotFoundException(String message, Exception cause, String context, String possibleReason) { super(message, cause, context, possibleReason); } public RecordsNotFoundException(Exception cause, String context, String possibleReason) { super(DEFAULT_MESSAGE, cause, context, possibleReason); } public RecordsNotFoundException(String message, Exception cause) { super(message, cause); } public RecordsNotFoundException(String message) { super(message); } public RecordsNotFoundException(Exception exception) { super(exception); } //PUBLIC METHODS //PRIVATE METHODS //GETTER AND SETTERS //INNER CLASSES }
26.659091
109
0.726343
4b9f4ffb8f7f140a3470bd0bf5449145af0bfa38
15,593
cpp
C++
tests/src/error_event_test.cpp
Appdynamics/iot-cpp-sdk
abb7d70b2364089495ac73adf2a992c0af6eaf8c
[ "Apache-2.0" ]
3
2018-09-13T21:26:27.000Z
2022-01-25T06:15:06.000Z
tests/src/error_event_test.cpp
Appdynamics/iot-cpp-sdk
abb7d70b2364089495ac73adf2a992c0af6eaf8c
[ "Apache-2.0" ]
11
2018-01-30T00:42:23.000Z
2019-10-20T07:19:37.000Z
tests/src/error_event_test.cpp
Appdynamics/iot-cpp-sdk
abb7d70b2364089495ac73adf2a992c0af6eaf8c
[ "Apache-2.0" ]
5
2018-01-29T18:52:21.000Z
2019-05-19T02:38:18.000Z
/* * Copyright (c) 2018 AppDynamics LLC and its affiliates * * 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 <cgreen/cgreen.h> #include <appd_iot_interface.h> #include <time.h> #include <unistd.h> #include "common_test.hpp" #include "http_mock_interface.hpp" #include "log_mock_interface.hpp" using namespace cgreen; Describe(error_event); BeforeEach(error_event) { } AfterEach(error_event) { } /** * @brief Unit Test for valid alert and critical error event */ Ensure(error_event, test_full_alert_and_critical_error_event) { appd_iot_sdk_config_t sdkcfg; appd_iot_device_config_t devcfg; appd_iot_error_code_t retcode; appd_iot_init_to_zero(&sdkcfg, sizeof(sdkcfg)); sdkcfg.appkey = TEST_APP_KEY; sdkcfg.eum_collector_url = TEST_EUM_COLLECTOR_URL; sdkcfg.log_write_cb = &appd_iot_log_write_cb; sdkcfg.log_level = APPD_IOT_LOG_ALL; devcfg.device_id = "1111"; devcfg.device_type = "SmartCar"; devcfg.device_name = "AudiS3"; devcfg.fw_version = "1.0"; devcfg.hw_version = "1.0"; devcfg.os_version = "1.0"; devcfg.sw_version = "1.0"; appd_iot_clear_log_write_cb_flags(); retcode = appd_iot_init_sdk(sdkcfg, devcfg); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_error_event_t error_event_1, error_event_2; appd_iot_init_to_zero(&error_event_1, sizeof(appd_iot_error_event_t)); appd_iot_init_to_zero(&error_event_2, sizeof(appd_iot_error_event_t)); error_event_1.name = "Warning Light"; error_event_1.message = "Oil Change Reminder"; error_event_1.severity = APPD_IOT_ERR_SEVERITY_ALERT; error_event_1.timestamp_ms = ((int64_t)time(NULL) * 1000); error_event_1.duration_ms = 0; error_event_1.data_count = 1; error_event_1.data = (appd_iot_data_t*)calloc(error_event_1.data_count, sizeof(appd_iot_data_t)); appd_iot_data_set_integer(&error_event_1.data[0], "Mileage", 27300); retcode = appd_iot_add_error_event(error_event_1); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); error_event_2.name = "Bluetooth Connection Error"; error_event_2.message = "connection dropped during voice call due to bluetooth exception"; error_event_2.severity = APPD_IOT_ERR_SEVERITY_CRITICAL; error_event_2.timestamp_ms = ((int64_t)time(NULL) * 1000); error_event_2.duration_ms = 0; error_event_2.data_count = 3; error_event_2.data = (appd_iot_data_t*)calloc(error_event_2.data_count, sizeof(appd_iot_data_t)); appd_iot_data_set_string(&error_event_2.data[0], "UUID", "00001101-0000-1000-8000-00805f9b34fb"); appd_iot_data_set_string(&error_event_2.data[1], "Bluetooth Version", "3.0"); appd_iot_data_set_integer(&error_event_2.data[2], "Error Code", 43); retcode = appd_iot_add_error_event(error_event_2); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_http_cb_t http_cb; http_cb.http_req_send_cb = &appd_iot_test_http_req_send_cb; http_cb.http_resp_done_cb = &appd_iot_test_http_resp_done_cb; retcode = appd_iot_register_network_interface(http_cb); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_data_t* resp_headers = NULL; int resp_headers_count = 3; resp_headers = (appd_iot_data_t*)calloc(resp_headers_count, sizeof(appd_iot_data_t)); appd_iot_data_set_string(&resp_headers[0], "Pragma", "no-cache"); appd_iot_data_set_string(&resp_headers[1], "Transfer-Encoding", "chunked"); appd_iot_data_set_string(&resp_headers[2], "Expires", "0"); appd_iot_set_response_code(202); appd_iot_set_response_headers(resp_headers_count, resp_headers); appd_iot_clear_http_cb_triggered_flags(); retcode = appd_iot_send_all_events(); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //test if callbacks are triggered assert_that(appd_iot_is_http_req_send_cb_triggered(), is_equal_to(true)); assert_that(appd_iot_is_http_resp_done_cb_triggered(), is_equal_to(true)); appd_iot_clear_http_cb_triggered_flags(); free(resp_headers); free(error_event_1.data); free(error_event_2.data); //test for log write cb assert_that(appd_iot_is_log_write_cb_success(), is_equal_to(true)); } /** * @brief Unit Test for minimal alert and critical error event */ Ensure(error_event, test_minimal_alert_and_critical_error_event) { appd_iot_sdk_config_t sdkcfg; appd_iot_device_config_t devcfg; appd_iot_error_code_t retcode; appd_iot_init_to_zero(&sdkcfg, sizeof(sdkcfg)); sdkcfg.appkey = TEST_APP_KEY; sdkcfg.eum_collector_url = TEST_EUM_COLLECTOR_URL; sdkcfg.log_write_cb = &appd_iot_log_write_cb; sdkcfg.log_level = APPD_IOT_LOG_ALL; devcfg.device_id = "1111"; devcfg.device_type = "SmartCar"; devcfg.device_name = "AudiS3"; devcfg.fw_version = "1.0"; devcfg.hw_version = "1.0"; devcfg.os_version = "1.0"; devcfg.sw_version = "1.0"; appd_iot_clear_log_write_cb_flags(); retcode = appd_iot_init_sdk(sdkcfg, devcfg); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_error_event_t error_event; appd_iot_init_to_zero(&error_event, sizeof(appd_iot_error_event_t)); error_event.name = "Tire Pressure Low"; error_event.timestamp_ms = ((int64_t)time(NULL) * 1000); retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_http_cb_t http_cb; http_cb.http_req_send_cb = &appd_iot_test_http_req_send_cb; http_cb.http_resp_done_cb = &appd_iot_test_http_resp_done_cb; retcode = appd_iot_register_network_interface(http_cb); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_data_t* resp_headers = NULL; int resp_headers_count = 3; resp_headers = (appd_iot_data_t*)calloc(resp_headers_count, sizeof(appd_iot_data_t)); appd_iot_data_set_string(&resp_headers[0], "Pragma", "no-cache"); appd_iot_data_set_string(&resp_headers[1], "Transfer-Encoding", "chunked"); appd_iot_data_set_string(&resp_headers[2], "Expires", "0"); appd_iot_set_response_code(202); appd_iot_set_response_headers(resp_headers_count, resp_headers); appd_iot_clear_http_cb_triggered_flags(); retcode = appd_iot_send_all_events(); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //test if callbacks are triggered assert_that(appd_iot_is_http_req_send_cb_triggered(), is_equal_to(true)); assert_that(appd_iot_is_http_resp_done_cb_triggered(), is_equal_to(true)); appd_iot_clear_http_cb_triggered_flags(); free(resp_headers); //test for log write cb assert_that(appd_iot_is_log_write_cb_success(), is_equal_to(true)); } /** * @brief Unit Test for valid fatal error event */ Ensure(error_event, test_full_fatal_error_event) { appd_iot_sdk_config_t sdkcfg; appd_iot_device_config_t devcfg; appd_iot_error_code_t retcode; appd_iot_init_to_zero(&sdkcfg, sizeof(sdkcfg)); sdkcfg.appkey = TEST_APP_KEY; sdkcfg.eum_collector_url = TEST_EUM_COLLECTOR_URL; sdkcfg.log_write_cb = &appd_iot_log_write_cb; sdkcfg.log_level = APPD_IOT_LOG_ALL; devcfg.device_id = "1111"; devcfg.device_type = "SmartCar"; devcfg.device_name = "AudiS3"; devcfg.fw_version = "1.0"; devcfg.hw_version = "1.0"; devcfg.os_version = "1.0"; devcfg.sw_version = "1.0"; appd_iot_clear_log_write_cb_flags(); retcode = appd_iot_init_sdk(sdkcfg, devcfg); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_error_event_t error_event; appd_iot_init_to_zero(&error_event, sizeof(appd_iot_error_event_t)); error_event.name = "I/O Exception"; error_event.message = "error while writing data to file"; error_event.severity = APPD_IOT_ERR_SEVERITY_FATAL; error_event.timestamp_ms = ((int64_t)time(NULL) * 1000); error_event.duration_ms = 0; error_event.stack_trace_count = 1; error_event.error_stack_trace_index = 0; appd_iot_stack_trace_t* stack_trace = (appd_iot_stack_trace_t*)calloc(error_event.stack_trace_count, sizeof(appd_iot_stack_trace_t)); stack_trace->stack_frame_count = 4; stack_trace->thread = "main"; appd_iot_stack_frame_t* stack_frame = (appd_iot_stack_frame_t*)calloc(stack_trace->stack_frame_count, sizeof(appd_iot_stack_frame_t)); stack_trace->stack_frame = stack_frame; stack_frame[0].symbol_name = "_libc_start_main"; stack_frame[0].package_name = "/system/lib/libc.so"; stack_frame[1].symbol_name = "main"; stack_frame[1].package_name = "/home/native-app/mediaplayer/build/mediaplayer_main.so"; stack_frame[1].absolute_addr = 0x7f8bd984876c; stack_frame[1].image_offset = 18861; stack_frame[1].symbol_offset = 10; stack_frame[1].file_name = "main.c"; stack_frame[1].lineno = 71; stack_frame[2].symbol_name = "write_data"; stack_frame[2].package_name = "/home/native-app/mediaplayer/build/mediaplayer_main.so"; stack_frame[2].absolute_addr = 0x7f8bda3f915b; stack_frame[2].image_offset = 116437; stack_frame[2].symbol_offset = 12; stack_frame[2].file_name = "writedata.c"; stack_frame[2].lineno = 271; stack_frame[3].symbol_name = "write_to_file"; stack_frame[3].package_name = "/home/native-app/mediaplayer/build/mediaplayer_main.so"; stack_frame[3].absolute_addr = 0x7f8bda9f69d1; stack_frame[3].image_offset = 287531; stack_frame[3].symbol_offset = 34; stack_frame[3].file_name = "writedata.c"; stack_frame[3].lineno = 524; error_event.stack_trace = stack_trace; error_event.data_count = 4; error_event.data = (appd_iot_data_t*)calloc(error_event.data_count, sizeof(appd_iot_data_t)); appd_iot_data_set_string(&error_event.data[0], "filename", "buffer-126543.mp3"); appd_iot_data_set_integer(&error_event.data[1], "filesize", 120000000); appd_iot_data_set_integer(&error_event.data[2], "signal number", 6); appd_iot_data_set_string(&error_event.data[3], "mediaplayer_version", "1.1"); retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_http_cb_t http_cb; http_cb.http_req_send_cb = &appd_iot_test_http_req_send_cb; http_cb.http_resp_done_cb = &appd_iot_test_http_resp_done_cb; retcode = appd_iot_register_network_interface(http_cb); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_data_t* resp_headers = NULL; int resp_headers_count = 3; resp_headers = (appd_iot_data_t*)calloc(resp_headers_count, sizeof(appd_iot_data_t)); appd_iot_data_set_string(&resp_headers[0], "Pragma", "no-cache"); appd_iot_data_set_string(&resp_headers[1], "Transfer-Encoding", "chunked"); appd_iot_data_set_string(&resp_headers[2], "Expires", "0"); appd_iot_set_response_code(202); appd_iot_set_response_headers(resp_headers_count, resp_headers); appd_iot_clear_http_cb_triggered_flags(); retcode = appd_iot_send_all_events(); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //test if callbacks are triggered assert_that(appd_iot_is_http_req_send_cb_triggered(), is_equal_to(true)); assert_that(appd_iot_is_http_resp_done_cb_triggered(), is_equal_to(true)); appd_iot_clear_http_cb_triggered_flags(); free(resp_headers); free(error_event.stack_trace->stack_frame); free(error_event.stack_trace); free(error_event.data); //test for log write cb assert_that(appd_iot_is_log_write_cb_success(), is_equal_to(true)); } /** * @brief Unit Test for null error event */ Ensure(error_event, test_null_error_event) { appd_iot_sdk_config_t sdkcfg; appd_iot_device_config_t devcfg; appd_iot_error_code_t retcode; appd_iot_init_to_zero(&sdkcfg, sizeof(sdkcfg)); sdkcfg.appkey = TEST_APP_KEY; sdkcfg.eum_collector_url = TEST_EUM_COLLECTOR_URL; sdkcfg.log_write_cb = &appd_iot_log_write_cb; sdkcfg.log_level = APPD_IOT_LOG_ALL; devcfg.device_id = "1111"; devcfg.device_type = "SmartCar"; devcfg.device_name = "AudiS3"; devcfg.fw_version = "1.0"; devcfg.hw_version = "1.0"; devcfg.os_version = "1.0"; devcfg.sw_version = "1.0"; appd_iot_clear_log_write_cb_flags(); retcode = appd_iot_init_sdk(sdkcfg, devcfg); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_error_event_t error_event; appd_iot_init_to_zero(&error_event, sizeof(appd_iot_error_event_t)); //null error event name retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //zero stack traces error_event.name = "SIGINT1"; error_event.stack_trace_count = 0; retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //null stack traces error_event.name = "SIGINT2"; error_event.stack_trace_count = 1; error_event.stack_trace = NULL; retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //null error stack frame error_event.name = "SIGINT3"; error_event.error_stack_trace_index = 0; appd_iot_stack_trace_t* stack_trace = (appd_iot_stack_trace_t*)calloc(error_event.stack_trace_count, sizeof(appd_iot_stack_trace_t)); error_event.stack_trace = stack_trace; stack_trace->stack_frame_count = 1; stack_trace->stack_frame = NULL; stack_trace->thread = "main"; retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //zero error stack frame count error_event.name = "SIGINT4"; stack_trace->stack_frame_count = 0; stack_trace->thread = "libc"; retcode = appd_iot_add_error_event(error_event); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); free(stack_trace); appd_iot_http_cb_t http_cb; http_cb.http_req_send_cb = &appd_iot_test_http_req_send_cb; http_cb.http_resp_done_cb = &appd_iot_test_http_resp_done_cb; retcode = appd_iot_register_network_interface(http_cb); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); appd_iot_data_t* resp_headers = NULL; int resp_headers_count = 3; resp_headers = (appd_iot_data_t*)calloc(resp_headers_count, sizeof(appd_iot_data_t)); appd_iot_data_set_string(&resp_headers[0], "Pragma", "no-cache"); appd_iot_data_set_string(&resp_headers[1], "Transfer-Encoding", "chunked"); appd_iot_data_set_string(&resp_headers[2], "Expires", "0"); appd_iot_set_response_code(202); appd_iot_set_response_headers(resp_headers_count, resp_headers); appd_iot_clear_http_cb_triggered_flags(); retcode = appd_iot_send_all_events(); assert_that(retcode, is_equal_to(APPD_IOT_SUCCESS)); //test if callbacks are triggered assert_that(appd_iot_is_http_req_send_cb_triggered(), is_equal_to(true)); assert_that(appd_iot_is_http_resp_done_cb_triggered(), is_equal_to(true)); appd_iot_clear_http_cb_triggered_flags(); free(resp_headers); //test for log write cb assert_that(appd_iot_is_log_write_cb_success(), is_equal_to(true)); } TestSuite* error_event_tests() { TestSuite* suite = create_test_suite(); add_test_with_context(suite, error_event, test_full_alert_and_critical_error_event); add_test_with_context(suite, error_event, test_minimal_alert_and_critical_error_event); add_test_with_context(suite, error_event, test_full_fatal_error_event); add_test_with_context(suite, error_event, test_null_error_event); return suite; }
33.897826
103
0.775669
03118c8e46c7107e174c5ab5f0ed56b3ea4bdb6f
2,120
hh
C++
include/Prostokat.hh
KPO-2020-2021/zad3-mszleger
96479d275c42e534821f55ab889ae83e0316d0bb
[ "Unlicense" ]
null
null
null
include/Prostokat.hh
KPO-2020-2021/zad3-mszleger
96479d275c42e534821f55ab889ae83e0316d0bb
[ "Unlicense" ]
null
null
null
include/Prostokat.hh
KPO-2020-2021/zad3-mszleger
96479d275c42e534821f55ab889ae83e0316d0bb
[ "Unlicense" ]
null
null
null
#ifndef PROSTOKAT_HH #define PROSTOKAT_HH #include <iostream> #include <fstream> #include "Wektor2D.hh" #include "Macierz2x2.hh" #define ILOSCWIERZCHOLKOW 4 /** * Klasa modelująca prostokąt **/ class Prostokat { Wektor wierzcholek[ILOSCWIERZCHOLKOW]; // Tablica przechowująca współrzędne wierzchołków prostokąta (w kolejności w jakiej sąsiadują) // Zaprzyjaźnione funkcje friend std::ostream& operator << (std::ostream &Strm, const Prostokat &Pr); // Przeciążenie operatora wypisywania współrzędnych prostokąta public: // Konstruktory // Metody bool obroc(double kat); // Metoda obracająca prostokąt o dany kąt - zwraca true jeśli obrócono bool obroc(double kat, int ileRazy); // Metoda obracająca prostokąt o dany kąt, daną ilość razy - zwraca true jeśli obrócono bool przesun(const Wektor &wektor); // Metoda przesówająca prostokąt o dany wektor - zwraca true jeśli przesunięto void sprawdzBoki() const; // Metoda sprawdzająca, czy długości naprzeciwległych boków są takie same (wyświetla komunikaty) bool wczytaj(const std::string &nazwaPliku); // Metoda wczytująca wierzchołki prostokąta z danego pliku - zwraca true jeśli udało się wczytać bool zapisz(const std::string &nazwaPliku) const; // Metoda zapisująca wierzchołki prostokąta w danym pliku - zwraca true jeśli udało się zapisać // Przeciążenia operatorów Wektor& operator [] (int indeks); // Przeciążenie operatora indeksującego do odczytu i zapisu wartości wierzchołka bool operator == (const Prostokat &prostokat) const; // Przeciążenie operatora porównywania dwóch macierzy bool operator != (const Prostokat &prostokat) const; // Przeciążenie operatora zanegowanego porównywania dwóch macierzy }; std::ostream& operator << (std::ostream &Strm, const Prostokat &Pr); // Przeciążenie operatora wypisywania współrzędnych prostokąta #endif
57.297297
165
0.675
f1ff68da5603090fb71338fab35450060a8d1803
13,496
rb
Ruby
lib/jenkins/jenkins_neo4j.rb
glennsarti/JenkinsAggregator
70bc1e4c6783709fb0fa80f3e9fc453143b565d9
[ "Apache-2.0" ]
null
null
null
lib/jenkins/jenkins_neo4j.rb
glennsarti/JenkinsAggregator
70bc1e4c6783709fb0fa80f3e9fc453143b565d9
[ "Apache-2.0" ]
null
null
null
lib/jenkins/jenkins_neo4j.rb
glennsarti/JenkinsAggregator
70bc1e4c6783709fb0fa80f3e9fc453143b565d9
[ "Apache-2.0" ]
null
null
null
require 'neo4j-core' require 'base64' class PipelineAggregator::JenkinsNeo4j < PipelineAggregator::Base def initialize(config_data) @config_data = config_data # TODO Validate config file is correct end public def purge neo4j_session = get_session neo4j_session.query("MATCH ()-[r]-() DELETE r") neo4j_session.query("MATCH (n) DELETE n") end def purge_job_cache # Noop end def setup neo4j_session = get_session # Add jenkins masters # Use a standard sync-list pattern... cypher = "MATCH (j:jenkins) SET j.deleteme = 1;" ignore = neo4j_session.query(cypher) @config_data["jenkins_masters"].each do |master,data| cypher = "MERGE (j:jenkins {name:'#{master}', url: '#{data['server_url']}'}) WITH j REMOVE j.deleteme" ignore = neo4j_session.query(cypher) end cypher = "MATCH (j:jenkins) WHERE EXISTS(j.deleteme) WITH j OPTIONAL MATCH (j)-[r]-() DELETE r WITH j DELETE j" ignore = neo4j_session.query(cypher) # Add projects cypher = "MATCH (proj:project) SET proj.deleteme = 1;" ignore = neo4j_session.query(cypher) @config_data["projects"].each do |project| cypher = "MERGE (proj:project {name: '#{ project['name'] }'}) WITH proj REMOVE proj.deleteme" ignore = neo4j_session.query(cypher) end cypher = "MATCH (proj:project) WHERE EXISTS(proj.deleteme) WITH proj OPTIONAL MATCH (proj)-[r]-() DELETE r WITH proj DELETE proj" ignore = neo4j_session.query(cypher) # Cleanup orphaned jobs and builds cypher = "MATCH (b:build) WHERE (NOT (b)-[:JOB]->(:job)) WITH b OPTIONAL MATCH (b)-[r]-() DELETE r WITH b DELETE b" ignore = neo4j_session.query(cypher) end def cleanup neo4j_session = get_session # Remove the file parameter as it takes up too much space and isn't required cypher = "MATCH (j:job) WHERE EXISTS(j.file) REMOVE j.file" ignore = neo4j_session.query(cypher) cypher = "MATCH (b:build) WHERE EXISTS(b.file) AND NOT EXISTS(b.generation_attempts) REMOVE b.file" ignore = neo4j_session.query(cypher) end # PROJECT def compute_estimated_durations neo4j_session = get_session cypher = "MATCH (j:job) RETURN ID(j) AS JobID" results = neo4j_session.query(cypher) results.each do |result| cypher = "MATCH (j)<-[:JOB]-(b:build) WHERE ID(j) = #{result.JobID} AND b.estimatedDuration <> -1 WITH j,b ORDER BY b.timestamp DESC LIMIT 1 SET j.estimatedDuration = b.estimatedDuration" ignore = neo4j_session.query(cypher) end end # JOB def get_job(jenkins_master,jobname) neo4j_session = get_session job_id = job_unique_name(jenkins_master,jobname) cypher = "MATCH (j:job {uid:'#{job_id}'}) RETURN j.file AS value" result = neo4j_session.query(cypher) result.count == 0 ? nil : JSON.parse(Base64.decode64(result.first.value)) end def get_all_jobs neo4j_session = get_session results = neo4j_session.query("MATCH (j:job)-[:JENKINS]->(m:jenkins) RETURN j.name as JobName, m.name as JenkinsMaster") results.each do |result| value = { 'jenkins_master': result.JenkinsMaster, 'jobname': result.JobName } yield value end end def set_job(jenkins_master,jobname,value) neo4j_session = get_session job_id = job_unique_name(jenkins_master,jobname) valuetext = Base64.encode64(JSON.pretty_generate(value)) result = neo4j_session.query("MERGE (j:job {uid:'#{job_id}'}) SET j.file = '#{valuetext}', j.name = '#{jobname}'") unless value['aggregator'].nil? order = value['aggregator']['order'] implicit_params = value['aggregator']['implicit_build_graph_parameters'].join(';') versioning_params = value['aggregator']['versioning_build_parameters'].join(';') cypher = "MATCH (j:job {uid:'#{job_id}'}) WITH j OPTIONAL MATCH (j)-[r:PROJECT]->(:project) DELETE r WITH j OPTIONAL MATCH (j)-[r:BRANCH]->(:branch) DELETE r WITH j OPTIONAL MATCH (j)-[r:JENKINS]->(:jenkins) DELETE r WITH j MERGE (branch:branch {name: '#{value['aggregator']['branch']}'}) WITH j,branch MATCH (proj:project {name: '#{value['aggregator']['name']}'}) MATCH (jenkins:jenkins {name: '#{value['aggregator']['jenkins_master']}'}) CREATE (j)-[:PROJECT]->(proj) CREATE (j)-[:BRANCH]->(branch) CREATE (j)-[:JENKINS]->(jenkins) SET j.order = #{order} ,j.implicit_params = '#{implicit_params}' ,j.versioning_params = '#{versioning_params}' RETURN j.uid" result = neo4j_session.query(cypher) end end # BUILD def get_build_exists?(jenkins_master,jobname,buildnumber,ignore_jobs_that_are_building = false) neo4j_session = get_session build_id = build_unique_name(jenkins_master,jobname,buildnumber) cypher = "MATCH (b:build {uid:'#{build_id}'}) RETURN b.building AS building" result = neo4j_session.query(cypher) result.count == 0 ? false : !ignore_jobs_that_are_building || result.first.building != 'true' end def get_build(jenkins_master,jobname,buildnumber) neo4j_session = get_session build_id = build_unique_name(jenkins_master,jobname,buildnumber) cypher = "MATCH (b:build {uid:'#{build_id}'}) RETURN b.file AS value" result = neo4j_session.query(cypher) result.count == 0 ? nil : JSON.parse(Base64.decode64(result.first.value)) end def set_build(jenkins_master,jobname,buildnumber,value) neo4j_session = get_session build_id = build_unique_name(jenkins_master,jobname,buildnumber) job_id = job_unique_name(jenkins_master,jobname) valuetext = Base64.encode64(JSON.pretty_generate(value)) cypher = "MATCH (j:job {uid: '#{job_id}'}) RETURN j.implicit_params AS implicit_params, j.versioning_params AS versioning_params" job_details = neo4j_session.query(cypher) # Extract the job properties we need paramlist = job_details.first.implicit_params.split(';') + job_details.first.versioning_params.split(';') paramlist.uniq! buildparams = get_build_parameters_from_build(value,paramlist).map do |name,param_value| ",b.#{name} = '#{param_value}'" end # Get an approximation of the version of this build buildversion = '' get_build_parameters_from_build(value,job_details.first.versioning_params.split(';')).each do |name,param_value| buildversion = param_value unless buildversion != '' end result = neo4j_session.query("MERGE (b:build {uid:'#{build_id}'}) ON CREATE SET b.generation_attempts = 3 WITH b SET b.file = '#{valuetext}' ,b.buildnumber = '#{buildnumber}' #{buildparams.join} ,b.timestamp = '#{value['timestamp']}' ,b.buildversion = '#{buildversion}' ,b.building = '#{value['building']}' ,b.duration = '#{value['duration']}' ,b.result = '#{value['result']}' ,b.url = '#{value['url']}' ,b.estimatedDuration = '#{value['estimatedDuration']}' WITH b MATCH (j:job {uid:'#{job_id}'}) MERGE (b)-[:JOB]->(j) RETURN b.uid") end # Build Graph def generate_buildgraph neo4j_session = get_session # Pass 1 # All init jobs (order == 1) don't have an upstream so don't care log("Generating build graph - Pass 1") cypher = 'MATCH (b:build)-[:JOB]->(j:job) WHERE j.order = 1 AND exists(b.generation_attempts) RETURN b.uid AS BuildUID' results = neo4j_session.query(cypher) results.each do |result| this_buildUID = result.BuildUID log("Found a graph start node for #{this_buildUID}") ignore = neo4j_session.query("MATCH (b:build {uid:'#{this_buildUID}'}) REMOVE b.generation_attempts") end # Pass 2 # Builds may have an `actions/cause/upStreamCause` parameter, which happens when builds are triggered from other jobs (Explicit) log("Generating build graph - Pass 2") cypher = "MATCH (build:build)-[:JOB]->(job:job)-[:JENKINS]->(jenkins:jenkins) WHERE exists(build.generation_attempts) RETURN build,job.uid AS JobUID,jenkins.name AS JenkinsName ORDER BY build.timestamp ASC" results = neo4j_session.query(cypher) results.each do |result| this_buildUID = result.build['uid'] this_build = JSON.parse(Base64.decode64(result.build['file'])) upstreamJobname = nil upstreamBuildNumber = nil this_build['actions'].each do |action| unless action['causes'].nil? action['causes'].each do |cause| unless cause['upstreamProject'].nil? upstreamJobname = cause['upstreamProject'] upstreamBuildNumber = cause['upstreamBuild'] end end end end unless upstreamJobname.nil? upstreamBuildUID = build_unique_name(result.JenkinsName,upstreamJobname,upstreamBuildNumber) log("Found an upstream cause for build #{this_buildUID} of build #{upstreamBuildUID}") cypher = "MATCH (me:build {uid:'#{this_buildUID}'}) REMOVE me.generation_attempts WITH me MATCH (upstream:build {uid:'#{upstreamBuildUID}'}) CREATE (upstream)-[:STARTED_BUILD {type:'EXPLICIT'}]->(me)" ignore = neo4j_session.query(cypher) end end # Pass 3 # Look for builds within the same Job that have the same `implicit_build_graph_parameters` *AND* has an explicit upstream cause (Implicit) log("Generating build graph - Pass 3") cypher = "MATCH (build:build)-[:JOB]->(job:job)-[:JENKINS]->(jenkins:jenkins) WHERE exists(build.generation_attempts) RETURN build,job.uid AS JobUID,job.implicit_params AS ImplicitParams,jenkins.name AS JenkinsName ORDER BY build.timestamp ASC" results = neo4j_session.query(cypher) results.each do |result| this_buildID = result.build.neo_id this_buildUID = result.build['uid'] params_to_check = [] result.ImplicitParams.split(';').each do |paramname| params_to_check << "this.#{paramname} = same.#{paramname}" end cypher = "MATCH (this:build)-[:JOB]->(:job)<-[:JOB]-(same:build)<-[:STARTED_BUILD {type:'EXPLICIT'}]-(upstream:build) WHERE ID(this) = #{this_buildID} AND #{params_to_check.join(' AND ')} RETURN ID(upstream) AS UpstreamID, upstream.uid AS UpstreamUID ORDER BY same.timestamp DESC LIMIT 1" implicit = neo4j_session.query(cypher) if implicit.count == 1 log("Found an implicit cause for build #{this_buildUID} of build #{implicit.first.UpstreamUID}") cypher = "MATCH (me) WHERE ID(me) = #{this_buildID} MATCH (upstream) WHERE ID(upstream) = #{implicit.first.UpstreamID} CREATE (upstream)-[:STARTED_BUILD {type:'IMPLICIT'}]->(me) WITH me REMOVE me.generation_attempts" ignore = neo4j_session.query(cypher) end end # Pass Final # Decrement generation_attempts. Any attempts <= 0 are marked as un-resolvable log("Generating build graph - Pass Final") cypher = "MATCH (build:build) WHERE exists(build.generation_attempts) SET build.generation_attempts = build.generation_attempts - 1" ignore = neo4j_session.query(cypher) cypher = "MATCH (build:build) WHERE exists(build.generation_attempts) AND build.generation_attempts <= 0 REMOVE build.generation_attempts" ignore = neo4j_session.query(cypher) true end private def get_session if @this_session.nil? @this_session = Neo4j::Session.open(:server_db, @config_data['neo4j']['uri'], { basic_auth: { username: @config_data['neo4j']['username'], password: @config_data['neo4j']['password'] } }) end @this_session end # private def job_unique_name(jenkins_master,jobname) "#{jenkins_master}_#{jobname}" end def build_unique_name(jenkins_master,jobname,buildnumber) "#{jenkins_master}_#{jobname}_#{buildnumber}" end def get_build_parameters_from_build(build, filter = nil) buildparams = {} unless build['actions'].nil? build['actions'].each do |action| unless action['parameters'].nil? action['parameters'].each do |param| if filter.nil? || filter.include?(param['name']) buildparams[param['name']] = param['value'] end end end end end buildparams end end
37.803922
145
0.60981
b739eb66a555bfff0b34e91c1b041133a2a1322c
1,121
cpp
C++
src/main.cpp
tomazas/open-bomber
ddbcbd701f1440acb579f8927dee02701dc44b7c
[ "MIT" ]
null
null
null
src/main.cpp
tomazas/open-bomber
ddbcbd701f1440acb579f8927dee02701dc44b7c
[ "MIT" ]
null
null
null
src/main.cpp
tomazas/open-bomber
ddbcbd701f1440acb579f8927dee02701dc44b7c
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------ // Open-bomber - open-source online bomberman remake // ------------------------------------------------------------------ #include "Elf.h" #include "ElfExtra.h" #include "game.h" #pragma comment(lib, "Elf2D.lib") #pragma comment(lib, "winmm.lib") Game* game = NULL; void myGameUpdate(const float deltaTime) { game->GameUpdate(deltaTime); } // ------------------------------------------------------------------ void myGameRender(const float deltaTime) { game->GameRender(); } //----------------------------------------------------------------------------- void myGameShutDown() { game->GameShutdown(); } // ------------------------------------------------------------------ int main(int argc, char* argv[]) { elfConfig_SetUpdateCallback(myGameUpdate); elfConfig_SetRenderCallback(myGameRender); elfConfig_SetShutdownCallback(myGameShutDown); if (elfSystem_Initialise()) { game = new Game(); elfSystem_Run(); delete game; game = NULL; elfSystem_Shutdown(); } return 0; }
22.877551
80
0.457627
f050210662cbaf973098b267cb9680a7b1ba2f0b
506
go
Go
01-Variable/var.go
Mixko50/Learn-GoLang
26ba3adfd8c23e3f08e8d6be02f55f77796ce47e
[ "MIT" ]
null
null
null
01-Variable/var.go
Mixko50/Learn-GoLang
26ba3adfd8c23e3f08e8d6be02f55f77796ce47e
[ "MIT" ]
null
null
null
01-Variable/var.go
Mixko50/Learn-GoLang
26ba3adfd8c23e3f08e8d6be02f55f77796ce47e
[ "MIT" ]
null
null
null
package main import "fmt" var ( actor string = "Mixko" geo string = "Geo" number1 int = 1 season float32 = .3 ) const ( yu string = "Hello" te string = "World" op int = 50 ) func main() { fmt.Println("Hello") var i int i = 50 k := 99 //Can't re assignment var t float32 = 5.5978 var convert int convert = int(t) fmt.Println(convert) println(i, k, t) fmt.Printf("%v, %T", i, i) fmt.Println(actor) fmt.Println(yu, te, op) fmt.Println(actor, geo, number1, season) }
14.055556
41
0.608696
977acf9304d66b08424594379e8808256cd4b945
158
rb
Ruby
lib/output/text.rb
ssoroka/grepmate
6b175a39a31f1ac43f31433e625c96c34fc9b8cf
[ "MIT" ]
1
2016-05-08T18:35:36.000Z
2016-05-08T18:35:36.000Z
lib/output/text.rb
ssoroka/grepmate
6b175a39a31f1ac43f31433e625c96c34fc9b8cf
[ "MIT" ]
null
null
null
lib/output/text.rb
ssoroka/grepmate
6b175a39a31f1ac43f31433e625c96c34fc9b8cf
[ "MIT" ]
null
null
null
module Output class Text def initialize(grepmate) @grepmate = grepmate end def process puts @grepmate.results end end end
14.363636
28
0.626582
d9a1cc6c1ed788ed971a712ae9b103d77af0b91c
161
swift
Swift
Sources/Models/Platform.swift
TICESoftware/TICE-SwiftModels
72cb6add59e5ef4156bea0aed8a5591459489085
[ "MIT" ]
null
null
null
Sources/Models/Platform.swift
TICESoftware/TICE-SwiftModels
72cb6add59e5ef4156bea0aed8a5591459489085
[ "MIT" ]
null
null
null
Sources/Models/Platform.swift
TICESoftware/TICE-SwiftModels
72cb6add59e5ef4156bea0aed8a5591459489085
[ "MIT" ]
null
null
null
// // Copyright © 2019 Anbion. All rights reserved. // import Foundation public enum Platform: String, Codable { case iOS case android case web }
13.416667
49
0.670807
364b306495d7d4936efa56daed17a1e1abbbf71d
4,241
lua
Lua
Client/Spec.lua
vugi99/nanos-vzombies
7aaf33a474cd1947c9bc12b93ebe238aefce1c7d
[ "Unlicense" ]
4
2021-11-17T22:04:49.000Z
2022-03-08T17:29:32.000Z
Client/Spec.lua
vugi99/nanos-vzombies
7aaf33a474cd1947c9bc12b93ebe238aefce1c7d
[ "Unlicense" ]
null
null
null
Client/Spec.lua
vugi99/nanos-vzombies
7aaf33a474cd1947c9bc12b93ebe238aefce1c7d
[ "Unlicense" ]
null
null
null
Spectating_Player = nil function GetResetPlyID(old_ply_id, prev_ply) local selected_ply_id local selected_ply for k, v in pairs(Player.GetPairs()) do if not v.BOT then if v ~= Client.GetLocalPlayer() then if v:GetID() ~= old_ply_id then local char = v:GetControlledCharacter() if char then if (not selected_ply_id or ((v:GetID() < selected_ply_id and not prev_ply) or (v:GetID() > selected_ply_id and prev_ply))) then selected_ply_id = v:GetID() selected_ply = v end end end end end end return selected_ply end function GetNewPlayerToSpec(old_ply_id, prev_ply) old_ply_id = old_ply_id or 0 local new_ply local new_ply_id for k, v in pairs(Player.GetPairs()) do if not v.BOT then if v ~= Client.GetLocalPlayer() then local char = v:GetControlledCharacter() if char then if (((v:GetID() > old_ply_id and not new_ply_id and not prev_ply) or (v:GetID() < old_ply_id and not new_ply_id and prev_ply)) or (((v:GetID() > old_ply_id and not prev_ply) or (v:GetID() < old_ply_id and prev_ply)) and ((new_ply_id > v:GetID() and not prev_ply) or (new_ply_id < v:GetID() and prev_ply)))) then new_ply = v new_ply_id = v:GetID() end end end end end if not new_ply then new_ply = GetResetPlyID(old_ply_id, prev_ply) end return new_ply end function IsSpectatingPlayerCharacter(char) if Spectating_Player then local spec_char = Spectating_Player:GetControlledCharacter() if spec_char == char then return true end end end function SpectatePlayer(to_spec) if to_spec then Client.GetLocalPlayer():Spectate(to_spec) Spectating_Player = to_spec local char = Spectating_Player:GetControlledCharacter() local picked = char:GetPicked() if picked then NeedToUpdateAmmoText(char, picked) end One_Time_Updates_Canvas:Repaint() end end function StopSpectate() Client.GetLocalPlayer():ResetCamera() Spectating_Player = nil One_Time_Updates_Canvas:Repaint() end VZ_EVENT_SUBSCRIBE("Player", "Possess", function(ply, char) --print("Player Possess") if ply == Client.GetLocalPlayer() then StopSpectate() elseif (not Spectating_Player and not Client.GetLocalPlayer():GetControlledCharacter()) then local new_spec = GetNewPlayerToSpec() SpectatePlayer(new_spec) end end) VZ_EVENT_SUBSCRIBE("Player", "UnPossess", function(ply, char) --print("Player UnPossess", ply, char) if ply == Client.GetLocalPlayer() then local new_spec = GetNewPlayerToSpec() --print("new_spec, unpossess", new_spec) SpectatePlayer(new_spec) elseif ply == Spectating_Player then local new_spec = GetNewPlayerToSpec() if new_spec then SpectatePlayer(new_spec) else StopSpectate() end end end) VZ_EVENT_SUBSCRIBE("Player", "Destroy", function(ply) --print("Player Destroy") if ply == Spectating_Player then local new_spec = GetNewPlayerToSpec() if new_spec then SpectatePlayer(new_spec) else StopSpectate() end end end) if not Client.GetLocalPlayer():GetControlledCharacter() then local new_spec = GetNewPlayerToSpec() --print("new_spec", new_spec) SpectatePlayer(new_spec) end Input.Register("SpectatePrev", "Left") Input.Register("SpectateNext", "Right") VZ_BIND("SpectatePrev", InputEvent.Pressed, function() if Spectating_Player then local new_spec = GetNewPlayerToSpec(Spectating_Player:GetID(), true) SpectatePlayer(new_spec) end end) VZ_BIND("SpectateNext", InputEvent.Pressed, function() if Spectating_Player then local new_spec = GetNewPlayerToSpec(Spectating_Player:GetID()) SpectatePlayer(new_spec) end end)
30.292857
331
0.626975
233ad2df22ad3c39ffb63510bb89820c4a5a4275
244
css
CSS
src/navBar/NavBar.module.css
thepuskar/yelp-clone
3b4418380624d432405c0a8c2666d8830b8a8602
[ "MIT" ]
3
2020-07-31T13:44:45.000Z
2021-01-19T06:39:50.000Z
src/navBar/NavBar.module.css
devpuskar/yelp-clone
3b4418380624d432405c0a8c2666d8830b8a8602
[ "MIT" ]
null
null
null
src/navBar/NavBar.module.css
devpuskar/yelp-clone
3b4418380624d432405c0a8c2666d8830b8a8602
[ "MIT" ]
1
2022-01-17T00:06:02.000Z
2022-01-17T00:06:02.000Z
.navBar { display: flex; background-color: #d32323; padding: 1rem 0; align-items: center; justify-content: center; } .logo { width: 75px; margin-right: 1rem; } :global(.button).nav-button { margin-left: 1rem; }
15.25
30
0.610656
e702dc1fedc757a461a24a44611dd26f779d228b
1,432
php
PHP
Factory/DoctrineOrmPaginatorFactory.php
dimmir/RestPaginatorBundle
07512e461440ecc156cc50712cc252c8b0526298
[ "MIT" ]
1
2018-02-11T16:23:38.000Z
2018-02-11T16:23:38.000Z
Factory/DoctrineOrmPaginatorFactory.php
dimmir/RestPaginatorBundle
07512e461440ecc156cc50712cc252c8b0526298
[ "MIT" ]
1
2017-08-09T19:48:46.000Z
2017-08-09T19:48:46.000Z
Factory/DoctrineOrmPaginatorFactory.php
dimmir/PaginatorBundle
07512e461440ecc156cc50712cc252c8b0526298
[ "MIT" ]
null
null
null
<?php namespace DMR\Bundle\PaginatorBundle\Factory; use DMR\Bundle\PaginatorBundle\Exception\RuntimeException; use DMR\Bundle\PaginatorBundle\Pagination\RequestParameters; use DMR\Bundle\PaginatorBundle\Paginator\DoctrineOrmPaginator; use DMR\Bundle\PaginatorBundle\Paginator\PaginatorInterface; use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\Tools\Pagination\Paginator; class DoctrineOrmPaginatorFactory implements PaginatorFactoryInterface { /** * @param QueryBuilder $target * @param RequestParameters $requestParameters * @param array $options * @return PaginatorInterface */ public function create($target, RequestParameters $requestParameters, array $options = []): PaginatorInterface { if (empty($requestParameters->getCurrentPage()) || empty($requestParameters->getItemsPerPage())) { throw new RuntimeException('CurrentPage or ItemsPerPage parameters are empty for RequestParameters instance'); } $target ->setFirstResult(($requestParameters->getCurrentPage() - 1) * $requestParameters->getItemsPerPage()) ->setMaxResults($requestParameters->getItemsPerPage()); $doctrinePaginator = new Paginator($target, $options['fetch_join_collection'] ?? true); return new DoctrineOrmPaginator($doctrinePaginator); } public function getTargetClass(): string { return QueryBuilder::Class; } }
36.717949
122
0.734637
db7c8958620cf45e9dc4055c9186f44096e1392f
1,451
php
PHP
resources/views/powernode/list.blade.php
lixingxuan246/1911admin1
fc6dc1ed140f4faf786323f7e54f849b2fd5f427
[ "MIT" ]
null
null
null
resources/views/powernode/list.blade.php
lixingxuan246/1911admin1
fc6dc1ed140f4faf786323f7e54f849b2fd5f427
[ "MIT" ]
null
null
null
resources/views/powernode/list.blade.php
lixingxuan246/1911admin1
fc6dc1ed140f4faf786323f7e54f849b2fd5f427
[ "MIT" ]
null
null
null
@extends('shou.index') @section('content') <table class="layui-table"> <colgroup> <col width="150"> <col width="200"> <col> </colgroup> <thead> <tr> <th>ID</th> <th>节点名称</th> <th>节点路径</th> <th>父级节点</th> <th>是否启用</th> <th>时间</th> <th>操作</th> </tr> </thead> @foreach($power_info as $k=>$v) <tbody> <tr> <td>{{$v->power_node_id}}</td> <td>{{$v->power_node_name}}</td> <td>{{$v->power_node_level}}</td> <td>{{$v->power_node_url}}</td> <td>{{$v->status==1?'√':'×'}}</td> <td>{{date('Y-m-d H:i:s',$v->ctime)}}</td> <td>{{--}}<a href="{{url('/powernode/auth/'.$v->power_node_id)}}" class="btn btn-success">编辑</a>--}} <a href="{{url('/powernode/destroy/'.$v->power_node_id)}}" class="btn btn-info">删除</a> </td> </tr> @endforeach </tbody> </table> {{$power_info->links()}} <div style="margin-top: 10px"></div> <table id="demo" lay-filter="test"></table> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a> <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> </script> @endsection
29.02
112
0.464507
52276f617171eb8650f617fa1dea856240313edb
1,905
lua
Lua
scripts/paint_bucket.lua
iamOgunyinka/tests
522825129820a2b0822980509540e1830fd76bea
[ "MIT" ]
2
2018-11-04T09:49:34.000Z
2020-07-20T23:07:01.000Z
scripts/paint_bucket.lua
iamOgunyinka/tests
522825129820a2b0822980509540e1830fd76bea
[ "MIT" ]
4
2021-09-23T18:03:15.000Z
2021-12-15T18:09:42.000Z
scripts/paint_bucket.lua
iamOgunyinka/tests
522825129820a2b0822980509540e1830fd76bea
[ "MIT" ]
3
2018-08-13T07:07:52.000Z
2021-09-20T10:08:39.000Z
-- Copyright (C) 2020-2021 Igara Studio S.A. -- -- This file is released under the terms of the MIT license. -- Read LICENSE.txt for more information. dofile('./test_utils.lua') app.activeTool = 'paint_bucket' assert(app.activeTool.id == 'paint_bucket') assert(app.activeBrush.type == BrushType.CIRCLE) assert(app.activeBrush.size == 1) assert(app.activeBrush.angle == 0) assert(app.preferences.tool('paint_bucket').floodfill.pixel_connectivity == 0) local function test_paint_bucket(colorMode, a, b, c) local spr = Sprite(4, 4, colorMode) local img = app.activeImage array_to_pixels({ a, a, a, a, a, b, b, a, a, a, b, a, a, a, a, b, }, img) app.useTool{ points={Point(0, 0)}, color=b } expect_img(img, { b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, }) app.undo() -- FOUR_CONNECTED=0 app.preferences.tool('paint_bucket').floodfill.pixel_connectivity = 0 assert(app.preferences.tool('paint_bucket').floodfill.pixel_connectivity == 0) app.useTool{ points={Point(1, 1)}, color=c } expect_img(img, { a, a, a, a, a, c, c, a, a, a, c, a, a, a, a, b, }) app.undo() -- EIGHT_CONNECTED=1 app.preferences.tool('paint_bucket').floodfill.pixel_connectivity = 1 assert(app.preferences.tool('paint_bucket').floodfill.pixel_connectivity == 1) app.useTool{ points={Point(1, 1)}, color=c } expect_img(img, { a, a, a, a, a, c, c, a, a, a, c, a, a, a, a, c, }) end local rgba = app.pixelColor.rgba local gray = app.pixelColor.graya test_paint_bucket(ColorMode.RGB, rgba(0, 0, 0), rgba(128, 128, 128), rgba(255, 255, 255)) test_paint_bucket(ColorMode.GRAYSCALE, gray(0), gray(128), gray(255)) test_paint_bucket(ColorMode.INDEXED, 1, 2, 3)
34.017857
89
0.595276
0dbb9b6548cedde6b1eb97ba17dd9fcfd09ef172
916
cshtml
C#
src/Payments.Emails/Views/Shared/_Layout.cshtml
ucdavis/payments
c9ee57801f1f51c7605cbcf646b2dfa5d9405671
[ "MIT" ]
null
null
null
src/Payments.Emails/Views/Shared/_Layout.cshtml
ucdavis/payments
c9ee57801f1f51c7605cbcf646b2dfa5d9405671
[ "MIT" ]
130
2016-11-30T17:33:10.000Z
2022-02-17T22:26:35.000Z
src/Payments.Emails/Views/Shared/_Layout.cshtml
ucdavis/payments
c9ee57801f1f51c7605cbcf646b2dfa5d9405671
[ "MIT" ]
null
null
null
@using Payments.Core.Domain @using RazorLight @inherits TemplatePage<dynamic> @{ var team = (Team) ViewBag.Team; } <mjml lang="en-us"> <mj-head> </mj-head> <mj-body background-color="#fff"> <mj-section padding-top="0" background-color="#f3f3f3"> <mj-column padding="0"> <mj-image padding="0 0 20px 0" height="50px" src="https://ucdpayment.blob.core.windows.net/email-assets/gradient.png" /> @RenderBody() </mj-column> </mj-section> <mj-section> <mj-column> <mj-text align="center"> <p>If you have any questions, contact us at <a href="mailto:@team.ContactEmail">@team.ContactEmail</a> or call at <a href="tel:@team.ContactPhoneNumber">@team.ContactPhoneNumber</a></p> </mj-text> </mj-column> </mj-section> </mj-body> </mjml>
27.757576
205
0.561135
d9fdfbe33e1ec76f66ecc92a5b9d5a79c2128b9e
549
sql
SQL
ADHDatabaseProject/dbo/Stored Procedures/spTestRequests_AddNewRequest.sql
AhmedDuraid/ADH-Medical-System
fd47cec5dc71d72b6d0ad8274398005f7c6996b6
[ "MIT" ]
null
null
null
ADHDatabaseProject/dbo/Stored Procedures/spTestRequests_AddNewRequest.sql
AhmedDuraid/ADH-Medical-System
fd47cec5dc71d72b6d0ad8274398005f7c6996b6
[ "MIT" ]
null
null
null
ADHDatabaseProject/dbo/Stored Procedures/spTestRequests_AddNewRequest.sql
AhmedDuraid/ADH-Medical-System
fd47cec5dc71d72b6d0ad8274398005f7c6996b6
[ "MIT" ]
null
null
null
-- ============================================= -- Author: dbo -- Create date: 2020-10-16 -- Description: AddNew request -- ============================================= CREATE PROCEDURE spTestRequests_AddNewRequest @Id nvarchar(128) ,@PatientId nvarchar(128) ,@TestId nvarchar(128) ,@CreatorID nvarchar(128) AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[TestRequests] ([Id] ,[Date] ,[PatientId] ,[TestId] ,[CreatorID]) VALUES (@Id ,GETDATE() ,@PatientId ,@TestId ,@CreatorID ) END
18.931034
49
0.510018
1993c0e0b3bbcd26c9ae571e4b192f650e050b00
385
dart
Dart
lib/gateway/data/model/remote/weather_data.dart
bowyer-app/weather-station-flutter
da8028889242af1ab50431e075e0c2cf57fa1ab2
[ "MIT" ]
6
2021-06-06T10:52:30.000Z
2022-03-08T14:54:59.000Z
lib/gateway/data/model/remote/weather_data.dart
bowyer-app/weather-station-flutter
da8028889242af1ab50431e075e0c2cf57fa1ab2
[ "MIT" ]
8
2021-06-04T13:01:08.000Z
2022-03-21T18:15:51.000Z
lib/gateway/data/model/remote/weather_data.dart
bowyer-app/weather-station-flutter
da8028889242af1ab50431e075e0c2cf57fa1ab2
[ "MIT" ]
null
null
null
import 'package:freezed_annotation/freezed_annotation.dart'; part 'weather_data.freezed.dart'; part 'weather_data.g.dart'; @freezed class WeatherData with _$WeatherData { factory WeatherData( {@Default("") String description, @Default("") String icon}) = _WeatherData; factory WeatherData.fromJson(Map<String, dynamic> json) => _$WeatherDataFromJson(json); }
24.0625
60
0.72987
964dee5d71f46251d086244f1f758b020f58de56
1,310
dart
Dart
lib/ui/pages/list_category_page/components/app_bar.dart
agusprayogi02/flu-indomic
0b62595f2868a2db515a2aa729719e0bda3696e5
[ "MIT" ]
null
null
null
lib/ui/pages/list_category_page/components/app_bar.dart
agusprayogi02/flu-indomic
0b62595f2868a2db515a2aa729719e0bda3696e5
[ "MIT" ]
null
null
null
lib/ui/pages/list_category_page/components/app_bar.dart
agusprayogi02/flu-indomic
0b62595f2868a2db515a2aa729719e0bda3696e5
[ "MIT" ]
1
2021-06-21T16:03:32.000Z
2021-06-21T16:03:32.000Z
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:indomic/controllers/list_category_controller.dart'; import 'package:indomic/ui/utils/utils.dart'; AppBar buildAppBar() { return AppBar( elevation: 0, backgroundColor: lightPrimaryC.withOpacity(0.8), title: Text( "daftar_komic".tr, style: TextStyle(color: blackC, fontWeight: FontWeight.w700), ), bottom: PreferredSize( preferredSize: Size(Get.width, 50), child: Padding( padding: EdgeInsets.symmetric( horizontal: defaultPadding * 2, vertical: defaultPadding, ), child: TabBar( labelColor: textC, unselectedLabelColor: blackC, indicatorSize: TabBarIndicatorSize.tab, indicator: BoxDecoration( color: primaryC, borderRadius: borderRadiusAll(), ), onTap: ListCategoryController.to.onSwich, labelStyle: TextStyle( fontSize: 16, fontFamily: "Poppins", ), tabs: [ Tab( text: "semua".tr, ), Tab( text: "Manhua", ), Tab( text: "Manhwa", ), ], ), ), ), ); }
26.2
67
0.540458
39171033648d5e97ba961743028825223e0906a7
1,152
lua
Lua
Test/TestNILModule.lua
jpbubble/NIL-isn-t-Lua
47ffccd02696ef1ef1638ebb70a9b4416a4ed0f2
[ "MIT" ]
2
2020-07-29T06:23:31.000Z
2020-08-03T22:39:38.000Z
Test/TestNILModule.lua
jpbubble/NIL-isn-t-Lua
47ffccd02696ef1ef1638ebb70a9b4416a4ed0f2
[ "MIT" ]
50
2019-04-30T16:23:50.000Z
2019-09-13T08:16:10.000Z
Test/TestNILModule.lua
jpbubble/NIL-isn-t-Lua
47ffccd02696ef1ef1638ebb70a9b4416a4ed0f2
[ "MIT" ]
1
2019-05-08T20:16:01.000Z
2019-05-08T20:16:01.000Z
--[[ *********************************************************** TestNILModule.lua This particular file has been released in the public domain and is therefore free of any restriction. You are allowed to credit me as the original author, but this is not required. This file was setup/modified in: If the law of your country does not support the concept of a product being released in the public domain, while the original author is still alive, or if his death was not longer than 70 years ago, you can deem this file "(c) Jeroen Broks - licensed under the CC0 License", with basically comes down to the same lack of restriction the public domain offers. (YAY!) *********************************************************** Version 19.05.14 ]] local NILCode = [[ module TestMe int a = 1 int b = 2 void Hi() print("Hello world") end end print("Let's test this out!") ]] local NIL=require "NIL" local NILTrans = NIL.Translate(NILCode,"NILCode") print("Original:\n"..NILCode,"\n\nTranslation:\n"..NILTrans) print("Executing transation!") local l = loadstring(NILTrans,"Translation") local tm = l().NEW() print(tm.a,tm.b) tm.Hi()
20.210526
60
0.652778
2b65a6214d4cdd3d0a98bda890ae6a4ce7d781c6
2,945
rb
Ruby
app/controllers/admin/offerings/restrictions/exemptions_controller.rb
uwexpd/expo
17315640d6db7bcbbf0e6f9c275b9194ac1bbe8f
[ "Unlicense" ]
null
null
null
app/controllers/admin/offerings/restrictions/exemptions_controller.rb
uwexpd/expo
17315640d6db7bcbbf0e6f9c275b9194ac1bbe8f
[ "Unlicense" ]
1
2020-07-15T21:53:05.000Z
2020-07-15T21:53:05.000Z
app/controllers/admin/offerings/restrictions/exemptions_controller.rb
uwexpd/expo
17315640d6db7bcbbf0e6f9c275b9194ac1bbe8f
[ "Unlicense" ]
1
2019-10-02T11:12:58.000Z
2019-10-02T11:12:58.000Z
class Admin::Offerings::Restrictions::ExemptionsController < Admin::Offerings::RestrictionsController before_filter :fetch_restriction before_filter :add_exemptions_breadcrumbs def index @exemptions = @restriction.exemptions.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @exemptions } end end def show @exemption = @restriction.exemptions.find(params[:id]) session[:breadcrumbs].add "#{@exemption.id}" respond_to do |format| format.html # show.html.erb format.xml { render :xml => @exemption } end end def new @exemption = @restriction.exemptions.new session[:breadcrumbs].add "New" respond_to do |format| format.html # new.html.erb format.xml { render :xml => @exemption } end end def create @exemption = @restriction.exemptions.new(params[:exemption]) respond_to do |format| if @exemption.save flash[:notice] = "Successfully created exemption." format.html { redirect_to offering_restriction_exemptions_path(@offering, @restriction) } format.xml { render :xml => @exemption, :status => :created, :location => offering_restriction_exemptions_path(@offering, @restriction) } else format.html { render :action => "new" } format.xml { render :xml => @exemption.errors, :status => :unprocessable_entity } end end end def edit @exemption = @restriction.exemptions.find(params[:id]) session[:breadcrumbs].add "#{@exemption.id}", offering_restriction_exemptions_path(@offering, @restriction) session[:breadcrumbs].add "Edit" end def update @exemption = @restriction.exemptions.find(params[:id]) respond_to do |format| if @exemption.update_attributes(params[:exemption]) flash[:notice] = "Successfully updated exemption." format.html { redirect_to offering_restriction_exemptions_path(@offering, @restriction) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @exemption.errors, :status => :unprocessable_entity } end end end def destroy @exemption = @restriction.exemptions.find(params[:id]) @exemption.destroy flash[:notice] = "Successfully destroyed exemption." respond_to do |format| format.html { redirect_to offering_restriction_exemptions_url(@offering, @restriction) } format.xml { head :ok } format.js end end protected def fetch_restriction @restriction = @offering.restrictions.find params[:restriction_id] session[:breadcrumbs].add "#{@restriction.title}", offering_restriction_path(@offering, @restriction) end def add_exemptions_breadcrumbs session[:breadcrumbs].add "Exemptions", offering_restriction_exemptions_path(@offering, @restriction) end end
31
111
0.675042
ec253a6b9ccff5840ede9b140c69d504c1eff0e4
735
rb
Ruby
lib/soulmate/matcher.rb
jwarchol/soulmate-goliath
879586747018d4ac5d0f78ecf2b1a57ec3e84621
[ "MIT" ]
2
2015-11-05T05:23:08.000Z
2019-05-14T11:59:31.000Z
lib/soulmate/matcher.rb
jwarchol/soulmate-goliath
879586747018d4ac5d0f78ecf2b1a57ec3e84621
[ "MIT" ]
null
null
null
lib/soulmate/matcher.rb
jwarchol/soulmate-goliath
879586747018d4ac5d0f78ecf2b1a57ec3e84621
[ "MIT" ]
null
null
null
module Soulmate class Matcher < Base def matches_for_term(term, options = {}) words = normalize(term).split(' ').reject do |w| w.size < MIN_COMPLETE or STOP_WORDS.include?(w) end.sort options[:limit] ||= 5 cachekey = "#{cachebase}:" + words.join('|') if !Soulmate.redis.exists(cachekey) interkeys = words.map { |w| "#{base}:#{w}" } Soulmate.redis.zinterstore(cachekey, interkeys.size, interkeys.join) Soulmate.redis.expire(cachekey, 60 * 60 * 10) # expire after 10 minutes end ids = Soulmate.redis.zrevrange(cachekey, 0, options[:limit] - 1) ids.size > 0 ? Soulmate.redis.hmget(database, *ids).map { |r| JSON.parse(r) } : [] end end end
29.4
88
0.609524
79a06129e1a4e8f9e9f8d753888b65ce029de2dd
2,301
php
PHP
resources/views/admin/products/index.blade.php
weihong19971222/nintendo
ca6dcbd0d2eea23652cac677a02ac8c481d2d4e1
[ "MIT" ]
null
null
null
resources/views/admin/products/index.blade.php
weihong19971222/nintendo
ca6dcbd0d2eea23652cac677a02ac8c481d2d4e1
[ "MIT" ]
null
null
null
resources/views/admin/products/index.blade.php
weihong19971222/nintendo
ca6dcbd0d2eea23652cac677a02ac8c481d2d4e1
[ "MIT" ]
null
null
null
@extends('layouts/app2') @section('css') <link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css"> @endsection @section('content') <a class="btn btn-info mb-3" href="/admin/products/create">新增商品</a> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>商品名稱</th> <th>商品圖片</th> <th>商品類別</th> <th>商品價錢</th> <th>商品資訊</th> <th>商品庫存</th> <th>商品上架日期</th> <th>排序</th> <th>功能</th> </tr> </thead> <tbody> @foreach ($products as $product) <tr> <td>{{$product->products_name}}</td> <td><img src="{{$product->products_image}}" width="100px" alt=""></td> <td>{{$product->products_type}}</td> <td>{{$product->products_price}}</td> <td>{{$product->products_info}}</td> <td>{{$product->products_quantity}}</td> <td>{{$product->created_at}}</td> <td>{{$product->sort}}</td> <td style="width: 100px"> <a href="/admin/products/{{$product->id}}/edit" class="btn btn-sm btn-secondary">編輯</a> <button data-ptid="{{$product->id}}" class="btn btn-sm btn btn-danger btn-del">刪除</button> <form id="del-form-{{$product->id}}" action="/admin/products/{{$product->id}}" method="POST" style="display: none;"> @csrf @method('DELETE') </form> </td> </tr> @endforeach </tbody> </table> @endsection @section('js') <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script> <script> $(document).ready(function() { $('#example').DataTable(); $('#example').on("click",".btn-del",function(){ var r=confirm("確認是否刪除"); if(r==true){ $("#del-form-"+$(this).attr('data-ptid')).submit(); } }); } ); </script> @endsection
35.4
136
0.480661
7027cdbb9be5fdb17bab6135670339352cb93e72
1,100
lua
Lua
game/dota_addons/dota_imba_reborn/scripts/vscripts/components/hero_selection.lua
EarthSalamander42/dota_imba
3be7127094e3752bcd8630145a669811675b7949
[ "Apache-2.0" ]
105
2018-07-10T11:53:23.000Z
2022-03-31T21:00:27.000Z
game/dota_addons/dota_imba_reborn/scripts/vscripts/components/hero_selection.lua
EarthSalamander42/dota_imba
3be7127094e3752bcd8630145a669811675b7949
[ "Apache-2.0" ]
52
2018-08-14T09:18:49.000Z
2021-09-22T12:24:36.000Z
game/dota_addons/dota_imba_reborn/scripts/vscripts/components/hero_selection.lua
EarthSalamander42/dota_imba
3be7127094e3752bcd8630145a669811675b7949
[ "Apache-2.0" ]
34
2018-08-06T20:32:59.000Z
2022-03-31T14:20:11.000Z
if not HeroSelection then HeroSelection = class({}) HeroSelection.herolist = {} HeroSelection.imbalist = {} end ListenToGameEvent('game_rules_state_change', function() if GameRules:State_Get() == DOTA_GAMERULES_STATE_HERO_SELECTION then HeroSelection:Init() end end, nil) function HeroSelection:Init() local herolistFile = "scripts/npc/activelist.txt" for key,value in pairs(LoadKeyValues(herolistFile)) do if KeyValues.HeroKV[key] == nil then -- Cookies: If the hero is not in custom file, load vanilla KV's -- print(key .. " is not in custom file!") local data = LoadKeyValues("scripts/npc/npc_heroes.txt") if data and data[key] then KeyValues.HeroKV[key] = data[key] end end HeroSelection.herolist[key] = KeyValues.HeroKV[key].AttributePrimary if KeyValues.HeroKV[key].IsImba == 1 then HeroSelection.imbalist[key] = 1 end assert(key ~= FORCE_PICKED_HERO, "FORCE_PICKED_HERO cannot be a pickable hero") end CustomNetTables:SetTableValue("game_options", "herolist", { herolist = HeroSelection.herolist, imbalist = HeroSelection.imbalist, }) end
27.5
103
0.741818
b34e65161cb58e31a73e1f60bad43fc81c1e0f3f
2,822
rs
Rust
attacker/src/lib.rs
jtimberlake/cherrybomb
d24c0864d0d88bfbd3b4270e3f2d79ab92bf0d5d
[ "Apache-2.0" ]
183
2022-01-31T14:22:23.000Z
2022-03-29T14:54:35.000Z
attacker/src/lib.rs
jtimberlake/cherrybomb
d24c0864d0d88bfbd3b4270e3f2d79ab92bf0d5d
[ "Apache-2.0" ]
5
2022-01-31T15:20:22.000Z
2022-03-31T05:24:43.000Z
attacker/src/lib.rs
jtimberlake/cherrybomb
d24c0864d0d88bfbd3b4270e3f2d79ab92bf0d5d
[ "Apache-2.0" ]
10
2022-02-01T01:45:08.000Z
2022-03-31T07:56:28.000Z
use decider::Anomaly; use mapper::digest::*; use serde::{Deserialize, Serialize}; use std::fs::OpenOptions; use std::io::Write; mod genetic; pub use genetic::*; mod genome; use genome::*; mod attack; use attack::*; mod auth; pub use auth::*; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct Attacker { base_url: String, populations: Vec<Population>, } const FILE: &str = "attacker.json"; impl Attacker { pub fn save(&self) -> Result<(), std::io::Error> { let mut file = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(FILE)?; file.write_all(serde_json::to_string(&self).unwrap().as_bytes())?; Ok(()) } pub fn load() -> Result<Self, Box<dyn std::error::Error>> { let file = std::fs::read_to_string(FILE)?; let a: Attacker = serde_json::from_str(&file)?; Ok(a) } } pub fn prepare(digest: Digest, base_url: String) -> Vec<Vec<String>> { let mut groups = vec![]; let mut populations = vec![]; for group in digest.groups { populations.push(Population::new(&group, 400, 50, None, 20, 10)); groups.push( group .endpoints .iter() .map(|e| e.path.path_ext.clone()) .collect::<Vec<String>>(), ); } let a = Attacker { populations, base_url, }; a.save().unwrap(); groups } pub fn get_populations() -> Vec<Vec<String>> { let attacker = if let Ok(a) = Attacker::load() { a } else { return vec![]; }; attacker.populations.iter().map(|p| p.endpoints()).collect() } pub fn refit(pop: usize, anomalies: Vec<Option<Anomaly>>, anomaly_scores: Vec<Vec<u16>>) { let mut attacker = if let Ok(a) = Attacker::load() { a } else { return; }; attacker.populations[pop].refit(anomalies, anomaly_scores); attacker.save().unwrap(); } pub async fn attack( pop: usize, verbosity: Verbosity, decide_file: &str, headers: &[Header], auth: &Authorization, ) -> Result<Vec<Session>, &'static str> { if let Ok(mut file) = OpenOptions::new() .write(true) .create(true) .open(decide_file) { if let Ok(attacker) = Attacker::load() { let sessions = attacker.populations[pop] .run_gen(verbosity, &attacker.base_url, headers, auth) .await; file.write_all(serde_json::to_string(&sessions).unwrap().as_bytes()) .unwrap(); attacker.save().unwrap(); Ok(sessions) } else { Err("Unable to load attacker module, needs to be prepared first") } } else { Err("Unable to open decider file") } }
27.666667
90
0.558469
ff9bc5ab4842e7843a1b236ef9a6f7677a154cd1
7,505
py
Python
ImageAnalysisSanSalvadorCNN.py
falbav/Image-Analysis-San-Salvador
c2cb2a27ffed3b134ceb329d9358563d374bddd9
[ "MIT" ]
1
2021-04-22T23:05:49.000Z
2021-04-22T23:05:49.000Z
ImageAnalysisSanSalvadorCNN.py
falbav/Image-Analysis-San-Salvador
c2cb2a27ffed3b134ceb329d9358563d374bddd9
[ "MIT" ]
null
null
null
ImageAnalysisSanSalvadorCNN.py
falbav/Image-Analysis-San-Salvador
c2cb2a27ffed3b134ceb329d9358563d374bddd9
[ "MIT" ]
null
null
null
""" This code explores Different Models of Convolutional Neural Networks for the San Salvador Gang Project @author: falba and ftop """ import os import google_streetview.api import pandas as pd import numpy as np import sys import matplotlib.image as mp_img from matplotlib import pyplot as plot from skimage import io from skimage.color import rgb2gray from sklearn.preprocessing import StandardScaler from sklearn import svm from sklearn.model_selection import train_test_split #pip install tensorflow keras numpy skimage matplotlib # Importing the Keras libraries and packages from keras.models import Sequential from keras import layers from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Dense, Dropout, Flatten from keras.utils import to_categorical from keras.layers import LSTM, Embedding from keras.preprocessing.image import ImageDataGenerator from sklearn.linear_model import LogisticRegression from numpy import where from keras import regularizers import random #### Load the data ## Set Directory os.chdir('C:/Users/falba/Dropbox/ImageAnalysis/San Salvador/GangBoundaries') df = pd.read_csv("C:/Users/falba/Dropbox/ImageAnalysis/San Salvador/GangBoundaries/sample.csv", header=0) df astr = "C:/Users/falba/Dropbox/ImageAnalysis/San Salvador/GangBoundaries/" # Let's create a sample for testing and training: train, test = train_test_split(df, test_size=0.25, random_state=38) # Obtaining the image data of testing test_cases=[] test_class=[] file=test.file for x in file: image = io.imread(astr+x) image =rgb2gray(image) test_cases.append(image) test_cases=np.reshape(np.ravel(test_cases),(579,480,480,-1)) for index, Series in test.iterrows(): test_class.append(Series["gang_territory10"]) test_class=np.reshape(test_class,(579,-1)) # The image data of training train_cases=[] train_class=[] fileT=train.file for x in fileT: image = io.imread(astr+x) image=rgb2gray(image) train_cases.append(image) train_cases=np.reshape(train_cases,(1735,480,480,-1)) for index, series in train.iterrows(): train_class.append(series["gang_territory10"]) train_class=np.reshape(train_class,(1735,-1)) ## To Categorical #y_train = to_categorical(train_class) #y_test= to_categorical(test_class) input_dim = train_cases.shape[1] maxlen = 100 ### Now let's try a Convolutional Neural Networks # Seeting up Convolution Layers and Filters model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=(480,480,1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(10, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy',optimizer='Adam',metrics=['accuracy']) model.summary() hist_1 = model.fit(train_cases,train_class,verbose=False,epochs=50,validation_data=(test_cases,test_class),batch_size=10) hist1acc=model.evaluate(test_cases,test_class) #accuracy: 0.6165 # plot loss during training plot.subplot(211) #plot.title('Loss / Binary Crossentropy') plot.plot(hist_1.history['loss'], label='Train') plot.plot(hist_1.history['val_loss'], label='Test') plot.legend() plot.show() plot.subplot(212) #plot.title('Accuracy / Binary Crossentropy') plot.plot(hist_1.history['accuracy'], label='Train') plot.plot(hist_1.history['val_accuracy'], label='Test') plot.legend() plot.show() #plot.savefig('LossBinCross.png') # Binary CrossEntropy - Model 2 model = Sequential() model.add(Conv2D(8, (5, 5), activation='relu', input_shape=(480,480,1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(2, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(3, 3))) model.add(Flatten()) model.add(Dense(10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() hist_2 = model.fit(train_cases,train_class,verbose=False,epochs=30,validation_data=(test_cases,test_class),batch_size=10) # evaluate the model hist2acc=model.evaluate(test_cases,test_class) #Accuracy 0.5354 # plot accuracy during training plot.subplot(212) plot.title('Accuracy / Binary Crossentropy') plot.plot(hist_2.history['accuracy'], label='Train') plot.plot(hist_2.history['val_accuracy'], label='Test') plot.legend() plot.show() plot.subplot(211) plot.title('Loss / Binary Crossentropy') plot.plot(hist_2.history['loss'], label='Train') plot.plot(hist_2.history['val_loss'], label='Test') plot.legend() plot.show() ## Seems like EPOCH migh be too high. Optimal can be less than 10 ## Maybe because overfitting # Binary CrossEntropy - Model 3 model = Sequential() model.add(Conv2D(10, (11, 11), activation='relu', input_shape=(480,480,1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(20, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(3, 3))) model.add(Conv2D(100, (4, 4), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() hist_3 = model.fit(train_cases,train_class,verbose=False,epochs=30,validation_data=(test_cases,test_class),batch_size=10) # evaluate the model hist3acc=model.evaluate(test_cases,test_class) #Accuracy 53% ## Graphs plot.subplot(212) #plot.title('Accuracy / Binary Crossentropy') plot.plot(hist_3.history['accuracy'], label='Train') plot.plot(hist_3.history['val_accuracy'], label='Test') plot.legend() plot.show() plot.subplot(211) #plot.title('Loss / Binary Crossentropy') plot.plot(hist_3.history['loss'], label='Train') plot.plot(hist_3.history['val_loss'], label='Test') plot.legend() plot.show() ## LET'S TRY REGULARIZATION model = Sequential() model.add(Conv2D(8, (5, 5), activation='relu', input_shape=(480,480,1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(2, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(3, 3))) model.add(Flatten()) model.add(Dense(10, kernel_regularizer=regularizers.l2(0.01), activity_regularizer=regularizers.l1(0.01))) #model.add(Dense(10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() hist= model.fit(train_cases,train_class,verbose=False,epochs=50,validation_data=(test_cases,test_class),batch_size=10) # evaluate the model hist_acc=model.evaluate(test_cases,test_class) #Accuracy 53% # plot accuracy during training plot.subplot(212) plot.title('Accuracy / Binary Crossentropy') plot.plot(hist.history['accuracy'], label='Train') plot.plot(hist.history['val_accuracy'], label='Test') plot.legend() plot.show() plot.subplot(211) plot.title('Loss / Binary Crossentropy') plot.plot(hist.history['loss'], label='Train') plot.plot(hist.history['val_loss'], label='Test') plot.legend() plot.show() ## It didnt help much with accuracy but it did with the loss
31.533613
122
0.72445
4483085aa1a5617f634634d102a9b9e536d610e8
931
py
Python
testproject/fiber_test/test_util.py
bsimons/django-fiber
0f4b03217a4aeba6b48908825507fbe8c5732c8d
[ "Apache-2.0" ]
null
null
null
testproject/fiber_test/test_util.py
bsimons/django-fiber
0f4b03217a4aeba6b48908825507fbe8c5732c8d
[ "Apache-2.0" ]
null
null
null
testproject/fiber_test/test_util.py
bsimons/django-fiber
0f4b03217a4aeba6b48908825507fbe8c5732c8d
[ "Apache-2.0" ]
null
null
null
import re from django.template import Template, Context try: from django.utils.timezone import make_aware, utc except ImportError: make_aware, utc = None, None def format_list(l, must_sort=True, separator=' '): """ Format a list as a string. Default the items in the list are sorted. E.g. >>> format_list([3, 2, 1]) u'1 2 3' """ titles = [unicode(v) for v in l] if must_sort: titles = sorted(titles) return separator.join(titles) def condense_html_whitespace(s): s = re.sub("\s\s*", " ", s) s = re.sub(">\s*<", "><", s) s = re.sub(" class=\"\s?(.*?)\s?\"", " class=\"\\1\"", s) s = s.strip() return s class RenderMixin(object): def assertRendered(self, template, expected, context=None): t, c = Template(template), Context(context or {}) self.assertEqual(condense_html_whitespace(t.render(c)), condense_html_whitespace(expected))
25.162162
99
0.619764
c6e5e9ca5bba0334cc99aaf95af172aebe594614
354
css
CSS
assets/css/footer.css
GilangBrilians/obati
137d6c204a9e8f64acdf78e704f2ac8e873aab00
[ "MIT" ]
null
null
null
assets/css/footer.css
GilangBrilians/obati
137d6c204a9e8f64acdf78e704f2ac8e873aab00
[ "MIT" ]
null
null
null
assets/css/footer.css
GilangBrilians/obati
137d6c204a9e8f64acdf78e704f2ac8e873aab00
[ "MIT" ]
null
null
null
footer { padding: 1em; background: #74BDCB; font-family: Roboto; } footer a { color: #FFFFFF; font-weight: 700; } footer a:hover { color: var(--passive-dark); } footer h4 { color: #FFFFFF; } footer p { color: #FFFFFF; } span { font-size: 0.7em; font-family: Roboto; } .page-break { border: 2px solid #FFFEFE; }
8.634146
31
0.587571
b13ccfad2951d647cb40f2c1270d80f96834712b
1,734
py
Python
tensorflowpractice/MNIST_data/transform.py
nifannn/MachineLearningNotes
de38b2072a52a22483168fb10ac2cb896826c7e5
[ "MIT" ]
1
2021-11-11T14:52:11.000Z
2021-11-11T14:52:11.000Z
tensorflowpractice/MNIST_data/transform.py
nifannn/MachineLearningNotes
de38b2072a52a22483168fb10ac2cb896826c7e5
[ "MIT" ]
null
null
null
tensorflowpractice/MNIST_data/transform.py
nifannn/MachineLearningNotes
de38b2072a52a22483168fb10ac2cb896826c7e5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from PIL import Image import struct import csv import progressbar def read_image(filename, saveaddr): with open(filename, 'rb') as f: buf = f.read() index = 0 magic, number, rows, cols = struct.unpack_from('>IIII', buf, index) index += struct.calcsize('>IIII') readbar = progressbar.ProgressBar('reading images ', number, 0) readbar.show() for cnt in range(number): img = Image.new('L', (cols, rows)) for x in range(rows): for y in range(cols): img.putpixel((y, x), int(struct.unpack_from('>B', buf, index)[0])) index += struct.calcsize('>B') img.save(saveaddr + '/' + str(cnt) + '.png') readbar.increase() readbar.present() print('Successfully read all images from ' + filename) def read_label(filename, savefile): with open(filename, 'rb') as f: buf = f.read() index = 0 magic, number = struct.unpack_from('>II', buf, index) index += struct.calcsize('>II') with open(savefile, 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter = ',') csvwriter.writerow(['No', 'label']) readbar = progressbar.ProgressBar('reading labels ', number, 0) readbar.show() for cnt in range(number): label = int(struct.unpack_from('>B', buf, index)[0]) index += struct.calcsize('>B') csvwriter.writerow(map(str, [cnt, label])) readbar.increase() readbar.present() print('Successfully read all labels from ' + filename) def main(): read_image('train-images-idx3-ubyte', 'train-images-idx3') read_label('train-labels-idx1-ubyte', 'train-labels-idx1/train-labels.csv') read_image('t10k-images-idx3-ubyte', 't10k-images-idx3') read_label('t10k-labels-idx1-ubyte', 't10k-labels-idx1/test-labels.csv') if __name__ == '__main__': main()
27.52381
76
0.67474
c2df81ed9b7feb3c6f937724c126f8937383c722
826
sql
SQL
Lab2/scripts/triggerAndProcedure.sql
yzghurovskyi/RelationalDBsLabs
13eed8c027f9b721e61edfc92d9ab2f38dcca7b2
[ "MIT" ]
null
null
null
Lab2/scripts/triggerAndProcedure.sql
yzghurovskyi/RelationalDBsLabs
13eed8c027f9b721e61edfc92d9ab2f38dcca7b2
[ "MIT" ]
null
null
null
Lab2/scripts/triggerAndProcedure.sql
yzghurovskyi/RelationalDBsLabs
13eed8c027f9b721e61edfc92d9ab2f38dcca7b2
[ "MIT" ]
2
2018-12-25T11:30:41.000Z
2019-11-19T21:58:04.000Z
CREATE OR REPLACE FUNCTION process_club_audit() RETURNS TRIGGER AS $club_audit$ BEGIN IF (TG_OP = 'DELETE') THEN INSERT INTO clubs_audit SELECT nextval('audit_id_seq'), 'D'::char, now(), user, OLD.club_id; RETURN OLD; ELSIF (TG_OP = 'UPDATE') THEN INSERT INTO clubs_audit SELECT nextval('audit_id_seq'), 'U'::char, now(), user, NEW.club_id; RETURN NEW; ELSIF (TG_OP = 'INSERT') THEN INSERT INTO clubs_audit SELECT nextval('audit_id_seq'), 'I'::char, now(), user, NEW.club_id; RETURN NEW; END IF; RETURN NULL; END; $club_audit$ LANGUAGE plpgsql; CREATE TRIGGER club_audit AFTER INSERT OR UPDATE OR DELETE ON clubs FOR EACH ROW EXECUTE PROCEDURE process_club_audit();
37.545455
80
0.610169
1a5deced67a2828d31afaddfb51aa5b844c7631f
6,106
cs
C#
base/Windows/BuildTasks/TaskBase.cs
sphinxlogic/Singularity-RDK-2.0
2968c3b920a5383f7360e3e489aa772f964a7c42
[ "MIT" ]
null
null
null
base/Windows/BuildTasks/TaskBase.cs
sphinxlogic/Singularity-RDK-2.0
2968c3b920a5383f7360e3e489aa772f964a7c42
[ "MIT" ]
null
null
null
base/Windows/BuildTasks/TaskBase.cs
sphinxlogic/Singularity-RDK-2.0
2968c3b920a5383f7360e3e489aa772f964a7c42
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Framework; #if ENABLE_INTEROP using System.Runtime.InteropServices; using System.Threading; using Windows; #endif namespace Microsoft.Singularity.BuildTasks { public abstract class TaskBase : Microsoft.Build.Framework.ITask { protected TaskBase() { _taskname = null; _disableMessagePumping = true; } string _taskname; protected string TaskName { get { if (_taskname == null) { _taskname = this.GetType().Name; } return _taskname; } set { _taskname = value; } } protected void LogMessage(string msg) { BuildMessageEventArgs e = new BuildMessageEventArgs(msg, null, this.TaskName, MessageImportance.Normal); _engine.LogMessageEvent(e); } protected void LogError(string msg) { BuildErrorEventArgs e = new BuildErrorEventArgs(null, null, null, 0, 0, 0, 0, msg, null, this.TaskName); _engine.LogErrorEvent(e); } protected void LogMessage(MessageImportance importance, string msg) { BuildMessageEventArgs e = new BuildMessageEventArgs(msg, null, this.TaskName, importance); _engine.LogMessageEvent(e); } protected abstract bool Execute(); bool ITask.Execute() { if (_engine == null) throw new InvalidOperationException("The BuildEngine property must be set before calling the Execute method."); #if false if (_host == null) throw new InvalidOperationException("The Host property must be set before calling the Execute method."); #endif if (_disableMessagePumping) return this.Execute(); bool returnValue = false; ExecuteMethodAndPump(delegate() { returnValue = this.Execute(); }); return returnValue; } ITaskHost _host; IBuildEngine _engine; public IBuildEngine BuildEngine { get { return _engine; } set { _engine = value; } } public ITaskHost HostObject { get { return _host; } set { _host = value; } } bool _disableMessagePumping; public bool DisableMessagePumping { get { return _disableMessagePumping; } set { _disableMessagePumping = value; } } #if ENABLE_INTEROP #region Code for pumping messages while executing tasks unsafe void ExecuteMethodAndPump(SimpleMethod method) { if (method == null) throw new ArgumentNullException("method"); if (_disableMessagePumping) { LogMessage("Message pumping is disabled - executing method directly"); method(); return; } if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA) { LogMessage("Message pumping is disabled - this thread is an MTA thread"); method(); return; } bool quit = false; uint mainThreadId = Kernel32.GetCurrentThreadId(); // LogMessage("main thread id = " + mainThreadId); Exception worker_exception = null; Thread thread = new Thread(delegate() { try { method(); worker_exception = null; } catch (Exception ex) { worker_exception = ex; } quit = true; User32.PostThreadMessageW(mainThreadId, User32.WM_NULL, IntPtr.Zero, IntPtr.Zero); }); thread.Start(); for (;;) { if (quit) { // LogMessage("Main thread received quit notification. Quitting."); break; } MSG msg = new MSG(); if (Windows.User32.GetMessageW(& msg, IntPtr.Zero, 0, 0)) { User32.TranslateMessage(&msg); User32.DispatchMessageW(&msg); } else { LogMessage("Received WM_QUIT or GetMessage failed! Bailing."); break; } } // LogMessage("Waiting for worker thread to finish..."); thread.Join(); // LogMessage("Worker thread is done."); if (worker_exception != null) { throw worker_exception; } } void ExecuteMethodAndPumpThreadMain(object untyped_method) { SimpleMethod method = (SimpleMethod)untyped_method; } #endregion #endif #region Helper methods that don't have a better place to live. protected bool ValidateCSharpIdentifier(string name, string id, bool allowDots) { if (String.IsNullOrEmpty(id)) { LogError(String.Format("The parameter '{0}' is required, but no value was provided.", name)); return false; } if (!Util.ValidateCSharpIdentifier(id, allowDots)) { LogError(String.Format("The value '{0}' provided to parameter '{1}' is not a valid C# identifier.", id, name)); return false; } return true; } #endregion } delegate void SimpleMethod(); }
30.378109
128
0.504586
14eed5172e267f3139ed5a2d73f778f134eefe9b
34
ts
TypeScript
src/app/staff/index.ts
sniper-ninja/MIS_SYSTEM
e4edbc0a66d9c35623e9c08a71109120e4993f3b
[ "MIT" ]
null
null
null
src/app/staff/index.ts
sniper-ninja/MIS_SYSTEM
e4edbc0a66d9c35623e9c08a71109120e4993f3b
[ "MIT" ]
8
2021-03-10T17:23:53.000Z
2022-02-27T04:19:54.000Z
src/app/staff/index.ts
thechamp325/frontend24_9
c2699d65c839b405c473372c74aa8b69b1c297c6
[ "MIT" ]
1
2019-09-10T02:58:04.000Z
2019-09-10T02:58:04.000Z
export * from './staff.component';
34
34
0.705882
23a045018c745b728f97a9aeba167c1f0d78390b
128
js
JavaScript
Blob_Lib/glfw-3.3.7/glfw/docs/html/search/variables_7.js
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/glfw-3.3.7/glfw/docs/html/search/variables_7.js
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/glfw-3.3.7/glfw/docs/html/search/variables_7.js
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:dfe8067e32d70806198b8fd156a8a23b580f1d93a7c23cba20c905c3a0b9bfea size 219
32
75
0.882813
1496ce6c0018f81f6e04305657fb7471155885f0
133
ts
TypeScript
packages/espoir-cli/lib/runnable/self-update/index.d.ts
AntoineYANG/electron-react-cli
83b477c7786c6624e430f9ac0b2516d97a19666a
[ "MIT" ]
null
null
null
packages/espoir-cli/lib/runnable/self-update/index.d.ts
AntoineYANG/electron-react-cli
83b477c7786c6624e430f9ac0b2516d97a19666a
[ "MIT" ]
null
null
null
packages/espoir-cli/lib/runnable/self-update/index.d.ts
AntoineYANG/electron-react-cli
83b477c7786c6624e430f9ac0b2516d97a19666a
[ "MIT" ]
null
null
null
import RunnableScript from '@runnable'; /** * @since 1.0.0 */ declare const SelfUpdate: RunnableScript; export default SelfUpdate;
19
41
0.744361
126df0d0b6af194128e85b99bff3977f5cbbad09
429
cs
C#
Source/SharpVectorCore/Svg/Painting/ISvgPaint.cs
johncao158/SharpVectors
6b72acccdc44e7b6062ab0119c7a2d90e7c2392c
[ "BSD-3-Clause" ]
450
2017-12-17T20:49:46.000Z
2022-03-30T02:55:40.000Z
Source/SharpVectorCore/Svg/Painting/ISvgPaint.cs
johncao158/SharpVectors
6b72acccdc44e7b6062ab0119c7a2d90e7c2392c
[ "BSD-3-Clause" ]
192
2017-11-29T02:32:28.000Z
2021-12-27T21:47:24.000Z
Source/SharpVectorCore/Svg/Painting/ISvgPaint.cs
johncao158/SharpVectors
6b72acccdc44e7b6062ab0119c7a2d90e7c2392c
[ "BSD-3-Clause" ]
112
2018-01-10T07:17:27.000Z
2022-03-02T06:29:17.000Z
namespace SharpVectors.Dom.Svg { /// <summary> /// The SvgPaint interface corresponds to basic type paint and represents the values of /// properties 'fill' and 'stroke'. /// </summary> public interface ISvgPaint : ISvgColor { SvgPaintType PaintType{get;} string Uri{get;} void SetUri ( string uri ); void SetPaint ( SvgPaintType paintType, string uri, string rgbColor, string iccColor ); } }
26.8125
90
0.682984
75d4793c6b6a59e2852780ea3690ee384d180a83
251
css
CSS
src/components/Navbar/style.css
AlexandreCMoraes/projeto-geek-react
d91b6cfb1c9a70069ca3b7133d542051074e5a52
[ "MIT" ]
null
null
null
src/components/Navbar/style.css
AlexandreCMoraes/projeto-geek-react
d91b6cfb1c9a70069ca3b7133d542051074e5a52
[ "MIT" ]
null
null
null
src/components/Navbar/style.css
AlexandreCMoraes/projeto-geek-react
d91b6cfb1c9a70069ca3b7133d542051074e5a52
[ "MIT" ]
null
null
null
@import url('https://fonts.googleapis.com/css2?family=Nerko+One&family=Roboto&display=swap'); .geral{ font-family: 'Nerko One', cursive; font-size: 25px; background-color: #8e249c; box-shadow: 2px 10px 10px black; } .logoNome{ }
20.916667
93
0.673307
63cc39d178e1ccbf55d8a1c46ed24536025571c3
3,581
dart
Dart
lib/app/modules/search_results/search_results_controller.dart
7ANV1R/RoveAssist
5b7cc71171bb03faa30ebde463e0e4766bfda261
[ "MIT" ]
2
2021-10-12T05:32:38.000Z
2021-11-04T22:01:39.000Z
lib/app/modules/search_results/search_results_controller.dart
7ANV1R/RoveAssist
5b7cc71171bb03faa30ebde463e0e4766bfda261
[ "MIT" ]
null
null
null
lib/app/modules/search_results/search_results_controller.dart
7ANV1R/RoveAssist
5b7cc71171bb03faa30ebde463e0e4766bfda261
[ "MIT" ]
null
null
null
import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:get/get.dart'; import 'package:http/http.dart' as http; import 'package:roveassist/app/data/models/service_model/place_model.dart'; import 'package:roveassist/app/data/models/service_model/restaurant_model.dart'; import '../../data/models/service_model/package_tour_model.dart'; class SearchResultsController extends GetxController { final String localhost = dotenv.env['BASE_URL'] ?? 'not found'; @override void onInit() { super.onInit(); } @override void onReady() { super.onReady(); } @override void onClose() {} TextEditingController queryController = TextEditingController(); RxList<PackageTourModel> packageTourList = RxList<PackageTourModel>(); RxList<RestaurantModel> restaurantResultList = RxList<RestaurantModel>(); RxList<PlaceModel> placeList = RxList<PlaceModel>(); Future<void> fetchPackageTour(String query) async { try { String baseUrl = '$localhost/features/packagetour/'; Map<String, String> headers = {'Content-Type': 'application/json'}; http.Response response = await http.get( Uri.parse(baseUrl), headers: headers, ); final List<PackageTourModel> fetchedPackageTour = List<PackageTourModel>.from( (json.decode(response.body) as List<dynamic>) .map( (e) => PackageTourModel.fromJson(e as Map<String, dynamic>), ) .where((result) { final titleLower = result.title.toLowerCase(); final searchLower = query.toLowerCase(); return titleLower.contains(searchLower); }), ).toList(); packageTourList.value = fetchedPackageTour.reversed.toList(); print(packageTourList); } catch (e) {} } Future<void> fetchRestaurant(String query) async { try { String baseUrl = '$localhost/features/restaurant/'; Map<String, String> headers = {'Content-Type': 'application/json'}; http.Response response = await http.get( Uri.parse(baseUrl), headers: headers, ); final List<RestaurantModel> fetchedRestaurant = List<RestaurantModel>.from( (json.decode(response.body) as List<dynamic>) .map( (e) => RestaurantModel.fromJson(e as Map<String, dynamic>), ) .where((result) { final titleLower = result.title.toLowerCase(); final searchLower = query.toLowerCase(); return titleLower.contains(searchLower); }), ).toList(); restaurantResultList.value = fetchedRestaurant.reversed.toList(); print(restaurantResultList); } catch (e) {} } Future<void> fetchPlace(String query) async { try { String baseUrl = '$localhost/features/place/'; Map<String, String> headers = {'Content-Type': 'application/json'}; http.Response response = await http.get( Uri.parse(baseUrl), headers: headers, ); final List<PlaceModel> fetchedPlace = List<PlaceModel>.from( (json.decode(response.body) as List<dynamic>) .map( (e) => PlaceModel.fromJson(e as Map<String, dynamic>), ) .where((result) { final titleLower = result.title.toLowerCase(); final searchLower = query.toLowerCase(); return titleLower.contains(searchLower); }), ).toList(); placeList.value = fetchedPlace.reversed.toList(); print(restaurantResultList); } catch (e) {} } }
31.690265
84
0.646188
473033793ca1b021402587d30137b92a5d6b3ab6
1,738
rb
Ruby
lib/scaffold/generators/views_generator.rb
gudata/scaffold_pico
04bdf0213f51e6743da584e31944cafe7ae569cc
[ "MIT" ]
21
2016-12-18T16:48:05.000Z
2022-03-12T09:37:27.000Z
lib/scaffold/generators/views_generator.rb
gudata/scaffold_pico
04bdf0213f51e6743da584e31944cafe7ae569cc
[ "MIT" ]
8
2017-03-20T14:20:55.000Z
2022-02-26T03:44:18.000Z
lib/scaffold/generators/views_generator.rb
gudata/scaffold_pico
04bdf0213f51e6743da584e31944cafe7ae569cc
[ "MIT" ]
3
2016-12-18T19:13:55.000Z
2018-05-03T07:36:16.000Z
module Scaffold module Generators class ViewsGenerator < Scaffold::Generators::BaseGenerator attr :css_framework, false attr :template, false def generate template, css_framework @css_framework = css_framework @template = template views_path = create_views_path templating_engine = choose_templating_engine # print "Creating view:" %w(index new edit show _form).each do |view_name| # print view_name, ' ' create views_path, view_name, templating_engine, css_framework end # print "\n" end def create views_path, view_name, templating_engine, css_framework source_file_name = "#{view_name}.html.#{templating_engine.extension}.erb" target_file_name = "#{view_name}.html.#{templating_engine.extension}" source_file_path = find_root(templates, 'views', css_framework, templating_engine.source_folder_name, source_file_name) content = File.read(source_file_path) content = parse_template(content, {rails: @rails}) target_file_path = File.join(create_views_path, target_file_name) write_with_confirmation(target_file_path, content) end def create_views_path views_path = File.join(Dir.pwd, 'app', 'views', @rails.controller.namespaces_as_path, @rails.view.folder_name) FileUtils.mkpath(views_path) views_path end def choose_templating_engine case template when 'slim' ::Scaffold::TemplateEngines::Slim.new else raise "I don't have defined templates for #{template}. However you can use [slim,]" end end end end end
30.491228
118
0.658803
b01dca4c7fd50c169eb78f6cd96703e886ac93bb
4,976
py
Python
src/data/make_dataset.py
maycownd/deep-learning-fashion-mnist
bbaf0c952d92f37f40052d76470c44fc3d71bad5
[ "MIT" ]
null
null
null
src/data/make_dataset.py
maycownd/deep-learning-fashion-mnist
bbaf0c952d92f37f40052d76470c44fc3d71bad5
[ "MIT" ]
null
null
null
src/data/make_dataset.py
maycownd/deep-learning-fashion-mnist
bbaf0c952d92f37f40052d76470c44fc3d71bad5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import os import click import logging from dotenv import find_dotenv, load_dotenv import pandas as pd import numpy as np from PIL import Image PATH_TRAIN = "data/raw/fashion-mnist_train.csv" PATH_TEST = "data/raw/fashion-mnist_test.csv" DATA_PATH = "data/raw/" dict_fashion = { 0: 'T-shirt/top', 1: 'Trouser', 2: 'Pullover', 3: 'Dress', 4: 'Coat', 5: 'Sandal', 6: 'Shirt', 7: 'Sneaker', 8: 'Bag', 9: 'Ankle boot' } def csv2img(csv, path, is_train=True): """ Convert pixel values from .csv to .png image Source: https://www.kaggle.com/alexanch/image-classification-w-fastai-fashion-mnist """ # define the name of the directory to be created if is_train: image_path = "working/train/" else: image_path = "working/test/" full_path = os.path.join(path, image_path) if os.path.isdir(full_path): return None try: os.makedirs(full_path) except OSError: print("Creation of the directory %s failed" % full_path) else: print("Successfully created the directory %s" % full_path) for i in range(len(csv)): # csv.iloc[i, 1:].to_numpy() returns pixel values array # for i'th imag excluding the label # next step: reshape the array to original shape(28, 28) # and add missing color channels result = Image.fromarray(np.uint8( np.stack( np.rot90( csv.iloc[i, 1:].to_numpy(). reshape((28, 28)))*3, axis=-1))) # save the image: result.save(f'{full_path}{str(i)}.png') print(f'{len(csv)} images were created.') def create_train_test(csv_train, csv_test, data_path=DATA_PATH): """Create images on `data_path` from data provided by csvs. This is just a wrapper of csv2img to create the images provided by many csvs at once. Args: csv_list ([type]): [description] data_path (str, optional): [description]. Defaults to "../../Data/raw". """ csv2img(csv_train, data_path, True) csv2img(csv_test, data_path, False) def import_xy( path_train=PATH_TRAIN, path_test=PATH_TEST, label_name="label"): """Import data from specified path. Args: path_train (str, optional): [description]. Defaults to PATH_TRAIN. path_test ([type], optional): [description]. Defaults to PATH_TEST. label_name (str, optional): [description]. Defaults to "label". Returns: [type]: [description] """ # importng the data from the paths which are there by default df_train = pd.read_csv(path_train) df_test = pd.read_csv(path_test) # creating images from csv data create_train_test(df_train, df_test) # creating labels df_train['label_text'] = df_train['label'].apply(lambda x: dict_fashion[x]) df_test['label_text'] = df_test['label'].apply(lambda x: dict_fashion[x]) # add image names: df_train['img'] = pd.Series([str(i)+'.png' for i in range(len(df_train))]) df_test['img'] = pd.Series([str(i)+'.png' for i in range(len(df_test))]) X_train, y_train = df_train.drop("label", axis=1), df_train["label"] X_test, y_test = df_test.drop("label", axis=1), df_test["label"] # save corresponding labels and image names to .csv file: df_train[['img', 'label_text']].to_csv( os.path.join(DATA_PATH, 'working/train_image_labels.csv'), index=False) df_test[['img', 'label_text']].to_csv( os.path.join(DATA_PATH, 'working/test_image_labels.csv'), index=False) return X_train, y_train, X_test, y_test @click.command() @click.argument('input_filepath', type=click.Path(exists=True), default="data/raw/") @click.argument('output_filepath', type=click.Path(), default="data/interim/") def main(input_filepath, output_filepath): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ if not input_filepath: input_filepath="data/raw/fashion-mnist_train.csv" if not output_filepath: output_filepath="data/interim/mnist_train.csv" logger = logging.getLogger(__name__) logger.info('making final data set from raw data') X_train, y_train, X_test, y_test = import_xy() print("imported data") if __name__ == '__main__': log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=log_fmt) # not used in this stub but often useful for finding various files project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) # find .env automagically by walking up directories until it's found, then # load up the .env entries as environment variables load_dotenv(find_dotenv()) main()
32.953642
87
0.635651
e243967487eee46a415e887eaa8e1ac94e34fbda
5,669
js
JavaScript
obj/Release/netcoreapp3.1/PubTmp/Out/wwwroot/_content/Syncfusion.Blazor/scripts/sf-barcode-866b4e.min.js
onejbsmith/BlazorTrader
aa05db83334e3a1980c627127d144e98c26d79e6
[ "MIT" ]
null
null
null
obj/Release/netcoreapp3.1/PubTmp/Out/wwwroot/_content/Syncfusion.Blazor/scripts/sf-barcode-866b4e.min.js
onejbsmith/BlazorTrader
aa05db83334e3a1980c627127d144e98c26d79e6
[ "MIT" ]
null
null
null
obj/Release/netcoreapp3.1/PubTmp/Out/wwwroot/_content/Syncfusion.Blazor/scripts/sf-barcode-866b4e.min.js
onejbsmith/BlazorTrader
aa05db83334e3a1980c627127d144e98c26d79e6
[ "MIT" ]
null
null
null
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="_content/Syncfusion.Blazor/scripts/",n(n.s="./bundles/sf-barcode.js")}({"./bundles/sf-barcode.js":function(e,t,n){"use strict";n.r(t);n("./modules/sf-barcode.js")},"./modules/sf-barcode.js":function(e,t){window.sfBlazor=window.sfBlazor||{},window.sfBlazor.Barcode=function(){"use strict";var e=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{s(r.next(e))}catch(e){o(e)}}function l(e){try{s(r.throw(e))}catch(e){o(e)}}function s(e){e.done?i(e.value):new n((function(t){t(e.value)})).then(a,l)}s((r=r.apply(e,t||[])).next())}))},t=function(e,t){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};return{getBarcodeSize:function(e){var t=e.getBoundingClientRect(),n={};return n.Width=t.width,n.Height=t.height,n},createHtmlElement:function(e,t){var n=sf.base.createElement(e);return t&&this.setAttribute(n,t),n},setAttribute:function(e,t){for(var n=Object.keys(t),r=0;r<n.length;r++)e.setAttribute(n[r],t[n[r]])},createMeasureElements:function(){if(window.barcodeMeasureElement)window.barcodeMeasureElement.usageCount+=1;else{var e=this.createHtmlElement("div",{id:"barcodeMeasureElement",class:"barcodeMeasureElement",style:"visibility:hidden ; height: 0px ; width: 0px; overflow: hidden;"}),t=this.createHtmlElement("span",{style:"display:inline-block ; line-height: normal"});e.appendChild(t);var n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("xlink","http://www.w3.org/1999/xlink"),e.appendChild(n);var r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),n.appendChild(r),window.barcodeMeasureElement=e,window.barcodeMeasureElement.usageCount=1,document.body.appendChild(e)}},measureText:function(e,t,n){window.barcodeMeasureElement.style.visibility="visible";var r=window.barcodeMeasureElement.children[1],i=this.getChildNode(r)[0];i.textContent=e,i.setAttribute("style","font-size:"+t+"px; font-family:"+n+";");var o=i.getBBox(),a={};return a.Width=o.width,a.Height=o.height,window.barcodeMeasureElement.style.visibility="hidden",a},getChildNode:function(e){var t,n=[];if("msie"===sf.base.Browser.info.name||"edge"===sf.base.Browser.info.name)for(var r=0;r<e.childNodes.length;r++)1===(t=e.childNodes[r]).nodeType&&n.push(t);else n=e.children;return n},checkOverlapTextPosition:function(e,t,n,r,i,o,a,l){return(l=l||{}).stringSize=t,r+i-(o+this.measureText(e,t,n).Width)<=a&&t>2&&(l.stringSize-=.2,this.checkOverlapTextPosition(e,l.stringSize,n,r,i,o,a,l)),l.stringSize},triggerDownload:function(e,t,n){var r=document.createElement("a");r.download=t+"."+e.toLocaleLowerCase(),r.href=n,r.click()},exportAsImage:function(n,r,i,o){return e(this,void 0,void 0,(function(){var e;return t(this,(function(t){switch(t.label){case 0:return[4,this.imageExport(n,r,i,o)];case 1:return(e=t.sent())instanceof Promise?(e.then((function(e){return e})),[2,e]):[2,e]}}))}))},imageExport:function(n,r,i,o){return e(this,void 0,void 0,(function(){var e;return t(this,(function(t){return e=this,[2,new Promise((function(t,a){var l="<svg xmlns=http://www.w3.org/2000/svg xmlns:xlink=http://www.w3.org/1999/xlink>"+i.children[0].outerHTML+"</svg>",s=window.URL.createObjectURL(new Blob("SVG"===n?[l]:[(new window.XMLSerializer).serializeToString(i)],{type:"image/svg+xml"}));if("SVG"===n)e.triggerDownload(n,r,s),t(null);else{var u=document.createElement("canvas");u.height=i.clientHeight,u.width=i.clientWidth;var c=u.getContext("2d"),d=new Image;d.onload=function(){if(c.drawImage(d,0,0),window.URL.revokeObjectURL(s),o){var i="JPEG"===n?u.toDataURL("image/jpeg"):"PNG"===n?u.toDataURL("image/png"):"";t(i)}else e.triggerDownload(n,r,u.toDataURL("image/png").replace("image/png","image/octet-stream")),t(null)},d.src=s}}))]}))}))}}}()}});
5,669
5,669
0.698889