hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
7293ad867e1ada02d74adf05793411ba2c8aae30
4,406
cs
C#
CpuMonitor/Processes.cs
SiMoStro/HumbleCpuMonitor
2a10db9282d5026b21b90524621413b8e8c059f1
[ "MIT" ]
null
null
null
CpuMonitor/Processes.cs
SiMoStro/HumbleCpuMonitor
2a10db9282d5026b21b90524621413b8e8c059f1
[ "MIT" ]
null
null
null
CpuMonitor/Processes.cs
SiMoStro/HumbleCpuMonitor
2a10db9282d5026b21b90524621413b8e8c059f1
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Linq; using HumbleCpuMonitor.Win32; using static HumbleCpuMonitor.Win32.Psapi; using FT = System.Runtime.InteropServices.ComTypes.FILETIME; namespace HumbleCpuMonitor { public class ProcessSnapshot { public DateTime _prevTime { get; set; } public DateTime _lastTime { get; set; } private PROCESS_MEMORY_COUNTERS_EX _memoryPrev; private PROCESS_MEMORY_COUNTERS_EX _memoryLast; private DateTime _creationTime; private DateTime _exitTime; private TimeSpan _prevKernelTime; private TimeSpan _prevUserTime; private TimeSpan _lastKernelTime; private TimeSpan _lastUserTime; public double CpuPerc { get { if (_prevKernelTime == TimeSpan.Zero) return 0.0; double deltaTime = _lastTime.Subtract(_prevTime).TotalMilliseconds; double totCpuTime = (_lastKernelTime + _lastUserTime).Subtract(_prevKernelTime + _prevUserTime).TotalMilliseconds; return (totCpuTime / deltaTime) * 100.0; } } public void Snapshot(IntPtr handle) { _prevKernelTime = _lastKernelTime; _prevUserTime = _lastUserTime; _prevTime = _lastTime; _memoryPrev = _memoryLast; _lastTime = DateTime.UtcNow; _memoryLast = new PROCESS_MEMORY_COUNTERS_EX(); _memoryLast.cb = (uint)Marshal.SizeOf(typeof(PROCESS_MEMORY_COUNTERS_EX)); GetProcessMemoryInfo(handle, out _memoryLast, _memoryLast.cb); FT kernelTime, userTime, creationTime, exitTime; GetProcessTimes(handle, out creationTime, out exitTime, out kernelTime, out userTime); _lastKernelTime = FiletimeToTimeSpan(kernelTime); _lastUserTime = FiletimeToTimeSpan(userTime); _creationTime = FiletimeToDateTime(creationTime); _exitTime = FiletimeToDateTime(exitTime); } } public class ProcessDescriptor { public uint Pid { get; set; } public string Name { get; set; } public ProcessSnapshot Snapshot { get; set; } public ProcessDescriptor() { Snapshot = new ProcessSnapshot(); } } public class Processes { private Dictionary<uint, ProcessDescriptor> _processes = new Dictionary<uint, ProcessDescriptor>(); public IReadOnlyList<ProcessDescriptor> Descriptors { get { return _processes.Values.ToArray(); } } public int ProcessCount { get; private set; } public void Update() { var oldSnapshot = _processes; _processes = new Dictionary<uint, ProcessDescriptor>(); uint[] buffer = new uint[4096]; uint bytesOut; EnumProcesses(buffer, 4096, out bytesOut); ProcessCount = (int)(bytesOut / 4); for (int p = 0; p < ProcessCount; p++) { IntPtr hndl = Kernel32.OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead, false, (int)buffer[p]); if (hndl != IntPtr.Zero) { uint pid = buffer[p]; ProcessDescriptor pd; if (oldSnapshot.ContainsKey(pid)) pd = oldSnapshot[pid]; else { pd = new ProcessDescriptor(); pd.Pid = pid; StringBuilder sb = new StringBuilder(1024); GetModuleFileNameEx(hndl, IntPtr.Zero, sb, 1024); string temp = sb.ToString(); int lio = temp.LastIndexOf('\\') + 1; if (lio > 0) temp = temp.Substring(lio); pd.Name = temp; } _processes[pid] = pd; pd.Snapshot.Snapshot(hndl); Kernel32.CloseHandle(hndl); } } oldSnapshot.Clear(); } } }
33.892308
151
0.551975
b040d9104205424c5158e808096d5c47161a331c
39
py
Python
src/compas/datastructures/graph/__init__.py
funkchaser/compas
b58de8771484aa0c6068d43df78b1679503215de
[ "MIT" ]
235
2017-11-07T07:33:22.000Z
2022-03-25T16:20:00.000Z
src/compas/datastructures/graph/__init__.py
funkchaser/compas
b58de8771484aa0c6068d43df78b1679503215de
[ "MIT" ]
770
2017-09-22T13:42:06.000Z
2022-03-31T21:26:45.000Z
src/compas/datastructures/graph/__init__.py
funkchaser/compas
b58de8771484aa0c6068d43df78b1679503215de
[ "MIT" ]
99
2017-11-06T23:15:28.000Z
2022-03-25T16:05:36.000Z
from .graph import Graph # noqa: F401
19.5
38
0.717949
5d90e81bf19edf19ce57074503f29e43b805b7df
996
hpp
C++
include/ShaderAST/Expr/ExprQuestion.hpp
jarrodmky/ShaderWriter
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
[ "MIT" ]
148
2018-10-11T16:51:37.000Z
2022-03-26T13:55:08.000Z
include/ShaderAST/Expr/ExprQuestion.hpp
jarrodmky/ShaderWriter
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
[ "MIT" ]
30
2019-11-30T11:43:07.000Z
2022-01-25T21:09:47.000Z
include/ShaderAST/Expr/ExprQuestion.hpp
jarrodmky/ShaderWriter
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
[ "MIT" ]
8
2020-04-17T13:18:30.000Z
2021-11-20T06:24:44.000Z
/* See LICENSE file in root folder */ #ifndef ___AST_ExprQuestion_H___ #define ___AST_ExprQuestion_H___ #pragma once #include "Expr.hpp" namespace ast::expr { class Question : public Expr { public: SDAST_API Question( type::TypePtr type , ExprPtr ctrlExpr , ExprPtr trueExpr , ExprPtr falseExpr ); SDAST_API void accept( VisitorPtr vis )override; inline Expr * getCtrlExpr()const { return m_ctrlExpr.get(); } inline Expr * getTrueExpr()const { return m_trueExpr.get(); } inline Expr * getFalseExpr()const { return m_falseExpr.get(); } private: ExprPtr m_ctrlExpr; ExprPtr m_trueExpr; ExprPtr m_falseExpr; }; using QuestionPtr = std::unique_ptr< Question >; inline QuestionPtr makeQuestion( type::TypePtr type , ExprPtr ctrlExpr , ExprPtr trueExpr , ExprPtr falseExpr ) { return std::make_unique< Question >( std::move( type ) , std::move( ctrlExpr ) , std::move( trueExpr ) , std::move( falseExpr ) ); } } #endif
17.172414
56
0.688755
c6d614a17dc12d56ea03512b337c5e1fdf8f136a
15,584
rs
Rust
sui_core/src/unit_tests/sui_json.rs
velvia/sui
976b6bbc2573b375776995a6d3239cba5b73c26e
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
sui_core/src/unit_tests/sui_json.rs
velvia/sui
976b6bbc2573b375776995a6d3239cba5b73c26e
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
sui_core/src/unit_tests/sui_json.rs
velvia/sui
976b6bbc2573b375776995a6d3239cba5b73c26e
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
// Copyright (c) 2022, Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::path::Path; use move_core_types::{ account_address::AccountAddress, identifier::Identifier, value::MoveTypeLayout, }; use serde_json::{json, Value}; use sui_types::base_types::{ObjectID, SuiAddress, TransactionDigest}; use sui_types::object::Object; use sui_types::SUI_FRAMEWORK_ADDRESS; use crate::sui_json::{resolve_move_function_args, SuiJsonCallArg, SuiJsonValue}; use super::{is_homogeneous, HEX_PREFIX}; #[test] fn test_json_is_homogeneous() { let checks = vec![ (json!([1, 2, 3, true, 5, 6, 7]), false), (json!([1, 2, 3, 4, 5, 6, 7]), true), // Although we can encode numbers as strings, we do not allow mixing primitive // numbers and string encoded numbers (json!([1, 2, "4", 4, 5, 6, 7]), false), (json!([1, 2, 3, 4, "", 6, 7]), false), (json!([]), true), (json!([[], 2, 3, 5, 6, 7]), false), ( json!([[[9, 53, 434], [0], [300]], [], [300, 4, 5, 6, 7]]), false, ), ( json!([[[9, 53, 434], [0], [300]], [], [[332], [4, 5, 6, 7]]]), true, ), (json!([[], [true], [false], []]), true), (json!([[[[[2]]]], [], [[]], []]), true), (json!([3]), true), (json!([]), true), (json!(1), true), ]; // Driver for (arg, expected_val) in checks { assert_eq!(is_homogeneous(&arg), expected_val); } } #[test] fn test_json_is_valid_sui_json() { let checks = vec![ // Not homogeneous (json!([1, 2, 3, true, 5, 6, 7]), false), // Homogeneous (json!([1, 2, 3, 4, 5, 6, 7]), true), // String allowed (json!("a string"), true), // Float not allowed (json!(1.3), false), // Bool allowed (json!(true), true), // Negative not allowed (json!(-10), false), // Uint allowed (json!(100), true), // Not homogeneous ( json!([[[9, 53, 434], [0], [300]], [], [300, 4, 5, 6, 7]]), false, ), (json!([]), true), // Homogeneous ( json!([[[9, 53, 434], [0], [300]], [], [[332], [4, 5, 6, 7]]]), true, ), ]; // Driver for (arg, expected_val) in checks { assert_eq!(SuiJsonValue::new(arg).is_ok(), expected_val); } } #[test] fn test_basic_args_linter_pure_args() { let good_ascii_str = "123456789hdffwfof libgude ihibhdede +_))@+"; let good_utf8_str = "enbeuf√12∫∆∂3456789hdπ˚ffwfof libgude ˚ø˙߃çß +_))@+"; let good_hex_val = "0x1234ABCD"; let bad_hex_val = "0x1234AB CD"; let u128_val = u64::MAX as u128 + 0xff; let checks = vec![ // Expected Bool match ( Value::from(true), MoveTypeLayout::Bool, Some(bcs::to_bytes(&true).unwrap()), ), // Expected U8 match ( Value::from(9u8), MoveTypeLayout::U8, Some(bcs::to_bytes(&9u8).unwrap()), ), // U64 value less than 256 can be used as U8 ( Value::from(9u64), MoveTypeLayout::U8, Some(bcs::to_bytes(&9u8).unwrap()), ), // U8 value encoded as str ( Value::from("89"), MoveTypeLayout::U8, Some(bcs::to_bytes(&89u8).unwrap()), ), // U8 value encoded as str promoted to U64 ( Value::from("89"), MoveTypeLayout::U64, Some(bcs::to_bytes(&89u64).unwrap()), ), // U64 value encoded as str ( Value::from("890"), MoveTypeLayout::U64, Some(bcs::to_bytes(&890u64).unwrap()), ), // U128 value encoded as str ( Value::from(format!("{u128_val}")), MoveTypeLayout::U128, Some(bcs::to_bytes(&u128_val).unwrap()), ), // U8 value encoded as hex str ( Value::from("0x12"), MoveTypeLayout::U8, Some(bcs::to_bytes(&0x12u8).unwrap()), ), // U8 value encoded as hex str promoted to U64 ( Value::from("0x12"), MoveTypeLayout::U64, Some(bcs::to_bytes(&0x12u64).unwrap()), ), // U64 value encoded as hex str ( Value::from("0x890"), MoveTypeLayout::U64, Some(bcs::to_bytes(&0x890u64).unwrap()), ), // U128 value encoded as hex str ( Value::from(format!("0x{:02x}", u128_val)), MoveTypeLayout::U128, Some(bcs::to_bytes(&u128_val).unwrap()), ), // Space not allowed (Value::from(" 9"), MoveTypeLayout::U8, None), // Hex must start with 0x (Value::from("AB"), MoveTypeLayout::U8, None), // Too large (Value::from("123456789"), MoveTypeLayout::U8, None), // Too large (Value::from("123456789123456789123456789123456789"), MoveTypeLayout::U64, None), // Too large (Value::from("123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"), MoveTypeLayout::U128, None), // U64 value greater than 255 cannot be used as U8 (Value::from(900u64), MoveTypeLayout::U8, None), // floats cannot be used as U8 (Value::from(0.4f32), MoveTypeLayout::U8, None), // floats cannot be used as U64 (Value::from(3.4f32), MoveTypeLayout::U64, None), // Negative cannot be used as Unsigned (Value::from(-1), MoveTypeLayout::U8, None), // u8 vector can be gotten from string ( Value::from(good_ascii_str), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)), Some(bcs::to_bytes(&good_ascii_str.as_bytes()).unwrap()), ), // u8 vector from bad string ( Value::from(good_utf8_str), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)), Some(bcs::to_bytes(&good_utf8_str.as_bytes()).unwrap()), ), // u8 vector from hex repr ( Value::from(good_hex_val), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)), Some( bcs::to_bytes(&hex::decode(&good_hex_val.trim_start_matches(HEX_PREFIX)).unwrap()) .unwrap(), ), ), // u8 vector from bad hex repr ( Value::from(bad_hex_val), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)), None, ), // u8 vector from u8 array ( json!([1, 2, 3, 4, 5, 6, 7]), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)), Some(bcs::to_bytes(&vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8]).unwrap()), ), // u8 vector from heterogenous array ( json!([1, 2, 3, true, 5, 6, 7]), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)), None, ), // Vector of vector of u8s ( json!([[1, 2, 3], [], [3, 4, 5, 6, 7]]), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)))), Some( bcs::to_bytes(&vec![ vec![1u8, 2u8, 3u8], vec![], vec![3u8, 4u8, 5u8, 6u8, 7u8], ]) .unwrap(), ), ), // U64 nest ( json!([[1111, 2, 3], [], [300, 4, 5, 6, 7]]), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U64)))), Some( bcs::to_bytes(&vec![ vec![1111u64, 2u64, 3u64], vec![], vec![300u64, 4u64, 5u64, 6u64, 7u64], ]) .unwrap(), ), ), // U64 deep nest, bad because heterogenous array ( json!([[[9, 53, 434], [0], [300]], [], [300, 4, 5, 6, 7]]), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U64)))), None, ), // U64 deep nest, good ( json!([[[9, 53, 434], [0], [300]], [], [[332], [4, 5, 6, 7]]]), MoveTypeLayout::Vector(Box::new(MoveTypeLayout::Vector(Box::new(MoveTypeLayout::Vector(Box::new( MoveTypeLayout::U64, )))))), Some( bcs::to_bytes(&vec![ vec![vec![9u64, 53u64, 434u64], vec![0u64], vec![300u64]], vec![], vec![vec![332u64], vec![4u64, 5u64, 6u64, 7u64]], ]) .unwrap(), ), ), ]; // Driver for (arg, expected_type, expected_val) in checks { let r = SuiJsonValue::new(arg); match expected_val { Some(q) => { // Must be conform assert!(r.is_ok()); // Must be serializable let sr = r.unwrap().to_bcs_bytes(&expected_type); // Must match expected serialized value assert_eq!(sr.unwrap(), q); } None => { assert!(r.is_err() || r.unwrap().to_bcs_bytes(&expected_type).is_err()); } } } } #[test] fn test_basic_args_linter_top_level() { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../sui_programmability/examples/nfts"); let compiled_modules = sui_framework::build_and_verify_user_package(&path).unwrap(); let example_package = Object::new_package(compiled_modules, TransactionDigest::genesis()); let module = Identifier::new("Geniteam").unwrap(); let function = Identifier::new("create_monster").unwrap(); /* Function signature: public fun create_monster( _player: &mut Player, farm: &mut Farm, pet_monsters: &mut Collection, monster_name: vector<u8>, monster_img_index: u64, breed: u8, monster_affinity: u8, monster_description: vector<u8>, display: vector<u8>, ctx: &mut TxContext ) */ let monster_name_raw = "MonsterName"; let monster_img_id_raw = 12345678; let breed_raw = 89; let monster_affinity_raw = 200; let monster_description_raw = "MonsterDescription"; let display_raw = "DisplayUrl"; let player_id = json!(format!("0x{:02x}", ObjectID::random())); let farm_id = json!(format!("0x{:02x}", ObjectID::random())); let pet_monsters_id = json!(format!("0x{:02x}", ObjectID::random())); // This is okay since not starting with 0x let monster_name = json!(monster_name_raw); // Well within U64 bounds let monster_img_id = json!(monster_img_id_raw); // Well within U8 bounds let breed = json!(breed_raw); // Well within U8 bounds let monster_affinity = json!(monster_affinity_raw); // This is okay since not starting with 0x let monster_description = json!(monster_description_raw); // This is okay since not starting with 0x let display = json!(display_raw); // They have to be ordered let args = vec![ player_id, farm_id, pet_monsters_id, monster_name.clone(), monster_img_id.clone(), breed, monster_affinity.clone(), monster_description.clone(), display.clone(), ] .iter() .map(|q| SuiJsonValue::new(q.clone()).unwrap()) .collect(); let json_args = resolve_move_function_args(&example_package, module.clone(), function.clone(), args) .unwrap(); assert!(!json_args.is_empty()); assert_eq!( json_args[3], SuiJsonCallArg::Pure(bcs::to_bytes(&monster_name_raw.as_bytes().to_vec()).unwrap()) ); assert_eq!( json_args[4], SuiJsonCallArg::Pure(bcs::to_bytes(&(monster_img_id_raw as u64)).unwrap()), ); assert_eq!( json_args[5], SuiJsonCallArg::Pure(bcs::to_bytes(&(breed_raw as u8)).unwrap()) ); assert_eq!( json_args[6], SuiJsonCallArg::Pure(bcs::to_bytes(&(monster_affinity_raw as u8)).unwrap()), ); assert_eq!( json_args[7], SuiJsonCallArg::Pure(bcs::to_bytes(&monster_description_raw.as_bytes().to_vec()).unwrap()), ); // Breed is u8 so too large let args = vec![ monster_name, monster_img_id, json!(10000u64), monster_affinity, monster_description, display, ] .iter() .map(|q| SuiJsonValue::new(q.clone()).unwrap()) .collect(); assert!(resolve_move_function_args(&example_package, module, function, args).is_err()); // Test with vecu8 as address let genesis_objs = sui_adapter::genesis::clone_genesis_packages(); let framework_pkg = genesis_objs .iter() .find(|q| q.id() == ObjectID::from(SUI_FRAMEWORK_ADDRESS)) .expect("Unable to find framework object"); let module = Identifier::new("ObjectBasics").unwrap(); let function = Identifier::new("create").unwrap(); /* Function signature: public fun create(value: u64, recipient: vector<u8>, ctx: &mut TxContext) */ let value_raw = 29897; let address = SuiAddress::random_for_testing_only(); let value = json!(value_raw); // Encode as hex string let addr = json!(format!("0x{:02x}", address)); // They have to be ordered let args = vec![value, addr] .iter() .map(|q| SuiJsonValue::new(q.clone()).unwrap()) .collect(); let args = resolve_move_function_args(framework_pkg, module, function, args).unwrap(); assert_eq!( args[0], SuiJsonCallArg::Pure(bcs::to_bytes(&(value_raw as u64)).unwrap()) ); // Need to verify this specially // BCS serialzes addresses like vectors so there's a length prefix, which makes the vec longer by 1 assert_eq!( args[1], SuiJsonCallArg::Pure(bcs::to_bytes(&AccountAddress::from(address)).unwrap()), ); // Test with object args let module = Identifier::new("ObjectBasics").unwrap(); let function = Identifier::new("transfer").unwrap(); /* Function signature: public fun transfer(o: Object, recipient: vector<u8>, _ctx: &mut TxContext) */ let object_id_raw = ObjectID::random(); let address = SuiAddress::random_for_testing_only(); let object_id = json!(format!("0x{:02x}", object_id_raw)); // Encode as hex string let addr = json!(format!("0x{:02x}", address)); // They have to be ordered let args = vec![object_id, addr] .iter() .map(|q| SuiJsonValue::new(q.clone()).unwrap()) .collect(); let args = resolve_move_function_args(framework_pkg, module, function, args).unwrap(); assert_eq!( args[0], SuiJsonCallArg::Object( ObjectID::from_hex_literal(&format!("0x{:02x}", object_id_raw)).unwrap() ) ); // Need to verify this specially // BCS serialzes addresses like vectors so there's a length prefix, which makes the vec longer by 1 assert_eq!( args[1], SuiJsonCallArg::Pure(bcs::to_bytes(&AccountAddress::from(address)).unwrap()) ); }
33.016949
198
0.53587
38612eeb4348c933c465be80dda780cd9b276cf8
6,267
php
PHP
wp-content/backup-1412383197-plugins/mojo-marketplace/inc/shortcode-generator.php
elperg/coketta-wp
7c62e51f7a9c05298ffdf2ae512d7dfe46d18bb3
[ "Artistic-2.0" ]
null
null
null
wp-content/backup-1412383197-plugins/mojo-marketplace/inc/shortcode-generator.php
elperg/coketta-wp
7c62e51f7a9c05298ffdf2ae512d7dfe46d18bb3
[ "Artistic-2.0" ]
null
null
null
wp-content/backup-1412383197-plugins/mojo-marketplace/inc/shortcode-generator.php
elperg/coketta-wp
7c62e51f7a9c05298ffdf2ae512d7dfe46d18bb3
[ "Artistic-2.0" ]
null
null
null
<?php function mm_add_button( $icons ) { $img = plugin_dir_url( dirname( __FILE__ ) ) . "img/mojo-icon-22.png"; $id = 'mm_sg_container'; $title = ''; $icons .= "<a class='thickbox button' title='" . $title . "' href='#TB_inline?width=640&inlineId=" . $id . "'> <img style='position:relative; bottom: 2px;' src='" . $img . "' /> Shortcodes</a>"; return $icons; } add_action( 'media_buttons_context', 'mm_add_button' ); function mm_add_inline_popup_content() { ?> <div id="mm_sg_container" style="display:none;"> <div class="mm_sg_header"> <img style="margin: 0 auto;" src="<?php echo plugin_dir_url( dirname( __FILE__ ) ) . "img/mojo-sg-header.png"; ?>" /> </div> <form id="mojo-sg-form"> <p>I would like to display <select name="mojo-sg-quantity" class="mojo-sg-quantity" style="width:40px;"> <?php for ( $i = 1; $i <= apply_filters( 'mm_sg_max_qty_themes', 10 ); $i++ ) { ?> <option value='<?php echo $i; ?>' <?php selected( apply_filters( 'mm_sg_default_qty_themes', 3 ), $i, true ); ?>><?php echo $i; ?></option> <?php } ?> </select> <select name="mojo-sg-platform" class="mojo-sg-platform"> <option value='wordpress' selected>WordPress</option> <option value='joomla'>Joomla</option> <option value='drupal'>Drupal</option> <option value='magento'>Magento</option> <option value='prestashop'>PrestaShop</option> </select> <select name="mojo-sg-type" class="mojo-sg-type"> <option value='themes' selected>Themes</option> <option value='plugins'>Plugins</option> </select> <br/>and I want them to be the most <select name="mojo-sg-items" class="mojo-sg-items"> <option value='popular' selected>Popular</option> <option value='recent'>Recent</option> </select> items. </p> <hr/> <p> Want a specific seller? <input type="text" name="mojo-sg-seller" class="mojo-sg-seller" /> <br/> Would you like to add your affiliate id? <input type="text" name="mojo-sg-aff" class="mojo-sg-aff" /> </p> <br/> <br/> <input class="mm-btn-primary" type="submit" value="Insert Into Content" /> </form> </div> <?php } add_action( 'admin_footer-post-new.php', 'mm_add_inline_popup_content' ); add_action( 'admin_footer-page-new.php', 'mm_add_inline_popup_content' ); add_action( 'admin_footer-post.php', 'mm_add_inline_popup_content' ); add_action( 'admin_footer-page.php', 'mm_add_inline_popup_content' ); add_action( 'admin_footer-widgets.php', 'mm_add_inline_popup_content' ); function mm_sg_js() { ?> <script type="text/javascript"> jQuery( document ).ready( function() { function mm_build_shortcode() { var platform = jQuery( '.mojo-sg-platform' ).val(); var type = jQuery( '.mojo-sg-type' ).val(); var item = jQuery( '.mojo-sg-items' ).val(); var quantity = jQuery( '.mojo-sg-quantity' ).val(); var aff = jQuery( '.mojo-sg-aff' ).val(); var seller = jQuery( '.mojo-sg-seller' ).val(); return "[mojoitem platform='" + platform + "' type='" + type + "' item='" + item + "' quantity='" + quantity + "' seller='" + seller + "' aff='" + aff + "']"; } jQuery( '#mojo-sg-form' ).submit( function( e ) { e.preventDefault(); var shortcode = mm_build_shortcode(); var position = jQuery( '.mojo-sg-position' ).val(); window.parent.send_to_editor( shortcode ); //Close window parent.tb_remove(); } ); } ); </script> <?php } add_action( 'admin_footer-post-new.php', 'mm_sg_js' ); add_action( 'admin_footer-page-new.php', 'mm_sg_js' ); add_action( 'admin_footer-post.php', 'mm_sg_js' ); add_action( 'admin_footer-page.php', 'mm_sg_js' ); add_action( 'admin_footer-widgets.php', 'mm_sg_js' ); function mm_item_shortcode( $atts ) { global $use_mm_styles; $use_mm_styles = true; $defaults = array( 'platform' => 'wordpress', 'type' => 'themes', 'item' => 'recent', 'quantity' => 1, 'aff' => ( defined( 'MMAFF' ) ) ? MMAFF : "", 'seller' => '' ); $atts = wp_parse_args( $atts, $defaults ); $args = array( 'mojo-platform' => $atts['platform'], 'mojo-type' => $atts['type'], 'mojo-items' => $atts['item'], ); $content = "<div class='mojo-items-wrap'>"; $response = mm_api( $args, array( 'count' => $atts['quantity'], 'seller' => $atts['seller'] ) ); if( ! is_wp_error( $response ) ) { $items = json_decode( $response['body'] ); foreach ( $items as $item ) { $item->name = apply_filters( 'mm_item_name', $item->name ); $content .= ' <article class="item"> <div class="box"> <div class="item-photo"> <a target="_blank" class="screenshot" href="' . mm_build_link( $item->page_url, array( 'utm_medium' => 'plugin_shortcode', 'utm_content' => 'item_thumbnail', 'r' => $atts['aff'] ) ) . '"> <img width="68" height="68" alt="' . $item->name . '" src="' . $item->images->square_thumbnail_url . '"> </a> </div> <div class="item-title"> <h3 class="title"> <a target="_blank" href="' . mm_build_link( $item->page_url, array( 'utm_medium' => 'plugin_shorcode', 'utm_content' => 'item_title_link', 'r' => $atts['aff'] ) ) . '">' . $item->name . '</a> </h3> <h5 class="author"> <a target="_blank" href="' . mm_build_link( $item->seller_url, array( 'utm_medium' => 'plugin_shortcode', 'utm_content' => 'item_seller_link', 'r' => $atts['aff'] ) ) . '">' . $item->seller_name . '</a> </h5> </div> <div class="item-details-actions"> <div class="price">$' . $item->prices->single_domain_license . '</div> <div class="sales"> <span class="num">( ' . $item->sales_count . ' Sales )</span> </div> <div class="add-to-cart"> <form accept-charset="utf-8" method="post" id="CartItemRouteForm" target="_blank" enctype="multipart-data" action="' . mm_build_link( 'http://mojomarketplace.com/cart', array( 'utm_medium' => 'plugin_shorcode', 'utm_content' => 'item_add_to_cart_button' ) ) . '"> <input type="hidden" id="CartItemItemId" value="' . $item->id . '" name="data[CartItem][item_id]"> <button class="mm-btn-primary" type="submit">Add to Cart</button> </form> </div> </div> <div class="clear"></div> </div> </article> '; } } $content .= "</div>"; return $content; } add_shortcode( 'mojoitem', 'mm_item_shortcode' );
36.436047
269
0.617999
a12b173987ef3b23435c671b967d1beb35270315
545
ts
TypeScript
src/app/modules/api/tickets/models/ticket-concern.model.ts
kamilk08/BookLoversClient
905c89dff03331425c1efff90d28ca3f140521fc
[ "MIT" ]
null
null
null
src/app/modules/api/tickets/models/ticket-concern.model.ts
kamilk08/BookLoversClient
905c89dff03331425c1efff90d28ca3f140521fc
[ "MIT" ]
null
null
null
src/app/modules/api/tickets/models/ticket-concern.model.ts
kamilk08/BookLoversClient
905c89dff03331425c1efff90d28ca3f140521fc
[ "MIT" ]
null
null
null
export class TicketConcern { public readonly value: number; public readonly name: string constructor(value: number, name: string) { this.value = value; this.name = name; } public static book() { return new TicketConcern(1, 'Book'); } public static author() { return new TicketConcern(2, 'Author'); } } export const TICKET_CONCERNS: TicketConcern[] = [TicketConcern.book(), TicketConcern.author()] export enum TicketConcernEnum { book = TicketConcern.book().value, author = TicketConcern.author().value };
22.708333
94
0.695413
60ce725d35d4e128a870ec88728ad57efcaadee9
29,896
sql
SQL
src/org.xtuml.bp.io.mdl.test/models/sql/BP50_evt.sql
rmulvey/bptest
27a01bf313f7ef3746b6eb9da24ed8c79168323d
[ "Apache-2.0" ]
1
2017-03-22T13:25:12.000Z
2017-03-22T13:25:12.000Z
src/com.mentor.nucleus.bp.io.mdl.test/models/sql/BP50_evt.sql
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
5
2017-03-09T20:43:52.000Z
2017-10-10T19:01:08.000Z
src/com.mentor.nucleus.bp.io.mdl.test/models/sql/BP50_evt.sql
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
30
2017-01-03T21:13:44.000Z
2022-03-25T03:17:20.000Z
-- BP 6.1D content: domain syschar: 3 INSERT INTO S_DOM VALUES (2470000, 'BP50_evt', 'This test deals with the new features of BP5.0 concering events. Generates a pre-created event stored in an attribute from : ( All events are generated from instance.attribute unless otherwise indicated ) - Function - Bridge ( wired to Functions in BP50_evt2 ) - Class Operation - Instance Operation - State Action ( using self.attribute ) - State Action - MDA ', 0, 1); INSERT INTO S_CDT VALUES (524289, 0); INSERT INTO S_DT VALUES (524289, 2470000, 'void', ''); INSERT INTO S_CDT VALUES (524290, 1); INSERT INTO S_DT VALUES (524290, 2470000, 'boolean', ''); INSERT INTO S_CDT VALUES (524291, 2); INSERT INTO S_DT VALUES (524291, 2470000, 'integer', ''); INSERT INTO S_CDT VALUES (524292, 3); INSERT INTO S_DT VALUES (524292, 2470000, 'real', ''); INSERT INTO S_CDT VALUES (524293, 4); INSERT INTO S_DT VALUES (524293, 2470000, 'string', ''); INSERT INTO S_CDT VALUES (524294, 5); INSERT INTO S_DT VALUES (524294, 2470000, 'unique_id', ''); INSERT INTO S_CDT VALUES (524295, 6); INSERT INTO S_DT VALUES (524295, 2470000, 'state<State_Model>', ''); INSERT INTO S_CDT VALUES (524296, 7); INSERT INTO S_DT VALUES (524296, 2470000, 'same_as<Base_Attribute>', ''); INSERT INTO S_CDT VALUES (524297, 8); INSERT INTO S_DT VALUES (524297, 2470000, 'inst_ref<Object>', ''); INSERT INTO S_CDT VALUES (524298, 9); INSERT INTO S_DT VALUES (524298, 2470000, 'inst_ref_set<Object>', ''); INSERT INTO S_CDT VALUES (524299, 10); INSERT INTO S_DT VALUES (524299, 2470000, 'inst<Event>', ''); INSERT INTO S_CDT VALUES (524300, 11); INSERT INTO S_DT VALUES (524300, 2470000, 'inst<Mapping>', ''); INSERT INTO S_CDT VALUES (524301, 12); INSERT INTO S_DT VALUES (524301, 2470000, 'inst_ref<Mapping>', ''); INSERT INTO S_UDT VALUES (524302, 524300, 1); INSERT INTO S_DT VALUES (524302, 2470000, 'date', ''); INSERT INTO S_UDT VALUES (524303, 524300, 2); INSERT INTO S_DT VALUES (524303, 2470000, 'timestamp', ''); INSERT INTO S_UDT VALUES (524304, 524301, 3); INSERT INTO S_DT VALUES (524304, 2470000, 'inst_ref<Timer>', ''); INSERT INTO S_UDT VALUES (524305, 524294, 0); INSERT INTO S_DT VALUES (524305, 2470000, 'arbitrary_id', 'Arbitrary ID with core data type of unique_id.'); INSERT INTO S_SYNC VALUES (524289, 2470000, 'Func_gen_evt', '', 'x = param.func_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance o of O_OBJ2(count:x+1) to o_obj; timer = TIM::timer_start(microseconds:5000000, event_inst:o); e_obj.my_timer = timer; create event instance e2 of E_OBJ2:''Event''(count:x+1) to e_obj; e_obj.my_event = e2; generate e_obj.my_event; ', 524289, 1); INSERT INTO S_SPARM VALUES (524313, 524289, 'func_param', 524291, 1); INSERT INTO S_EE VALUES (524289, 'Logger', '', 'LOG', 2470000); INSERT INTO S_BRG VALUES (524290, 524289, 'LogFailure', '', 0, 524289, '', 1); INSERT INTO S_BPARM VALUES (524289, 524290, 'message', 524293, 0); INSERT INTO S_BRG VALUES (524291, 524289, 'LogSuccess', '', 0, 524289, '', 1); INSERT INTO S_BPARM VALUES (524290, 524291, 'message', 524293, 0); INSERT INTO S_EE VALUES (524290, 'Architecture', '', 'ARCH', 2470000); INSERT INTO S_BRG VALUES (524289, 524290, 'shutdown', '', 0, 524289, '', 1); INSERT INTO S_EE VALUES (524291, 'Time', '', 'TIM', 2470000); INSERT INTO S_BRG VALUES (524292, 524291, 'current_date', '', 1, 524302, '', 0); INSERT INTO S_BRG VALUES (524293, 524291, 'create_date', '', 1, 524302, '', 0); INSERT INTO S_BPARM VALUES (524291, 524293, 'second', 524291, 0); INSERT INTO S_BPARM VALUES (524292, 524293, 'minute', 524291, 0); INSERT INTO S_BPARM VALUES (524293, 524293, 'hour', 524291, 0); INSERT INTO S_BPARM VALUES (524294, 524293, 'day', 524291, 0); INSERT INTO S_BPARM VALUES (524295, 524293, 'month', 524291, 0); INSERT INTO S_BPARM VALUES (524296, 524293, 'year', 524291, 0); INSERT INTO S_BRG VALUES (524294, 524291, 'get_second', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524297, 524294, 'date', 524302, 0); INSERT INTO S_BRG VALUES (524295, 524291, 'get_minute', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524298, 524295, 'date', 524302, 0); INSERT INTO S_BRG VALUES (524296, 524291, 'get_hour', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524299, 524296, 'date', 524302, 0); INSERT INTO S_BRG VALUES (524297, 524291, 'get_day', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524300, 524297, 'date', 524302, 0); INSERT INTO S_BRG VALUES (524298, 524291, 'get_month', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524301, 524298, 'date', 524302, 0); INSERT INTO S_BRG VALUES (524299, 524291, 'get_year', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524302, 524299, 'date', 524302, 0); INSERT INTO S_BRG VALUES (524300, 524291, 'current_clock', '', 1, 524303, '', 0); INSERT INTO S_BRG VALUES (524301, 524291, 'timer_start', '', 1, 524304, '', 0); INSERT INTO S_BPARM VALUES (524303, 524301, 'microseconds', 524291, 0); INSERT INTO S_BPARM VALUES (524304, 524301, 'event_inst', 524299, 0); INSERT INTO S_BRG VALUES (524302, 524291, 'timer_start_recurring', '', 1, 524304, '', 0); INSERT INTO S_BPARM VALUES (524305, 524302, 'microseconds', 524291, 0); INSERT INTO S_BPARM VALUES (524306, 524302, 'event_inst', 524299, 0); INSERT INTO S_BRG VALUES (524303, 524291, 'timer_remaining_time', '', 1, 524291, '', 0); INSERT INTO S_BPARM VALUES (524307, 524303, 'timer_inst_ref', 524304, 0); INSERT INTO S_BRG VALUES (524304, 524291, 'timer_reset_time', '', 1, 524290, '', 0); INSERT INTO S_BPARM VALUES (524308, 524304, 'timer_inst_ref', 524304, 0); INSERT INTO S_BPARM VALUES (524309, 524304, 'microseconds', 524291, 0); INSERT INTO S_BRG VALUES (524305, 524291, 'timer_add_time', '', 1, 524290, '', 0); INSERT INTO S_BPARM VALUES (524310, 524305, 'timer_inst_ref', 524304, 0); INSERT INTO S_BPARM VALUES (524311, 524305, 'microseconds', 524291, 0); INSERT INTO S_BRG VALUES (524306, 524291, 'timer_cancel', '', 1, 524290, '', 0); INSERT INTO S_BPARM VALUES (524312, 524306, 'timer_inst_ref', 524304, 0); INSERT INTO S_EE VALUES (524292, 'Extern', '', 'EE', 2470000); INSERT INTO S_BRG VALUES (524307, 524292, 'brdg_gen_evt', 'x = param.brdg_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance e of O_OBJ2:''TimeOut'' to o_obj; timer = TIM::timer_start(microseconds:1000000, event_inst:e); create event instance e2 of E_OBJ2:''Event''(count:x+1, timer:timer) to e_obj; e_obj.my_event = e2; generate e_obj.my_event; ', 0, 524289, 'x = param.brdg_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance o of O_OBJ2(count:x+2) to o_obj; timer = TIM::timer_start(microseconds:5000000, event_inst:o); e_obj.my_timer = timer; create event instance e2 of E_OBJ2:''Event''(count:x+2) to e_obj; e_obj.my_event = e2; generate e_obj.my_event; ', 1); INSERT INTO S_BPARM VALUES (524314, 524307, 'brdg_param', 524291, 1); INSERT INTO GD_MD VALUES (524289, 1, 2470000, 1, 1, 0, 1, 1, 0, 12, 1647, 4154, 1.000000, 0); INSERT INTO GD_GE VALUES (524296, 524289, 1048578, 11); INSERT INTO GD_SHP VALUES (524296, 1680, 1264, 1920, 1392); INSERT INTO GD_GE VALUES (524309, 524289, 524289, 12); INSERT INTO GD_SHP VALUES (524309, 1680, 1408, 1920, 1536); INSERT INTO GD_GE VALUES (524310, 524289, 524290, 12); INSERT INTO GD_SHP VALUES (524310, 1968, 1408, 2208, 1536); INSERT INTO GD_GE VALUES (524311, 524289, 524291, 12); INSERT INTO GD_SHP VALUES (524311, 1680, 1552, 1920, 1680); INSERT INTO GD_GE VALUES (524319, 524289, 524292, 12); INSERT INTO GD_SHP VALUES (524319, 1968, 1264, 2208, 1392); INSERT INTO GD_MD VALUES (524290, 2, 2470000, 1, 1, 0, 1, 1, 0, 12, 1600, 4200, 1.000000, 0); INSERT INTO GD_GE VALUES (524297, 524290, 1048578, 11); INSERT INTO GD_SHP VALUES (524297, 1680, 1264, 1920, 1424); INSERT INTO GD_MD VALUES (524291, 3, 2470000, 1, 1, 0, 1, 1, 0, 12, 1600, 4200, 1.000000, 0); INSERT INTO GD_GE VALUES (524298, 524291, 1048578, 11); INSERT INTO GD_SHP VALUES (524298, 1680, 1264, 1920, 1424); INSERT INTO GD_MD VALUES (524292, 4, 2470000, 1, 1, 0, 1, 1, 0, 12, 1600, 4200, 1.000000, 0); INSERT INTO GD_GE VALUES (524299, 524292, 1048578, 11); INSERT INTO GD_SHP VALUES (524299, 1680, 1264, 1920, 1424); INSERT INTO S_SS VALUES (1048578, 'Event_generation', '', 'EVT', 1, 2470000, 1048578); INSERT INTO O_OBJ VALUES (1048577, 'Initialization Object', 1, 'INIT', '', 1048578); INSERT INTO O_NBATTR VALUES (1048577, 1048577); INSERT INTO O_BATTR VALUES (1048577, 1048577); INSERT INTO O_ATTR VALUES (1048577, 1048577, 0, 'current_state', '', '', 'current_state', 0, 524295); INSERT INTO SM_ISM VALUES (1572867, 1048577); INSERT INTO SM_SM VALUES (1572867, '', 3); INSERT INTO SM_MOORE VALUES (1572867); INSERT INTO SM_SUPDT VALUES (1572865, 1572867, 0); INSERT INTO SM_STATE VALUES (1572865, 1572867, 1572865, 'Init', 1, 0); INSERT INTO SM_LEVT VALUES (1572865, 1572867, 1572865); INSERT INTO SM_SEVT VALUES (1572865, 1572867, 1572865); INSERT INTO SM_EVT VALUES (1572865, 1572867, 1572865, 1, 'Init', 0, '', 'INIT1', ''); INSERT INTO SM_SEME VALUES (1572865, 1572865, 1572867, 1572865); INSERT INTO SM_NSTXN VALUES (1572865, 1572867, 1572865, 1572865, 1572865); INSERT INTO SM_TXN VALUES (1572865, 1572867, 1572865, 1572865); INSERT INTO SM_MOAH VALUES (1572865, 1572867, 1572865); INSERT INTO SM_AH VALUES (1572865, 1572867); INSERT INTO SM_ACT VALUES (1572865, 1572867, 1, 'create object instance e_obj of E_OBJ; create object instance o_obj of O_OBJ; generate E_OBJ1:''Start'' to e_obj;', ''); INSERT INTO GD_MD VALUES (1572865, 8, 1572867, 40, 1, 0, 1, 1, 0, 12, 1600, 4142, 1.000000, 0); INSERT INTO GD_GE VALUES (1572866, 1572865, 1572865, 41); INSERT INTO GD_SHP VALUES (1572866, 1776, 1360, 2016, 1568); INSERT INTO GD_GE VALUES (1572867, 1572865, 1572865, 42); INSERT INTO GD_CON VALUES (1572867, 1572866, 1572866, 0); INSERT INTO GD_CTXT VALUES (1572867, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (1572868, 1572867, 1808, 1360, 1808, 1328, 0); INSERT INTO GD_LS VALUES (1572869, 1572867, 1808, 1328, 1984, 1328, 1572868); INSERT INTO GD_LS VALUES (1572870, 1572867, 1984, 1328, 1984, 1360, 1572869); INSERT INTO O_OBJ VALUES (1048578, 'Event Object', 2, 'E_OBJ', '', 1048578); INSERT INTO O_TFR VALUES (1048577, 1048578, 'op_gen_evt_c', 'x = param.op_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance e of O_OBJ2:''TimeOut'' to o_obj; timer = TIM::timer_start(microseconds:1000000, event_inst:e); create event instance e2 of E_OBJ2:''Event''(count:x+1, timer:timer) to e_obj; e_obj.my_event = e2; generate e_obj.my_event; ', 524289, 0, 'x = param.op_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance o of O_OBJ2(count:x+1) to o_obj; timer = TIM::timer_start(microseconds:5000000, event_inst:o); e_obj.my_timer = timer; create event instance e2 of E_OBJ2:''Event''(count:x+1) to e_obj; e_obj.my_event = e2; generate e_obj.my_event;', 1); INSERT INTO O_TPARM VALUES (1048577, 1048577, 'op_param', 524291, 1); INSERT INTO O_TFR VALUES (1048578, 1048578, 'op_gen_evt_i', 'x = param.op_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance e of O_OBJ2:''TimeOut'' to o_obj; timer = TIM::timer_start(microseconds:1000000, event_inst:e); create event instance e2 of E_OBJ2:''Event''(count:x+1, timer:timer) to e_obj; e_obj.my_event = e2; generate e_obj.my_event;', 524289, 1, 'x = param.op_param; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance o of O_OBJ2(count:x+1) to o_obj; timer = TIM::timer_start(microseconds:5000000, event_inst:o); e_obj.my_timer = timer; create event instance e2 of E_OBJ2:''Event''(count:x+1) to e_obj; e_obj.my_event = e2; generate e_obj.my_event;', 1); INSERT INTO O_TPARM VALUES (1048578, 1048578, 'op_param', 524291, 1); INSERT INTO O_NBATTR VALUES (1048578, 1048578); INSERT INTO O_BATTR VALUES (1048578, 1048578); INSERT INTO O_ATTR VALUES (1048578, 1048578, 0, 'my_event', '', '', 'my_event', 0, 524299); INSERT INTO O_NBATTR VALUES (1048580, 1048578); INSERT INTO O_BATTR VALUES (1048580, 1048578); INSERT INTO O_ATTR VALUES (1048580, 1048578, 1048578, 'e_obj_id', '', '', 'e_obj_id', 0, 524294); INSERT INTO O_NBATTR VALUES (1048579, 1048578); INSERT INTO O_BATTR VALUES (1048579, 1048578); INSERT INTO O_ATTR VALUES (1048579, 1048578, 1048580, 'current_state', '', '', 'current_state', 0, 524295); INSERT INTO O_DBATTR VALUES (1048583, 1048578, 'self.mda_gen_evt = 7; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance o of O_OBJ2(count:8) to o_obj; timer = TIM::timer_start(microseconds:5000000, event_inst:o); self.my_timer = timer; create event instance e2 of E_OBJ2:''Event''(count:8) to e_obj; e_obj.my_event = e2; generate e_obj.my_event; ', 1); INSERT INTO O_BATTR VALUES (1048583, 1048578); INSERT INTO O_ATTR VALUES (1048583, 1048578, 1048579, 'mda_gen_evt', 'self.mda_gen_evt = 7; select any e_obj from instances of E_OBJ; select any o_obj from instances of O_OBJ; create event instance e of O_OBJ2:''TimeOut'' to o_obj; timer = TIM::timer_start(microseconds:1000000, event_inst:e); create event instance e2 of E_OBJ2:''Event''(count:8, timer:timer) to e_obj; e_obj.my_event = e2; generate e_obj.my_event;', '', 'mda_gen_evt', 0, 524291); INSERT INTO O_NBATTR VALUES (1048584, 1048578); INSERT INTO O_BATTR VALUES (1048584, 1048578); INSERT INTO O_ATTR VALUES (1048584, 1048578, 1048583, 'my_timer', '', '', 'my_timer', 0, 524304); INSERT INTO O_ID VALUES (0, 1048578); INSERT INTO O_OIDA VALUES (1048580, 1048578, 0); INSERT INTO SM_ISM VALUES (2097156, 1048578); INSERT INTO SM_SM VALUES (2097156, '', 4); INSERT INTO SM_MOORE VALUES (2097156); INSERT INTO SM_EVTDI VALUES (2097154, 2097156, 'count', '', 524291); INSERT INTO SM_SUPDT VALUES (2097153, 2097156, 0); INSERT INTO SM_SUPDT VALUES (2097156, 2097156, 0); INSERT INTO SM_SDI VALUES (2097154, 2097156, 2097156); INSERT INTO SM_STATE VALUES (2097153, 2097156, 2097153, 'Event_State_1', 1, 0); INSERT INTO SM_LEVT VALUES (2097153, 2097156, 2097153); INSERT INTO SM_SEVT VALUES (2097153, 2097156, 2097153); INSERT INTO SM_EVT VALUES (2097153, 2097156, 2097153, 1, 'Start', 0, '', 'E_OBJ1', ''); INSERT INTO SM_SEME VALUES (2097153, 2097153, 2097156, 2097153); INSERT INTO SM_LEVT VALUES (2097154, 2097156, 2097156); INSERT INTO SM_SEVT VALUES (2097154, 2097156, 2097156); INSERT INTO SM_EVT VALUES (2097154, 2097156, 2097156, 2, 'Event', 0, '', 'E_OBJ2', ''); INSERT INTO SM_SEME VALUES (2097153, 2097154, 2097156, 2097156); INSERT INTO SM_LEVT VALUES (2097155, 2097156, 2097156); INSERT INTO SM_SEVT VALUES (2097155, 2097156, 2097156); INSERT INTO SM_EVT VALUES (2097155, 2097156, 2097156, 3, 'TimeOut', 0, '', 'E_OBJ3', ''); INSERT INTO SM_SEME VALUES (2097153, 2097155, 2097156, 2097156); INSERT INTO SM_STATE VALUES (2097154, 2097156, 2097156, 'Event_State_2', 2, 0); INSERT INTO SM_EIGN VALUES (2097154, 2097153, 2097156, 2097153, ''); INSERT INTO SM_SEME VALUES (2097154, 2097153, 2097156, 2097153); INSERT INTO SM_SEME VALUES (2097154, 2097154, 2097156, 2097156); INSERT INTO SM_EIGN VALUES (2097154, 2097155, 2097156, 2097156, ''); INSERT INTO SM_SEME VALUES (2097154, 2097155, 2097156, 2097156); INSERT INTO SM_STATE VALUES (2097155, 2097156, 2097156, 'Timed_Out', 3, 0); INSERT INTO SM_EIGN VALUES (2097155, 2097153, 2097156, 2097153, ''); INSERT INTO SM_SEME VALUES (2097155, 2097153, 2097156, 2097153); INSERT INTO SM_SEME VALUES (2097155, 2097154, 2097156, 2097156); INSERT INTO SM_EIGN VALUES (2097155, 2097155, 2097156, 2097156, ''); INSERT INTO SM_SEME VALUES (2097155, 2097155, 2097156, 2097156); INSERT INTO SM_NSTXN VALUES (2097153, 2097156, 2097153, 2097153, 2097153); INSERT INTO SM_TXN VALUES (2097153, 2097156, 2097153, 2097153); INSERT INTO SM_NSTXN VALUES (2097154, 2097156, 2097153, 2097154, 2097156); INSERT INTO SM_TXN VALUES (2097154, 2097156, 2097154, 2097156); INSERT INTO SM_NSTXN VALUES (2097155, 2097156, 2097154, 2097154, 2097156); INSERT INTO SM_TXN VALUES (2097155, 2097156, 2097154, 2097156); INSERT INTO SM_NSTXN VALUES (2097156, 2097156, 2097153, 2097155, 2097156); INSERT INTO SM_TXN VALUES (2097156, 2097156, 2097155, 2097156); INSERT INTO SM_NSTXN VALUES (2097158, 2097156, 2097155, 2097154, 2097156); INSERT INTO SM_TXN VALUES (2097158, 2097156, 2097154, 2097156); INSERT INTO SM_MOAH VALUES (2097153, 2097156, 2097153); INSERT INTO SM_AH VALUES (2097153, 2097156); INSERT INTO SM_ACT VALUES (2097153, 2097156, 1, 'create event instance e2 of E_OBJ3(count:0) to self; timer = TIM::timer_start(microseconds:5000000, event_inst:e2); self.my_timer = timer; create event instance e of E_OBJ2:''Event''(count:0) to self; self.my_event = e; generate self.my_event; ', ''); INSERT INTO SM_MOAH VALUES (2097154, 2097156, 2097154); INSERT INTO SM_AH VALUES (2097154, 2097156); INSERT INTO SM_ACT VALUES (2097154, 2097156, 1, 'bool = TIM::timer_cancel(timer_inst_ref:self.my_timer); if ( bool == TRUE ) LOG::LogSuccess(message:"Self-Attribute Event Received in State Action."); else LOG::LogFailure(message:"Self-Attribute Event NOT Received in State Action."); end if; count = rcvd_evt.count; if(count <= 7) select any o_obj from instances of O_OBJ; generate O_OBJ1:''Start''(count:count) to o_obj; else ARCH::shutdown(); control stop; end if;', ''); INSERT INTO SM_MOAH VALUES (2097155, 2097156, 2097155); INSERT INTO SM_AH VALUES (2097155, 2097156); INSERT INTO SM_ACT VALUES (2097155, 2097156, 1, 'generate E_OBJ2(count:rcvd_evt.count) to self; ', ''); INSERT INTO GD_MD VALUES (2097153, 8, 2097156, 40, 1, 0, 1, 1, 0, 12, 1654, 3995, 0.671540, 0); INSERT INTO GD_GE VALUES (2097154, 2097153, 2097153, 41); INSERT INTO GD_SHP VALUES (2097154, 1648, 1296, 2176, 1472); INSERT INTO GD_GE VALUES (2097177, 2097153, 2097154, 41); INSERT INTO GD_SHP VALUES (2097177, 1648, 1552, 2176, 1840); INSERT INTO GD_GE VALUES (2097184, 2097153, 2097155, 41); INSERT INTO GD_SHP VALUES (2097184, 2352, 1328, 2800, 1408); INSERT INTO GD_GE VALUES (2097155, 2097153, 2097153, 42); INSERT INTO GD_CON VALUES (2097155, 2097154, 2097154, 0); INSERT INTO GD_CTXT VALUES (2097155, 0, 0, 0, 0, 0, 0, 1818, 1229, 1919, 1251, -6, -7, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2097373, 2097155, 1776, 1296, 1776, 1264, 0); INSERT INTO GD_LS VALUES (2097374, 2097155, 1776, 1264, 1968, 1264, 2097373); INSERT INTO GD_LS VALUES (2097375, 2097155, 1968, 1264, 1968, 1296, 2097374); INSERT INTO GD_GE VALUES (2097178, 2097153, 2097154, 42); INSERT INTO GD_CON VALUES (2097178, 2097154, 2097177, 0); INSERT INTO GD_CTXT VALUES (2097178, 0, 0, 0, 0, 0, 0, 1904, 1498, 2107, 1520, 225, -5, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2097504, 2097178, 1888, 1472, 1888, 1552, 0); INSERT INTO GD_GE VALUES (2097180, 2097153, 2097155, 42); INSERT INTO GD_CON VALUES (2097180, 2097177, 2097177, 0); INSERT INTO GD_CTXT VALUES (2097180, 0, 0, 0, 0, 0, 0, 2239, 1688, 2442, 1710, 224, 1, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2097547, 2097180, 2176, 1808, 2224, 1808, 0); INSERT INTO GD_LS VALUES (2097548, 2097180, 2224, 1808, 2224, 1584, 2097547); INSERT INTO GD_LS VALUES (2097549, 2097180, 2224, 1584, 2176, 1584, 2097548); INSERT INTO GD_GE VALUES (2097185, 2097153, 2097156, 42); INSERT INTO GD_CON VALUES (2097185, 2097154, 2097184, 0); INSERT INTO GD_CTXT VALUES (2097185, 0, 0, 0, 0, 0, 0, 2202, 1328, 2329, 1350, -1, -20, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2097553, 2097185, 2176, 1376, 2352, 1376, 0); INSERT INTO GD_GE VALUES (2097554, 2097153, 2097158, 42); INSERT INTO GD_CON VALUES (2097554, 2097184, 2097177, 0); INSERT INTO GD_CTXT VALUES (2097554, 0, 0, 0, 0, 0, 0, 2272, 1477, 2409, 1499, 183, 15, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2097555, 2097554, 2384, 1408, 2080, 1552, 0); INSERT INTO O_OBJ VALUES (1048579, 'Other Object', 3, 'O_OBJ', '', 1048578); INSERT INTO O_NBATTR VALUES (1048581, 1048579); INSERT INTO O_BATTR VALUES (1048581, 1048579); INSERT INTO O_ATTR VALUES (1048581, 1048579, 0, 'o_obj_id', '', '', 'o_obj_id', 0, 524294); INSERT INTO O_NBATTR VALUES (1048582, 1048579); INSERT INTO O_BATTR VALUES (1048582, 1048579); INSERT INTO O_ATTR VALUES (1048582, 1048579, 1048581, 'current_state', '', '', 'current_state', 0, 524295); INSERT INTO O_ID VALUES (0, 1048579); INSERT INTO O_OIDA VALUES (1048581, 1048579, 0); INSERT INTO SM_ISM VALUES (2621445, 1048579); INSERT INTO SM_SM VALUES (2621445, '', 5); INSERT INTO SM_MOORE VALUES (2621445); INSERT INTO SM_EVTDI VALUES (2621441, 2621445, 'count', '', 524291); INSERT INTO SM_SUPDT VALUES (2621441, 2621445, 0); INSERT INTO SM_SDI VALUES (2621441, 2621441, 2621445); INSERT INTO SM_STATE VALUES (2621441, 2621445, 2621441, 'Other_State', 1, 0); INSERT INTO SM_LEVT VALUES (2621441, 2621445, 2621441); INSERT INTO SM_SEVT VALUES (2621441, 2621445, 2621441); INSERT INTO SM_EVT VALUES (2621441, 2621445, 2621441, 1, 'Start', 0, '', 'O_OBJ1', ''); INSERT INTO SM_SEME VALUES (2621441, 2621441, 2621445, 2621441); INSERT INTO SM_LEVT VALUES (2621442, 2621445, 2621441); INSERT INTO SM_SEVT VALUES (2621442, 2621445, 2621441); INSERT INTO SM_EVT VALUES (2621442, 2621445, 2621441, 2, 'TimeOut', 0, '', 'O_OBJ2', ''); INSERT INTO SM_SEME VALUES (2621441, 2621442, 2621445, 2621441); INSERT INTO SM_STATE VALUES (2621442, 2621445, 2621441, 'Timed_Out', 2, 0); INSERT INTO SM_EIGN VALUES (2621442, 2621441, 2621445, 2621441, ''); INSERT INTO SM_SEME VALUES (2621442, 2621441, 2621445, 2621441); INSERT INTO SM_SEME VALUES (2621442, 2621442, 2621445, 2621441); INSERT INTO SM_NSTXN VALUES (2621441, 2621445, 2621441, 2621441, 2621441); INSERT INTO SM_TXN VALUES (2621441, 2621445, 2621441, 2621441); INSERT INTO SM_NSTXN VALUES (2621442, 2621445, 2621441, 2621442, 2621441); INSERT INTO SM_TXN VALUES (2621442, 2621445, 2621442, 2621441); INSERT INTO SM_NSTXN VALUES (2621443, 2621445, 2621442, 2621442, 2621441); INSERT INTO SM_TXN VALUES (2621443, 2621445, 2621442, 2621441); INSERT INTO SM_MOAH VALUES (2621441, 2621445, 2621441); INSERT INTO SM_AH VALUES (2621441, 2621445); INSERT INTO SM_ACT VALUES (2621441, 2621445, 1, 'x = rcvd_evt.count; select any e_obj from instances of E_OBJ; if(x <= 1) create event instance o of O_OBJ2(count:x+1) to self; timer = TIM::timer_start(microseconds:5000000, event_inst:o); e_obj.my_timer = timer; create event instance e2 of E_OBJ2:''Event''(count:rcvd_evt.count+1) to e_obj; e_obj.my_event = e2; generate e_obj.my_event; elif (x == 2) EE::brdg_gen_evt(brdg_param:x); elif (x == 4) e_obj.op_gen_evt_i(op_param:x); elif (x == 5) E_OBJ::op_gen_evt_c(op_param:x); else if( e_obj.mda_gen_evt == 7) LOG::LogSuccess(message:"Accessing MDA"); end if; end if; ', ''); INSERT INTO SM_MOAH VALUES (2621442, 2621445, 2621442); INSERT INTO SM_AH VALUES (2621442, 2621445); INSERT INTO SM_ACT VALUES (2621442, 2621445, 1, 'select any e_obj from instances of E_OBJ; generate E_OBJ2(count:rcvd_evt.count) to e_obj;', ''); INSERT INTO GD_MD VALUES (2621441, 8, 2621445, 40, 1, 0, 1, 1, 0, 12, 1642, 4015, 0.801897, 0); INSERT INTO GD_GE VALUES (2621442, 2621441, 2621441, 41); INSERT INTO GD_SHP VALUES (2621442, 1664, 1296, 2384, 1744); INSERT INTO GD_GE VALUES (2621453, 2621441, 2621442, 41); INSERT INTO GD_SHP VALUES (2621453, 1664, 1840, 2384, 1952); INSERT INTO GD_GE VALUES (2621443, 2621441, 2621441, 42); INSERT INTO GD_CON VALUES (2621443, 2621442, 2621442, 0); INSERT INTO GD_CTXT VALUES (2621443, 0, 0, 0, 0, 0, 0, 1947, 1227, 2102, 1249, -2, -9, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2621593, 2621443, 1696, 1296, 1696, 1264, 0); INSERT INTO GD_LS VALUES (2621594, 2621443, 1696, 1264, 2352, 1264, 2621593); INSERT INTO GD_LS VALUES (2621595, 2621443, 2352, 1264, 2352, 1296, 2621594); INSERT INTO GD_GE VALUES (2621454, 2621441, 2621442, 42); INSERT INTO GD_CON VALUES (2621454, 2621442, 2621453, 0); INSERT INTO GD_CTXT VALUES (2621454, 0, 0, 0, 0, 0, 0, 1962, 1779, 2143, 1801, 213, -4, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2621605, 2621454, 1936, 1744, 1936, 1840, 0); INSERT INTO GD_GE VALUES (2621606, 2621441, 2621443, 42); INSERT INTO GD_CON VALUES (2621606, 2621453, 2621453, 0); INSERT INTO GD_CTXT VALUES (2621606, 0, 0, 0, 0, 0, 0, 2441, 1884, 2622, 1906, 196, -3, 0, 0, 0, 0, 0, 0); INSERT INTO GD_LS VALUES (2621607, 2621606, 2384, 1936, 2432, 1936, 0); INSERT INTO GD_LS VALUES (2621608, 2621606, 2432, 1936, 2432, 1856, 2621607); INSERT INTO GD_LS VALUES (2621609, 2621606, 2432, 1856, 2384, 1856, 2621608); INSERT INTO GD_MD VALUES (1048581, 5, 1048578, 11, 1, 0, 1, 1, 0, 12, 1600, 4142, 1.000000, 0); INSERT INTO GD_GE VALUES (1048588, 1048581, 1048577, 21); INSERT INTO GD_SHP VALUES (1048588, 1712, 1280, 1984, 1456); INSERT INTO GD_GE VALUES (1048591, 1048581, 1048578, 21); INSERT INTO GD_SHP VALUES (1048591, 1712, 1504, 1984, 1712); INSERT INTO GD_GE VALUES (1048594, 1048581, 1048579, 21); INSERT INTO GD_SHP VALUES (1048594, 2032, 1280, 2272, 1456); INSERT INTO GD_MD VALUES (1048582, 6, 1048578, 11, 1, 0, 1, 1, 0, 12, 1600, 4200, 1.000000, 0); INSERT INTO GD_GE VALUES (1048590, 1048582, 1048577, 21); INSERT INTO GD_SHP VALUES (1048590, 1712, 1280, 1904, 1344); INSERT INTO GD_GE VALUES (1048593, 1048582, 1048578, 21); INSERT INTO GD_SHP VALUES (1048593, 1712, 1504, 1904, 1568); INSERT INTO GD_GE VALUES (1048596, 1048582, 1048579, 21); INSERT INTO GD_SHP VALUES (1048596, 2032, 1280, 2224, 1344); INSERT INTO GD_MD VALUES (1048583, 7, 1048578, 11, 1, 0, 1, 1, 0, 12, 1600, 4200, 1.000000, 0); INSERT INTO GD_GE VALUES (1048589, 1048583, 1048577, 21); INSERT INTO GD_SHP VALUES (1048589, 1712, 1280, 1904, 1344); INSERT INTO GD_GE VALUES (1048592, 1048583, 1048578, 21); INSERT INTO GD_SHP VALUES (1048592, 1712, 1504, 1904, 1568); INSERT INTO GD_GE VALUES (1048595, 1048583, 1048579, 21); INSERT INTO GD_SHP VALUES (1048595, 2032, 1280, 2224, 1344);
13.847151
83
0.632794
851bf080118d5ddd9c448a1b6f8b286c0ac02977
2,917
cs
C#
Source/MonoGame.Extended.Tests/Vector2ExtensionsTests.cs
Measurity/MonoGame.Extended
7fadd78fd26bb8be68ec598c971d69285f58853f
[ "MIT" ]
1
2020-01-09T02:39:40.000Z
2020-01-09T02:39:40.000Z
Source/MonoGame.Extended.Tests/Vector2ExtensionsTests.cs
sslm74/MonoGame.Extended
7fadd78fd26bb8be68ec598c971d69285f58853f
[ "MIT" ]
null
null
null
Source/MonoGame.Extended.Tests/Vector2ExtensionsTests.cs
sslm74/MonoGame.Extended
7fadd78fd26bb8be68ec598c971d69285f58853f
[ "MIT" ]
1
2020-01-08T23:39:45.000Z
2020-01-08T23:39:45.000Z
using System; using Microsoft.Xna.Framework; using NUnit.Framework; namespace MonoGame.Extended.Tests { [TestFixture] public class Vector2ExtensionsTests { [Test] public void Vector2_EqualsWithTolerence_Test() { var a = new Vector2(1f, 1f); var b = new Vector2(1.0000001f, 1.0000001f); Assert.IsFalse(a.Equals(b)); Assert.IsTrue(a.EqualsWithTolerance(b)); } [Test] public void Vector2_NormalizedCopy_Test() { var a = new Vector2(5, -10); var b = a.NormalizedCopy(); Assert.IsTrue(new Vector2(0.4472136f, -0.8944272f).EqualsWithTolerance(b)); } [Test] public void Vector2_Perpendicular_Test() { var a = new Vector2(5, -10); var b = a.PerpendicularClockwise(); var c = a.PerpendicularCounterClockwise(); Assert.AreEqual(new Vector2(10, 5), b); Assert.AreEqual(new Vector2(-10, -5), c); } [Test] public void Vector2_Rotate_90_Degrees_Test() { var a = new Vector2(0, -10); var b = a.Rotate(MathHelper.ToRadians(90)); Assert.IsTrue(new Vector2(10, 0).EqualsWithTolerance(b)); } [Test] public void Vector2_Rotate_360_Degrees_Test() { var a = new Vector2(0, 10); var b = a.Rotate(MathHelper.ToRadians(360)); Assert.IsTrue(new Vector2(0, 10).EqualsWithTolerance(b)); } [Test] public void Vector2_Rotate_45_Degrees_Test() { var a = new Vector2(0, -10); var b = a.Rotate(MathHelper.ToRadians(45)); Assert.IsTrue(new Vector2(7.071068f, -7.071068f).EqualsWithTolerance(b)); } [Test] public void Vector2_Truncate_Test() { var a = new Vector2(10, 10); var b = a.Truncate(5); Assert.AreEqual(5f, b.Length(), 0.001f); } [Test] public void Vector2_IsNaN_Test() { var a = new Vector2(float.NaN, 10); var b = new Vector2(10, float.NaN); var c = new Vector2(float.NaN, float.NaN); var d = new Vector2(10, 10); Assert.IsTrue(a.IsNaN()); Assert.IsTrue(b.IsNaN()); Assert.IsTrue(c.IsNaN()); Assert.IsFalse(d.IsNaN()); } [Test] public void Vector2_ToAngle_Test() { var a = new Vector2(0, -10); var b = new Vector2(10, 0); var c = -Vector2.UnitY.Rotate(MathHelper.ToRadians(45)); Assert.AreEqual(MathHelper.ToRadians(0), a.ToAngle()); Assert.AreEqual(MathHelper.ToRadians(90), b.ToAngle()); Assert.AreEqual(MathHelper.ToRadians(45), c.ToAngle()); } } }
28.598039
87
0.533082
3872871b383f15087dfeb30fc02e58b7189e4c2e
251
php
PHP
app/Http/Controllers/Production/ProductionController.php
moinularif/mtrims
170999adbb736f30c681517c72336bca6ebf9f69
[ "MIT" ]
null
null
null
app/Http/Controllers/Production/ProductionController.php
moinularif/mtrims
170999adbb736f30c681517c72336bca6ebf9f69
[ "MIT" ]
null
null
null
app/Http/Controllers/Production/ProductionController.php
moinularif/mtrims
170999adbb736f30c681517c72336bca6ebf9f69
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Production; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class ProductionController extends Controller { public function index(){ return view('production.layout.index'); } }
17.928571
47
0.74502
a60b894d14aca696763bf969c8b3db1cba2a1b6b
358
rb
Ruby
Chapter 09/circuit-oneops-1-master/components/cookbooks/hadoop-yarn-v1/recipes/secondarynamenode_stop.rb
PacktPublishing/Practical-OneOps
74f7e3b60051101a5560a69523b25b9868cc5bec
[ "MIT" ]
1
2018-04-11T20:26:13.000Z
2018-04-11T20:26:13.000Z
Chapter 09/circuit-oneops-1-master/components/cookbooks/hadoop-yarn-v1/recipes/secondarynamenode_stop.rb
PacktPublishing/Practical-OneOps
74f7e3b60051101a5560a69523b25b9868cc5bec
[ "MIT" ]
null
null
null
Chapter 09/circuit-oneops-1-master/components/cookbooks/hadoop-yarn-v1/recipes/secondarynamenode_stop.rb
PacktPublishing/Practical-OneOps
74f7e3b60051101a5560a69523b25b9868cc5bec
[ "MIT" ]
1
2019-12-25T15:54:18.000Z
2019-12-25T15:54:18.000Z
# # Cookbook Name:: hadoop-yarn-v1 # Recipe:: secondarynamenode_stop # # # stop secondarynamenode ruby_block "Stop hadoop-secondarynamenode service" do block do Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut) shell_out!("service hadoop-secondarynamenode stop ", :live_stream => Chef::Log::logger) end end
23.866667
71
0.692737
d965091c1b61a57e909515db8d4117dd623a9cf8
14,257
rs
Rust
tests/all/closures.rs
spastorino/wasm-bindgen
a02f9e0eed3052bef6ad9847a09ae69b877c5bf3
[ "Apache-2.0", "MIT" ]
null
null
null
tests/all/closures.rs
spastorino/wasm-bindgen
a02f9e0eed3052bef6ad9847a09ae69b877c5bf3
[ "Apache-2.0", "MIT" ]
null
null
null
tests/all/closures.rs
spastorino/wasm-bindgen
a02f9e0eed3052bef6ad9847a09ae69b877c5bf3
[ "Apache-2.0", "MIT" ]
1
2020-06-08T16:52:38.000Z
2020-06-08T16:52:38.000Z
use super::project; #[test] fn works() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use std::cell::Cell; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call(a: &Fn()); fn thread(a: &Fn(u32) -> u32) -> u32; } #[wasm_bindgen] pub fn run() { let a = Cell::new(false); call(&|| a.set(true)); assert!(a.get()); assert_eq!(thread(&|a| a + 1), 3); } "#) .file("test.ts", r#" import { run } from "./out"; export function call(a: any) { a(); } export function thread(a: any) { return a(2); } export function test() { run(); } "#) .test(); } #[test] fn cannot_reuse() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call(a: &Fn()); #[wasm_bindgen(catch)] fn call_again() -> Result<(), JsValue>; } #[wasm_bindgen] pub fn run() { call(&|| {}); assert!(call_again().is_err()); } "#) .file("test.ts", r#" import { run } from "./out"; let CACHE: any = null; export function call(a: any) { CACHE = a; } export function call_again() { CACHE(); } export function test() { run(); } "#) .test(); } #[test] fn long_lived() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use std::cell::Cell; use std::rc::Rc; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call1(a: &Closure<Fn()>); fn call2(a: &Closure<FnMut(u32) -> u32>) -> u32; } #[wasm_bindgen] pub fn run() { let hit = Rc::new(Cell::new(false)); let hit2 = hit.clone(); let a = Closure::new(move || hit2.set(true)); assert!(!hit.get()); call1(&a); assert!(hit.get()); let hit = Rc::new(Cell::new(false)); { let hit = hit.clone(); let a = Closure::new(move |x| { hit.set(true); x + 3 }); assert_eq!(call2(&a), 5); } assert!(hit.get()); } "#) .file("test.ts", r#" import { run } from "./out"; export function call1(a: any) { a(); } export function call2(a: any) { return a(2); } export function test() { run(); } "#) .test(); } #[test] fn many_arity() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call1(a: &Closure<Fn()>); fn call2(a: &Closure<Fn(u32)>); fn call3(a: &Closure<Fn(u32, u32)>); fn call4(a: &Closure<Fn(u32, u32, u32)>); fn call5(a: &Closure<Fn(u32, u32, u32, u32)>); fn call6(a: &Closure<Fn(u32, u32, u32, u32, u32)>); fn call7(a: &Closure<Fn(u32, u32, u32, u32, u32, u32)>); fn call8(a: &Closure<Fn(u32, u32, u32, u32, u32, u32, u32)>); #[wasm_bindgen(js_name = call1)] fn stack1(a: &Fn()); #[wasm_bindgen(js_name = call2)] fn stack2(a: &Fn(u32)); #[wasm_bindgen(js_name = call3)] fn stack3(a: &Fn(u32, u32)); #[wasm_bindgen(js_name = call4)] fn stack4(a: &Fn(u32, u32, u32)); #[wasm_bindgen(js_name = call5)] fn stack5(a: &Fn(u32, u32, u32, u32)); #[wasm_bindgen(js_name = call6)] fn stack6(a: &Fn(u32, u32, u32, u32, u32)); #[wasm_bindgen(js_name = call7)] fn stack7(a: &Fn(u32, u32, u32, u32, u32, u32)); #[wasm_bindgen(js_name = call8)] fn stack8(a: &Fn(u32, u32, u32, u32, u32, u32, u32)); } #[wasm_bindgen] pub fn run() { call1(&Closure::new(|| {})); call2(&Closure::new(|a| assert_eq!(a, 1))); call3(&Closure::new(|a, b| assert_eq!((a, b), (1, 2)))); call4(&Closure::new(|a, b, c| assert_eq!((a, b, c), (1, 2, 3)))); call5(&Closure::new(|a, b, c, d| { assert_eq!((a, b, c, d), (1, 2, 3, 4)) })); call6(&Closure::new(|a, b, c, d, e| { assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)) })); call7(&Closure::new(|a, b, c, d, e, f| { assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)) })); call8(&Closure::new(|a, b, c, d, e, f, g| { assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7)) })); stack1(&(|| {})); stack2(&(|a| assert_eq!(a, 1))); stack3(&(|a, b| assert_eq!((a, b), (1, 2)))); stack4(&(|a, b, c| assert_eq!((a, b, c), (1, 2, 3)))); stack5(&(|a, b, c, d| { assert_eq!((a, b, c, d), (1, 2, 3, 4)) })); stack6(&(|a, b, c, d, e| { assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)) })); stack7(&(|a, b, c, d, e, f| { assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)) })); stack8(&(|a, b, c, d, e, f, g| { assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7)) })); } "#) .file("test.ts", r#" import { run } from "./out"; export function call1(a: any) { a() } export function call2(a: any) { a(1) } export function call3(a: any) { a(1, 2) } export function call4(a: any) { a(1, 2, 3) } export function call5(a: any) { a(1, 2, 3, 4) } export function call6(a: any) { a(1, 2, 3, 4, 5) } export function call7(a: any) { a(1, 2, 3, 4, 5, 6) } export function call8(a: any) { a(1, 2, 3, 4, 5, 6, 7) } export function test() { run(); } "#) .test(); } #[test] fn long_lived_dropping() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use std::cell::Cell; use std::rc::Rc; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn cache(a: &Closure<Fn()>); #[wasm_bindgen(catch)] fn call() -> Result<(), JsValue>; } #[wasm_bindgen] pub fn run() { let hit = Rc::new(Cell::new(false)); let hit2 = hit.clone(); let a = Closure::new(move || hit2.set(true)); cache(&a); assert!(!hit.get()); assert!(call().is_ok()); assert!(hit.get()); drop(a); assert!(call().is_err()); } "#) .file("test.ts", r#" import { run } from "./out"; let CACHE: any = null; export function cache(a: any) { CACHE = a; } export function call() { CACHE() } export function test() { run(); } "#) .test(); } #[test] fn long_fnmut_recursive() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn cache(a: &Closure<FnMut()>); #[wasm_bindgen(catch)] fn call() -> Result<(), JsValue>; } #[wasm_bindgen] pub fn run() { let a = Closure::new(|| { assert!(call().is_err()); }); cache(&a); assert!(call().is_ok()); } "#) .file("test.ts", r#" import { run } from "./out"; let CACHE: any = null; export function cache(a: any) { CACHE = a; } export function call() { CACHE() } export function test() { run(); } "#) .test(); } #[test] fn fnmut() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call(a: &mut FnMut()); fn thread(a: &mut FnMut(u32) -> u32) -> u32; } #[wasm_bindgen] pub fn run() { let mut a = false; call(&mut || a = true); assert!(a); let mut x = false; assert_eq!(thread(&mut |a| { x = true; a + 1 }), 3); assert!(x); } "#) .file("test.ts", r#" import { run } from "./out"; export function call(a: any) { a(); } export function thread(a: any) { return a(2); } export function test() { run(); } "#) .test(); } #[test] fn fnmut_bad() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call(a: &mut FnMut()); #[wasm_bindgen(catch)] fn again(a: bool) -> Result<(), JsValue>; } #[wasm_bindgen] pub fn run() { let mut x = true; let mut hits = 0; call(&mut || { hits += 1; if again(hits == 1).is_err() { return } x = false; }); assert!(hits == 1); assert!(x); assert!(again(true).is_err()); } "#) .file("test.ts", r#" import { run } from "./out"; let F: any = null; export function call(a: any) { F = a; a(); } export function again(x: boolean) { if (x) F(); } export function test() { run(); } "#) .test(); } #[test] fn string_arguments() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call(a: &mut FnMut(String)); } #[wasm_bindgen] pub fn run() { let mut x = false; call(&mut |s| { assert_eq!(s, "foo"); x = true; }); assert!(x); } "#) .file("test.ts", r#" import { run } from "./out"; export function call(a: any) { a("foo") } export function test() { run(); } "#) .test(); } #[test] fn string_ret() { project() .file("src/lib.rs", r#" #![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "./test")] extern { fn call(a: &mut FnMut(String) -> String); } #[wasm_bindgen] pub fn run() { let mut x = false; call(&mut |mut s| { assert_eq!(s, "foo"); s.push_str("bar"); x = true; s }); assert!(x); } "#) .file("test.ts", r#" import { run } from "./out"; import * as assert from "assert"; export function call(a: any) { const s = a("foo"); assert.strictEqual(s, "foobar"); } export function test() { run(); } "#) .test(); }
27.683495
81
0.377358
3b63c2d532bae46f849410cd3d72d1c96ff72e2f
1,353
php
PHP
app/Http/Controllers/Api/CarController.php
darciofjunior/API-em-Laravel-com-SPA-em-VUE.JS
2885984be30ccc8899b801a6487dc96f2b4e3715
[ "MIT" ]
null
null
null
app/Http/Controllers/Api/CarController.php
darciofjunior/API-em-Laravel-com-SPA-em-VUE.JS
2885984be30ccc8899b801a6487dc96f2b4e3715
[ "MIT" ]
2
2021-02-02T21:26:35.000Z
2022-02-19T05:54:11.000Z
app/Http/Controllers/Api/CarController.php
darciofjunior/API-autenticada-com-JWT
99c9f3f0cad4cfb998bba897cd8695059ad5baab
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\Car; class CarController extends Controller { private $car; public function __construct(Car $car) { $this->car = $car; } public function index() { if(!$cars = $this->car->orderBy('modelo', 'ASC')->get()) return response()->json(['mensagem' => 'Not Found Car(s) !'], 404); return response()->json($cars); } public function show($id) { if(!$car = $this->car->find($id)) return response()->json(['mensagem' => 'Not Found Car !'], 404); return response()->json($car); } public function store(Request $request) { $car = $this->car->create($request->all()); return response()->json($car, 201); } public function update(Request $request, $id) { if(!$car = $this->car->find($id)) return response()->json(['mensagem' => 'Not Found Car !'], 404); $car->update($request->all()); return response()->json($car); } public function destroy($id) { if(!$car = $this->car->find($id)) return response()->json(['mensagem' => 'Not Found Car !'], 404); $car->delete(); return response()->json($car, 204); } }
22.180328
79
0.54102
b046300b981c773725f526bde993a097a7d89f16
530
py
Python
apps/api/urls.py
rddimon/test-product-scanner
e614e4c801e9235710b7c2a6956615c47dfc66a4
[ "MIT" ]
null
null
null
apps/api/urls.py
rddimon/test-product-scanner
e614e4c801e9235710b7c2a6956615c47dfc66a4
[ "MIT" ]
1
2017-12-14T06:52:30.000Z
2017-12-14T07:18:23.000Z
apps/api/urls.py
rddimon/test-product-scanner
e614e4c801e9235710b7c2a6956615c47dfc66a4
[ "MIT" ]
null
null
null
from django.conf.urls import url, include from rest_framework import routers from apps.api import views from apps.api.viewsets import payment router = routers.DefaultRouter() router.register(r'number-of-products', payment.NumberOfProductsViewSet) router.register(r'crawls-per-month', payment.CrawlsPerMonthViewSet) router.register(r'connected-accounts', payment.ConnectedAccountsViewSet) urlpatterns = [ url(r'^payment/', include(router.urls)), url(r'^validate$', views.validate), url(r'^update', views.update), ]
29.444444
72
0.775472
5da1aa668d1af27127b8511fba239273f559a099
1,972
cpp
C++
tests/src/test_BedWriter.cpp
bio-nim/pbbam
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
[ "BSD-3-Clause-Clear" ]
null
null
null
tests/src/test_BedWriter.cpp
bio-nim/pbbam
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
[ "BSD-3-Clause-Clear" ]
null
null
null
tests/src/test_BedWriter.cpp
bio-nim/pbbam
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
[ "BSD-3-Clause-Clear" ]
null
null
null
// Author: Derek Barnett #include <pbbam/bed/BedWriter.h> #include <cstdio> #include <algorithm> #include <string> #include <vector> #include <gtest/gtest.h> #include <pbbam/FormatUtils.h> #include <pbbam/GenomicInterval.h> #include <pbbam/bed/BedReader.h> #include "PbbamTestData.h" using BedReader = PacBio::BED::BedReader; using BedWriter = PacBio::BED::BedWriter; using GenomicInterval = PacBio::BAM::GenomicInterval; using HtslibCompression = PacBio::BAM::HtslibCompression; namespace BedWriterTests { const std::vector<GenomicInterval> Intervals{ {"chr1", 213941196, 213942363}, {"chr1", 213942363, 213943530}, {"chr1", 213943530, 213944697}, {"chr2", 158364697, 158365864}, {"chr2", 158365864, 158367031}, {"chr3", 127477031, 127478198}, {"chr3", 127478198, 127479365}, {"chr3", 127479365, 127480532}, {"chr3", 127480532, 127481699}}; void CheckRoundTrip(const std::string& outFn, const HtslibCompression compressionType) { { BedWriter writer{outFn}; for (const auto& interval : BedWriterTests::Intervals) writer.Write(interval); } EXPECT_EQ(compressionType, PacBio::BAM::FormatUtils::CompressionType(outFn)); const auto contents = BedReader::ReadAll(outFn); EXPECT_TRUE(std::equal(BedWriterTests::Intervals.cbegin(), BedWriterTests::Intervals.cend(), contents.cbegin())); remove(outFn.c_str()); } } // namespace BedWriterTests TEST(BAM_BedWriter, throws_on_empty_filename) { EXPECT_THROW(BedWriter writer{""}, std::runtime_error); } TEST(BAM_BedWriter, can_write_plain_text) { const std::string outFn = PacBio::BAM::PbbamTestsConfig::GeneratedData_Dir + "/out.bed"; BedWriterTests::CheckRoundTrip(outFn, HtslibCompression::NONE); } TEST(BAM_BedWriter, can_write_gzipped_text) { const std::string outFn = PacBio::BAM::PbbamTestsConfig::GeneratedData_Dir + "/out.bed.gz"; BedWriterTests::CheckRoundTrip(outFn, HtslibCompression::GZIP); }
30.338462
100
0.719574
580a5949c79495d79c5a5f513ab4f3f67fe72a03
630
css
CSS
evaluaciones/evaluacion360/resultados/admin/impresion.css
elmerolero/evaluaciones
ab19eafc6424c7a8eaabd23739fcea691ec30878
[ "MIT" ]
null
null
null
evaluaciones/evaluacion360/resultados/admin/impresion.css
elmerolero/evaluaciones
ab19eafc6424c7a8eaabd23739fcea691ec30878
[ "MIT" ]
null
null
null
evaluaciones/evaluacion360/resultados/admin/impresion.css
elmerolero/evaluaciones
ab19eafc6424c7a8eaabd23739fcea691ec30878
[ "MIT" ]
null
null
null
@media print{ header{ height: 95px; margin: 0; } #datos-empleado{ height: 65px; } #Resultados{ font-size: 14px; } .preguntas{ padding: 1px 0px 1px 0px; } #Regresar{ display: none; } #contenedor{ width: 100%; padding: 0; } #R1, #R2, #R3, #R4, #R5, #R6, #R7{ margin: 0px 10px 0px 10px; } #datos-resultados-h{ display: inline-block; } #Sesion{ display: none; } #img-perfil{ display: none; } } .numero{ border-right: 1px black solid; } #margen{ vertical-align: middle; width: 100%; margin-left: auto; margin-right: auto; }
12.115385
36
0.552381
b01fc9fd99dc545f5a8930fd38ef8ceac81d37f2
2,255
py
Python
prototypes/pyplasma/plasma.py
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
5
2018-10-26T07:08:16.000Z
2019-05-10T06:47:37.000Z
prototypes/pyplasma/plasma.py
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
9
2018-11-09T08:50:48.000Z
2019-06-06T20:11:12.000Z
prototypes/pyplasma/plasma.py
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
null
null
null
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt import sys, os sys.path.append('../../python') #plasma, plasmatools sys.path.append('../../corgi/pycorgi') #corgi mesh infrastucture import corgi import plasmatools as ptools import pyplasma as plasma from configSetup import Configuration import initialize as init from visualize import plotNode from visualize import plotXmesh from visualize import saveVisz import injector if __name__ == "__main__": ################################################## # set up plotting and figure plt.fig = plt.figure(1, figsize=(8,4)) plt.rc('font', family='serif', size=12) plt.rc('xtick') plt.rc('ytick') gs = plt.GridSpec(2, 1) gs.update(hspace = 0.5) axs = [] axs.append( plt.subplot(gs[0]) ) axs.append( plt.subplot(gs[1]) ) ################################################## #initialize node conf = Configuration('config.ini') node = plasma.Grid(conf.Nx, conf.Ny) node.setGridLims(conf.xmin, conf.xmax, conf.ymin, conf.ymax) #node.initMpi() #loadMpiXStrides(node) init.loadCells(node) ################################################## # Path to be created if node.master: if not os.path.exists( conf.outdir ): os.makedirs(conf.outdir) ################################################## #visualize as a test plotNode(axs[0], node, conf) ################################################## # test step #node.analyzeBoundaryCells() #print("{}: send queue : {}".format(node.rank, node.send_queue)) #print("{}: send queue address: {}".format(node.rank, node.send_queue_address)) #node.communicateSendCells() #node.communicateRecvCells() #plot_node(axs[0], node, 1) ################################################## print(" Node howling: {}".format(node.howl())) c = node.getCellPtr(1) print(" Cell barking: {}".format(c.bark())) ################################################## # initialize injector.inject(node, conf) #injecting plasma plotXmesh(axs[1], node, conf) saveVisz(0, node, conf) #node.finalizeMpi()
21.893204
83
0.536142
c2433467bd1b0081e5a4a19846b797b6b8ba23d4
207
sh
Shell
test/tests/override-cmd/run.sh
benbc/docker-official-images
2f94d1f1ec485351c29927eeddd96d9faf934bf8
[ "Apache-2.0" ]
null
null
null
test/tests/override-cmd/run.sh
benbc/docker-official-images
2f94d1f1ec485351c29927eeddd96d9faf934bf8
[ "Apache-2.0" ]
1
2016-01-25T16:54:08.000Z
2016-01-25T22:21:10.000Z
test/tests/override-cmd/run.sh
donejs/official-images
2e740cf7d21de486587aafd7d84d51f6f4201956
[ "MIT" ]
null
null
null
#!/bin/bash set -eo pipefail image="$1" # Test that we can override the CMD with echo hello="world-$RANDOM-$RANDOM" output="$(docker run --rm "$image" echo "Hello $hello")" [ "$output" = "Hello $hello" ]
18.818182
56
0.652174
e230195b09628c333ad82258e4b8447b51077a50
2,260
js
JavaScript
components/Layout/Header.js
josephdburdick/Joey-2013
cdf91b8a402aa335bcf367467f7cb80b9e783e9e
[ "MIT" ]
null
null
null
components/Layout/Header.js
josephdburdick/Joey-2013
cdf91b8a402aa335bcf367467f7cb80b9e783e9e
[ "MIT" ]
1
2015-10-03T21:37:04.000Z
2015-10-03T21:37:04.000Z
components/Layout/Header.js
josephdburdick/Joey-2013
cdf91b8a402aa335bcf367467f7cb80b9e783e9e
[ "MIT" ]
null
null
null
import React from 'react'; import Navigation from './Navigation'; import history from '../../core/history.js'; import Link from '../Link'; import Button from '../Button'; import cx from 'classnames'; import s from './Header.css'; import Logo from '../Logo/Logo'; import Modal from '../Modal/Modal'; import { name, title, hood, city, html } from '../../pages/about/index.md'; class Header extends React.Component { constructor(props){ super(props); this.state = { isModalOpen: false } this.toggleModal = this.toggleModal.bind(this); } toggleModal() { this.setState({ isModalOpen: !this.state.isModalOpen }); } componentDidMount() { window.componentHandler.upgradeElement(this.root); } render() { const renderModalToggleButton = this.state.isModalOpen ? ( <span className={cx([ 'mdl-chip mdl-chip--deletable', s['btn-modal--open'] ])} onClick={this.toggleModal}> <span className="mdl-chip__text">Close Info</span> <button type="button" className="mdl-chip__action"> <i className="material-icons">cancel</i> </button> </span> ) : ( <Button ripple type="icon" onClick={this.toggleModal}> <i className="material-icons">comment</i> </Button> ); return ( <header className={cx([ 'mdl-layout__header', s.header ])} ref={node => (this.root = node)}> <div className={s.container}> <Logo className={s.logo} search="perfect loop" limit={5} size="fixed_height" interval={5000} {...this.props} /> <div className="hidden--sm"> {name}<br/> {title}<br/> </div> <div className="hidden--sm"> {hood}<br/> {city} </div> <div className={s.divider} /> <div> {renderModalToggleButton} </div> </div> <Modal isOpen={this.state.isModalOpen} transitionName="modal-anim" onClick={this.toggleModal}> <div className={s.modal} dangerouslySetInnerHTML={{__html: html }} /> </Modal> </header> ); } } export default Header;
25.111111
102
0.558407
25617bdb3dfc635116235451961a3e4c0c23a90f
182
js
JavaScript
slyd/tests/unit/utils/slyd-api-test.js
ruairif/portia
175b1f5bbec50fda6adda042481bd09c77d12bf0
[ "BSD-3-Clause" ]
null
null
null
slyd/tests/unit/utils/slyd-api-test.js
ruairif/portia
175b1f5bbec50fda6adda042481bd09c77d12bf0
[ "BSD-3-Clause" ]
null
null
null
slyd/tests/unit/utils/slyd-api-test.js
ruairif/portia
175b1f5bbec50fda6adda042481bd09c77d12bf0
[ "BSD-3-Clause" ]
null
null
null
import slydApi from 'portia-web/utils/slyd-api'; module('slydApi'); // Replace this with your real tests. test('it works', function() { var result = slydApi(); ok(result); });
18.2
48
0.67033
00035bf897bf7c6d59edf1bebaea09e32d3905ae
933
cs
C#
DemoProjects/NetCore/TodoApi/Store/AppDbContext/Entities/Todo.cs
twabbott/Projects
0f4370611495a45b63a0a7570966baf67b91cc9b
[ "MIT" ]
1
2018-10-30T17:38:23.000Z
2018-10-30T17:38:23.000Z
DemoProjects/NetCore/TodoApi/Store/AppDbContext/Entities/Todo.cs
twabbott/Projects
0f4370611495a45b63a0a7570966baf67b91cc9b
[ "MIT" ]
110
2020-03-07T00:52:11.000Z
2022-03-08T22:52:22.000Z
DemoProjects/NetCore/TodoApi/Store/AppDbContext/Entities/Todo.cs
twabbott/Projects
0f4370611495a45b63a0a7570966baf67b91cc9b
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace TodoApi.Store.AppDbContext.Entities { public class Todo { [Key] // Not required (EFC will automatically select "Id" to be the PK) [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } public string Name { get; set; } public bool IsComplete { get; set; } public ICollection<Step> Steps { get; set; } = new List<Step>(); public bool IsBlocked { get; set; } public TodoApi.Shared.TodoStatus Status { get; set; } public bool IsActive { get; set; } public DateTime DateCreated { get; set; } public DateTime DateLastChanged { get; set; } public DateTime? DateCompleted { get; set; } } }
26.657143
79
0.663451
b355c5045d4b2757a6af5375993068c8361b9be2
1,176
swift
Swift
PrivacyPrompts/PhotoAccessProvider.swift
AnatoleZho/PrivacyPrompts
e28a3028aee99c40330d7646b731bc5f268f8966
[ "MIT" ]
null
null
null
PrivacyPrompts/PhotoAccessProvider.swift
AnatoleZho/PrivacyPrompts
e28a3028aee99c40330d7646b731bc5f268f8966
[ "MIT" ]
null
null
null
PrivacyPrompts/PhotoAccessProvider.swift
AnatoleZho/PrivacyPrompts
e28a3028aee99c40330d7646b731bc5f268f8966
[ "MIT" ]
null
null
null
/* Copyright (C) 2017 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Demonstrates the APIs to check and request access to photos. */ import Foundation import Photos class PhotoAccessProvider: NSObject, PrivateDataAccessProvider { var accessLevel: PrivateDataAccessLevel { let authorizationStatus = PHPhotoLibrary.authorizationStatus() return authorizationStatus.accessLevel } func requestAccess(completionHandler: @escaping (PrivateDataRequestAccessResult) -> Void) { PHPhotoLibrary.requestAuthorization { (authorizationStatus) in DispatchQueue.main.async { completionHandler(PrivateDataRequestAccessResult(authorizationStatus.accessLevel)) } } } } extension PHAuthorizationStatus: PrivateDataAccessLevelConvertible { var accessLevel: PrivateDataAccessLevel { switch self { case .authorized: return .granted case .denied: return .denied case .notDetermined: return .undetermined case .restricted: return .restricted } } }
28.682927
98
0.687925
c0b7d5556396dbe481714d8c1f37ca75fce41ada
8,599
ps1
PowerShell
eng/common/scripts/Update-DocsMsMetadata.ps1
billwert/azure-sdk-for-java
f907d9027d253cdfb37850852cf9cfe500d5c1f6
[ "MIT" ]
43
2018-03-12T20:45:34.000Z
2019-11-14T19:58:35.000Z
eng/common/scripts/Update-DocsMsMetadata.ps1
billwert/azure-sdk-for-java
f907d9027d253cdfb37850852cf9cfe500d5c1f6
[ "MIT" ]
117
2018-03-12T19:25:26.000Z
2019-11-15T21:39:40.000Z
eng/common/scripts/Update-DocsMsMetadata.ps1
billwert/azure-sdk-for-java
f907d9027d253cdfb37850852cf9cfe500d5c1f6
[ "MIT" ]
15
2018-03-21T17:10:35.000Z
2019-09-26T18:33:48.000Z
<# .SYNOPSIS Updates package README.md for publishing to docs.microsoft.com .DESCRIPTION Given a PackageInfo .json file, format the package README.md file with metadata and other information needed to release reference docs: * Adjust README.md content to include metadata * Insert the package verison number in the README.md title * Copy file to the appropriate location in the documentation repository * Copy PackageInfo .json file to the metadata location in the reference docs repository. This enables the Docs CI build to onboard packages which have not shipped and for which there are no entries in the metadata CSV files. .PARAMETER PackageInfoJsonLocations List of locations of the artifact information .json file. This is usually stored in build artifacts under packages/PackageInfo/<package-name>.json. Can also be a single item. .PARAMETER DocRepoLocation Location of the root of the docs.microsoft.com reference doc location. Further path information is provided by $GetDocsMsMetadataForPackageFn .PARAMETER Language Programming language to supply to metadata .PARAMETER RepoId GitHub repository ID of the SDK. Typically of the form: 'Azure/azure-sdk-for-js' .PARAMETER DocValidationImageId The docker image id in format of '$containerRegistry/$imageName:$tag' e.g. azuresdkimages.azurecr.io/jsrefautocr:latest .PARAMETER TenantId The aad tenant id/object id. .PARAMETER ClientId The add client id/application id. .PARAMETER ClientSecret The client secret of add app. #> param( [Parameter(Mandatory = $true)] [array]$PackageInfoJsonLocations, [Parameter(Mandatory = $true)] [string]$DocRepoLocation, [Parameter(Mandatory = $true)] [string]$Language, [Parameter(Mandatory = $true)] [string]$RepoId, [Parameter(Mandatory = $false)] [string]$DocValidationImageId, [Parameter(Mandatory = $false)] [string]$PackageSourceOverride, [Parameter(Mandatory = $false)] [string]$TenantId, [Parameter(Mandatory = $false)] [string]$ClientId, [Parameter(Mandatory = $false)] [string]$ClientSecret ) Set-StrictMode -Version 3 . (Join-Path $PSScriptRoot common.ps1) . (Join-Path $PSScriptRoot Helpers Metadata-Helpers.ps1) $releaseReplaceRegex = "(https://github.com/$RepoId/(?:blob|tree)/)(?:master|main)" $TITLE_REGEX = "(\#\s+(?<filetitle>Azure .+? (?:client|plugin|shared) library for (?:JavaScript|Java|Python|\.NET|C)))" function GetAdjustedReadmeContent($ReadmeContent, $PackageInfo, $PackageMetadata) { # The $PackageMetadata could be $null if there is no associated metadata entry # based on how the metadata CSV is filtered $service = $PackageInfo.ServiceDirectory.ToLower() if ($PackageMetadata -and $PackageMetadata.MSDocService) { # Use MSDocService in csv metadata to override the service directory # TODO: Use taxonomy for service name -- https://github.com/Azure/azure-sdk-tools/issues/1442 $service = $PackageMetadata.MSDocService } Write-Host "The service of package: $service" # Generate the release tag for use in link substitution $tag = "$($PackageInfo.Name)_$($PackageInfo.Version)" Write-Host "The tag of package: $tag" $date = Get-Date -Format "MM/dd/yyyy" $foundTitle = "" if ($ReadmeContent -match $TITLE_REGEX) { $ReadmeContent = $ReadmeContent -replace $TITLE_REGEX, "`${0} - Version $($PackageInfo.Version) `n" $foundTitle = $matches["filetitle"] } # If this is not a daily dev package, perform link replacement if (!$packageInfo.DevVersion) { $replacementPattern = "`${1}$tag" $ReadmeContent = $ReadmeContent -replace $releaseReplaceRegex, $replacementPattern } # Get the first code owners of the package. Write-Host "Retrieve the code owner from $($PackageInfo.DirectoryPath)." $author = GetPrimaryCodeOwner -TargetDirectory $PackageInfo.DirectoryPath if (!$author) { $author = "ramya-rao-a" $msauthor = "ramyar" } else { $msauthor = GetMsAliasFromGithub -TenantId $TenantId -ClientId $ClientId -ClientSecret $ClientSecret -GithubUser $author } # Default value if (!$msauthor) { $msauthor = $author } Write-Host "The author of package: $author" Write-Host "The ms author of package: $msauthor" $header = @" --- title: $foundTitle keywords: Azure, $Language, SDK, API, $($PackageInfo.Name), $service author: $author ms.author: $msauthor ms.date: $date ms.topic: reference ms.devlang: $Language ms.service: $service --- "@ $ReadmeContent = $ReadmeContent -replace "https://docs.microsoft.com(/en-us)?/?", "/" return "$header`n$ReadmeContent" } function GetPackageInfoJson ($packageInfoJsonLocation) { if (!(Test-Path $packageInfoJsonLocation)) { LogWarning "Package metadata not found for $packageInfoJsonLocation" return } $packageInfoJson = Get-Content $packageInfoJsonLocation -Raw $packageInfo = ConvertFrom-Json $packageInfoJson if ($packageInfo.DevVersion) { # If the package is of a dev version there may be language-specific needs to # specify the appropriate version. For example, in the case of JS, the dev # version is always 'dev' when interacting with NPM. if ($GetDocsMsDevLanguageSpecificPackageInfoFn -and (Test-Path "Function:$GetDocsMsDevLanguageSpecificPackageInfoFn")) { $packageInfo = &$GetDocsMsDevLanguageSpecificPackageInfoFn $packageInfo } else { # Default: use the dev version from package info as the version for # downstream processes $packageInfo.Version = $packageInfo.DevVersion } } return $packageInfo } function UpdateDocsMsMetadataForPackage($packageInfoJsonLocation) { $packageInfo = GetPackageInfoJson $packageInfoJsonLocation $originalVersion = [AzureEngSemanticVersion]::ParseVersionString($packageInfo.Version) $packageMetadataArray = (Get-CSVMetadata).Where({ $_.Package -eq $packageInfo.Name -and $_.Hide -ne 'true' -and $_.New -eq 'true' }) if ($packageInfo.Group) { $packageMetadataArray = ($packageMetadataArray).Where({ $_.GroupId -eq $packageInfo.Group }) } if ($packageMetadataArray.Count -eq 0) { LogWarning "Could not retrieve metadata for $($packageInfo.Name) from metadata CSV. Using best effort defaults." $packageMetadata = $null } elseif ($packageMetadataArray.Count -gt 1) { LogWarning "Multiple metadata entries for $($packageInfo.Name) in metadata CSV. Using first entry." $packageMetadata = $packageMetadataArray[0] } else { $packageMetadata = $packageMetadataArray[0] } # Copy package info file to the docs repo $docsMsMetadata = &$GetDocsMsMetadataForPackageFn $packageInfo $readMePath = $docsMsMetadata.LatestReadMeLocation $metadataMoniker = 'latest' if ($originalVersion -and $originalVersion.IsPrerelease) { $metadataMoniker = 'preview' $readMePath = $docsMsMetadata.PreviewReadMeLocation } $packageMetadataName = Split-Path $packageInfoJsonLocation -Leaf $packageInfoLocation = Join-Path $DocRepoLocation "metadata/$metadataMoniker" $packageInfoJson = ConvertTo-Json $packageInfo New-Item -ItemType Directory -Path $packageInfoLocation -Force Set-Content ` -Path $packageInfoLocation/$packageMetadataName ` -Value $packageInfoJson # Update Readme Content if (!$packageInfo.ReadMePath -or !(Test-Path $packageInfo.ReadMePath)) { Write-Warning "$($packageInfo.Name) does not have Readme file. Skipping update readme." return } $readmeContent = Get-Content $packageInfo.ReadMePath -Raw $outputReadmeContent = "" if ($readmeContent) { $outputReadmeContent = GetAdjustedReadmeContent $readmeContent $packageInfo $packageMetadata } $suffix = $docsMsMetadata.Suffix $readMeName = "$($docsMsMetadata.DocsMsReadMeName.ToLower())-readme${suffix}.md" $readmeLocation = Join-Path $DocRepoLocation $readMePath $readMeName Set-Content -Path $readmeLocation -Value $outputReadmeContent } # For daily update and release, validate DocsMS publishing using the language-specific validation function if ($ValidateDocsMsPackagesFn -and (Test-Path "Function:$ValidateDocsMsPackagesFn")) { Write-Host "Validating the packages..." $packageInfos = @($PackageInfoJsonLocations | ForEach-Object { GetPackageInfoJson $_ }) &$ValidateDocsMsPackagesFn -PackageInfos $packageInfos -PackageSourceOverride $PackageSourceOverride -DocValidationImageId $DocValidationImageId -DocRepoLocation $DocRepoLocation } foreach ($packageInfoLocation in $PackageInfoJsonLocations) { Write-Host "Updating metadata for package: $packageInfoLocation" # Convert package metadata json file to metadata json property. UpdateDocsMsMetadataForPackage $packageInfoLocation }
36.591489
180
0.749855
0d371a7ca8a3565681f28bf2e7766a601a89b3a4
195
sql
SQL
migrations/sqls/20180421013030-initial-down.sql
matchai/camperbot
b2851c18f39f58fb48ae1d5d269ee4b14a250d96
[ "MIT" ]
4
2018-04-30T05:09:12.000Z
2018-05-14T21:18:39.000Z
migrations/sqls/20180421013030-initial-down.sql
matchai/camperbot
b2851c18f39f58fb48ae1d5d269ee4b14a250d96
[ "MIT" ]
19
2018-05-04T02:44:02.000Z
2018-07-15T22:32:04.000Z
migrations/sqls/20180421013030-initial-down.sql
matchai/camperbot
b2851c18f39f58fb48ae1d5d269ee4b14a250d96
[ "MIT" ]
4
2018-05-01T19:43:00.000Z
2018-06-29T02:49:44.000Z
-- Table was named users before :p DROP TABLE IF EXISTS users_techs; DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS accounts_techs; DROP TABLE IF EXISTS accounts; DROP TABLE IF EXISTS techs;
21.666667
36
0.784615
f79e777e506deae81e0ef63fdb80acb311ac573b
311
rb
Ruby
20110826_TissotChecker/framework/scripts/mount/mount.compact_images.rb
andrehtissot/old_things
e947f6ca168939c3781de39bdf5799e49a0021a9
[ "MIT" ]
null
null
null
20110826_TissotChecker/framework/scripts/mount/mount.compact_images.rb
andrehtissot/old_things
e947f6ca168939c3781de39bdf5799e49a0021a9
[ "MIT" ]
null
null
null
20110826_TissotChecker/framework/scripts/mount/mount.compact_images.rb
andrehtissot/old_things
e947f6ca168939c3781de39bdf5799e49a0021a9
[ "MIT" ]
null
null
null
pngs = get_files_recursively("build/resources/", /\.png$/i) pngs.each do |png| system "optipng #{ROOT_PATH}build/resources/#{png} -o 4 -quiet" end jpgs = get_files_recursively("build/resources/", /\.jpe?g$/i) jpgs.each do |jpg| system "jpegoptim --quiet #{ROOT_PATH}build/resources/#{jpg} > /dev/null" end
31.1
75
0.700965
f4ec0fe0364dc585942d52a067d5a9f8f8c56c0e
170
ts
TypeScript
src/restaurant/restaurant.spec.ts
lamnv60533/nest-typeorm
96e7d94c8d9bc0e2f0190b8827b824a6fa25ad6c
[ "MIT" ]
null
null
null
src/restaurant/restaurant.spec.ts
lamnv60533/nest-typeorm
96e7d94c8d9bc0e2f0190b8827b824a6fa25ad6c
[ "MIT" ]
null
null
null
src/restaurant/restaurant.spec.ts
lamnv60533/nest-typeorm
96e7d94c8d9bc0e2f0190b8827b824a6fa25ad6c
[ "MIT" ]
null
null
null
import { Restaurant } from './restaurant.entity'; describe('Restaurant', () => { it('should be defined', () => { expect(new Restaurant()).toBeDefined(); }); });
21.25
49
0.594118
da4fc072d382086a9ec69b93213b537691afa4a9
1,027
cs
C#
src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs
BaseCoreVueProject/Destiny.Core.Flow
6977597680bff62c2367e5dbd2f29d75f5224600
[ "Net-SNMP", "Xnet" ]
16
2020-11-03T13:15:51.000Z
2022-02-03T08:15:32.000Z
src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs
dotNetTreasury/Destiny.Core.Flow
40a9078c2049cdfd41976cda326b951417c89c80
[ "MIT" ]
null
null
null
src/Destiny.Core.Flow/Validation/Interceptor/ModelValidationMethodParameterValidator.cs
dotNetTreasury/Destiny.Core.Flow
40a9078c2049cdfd41976cda326b951417c89c80
[ "MIT" ]
12
2020-11-13T08:38:01.000Z
2022-03-30T07:50:56.000Z
 using System; using System.Collections.Generic; using System.Linq; namespace Destiny.Core.Flow.Validation.Interceptor { internal sealed class ModelValidationMethodParameterValidator : IMethodParameterValidator { private readonly IServiceProvider _provider; public ModelValidationMethodParameterValidator(IServiceProvider provider) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); } public IEnumerable<ValidationFailure> Validate(object parameter) { if (parameter == null) { return Enumerable.Empty<ValidationFailure>(); } var validatorType = typeof(IModelValidator<>).MakeGenericType(parameter.GetType()); if (!(_provider.GetService(validatorType) is IModelValidator validator)) return Enumerable.Empty<ValidationFailure>(); var failures = validator.Validate(parameter); return failures; } } }
29.342857
95
0.661149
aff8524799a2e94f4cc924fe90fee3d383128306
245
py
Python
tesseract.py
Swarnava-Sadhukhan/Vehicle-Reg.-Details-using-Number-Plate
71a11a1c348bd4707ec286cef690d197c877a864
[ "MIT" ]
null
null
null
tesseract.py
Swarnava-Sadhukhan/Vehicle-Reg.-Details-using-Number-Plate
71a11a1c348bd4707ec286cef690d197c877a864
[ "MIT" ]
null
null
null
tesseract.py
Swarnava-Sadhukhan/Vehicle-Reg.-Details-using-Number-Plate
71a11a1c348bd4707ec286cef690d197c877a864
[ "MIT" ]
null
null
null
from PIL import Image import pytesseract pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" image = Image.open(your_image) image_to_text = pytesseract.image_to_string(image, lang='eng') print(image_to_text)
30.625
87
0.820408
1c8db79484bce0e31d50bf6ddece2b49e69e5d42
87
sql
SQL
src/main/resources/db/migration/V_2016.06.21_21.24__BroConn_history.sql
valery1707/test-sorm
fa1c72eaa9cae33bd1a55c71b58aa5c8ac99a5ac
[ "MIT" ]
null
null
null
src/main/resources/db/migration/V_2016.06.21_21.24__BroConn_history.sql
valery1707/test-sorm
fa1c72eaa9cae33bd1a55c71b58aa5c8ac99a5ac
[ "MIT" ]
null
null
null
src/main/resources/db/migration/V_2016.06.21_21.24__BroConn_history.sql
valery1707/test-sorm
fa1c72eaa9cae33bd1a55c71b58aa5c8ac99a5ac
[ "MIT" ]
null
null
null
ALTER TABLE bro_conn MODIFY history VARCHAR(200) COMMENT 'История состояния коннекта';
43.5
86
0.827586
ae193ecc2afa021a8bec141ade942154f5ad3601
8,792
cs
C#
gui/Profiler.Data/EventTree.cs
dnikolaidis2/optick
9c692bca0d542c768eb02db8f81f44d57f626e55
[ "MIT" ]
1,711
2019-04-15T16:39:00.000Z
2022-03-31T22:06:38.000Z
gui/Profiler.Data/EventTree.cs
dnikolaidis2/optick
9c692bca0d542c768eb02db8f81f44d57f626e55
[ "MIT" ]
69
2019-04-21T20:42:10.000Z
2022-03-23T06:08:59.000Z
gui/Profiler.Data/EventTree.cs
dnikolaidis2/optick
9c692bca0d542c768eb02db8f81f44d57f626e55
[ "MIT" ]
172
2019-04-23T05:08:55.000Z
2022-03-31T17:30:35.000Z
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Threading; using System.Windows.Media; using System.ComponentModel; namespace Profiler.Data { public struct FilterMode { public bool HideNotRelative { get; set; } public bool ChangeExpand { get; set; } public double TimeLimit { get; set; } } public abstract class BaseTreeNode : INotifyPropertyChanged { private bool isExpanded; private bool isSelected; private Visibility visible; public BaseTreeNode Parent { get; set; } public BaseTreeNode RootParent { get; private set; } public List<BaseTreeNode> Children { get; private set; } public double Duration { get; protected set; } public double ChildrenDuration { get; protected set; } public double SelfDuration { get { return Duration - ChildrenDuration; } } public abstract String Name { get; } public abstract String ToolTipName { get; } public virtual List<Tag> Tags { get { return null; } set { } } public virtual List<BaseTreeNode> ShadowNodes { get { return null; } } public event PropertyChangedEventHandler PropertyChanged; private void Raise(string propertyName) { var tmp = PropertyChanged; if (tmp != null) tmp(this, new PropertyChangedEventArgs(propertyName)); } public double Ratio { get { return Parent != null ? Duration / Parent.Duration : 1.0; } } public double TotalPercent { get { return RootParent != null ? (100.0 * Duration / RootParent.Duration) : 100.0; } } public double SelfPercent { get { if (RootParent != null) return (100.0 * SelfDuration / RootParent.Duration); if (Duration > 0.0) return SelfDuration / Duration; return 0.0; } } public abstract String Path { get; } public bool IsExpanded { get { return isExpanded; } set { if (isExpanded != value) { isExpanded = value; Raise("IsExpanded"); } } } public bool IsSelected { get { return isSelected; } set { if (isSelected != value) { isSelected = value; Raise("IsSelected"); } } } public Visibility Visible { get { return visible; } set { if (visible != value) { visible = value; Raise("Visible"); } } } public void ApplyFilterTerminal(FilterMode mode) { if (Duration < mode.TimeLimit) { Hide(); return; } //if (Expanded == false && Visible == Visibility.Visible) // return; IsExpanded = false; Visible = Visibility.Visible; foreach (var node in Children) node.ApplyFilterTerminal(mode); } public void Hide() { if (IsExpanded == false && Visible == Visibility.Collapsed) return; IsExpanded = false; Visible = Visibility.Collapsed; } public BaseTreeNode(BaseTreeNode root, double duration) { Visible = Visibility.Visible; RootParent = root; Children = new List<BaseTreeNode>(); Duration = duration; } public void AddChild(BaseTreeNode node) { node.Parent = this; Children.Add(node); ChildrenDuration += node.Duration; } public abstract void ApplyFilter(HashSet<Object> roof, HashSet<Object> nodes, FilterMode mode); public abstract void CalculateRecursiveExcludeFlag(Dictionary<Object, int> parentCallStorage); public delegate bool TreeNodeDelegate(BaseTreeNode node, int level); public void ForEach(TreeNodeDelegate action, int level = 0) { if (!action(this, level)) return; Children.ForEach(node => node.ForEach(action, level + 1)); } public override String ToString() { return Name; } public void Sort() { Children.Sort((a, b) => (b.Duration.CompareTo(a.Duration))); foreach (BaseTreeNode child in Children) child.Sort(); } } public abstract class TreeNode<TDescription> : BaseTreeNode where TDescription : Description { public TDescription Description { get; private set; } public override String Path { get { return Description.Path.ToString(); } } public override String Name { get { return Description.Name; } } public override String ToolTipName { get { return String.Format("{0}\n{1}", Description.FullName, Description.Path); } } public bool ExcludeFromTotal { get; set; } = false; public bool ExcludeFromSelf { get; set; } = false; public TreeNode(TreeNode<TDescription> root, TDescription desc, double duration) : base(root, duration) { Description = desc; } public override void ApplyFilter(HashSet<Object> roof, HashSet<Object> nodes, FilterMode mode) { if (Duration < mode.TimeLimit) { Hide(); } else if (roof != null && roof.Contains(this)) { Visible = Visibility.Visible; foreach (var node in Children) node.ApplyFilter(roof, nodes, mode); IsExpanded = true; } else if (nodes == null || nodes.Contains(this) || !mode.HideNotRelative) { //Application.Current.Dispatcher.BeginInvoke(new Action(() => //{ ApplyFilterTerminal(mode); //}), System.Windows.Threading.DispatcherPriority.DataBind); return; } else { Hide(); } } public double CalculateFilteredTime(HashSet<Object> filter) { if (filter.Contains(Description)) return Duration; double sum = 0.0; foreach (var node in Children) sum += (node as TreeNode<TDescription>).CalculateFilteredTime(filter); return sum; } public override void CalculateRecursiveExcludeFlag(Dictionary<Object, int> parentCallStorage) { Object key = Description != null ? Description.GetSharedKey() : null; if (key == null) { foreach (var node in Children) node.CalculateRecursiveExcludeFlag(parentCallStorage); } else { int count = 0; if (parentCallStorage.TryGetValue(key, out count)) { ExcludeFromTotal = count > 0; parentCallStorage[Description] = count + 1; } else { ExcludeFromTotal = false; parentCallStorage.Add(key, 1); } foreach (var node in Children) node.CalculateRecursiveExcludeFlag(parentCallStorage); parentCallStorage[key]--; } } } public class EventNode : TreeNode<EventDescription> { public Entry Entry { get; private set; } public Brush Brush { get { return Entry.Description.Brush; } } private List<Tag> tags = null; public override List<Tag> Tags { get { return tags; } set { tags = value; } } public EventNode(EventNode root, Entry entry) : base(root, entry.Description, entry.Duration) { Entry = entry; } public void ApplyTags(List<Tag> toAdd, ref int index) { if (index < toAdd.Count && toAdd[index].Start < Entry.Start) ++index; if (index < toAdd.Count && Entry.IsValid && Entry.Finish < toAdd[index].Start) return; for (int i = 0; i < Children.Count; ++i) { EventNode child = Children[i] as EventNode; while (index < toAdd.Count && toAdd[index].Start < child.Entry.Start) { if (tags == null) tags = new List<Tag>(); tags.Add(toAdd[index++]); } child.ApplyTags(toAdd, ref index); } while (index < toAdd.Count && Entry.IsValid && toAdd[index].Start <= Entry.Finish) { if (tags == null) tags = new List<Tag>(); tags.Add(toAdd[index++]); } } public EventNode FindNode(Entry entry) { if (Entry == entry) return this; foreach (EventNode node in Children) if (node.Entry.Contains(entry)) return node.FindNode(entry); return null; } } public class EventTree : EventNode { private int depth = 1; private EventFrame frame; public EventTree(EventFrame frame, List<Entry> entries) : base(null, new Entry(null, frame.Start, frame.Finish) { Frame = frame }) { this.frame = frame; BuildTree(entries); CalculateRecursiveExcludeFlag(new Dictionary<Object, int>()); } public int Depth { get { return depth - 1; } } private void BuildTree(List<Entry> entries) { if (entries.Count == 0) return; Stack<EventNode> curNodes = new Stack<EventNode>(); curNodes.Push(this); depth = curNodes.Count; foreach (var entry in entries) { if (entry.Start == entry.Finish) continue; while (entry.Start >= curNodes.Peek().Entry.Finish) { curNodes.Pop(); } EventNode node = new EventNode(this, entry); curNodes.Peek().AddChild(node); curNodes.Push(node); depth = Math.Max(depth, curNodes.Count); } while (curNodes.Count > 0) { curNodes.Pop(); } } public void ForEachChild(TreeNodeDelegate action) { Children.ForEach(node => node.ForEach(action)); } public void ApplyTags(List<Tag> tags) { if (tags == null || tags.Count == 0) return; int index = 0; ApplyTags(tags, ref index); } } }
21.98
132
0.654117
c65b18529ecb5d78a5fdbc4845f3d1856bec32db
3,341
css
CSS
src/assets/css/mobile-gallery-settings.css
seatable/seatable-app-gallery
6b0574ffd9c33243d1af1bc067a28b2802ca0b5e
[ "Apache-2.0" ]
null
null
null
src/assets/css/mobile-gallery-settings.css
seatable/seatable-app-gallery
6b0574ffd9c33243d1af1bc067a28b2802ca0b5e
[ "Apache-2.0" ]
null
null
null
src/assets/css/mobile-gallery-settings.css
seatable/seatable-app-gallery
6b0574ffd9c33243d1af1bc067a28b2802ca0b5e
[ "Apache-2.0" ]
null
null
null
.gallery-app-settings { position: fixed; z-index: 101; height: 100%; width: 100%; display: flex; flex-direction: column; left: 0; top: 0; background-color: #F3F3F3; } .gallery-app-settings .dtable-gallery-app-title { display: flex; justify-content: space-between; height: 50px; width: 100%; background-color: #ffffff; border-bottom: 1px solid #e9ecef; } .gallery-app-settings .dtable-gallery-app-header-btn { min-width: 75px; padding: 13px 16px; line-height: 24px; color: #888; } .gallery-app-settings .dtable-gallery-app-header-btn:first-child { text-align: left; } .gallery-app-settings .dtable-gallery-app-header-btn:last-child { text-align: right; } .gallery-app-settings .dtable-gallery-app-header-btn-highlight { color: rgb(240, 159, 63); } .gallery-app-settings .dtable-gallery-app-header-title { margin-bottom: 0; color: #333; line-height: 50px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .gallery-app-settings .dtable-gallery-app-setting-wrapper { width: 100%; height: calc(100% - 50px); overflow: auto; } .gallery-app-settings .mobile-setting-item { font-size: 14px; } .mobile-setting-item .mobile-field-switch-container .custom-switch-description { margin-left: 0; font-size: 16px; } .gallery-app-settings .mobile-setting-title { margin-bottom: 5px; padding: 0 16px; color: #888; display: flex; justify-content: space-between; } .gallery-app-settings .selected-selector { background-color: #dddddd; user-select: none; transition: background-color .2s; } .gallery-app-settings .mobile-selector { background-color: #ffffff; border-bottom: 1px solid #e9e9e9; border-top: 1px solid #e9e9e9; height: 52px; display: flex; padding: 0 16px; user-select: none; box-sizing: border-box; line-height: 50px; justify-content: space-between; color: #202428; } .gallery-app-settings .mobile-selector-icon { color: #bcbcbc; } .gallery-app-settings .mobile-select-options { border-bottom: 1px solid #e9e9e9; border-top: 1px solid #e9e9e9; color: #202428; } .gallery-app-settings .mobile-select-option { height: 51px; padding-left: 16px; background-color: #ffffff; box-sizing: border-box; } .gallery-app-settings .mobile-selector-option-wrapper { width: 100%; padding-right: 16px; border-bottom: 1px solid #e9e9e9; display: flex; justify-content: space-between; height: 51px; line-height: 50px; } .gallery-app-settings .mobile-select-option:last-child .mobile-selector-option-wrapper { border-bottom: none; } .gallery-app-settings .mobile-column-setting-item { padding: 0 16px; background-color: #ffffff; height: 51px; box-sizing: border-box; border-top: 1px solid #e9ecef; display: flex; line-height: 50px; } .gallery-app-settings .mobile-column-setting-item .custom-switch { width: 100%; justify-content: space-between; } .gallery-app-settings .mobile-column-switch { width: 100%; } .gallery-app-settings .mobile-custom-switch { width: 100%; justify-content: space-between; } .gallery-app-settings .gallery-column-switch { width: 100%; } .gallery-app-settings .column-item-icon { margin-right: 5px; display: inline-block; transform: scale(.8); color: #666666; } .gallery-app-settings .mobile-select-all { color: #ff8000; }
20.496933
88
0.700688
b89669d75b82554c3a1ae23134ae3862681a798b
306
c
C
tools-src/gnu/gcc/gcc/testsuite/gcc.c-torture/compile/20021212-1.c
enfoTek/tomato.linksys.e2000.nvram-mod
2ce3a5217def49d6df7348522e2bfda702b56029
[ "FSFAP" ]
178
2016-03-03T12:31:18.000Z
2021-11-05T22:36:55.000Z
tools-src/gnu/gcc/gcc/testsuite/gcc.c-torture/compile/20021212-1.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
106
2016-03-03T13:11:42.000Z
2018-09-27T13:01:51.000Z
tools-src/gnu/gcc/gcc/testsuite/gcc.c-torture/compile/20021212-1.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
69
2015-01-02T10:45:56.000Z
2021-09-06T07:52:13.000Z
/* PR optimization/8334 */ /* Verify that GCC produces valid operands after simplifying an addition. */ void foo(int m, int n, double *f) { int i, j, k = 1; for (j = 0; j < n; j++) { for (i = k; i < m; i++) { f[i] = (double) (i * j); f[i + j] = (double) ((i + 1) * j); } } }
19.125
42
0.473856
444205daf4000403ba3fc459dc41eb80985b5f80
785
py
Python
src/posts/urls.py
OmarYehia/django-social_network
83fc6fd288fe23684409c43bf51c7fca01297481
[ "MIT" ]
null
null
null
src/posts/urls.py
OmarYehia/django-social_network
83fc6fd288fe23684409c43bf51c7fca01297481
[ "MIT" ]
null
null
null
src/posts/urls.py
OmarYehia/django-social_network
83fc6fd288fe23684409c43bf51c7fca01297481
[ "MIT" ]
1
2021-05-13T15:08:12.000Z
2021-05-13T15:08:12.000Z
from django.urls import path from .views import posts_index, like_unlike_post, post_delete_view, post_update_view, CommentDelete, post_notifications, follow_notifications, view_post app_name = 'posts' urlpatterns = [ path('', posts_index, name='posts-index'), path('like/', like_unlike_post, name="like-unlike"), path('<int:pk>/delete/', post_delete_view, name="post-delete"), path('<int:pk>/update/', post_update_view, name="post-update"), path('<int:pk>/delete-comment/', CommentDelete, name="comment-delete"), path('<int:post_pk>', post_notifications, name="post-notification"), path('notification/<int:notification_pk>/profile/<int:profile_pk>', follow_notifications, name="follow-notification"), path('<int:pk>/', view_post, name='view-post') ]
46.176471
152
0.724841
07684e2ab815d622c5c74f7e22b751fe959dee2b
102
css
CSS
css/count.css
derrickqin/true-card-age-for-trello
4038c2af7a75cea18aa432e74f07c2742910957c
[ "MIT" ]
4
2020-09-30T00:32:32.000Z
2021-05-04T12:34:59.000Z
css/count.css
derrickqin/true-card-age-for-trello
4038c2af7a75cea18aa432e74f07c2742910957c
[ "MIT" ]
1
2020-03-27T00:34:59.000Z
2020-10-27T10:31:14.000Z
css/count.css
derrickqin/true-card-age-for-trello
4038c2af7a75cea18aa432e74f07c2742910957c
[ "MIT" ]
2
2020-03-06T10:45:50.000Z
2020-05-28T00:52:16.000Z
/* card count */ .list-header-num-cards { display: inline-block!important; white-space: nowrap; }
12.75
34
0.686275
43ef186e7ae05c64f3b1fc0d927c31f9020cdecf
941
ts
TypeScript
hello-world/src/app/favorite/favorite.component.ts
Doodely/Udemy-Course
8112a76ec99d5157c17a04fbee774fcc5cca79fd
[ "MIT" ]
null
null
null
hello-world/src/app/favorite/favorite.component.ts
Doodely/Udemy-Course
8112a76ec99d5157c17a04fbee774fcc5cca79fd
[ "MIT" ]
null
null
null
hello-world/src/app/favorite/favorite.component.ts
Doodely/Udemy-Course
8112a76ec99d5157c17a04fbee774fcc5cca79fd
[ "MIT" ]
null
null
null
/* Shadow DOM: - Specification that allows DOM tree encapsulation - In component you can utilize + Emulated: utilizes shadowDOM + Native shadowDom: non-emulated and very dependant on browser + None: can leak styles */ import { Component, OnInit, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'favorite', templateUrl: './favorite.component.html', styleUrls: ['./favorite.component.css'], styles: [ ` .fa-star.blue { color: green; } ` ], encapsulation: ViewEncapsulation.Emulated }) export class FavoriteComponent { @Input('is-favorite') isFavorite: boolean; @Output('change') click = new EventEmitter(); onClick() { // Toggle this.isFavorite = !this.isFavorite; // Can also pass an object this.click.emit({ newValue: this.isFavorite }) } } export interface FavoriteChangedEventArgs { newValue: boolean; }
24.763158
98
0.675877
a84b85991608035125d7d22cd8e4c6db21ee9ea8
5,287
swift
Swift
ENcordNCU/StudentClass.swift
warren30815/ENcordNCU
db75cbbb626f6f0014fe8f97dcabf9d093caf74a
[ "MIT" ]
null
null
null
ENcordNCU/StudentClass.swift
warren30815/ENcordNCU
db75cbbb626f6f0014fe8f97dcabf9d093caf74a
[ "MIT" ]
null
null
null
ENcordNCU/StudentClass.swift
warren30815/ENcordNCU
db75cbbb626f6f0014fe8f97dcabf9d093caf74a
[ "MIT" ]
null
null
null
// // StudentClass.swift // Rec Walker // // Created by BnLab on 2017/9/30. // Copyright © 2017年 BnLab. All rights reserved. // import UIKit class StudentClass: UIViewController,UITableViewDataSource,UITableViewDelegate { var Teachername = [String]() var Practicename = [String]() var ID = [Int]() var demand = [String]() var content = [String]() var example_audio = [String]() var example_url = [String]() var bartitle: String! var path = "http://140.115.152.223:7000/api/" var token: String! @IBOutlet weak var table: UITableView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) downloadJsonWithURL() } override func viewDidLoad() { super.viewDidLoad() self.title = bartitle token = "Token " + (UserDefaults.standard.object(forKey: "token") as! String) UserDefaults.standard.set(bartitle, forKey: "StudentCategory") // Do any additional setup after loading the view. } func downloadJsonWithURL() { path = "http://140.115.152.223:7000/api/" path = path + bartitle + "/" Teachername.removeAll() Practicename.removeAll() ID.removeAll() demand.removeAll() content.removeAll() example_audio.removeAll() example_url.removeAll() let request = NSMutableURLRequest(url: NSURL(string: path)! as URL) request.httpMethod = "GET" request.addValue(token, forHTTPHeaderField: "Authorization") let session = URLSession.shared session.dataTask(with: request as URLRequest ) { (data, response, error) in guard let data = data else { print("Error \(error!)") return } // Read the JSON do { // Parse the JSON let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSArray if jsonDictionary.count < 1{ let alert = UIAlertController(title: "尚未有任何練習", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) }else{ for i in 0...(jsonDictionary.count - 1){ let origin = jsonDictionary[i] as? NSDictionary let name = origin?.value(forKey: "author") let ID = origin?.value(forKey: "id") let hw = origin?.value(forKey: "topic") let demand = origin?.value(forKey: "demand") let content = origin?.value(forKey: "content") let audio = origin?.value(forKey: "example_audio") as! String let example_url = origin?.value(forKey: "example_url") as! String self.Teachername.append(name as! String) self.ID.append(ID as! Int) self.Practicename.append(hw as! String) self.demand.append(demand as! String) self.content.append(content as! String) self.example_audio.append(audio) self.example_url.append(example_url) } } }catch{ print("bad things happened") } DispatchQueue.main.async { self.table.reloadData() } }.resume() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Practicename.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StudentClassCell cell.name.text = Teachername[indexPath.row] cell.homework.text = Practicename[indexPath.row] return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "studentpractice"{ let index = table.indexPathForSelectedRow?.row let vc = segue.destination as! StudentPractice vc.name = Practicename[index!] vc.practice_id = ID[index!] vc.demand = demand[index!] vc.content = content[index!] vc.example_audio = example_audio[index!] vc.example_url = example_url[index!] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
37.496454
122
0.575752
47e572525dfcf34a5b5eaebe012c9493d20276d2
331
rb
Ruby
spec/shared_examples/identity_detection_in_chile.rb
vovimayhem/mobile-subscriber-gem
51fcdf4915101788d8c1e91eca11c4f9a18b8d92
[ "MIT" ]
1
2018-06-23T05:50:24.000Z
2018-06-23T05:50:24.000Z
spec/shared_examples/identity_detection_in_chile.rb
vovimayhem/mobile-subscriber-gem
51fcdf4915101788d8c1e91eca11c4f9a18b8d92
[ "MIT" ]
null
null
null
spec/shared_examples/identity_detection_in_chile.rb
vovimayhem/mobile-subscriber-gem
51fcdf4915101788d8c1e91eca11c4f9a18b8d92
[ "MIT" ]
null
null
null
require "spec_helper" shared_examples "of mobile subcriber identity detection from a valid chilean mobile network http request" do it "the msisdn starts with '56'" do expect(subject.msisdn).to start_with '56' end it "the mobile country code is '730'" do expect(subject.mobile_country_code).to eq '730' end end
25.461538
108
0.740181
9ff24871cfaaa5871c5418fae4e09ba4c2761b0e
664
py
Python
setup.py
MSAdministrator/slack-url-utils
59cd6f1ab0b77f607c24a7d4ecda45315e4c373e
[ "MIT" ]
3
2020-03-31T00:34:57.000Z
2021-05-14T02:05:21.000Z
setup.py
MSAdministrator/slack-url-utils
59cd6f1ab0b77f607c24a7d4ecda45315e4c373e
[ "MIT" ]
null
null
null
setup.py
MSAdministrator/slack-url-utils
59cd6f1ab0b77f607c24a7d4ecda45315e4c373e
[ "MIT" ]
3
2020-03-31T16:52:07.000Z
2021-05-14T02:05:23.000Z
from setuptools import setup, find_packages def parse_requirements(requirement_file): with open(requirement_file) as f: return f.readlines() setup( name='slack-url-utils', version='1.0.0', packages=find_packages(exclude=['tests*']), license='MIT', description='A Python package of URL utilities for use in slack using a slash command', long_description=open('README.md').read(), long_description_content_type="text/markdown", install_requires=parse_requirements('./requirements.txt'), keywords=['slack', 'url', 'utilities'], url='https://github.com/MSAdministrator/slack-url-utils', author='Josh Rickard' )
34.947368
91
0.710843
0a52a2746042f0bbfb3b8ff2b93a4be7e4cdd9d6
1,441
cs
C#
Senai.Enderecos.WebApi/Repositories/EnderecoRepository.cs
geovannanogueira/VIACEP
8764b09affc69489e11d4ab000038c1cf71e13af
[ "MIT" ]
null
null
null
Senai.Enderecos.WebApi/Repositories/EnderecoRepository.cs
geovannanogueira/VIACEP
8764b09affc69489e11d4ab000038c1cf71e13af
[ "MIT" ]
9
2020-09-07T14:34:35.000Z
2022-03-24T20:22:09.000Z
enderecos/Senai.Enderecos.WebApi/Repositories/EnderecoRepository.cs
regiamariana/React-JS
8c5db7130f2655c3295ed00d1a7166dee4b0044f
[ "MIT" ]
null
null
null
using Senai.Enderecos.WebApi.Domains; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Senai.Enderecos.WebApi.Repositories { public class EnderecoRepository { private string StringConexao = "Data Source=localhost; initial catalog=Endereco;Integrated Security=true"; public void Cadastrar(EnderecoDomain endereco) { using (SqlConnection con = new SqlConnection(StringConexao)) { string query = "INSERT INTO Enderecos (Nome, Logradouro, Complemento, Bairro, Localidade, UF, CEP) VALUES (@Nome, @Logradouro, @Complemento, @Bairro, @Localidade, @UF, @CEP)"; SqlCommand cmd = new SqlCommand(query, con); //Passa o valor do parametro cmd.Parameters.AddWithValue("@Nome", endereco.Nome); cmd.Parameters.AddWithValue("@Logradouro", endereco.Logradouro); cmd.Parameters.AddWithValue("@Complemento", endereco.Complemento); cmd.Parameters.AddWithValue("@Bairro", endereco.Bairro); cmd.Parameters.AddWithValue("@Localidade", endereco.Localidade); cmd.Parameters.AddWithValue("@UF", endereco.UF); cmd.Parameters.AddWithValue("@CEP", endereco.CEP); con.Open(); cmd.ExecuteNonQuery(); } } } }
41.171429
191
0.637058
c68bad95c4e672ee2bedabc2bbab4e630ffbb47b
737
py
Python
src/database.py
Alchemication/third-eye
0935c31cbe24c01dfbe9a8e02b2cef602a8eacbe
[ "MIT" ]
null
null
null
src/database.py
Alchemication/third-eye
0935c31cbe24c01dfbe9a8e02b2cef602a8eacbe
[ "MIT" ]
null
null
null
src/database.py
Alchemication/third-eye
0935c31cbe24c01dfbe9a8e02b2cef602a8eacbe
[ "MIT" ]
null
null
null
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from config import DB_FILE_PATH, LOG_DB_EVENTS # Sql lite connection params, change connection params below to other DB for more production-ready code engine = create_engine(f"sqlite:///{DB_FILE_PATH}", connect_args={"check_same_thread": False, "timeout": 15}, echo=LOG_DB_EVENTS) session_factory = sessionmaker(autocommit=False, autoflush=False, bind=engine) # for sharing thread-safe sessions: https://docs.sqlalchemy.org/en/14/orm/contextual.html Session = scoped_session(session_factory) Base = declarative_base()
49.133333
103
0.744912
0d96d6e5bf186d517ce2d2b08ea52c95db9ebb07
1,326
rb
Ruby
spec/cases/mocker_spec.rb
EvilFaeton/linkedin
05296fbccbc188de8dbc992ff12124cccc08ad27
[ "MIT" ]
null
null
null
spec/cases/mocker_spec.rb
EvilFaeton/linkedin
05296fbccbc188de8dbc992ff12124cccc08ad27
[ "MIT" ]
null
null
null
spec/cases/mocker_spec.rb
EvilFaeton/linkedin
05296fbccbc188de8dbc992ff12124cccc08ad27
[ "MIT" ]
null
null
null
require 'helper' class MyMocker < LinkedIn::Mocker end describe LinkedIn::Mocker do before do LinkedIn.debug = true LinkedIn.mocking = true end let(:client){LinkedIn::Client.new('token', 'secret')} it "should be able to mock search results" do s = client.search s.should be_an_instance_of(LinkedIn::Mash) s.people._count.should == 2 s.people.all.count.should == 2 s.people.all.first.should have_key('first_name') s.people.all.first.should have_key('last_name') end it "should be able to mock the account profile" do profile = client.profile profile.should be_an_instance_of(LinkedIn::Mash) profile.first_name.should == "My First Name" profile.last_name.should == "My Last Name" end it "should be able to mock the account connections" do c = client.connections c.should be_an_instance_of(LinkedIn::Mash) end it "should be able to mock another profile" do [client.profile(:id => 123), client.profile(:url => "http://www.google.com")].each do |profile| profile.should be_an_instance_of(LinkedIn::Mash) profile.first_name.should_not == "My First Name" profile.last_name.should_not == "My Last Name" end end it "should be able to mock network updates" do n = client.network_updates n.should be_an_instance_of(LinkedIn::Mash) n.numResults.should == 42 end end
26
97
0.729261
e2645575bef89ef217bb0819b873c44f17be3562
1,574
js
JavaScript
app/containers/DiagramConstructPage/Canvas.js
1412578/rctrdxex1
c64c5fe566a39e8726e80dd6264836b3142c7640
[ "MIT" ]
null
null
null
app/containers/DiagramConstructPage/Canvas.js
1412578/rctrdxex1
c64c5fe566a39e8726e80dd6264836b3142c7640
[ "MIT" ]
null
null
null
app/containers/DiagramConstructPage/Canvas.js
1412578/rctrdxex1
c64c5fe566a39e8726e80dd6264836b3142c7640
[ "MIT" ]
null
null
null
import React from 'react'; import {connect} from 'react-redux'; import {selectShape} from './selectors'; export class Canvas extends React.Component { constructor(props){ super(props); this.state = { shapes: [] } } rect = () =>{ return { type: "rect", x: 100, y: 100, width: 300, height: 300, } } circle = () => { return { type: "circle", r: 100, cx: 200, cy: 300, } } handleMouseUp = (e)=>{ console.log(e.s); this.setState(prevState => ({ shapes: [...prevState.shapes, this[this.props.shape]()] // FIX })); } renderRect(options){ return <rect {...options}/> } renderCircle(options){ return <circle {...options}/> } render(){ return <svg className="canvas" onMouseUp={this.handleMouseUp} viewBox="0 0 1000 1000" width={200} height={200} className="canvas"> {this.state.shapes.map(shape => { const {type, ...options} = shape; switch (type){ case "rect": return this.renderRect(options); case "circle": return this.renderCircle(options); default: return undefined; } })} </svg> } } const mapStateToProps = (state) => ({ shape: selectShape, }); export default connect(mapStateToProps)(Canvas);
26.677966
138
0.467598
da30cab4cbc03aa42cd485ff30169a81e02369fa
2,571
php
PHP
cities/cities.php
saczmateusz/web-example-v2
497dd86b269fbc4f10f9f165538504c1368dbad6
[ "MIT" ]
null
null
null
cities/cities.php
saczmateusz/web-example-v2
497dd86b269fbc4f10f9f165538504c1368dbad6
[ "MIT" ]
null
null
null
cities/cities.php
saczmateusz/web-example-v2
497dd86b269fbc4f10f9f165538504c1368dbad6
[ "MIT" ]
null
null
null
<?php function getCities() { return json_decode(file_get_contents(__DIR__ . '/cities.json'), true); } function getCityById($id) { $cities = getCities(); foreach ($cities as $city) { if ($city['id'] == $id) { return $city; } } return null; } function createCity($data) { $cities = getCities(); $data['id'] = rand(1000000, 2000000); $data['icon'] = addIcon($data['description']); $cities[] = $data; putJson($cities); return $data; } function updateCity($data, $id) { $data['icon'] = addIcon($data['description']); $updatecity = []; $cities = getCities(); foreach ($cities as $i => $city) { if ($city['id'] == $id) { $cities[$i] = $updateCity = array_merge($city, $data); } } putJson($cities); return $updateCity; } function deleteCity($id) { $cities = getCities(); foreach ($cities as $i => $city) { if ($city['id'] == $id) { array_splice($cities, $i, 1); } } putJson($cities); } function putJson($cities) { file_put_contents(__DIR__ . '/cities.json', json_encode($cities, JSON_PRETTY_PRINT)); } function validateCity($city, &$errors) { $isValid = true; if (!$city['name']) { $isValid = false; $errors['name'] = 'Nazwa jest wymagana'; } if (!$city['temperature'] || !filter_var($city['temperature'], FILTER_VALIDATE_FLOAT)) { $isValid = false; $errors['temperature'] = 'Temperatura musi być liczbą'; } if (!$city['humidity'] || !filter_var($city['humidity'], FILTER_VALIDATE_INT)) { $isValid = false; $errors['humidity'] = 'Wilgotność musi być liczbą'; } if (!$city['wind'] || !filter_var($city['wind'], FILTER_VALIDATE_FLOAT)) { $isValid = false; $errors['wind'] = 'Wiatr musi być liczbą'; } if (!$city['description']) { $isValid = false; $errors['description'] = 'Opis jest wymagany'; } return $isValid; } function addIcon($description) { switch ($description) { case "bezchmurnie": return "01d"; case "rozproszone chmury": return "02d"; case "całkowite zachmurzenie": return "04d"; case "deszcz": return "10d"; case "ulewa": return "09d"; case "śnieg": return "13d"; case "mgła": return "50d"; case "burza z piorunami": return "11d"; default: return "02d"; } }
21.974359
92
0.531311
8eef7dedec0a9064766d7f77a31806441b1caf02
47
jbuilder
Ruby
app/views/api/events/show.json.jbuilder
cptleo92/MeetGreet
02b4cda18e905418f67bbcc29ea51a7b4423f843
[ "MIT" ]
null
null
null
app/views/api/events/show.json.jbuilder
cptleo92/MeetGreet
02b4cda18e905418f67bbcc29ea51a7b4423f843
[ "MIT" ]
null
null
null
app/views/api/events/show.json.jbuilder
cptleo92/MeetGreet
02b4cda18e905418f67bbcc29ea51a7b4423f843
[ "MIT" ]
null
null
null
json.partial! 'api/events/event', event: @event
47
47
0.744681
75ad73ef53d6096b05853158b493ccb83d328175
273
css
CSS
src/app/home/filter/color-modal/color-modal.component.css
open-student-environment/ose-client
5b832d03fa0986c689f3d98edc06e3458705d248
[ "MIT" ]
null
null
null
src/app/home/filter/color-modal/color-modal.component.css
open-student-environment/ose-client
5b832d03fa0986c689f3d98edc06e3458705d248
[ "MIT" ]
16
2018-08-31T10:15:31.000Z
2018-11-12T10:42:38.000Z
src/app/home/filter/color-modal/color-modal.component.css
open-student-environment/ose-client
5b832d03fa0986c689f3d98edc06e3458705d248
[ "MIT" ]
1
2019-11-01T22:20:02.000Z
2019-11-01T22:20:02.000Z
.color-picker { display: flex; align-items: center; } .gradient { display: flex; flex: 1; height: 23px; width: 100%; margin: 12px; /* background-image: linear-gradient(to right, red, yellow); */ } .actions { display: flex; justify-content: flex-end; }
15.166667
65
0.637363
391178e7295957a95095df516f6e48435ac89ade
1,951
py
Python
src/export/objects/LanHostAccessPoint.py
Aloike/Freebox-Revolution-Monitoring
2b21bb36e9dc9d6dbec1bddf22c1174a9280f28b
[ "MIT" ]
1
2021-04-27T16:48:50.000Z
2021-04-27T16:48:50.000Z
src/export/objects/LanHostAccessPoint.py
Aloike/Freebox-Revolution-Monitoring
2b21bb36e9dc9d6dbec1bddf22c1174a9280f28b
[ "MIT" ]
3
2021-09-28T11:46:30.000Z
2021-09-28T13:02:14.000Z
src/export/objects/LanHostAccessPoint.py
Aloike/Freebox-Revolution-Monitoring
2b21bb36e9dc9d6dbec1bddf22c1174a9280f28b
[ "MIT" ]
null
null
null
#!/usr/bin/python3 #-*- coding: utf-8 -*- # coding: utf-8 # pylint: disable=C0103,C0111,W0621 from .. import _generic from . import LanHostAccessPointEthInformation from . import LanHostAccessPointWifiInformation # ############################################################################## # ############################################################################## # # Logging configuration # import logging log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ############################################################################## # ############################################################################## def fromJson(pApiPath, pApiSubpath, pTagsDict, pJsonObjectLanHostAccessPoint): lTags = pTagsDict.copy() lTags['access_point_uid'] = pJsonObjectLanHostAccessPoint['uid'] # # Iterate over available keys # for lJsonKey in pJsonObjectLanHostAccessPoint: # # Those keys are used in tags, skip them. # if lJsonKey == 'uid': continue # # Those keys identify subpath; they are managed separately. # elif lJsonKey == 'ethernet_information': LanHostAccessPointEthInformation.fromJson( pApiPath, pApiSubpath + '/ethernet_information', lTags, pJsonObjectLanHostAccessPoint[lJsonKey] ) elif lJsonKey == 'wifi_information': LanHostAccessPointWifiInformation.fromJson( pApiPath, pApiSubpath + '/wifi_information', lTags, pJsonObjectLanHostAccessPoint[lJsonKey] ) # # Default export rule # else: # log.error("Unmanaged key '%s'." % lJsonKey) _generic.measurement( pApiPath = pApiPath, pApiSubpath = pApiSubpath, pApiAttribute = lJsonKey, pAttrValue = pJsonObjectLanHostAccessPoint[lJsonKey], pTagsDict = lTags#, # pFieldsDict = lFields ) # ############################################################################## # ##############################################################################
25.671053
80
0.541261
797f9aa8bbf226c0d1095ab0c6556b7b09293235
6,189
php
PHP
resources/views/sales/layouts/customJs/familyAccess.blade.php
Motaweron-Web/skyPark
f963ee27c84498840e715671d2aa3a86f55621f2
[ "MIT" ]
null
null
null
resources/views/sales/layouts/customJs/familyAccess.blade.php
Motaweron-Web/skyPark
f963ee27c84498840e715671d2aa3a86f55621f2
[ "MIT" ]
null
null
null
resources/views/sales/layouts/customJs/familyAccess.blade.php
Motaweron-Web/skyPark
f963ee27c84498840e715671d2aa3a86f55621f2
[ "MIT" ]
null
null
null
<script> var table = $('.customDataTable').DataTable({ responsive: true, paging: false // "ordering": true, // columnDefs: [{ // 'targets': [4, 5], // 'orderable': false // }, ] }); accessWhenLoad() function accessWhenLoad() { var url = window.location.href; if (url.includes('search')) { getSearchValue(url) var slug = url.substring(url.indexOf("=") + 1); $('#searchValue').val(slug) } } $(document).on('click', '#searchButton', function () { var searchValue = $('#searchValue').val(), url; if (searchValue.length == 0) { url = "{{route('familyAccess.index')}}?search=all" }else{ url = "{{route('familyAccess.index')}}?search=" + searchValue } getSearchValue(url) }) //////////////// البحث /////////// function getSearchValue(url) { $.ajax({ type: 'GET', url: url, beforeSend: function () { window.history.pushState({path: url}, '', url); $('.spinner').show() table.clear().draw(); }, complete: function (data) { $('.spinner').hide() }, success: function (data) { if (data.status === 200) { var Rows = data.backArray; $.each(Rows, function (key, val) { table.row.add(data.backArray[key]).draw(false); }) } else if (data.status === 300) { toastr.info('there is no data') } }, error: function (data) { if (data.status === 500) { toastr.error('Unexpected Error'); } else if (data.status === 422) { var errors = $.parseJSON(data.responseText); $.each(errors, function (key, value) { if ($.isPlainObject(value)) { $.each(value, function (key, value) { // toastr.error(value, key); }); } }); } },//end error method }); } $(document).on('click','.check',function () { var id = $(this).data('id') var braceletNumber = $('#braceletNumber' + id).val() $('.spinner').show() if (!braceletNumber.length) { toastr.warning('you should fill bracelet number') }else { submitRow(id) // if (submitRow(id)){ // } } setTimeout(function () { $('.spinner').hide() }, 500) }) function submitRow(id) { var return_ = 0; var braceletNumber = $('#braceletNumber' + id).val() var birthDay = $('#birthDay' + id).val() var name = $('#name' + id).val() var gender = $('input[name=gender' + id + ']:checked').val(); if (!braceletNumber.length) { return false; } var method = { bracelet_number: braceletNumber, birthday: birthDay, gender: gender, name: name, id: id, _method: "PUT", } var url = "{{route('familyAccess.update',":id")}}" url = url.replace(':id', id) $.post(url, method, function (data) { if (data) { if(data.status == 405){ toastr.error('An Amount Of '+data.rem_amount+' EGP Is Unpaid'); $('#payBtn').removeClass('d-none'); $('#payBtn').attr('data-ticket_id',data.ticket_id); $('#idOfTicket').val(data.ticket_id); }else{ $('#check'+id).addClass('checked'); $('#check'+id).removeClass('check'); $('#birthDay'+id).attr('disabled', true); $('#braceletNumber'+id).attr('disabled', true); $('#option1'+id).attr('disabled', true); $('#option2'+id).attr('disabled', true); $('#name'+id).attr('disabled', true); } } }).fail(function (data) { if (data.status === 500) { toastr.error('there is an error'); } else if (data.status === 422) { var errors = $.parseJSON(data.responseText); $.each(errors, function (key, value) { if ($.isPlainObject(value)) { $.each(value, function (key, value) { toastr.error(value, key); }); } else { } }); } else { toastr.error('there in an error'); } return true; }).then(function (return_) { return return_ }) } // Pay Amount $(document).on('click', '#confirmBtn', function (event) { var id = $('#idOfTicket').val(); $('#confirmBtn').html('<span class="spinner-border spinner-border-sm mr-2" ' + ' ></span> <span style="margin-left: 4px;">working</span>').attr('disabled', true); $.ajax({ type: 'POST', url: "{{route('ticket.updateAmount')}}", data: { '_token': "{{csrf_token()}}", 'id': id, }, success: function (data) { if (data.status === 200) { $('#payBtn').addClass('d-none'); toastr.success(data.message) } else { toastr.error(data.message) } $('#confirmBtn').html(`Confirm`).attr('disabled', false); $("#payAmount").modal('hide'); } }); }); </script>
31.738462
99
0.405235
b0a31617ff1d0e29e4aefae33e29d7683639ff2d
155
py
Python
Chapter05/example03/usecmd.py
PacktPublishing/Daniel-Arbuckles-Mastering-Python
ecd1e78d95aedc832d8f5ceec4794374459e890a
[ "MIT" ]
28
2017-08-10T18:21:52.000Z
2021-11-22T11:13:01.000Z
Chapter05/example03/usecmd.py
PacktPublishing/Daniel-Arbuckles-Mastering-Python
ecd1e78d95aedc832d8f5ceec4794374459e890a
[ "MIT" ]
2
2019-06-17T13:22:00.000Z
2019-06-17T14:06:18.000Z
Chapter05/example03/usecmd.py
PacktPublishing/Daniel-Arbuckles-Mastering-Python
ecd1e78d95aedc832d8f5ceec4794374459e890a
[ "MIT" ]
20
2017-07-07T16:25:50.000Z
2022-01-11T15:57:18.000Z
import cmd class Interface(cmd.Cmd): prompt = 'Command: ' def do_foo(self, arg): print(arg) interface = Interface() interface.cmdloop()
14.090909
26
0.645161
14624f637705a09ee0daf4dd86dd61f3a629cc5a
452
ts
TypeScript
resources/assets/typescript/app/app.component.ts
mbackonja/vivify-ToDoApp
9d62ae51a17c3a73dd0980d28e72e4083e7ea002
[ "MIT" ]
null
null
null
resources/assets/typescript/app/app.component.ts
mbackonja/vivify-ToDoApp
9d62ae51a17c3a73dd0980d28e72e4083e7ea002
[ "MIT" ]
null
null
null
resources/assets/typescript/app/app.component.ts
mbackonja/vivify-ToDoApp
9d62ae51a17c3a73dd0980d28e72e4083e7ea002
[ "MIT" ]
null
null
null
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from './authentication.service'; @Component({ selector: 'my-app', template: require('./app.component.html') }) export class AppComponent implements OnInit { private loggedIn: boolean; constructor(private authenticationService: AuthenticationService) { } ngOnInit(): void { this.loggedIn = this.authenticationService.loggedIn(); } }
25.111111
73
0.705752
617d68f9a696fd9f1b5c7f40da8674104d4f6ff9
566
lua
Lua
campaign/scripts/power_action_mini.lua
MeAndUnique/KitNKadooble
0943f7a9902aca4d6647b60a7cbba2953a629c08
[ "MIT" ]
8
2021-03-16T01:48:05.000Z
2022-01-22T23:18:18.000Z
campaign/scripts/power_action_mini.lua
MeAndUnique/KitNKadooble
0943f7a9902aca4d6647b60a7cbba2953a629c08
[ "MIT" ]
1
2022-01-31T23:06:10.000Z
2022-01-31T23:06:10.000Z
campaign/scripts/power_action_mini.lua
MeAndUnique/KitNKadooble
0943f7a9902aca4d6647b60a7cbba2953a629c08
[ "MIT" ]
1
2022-01-22T21:48:10.000Z
2022-01-22T21:48:10.000Z
-- -- Please see the license.txt file included with this distribution for -- attribution and copyright information. -- local updateViewsOriginal; local bIsItem; function onInit() bIsItem = getDatabaseNode().getPath():match("inventorylist"); updateViewsOriginal = super.updateViews; super.updateViews = updateViews; super.onInit(); end function updateViews() if bIsItem then ActorManagerKNK.beginResolvingItem(getDatabaseNode().getChild(".......") or true); end updateViewsOriginal(); if bIsItem then ActorManagerKNK.endResolvingItem(); end end
19.517241
84
0.759717
2d30158e7ff30b09d8bdd7e524a1eb029d5d0fc3
1,734
css
CSS
IndicatorsUI/MainUI/angular-app/src/app/map/practice-search/practice-search.component.css
publichealthengland/fingertips-open
678089724a516138232d273c4c7f511ed3c5a338
[ "MIT" ]
2
2016-01-22T10:32:57.000Z
2020-02-05T15:47:19.000Z
IndicatorsUI/MainUI/angular-app/src/app/map/practice-search/practice-search.component.css
PublicHealthEngland/fingertips-open
678089724a516138232d273c4c7f511ed3c5a338
[ "MIT" ]
2
2021-05-06T15:49:22.000Z
2022-03-02T01:00:49.000Z
IndicatorsUI/MainUI/angular-app/src/app/map/practice-search/practice-search.component.css
publichealthengland/fingertips-open
678089724a516138232d273c4c7f511ed3c5a338
[ "MIT" ]
1
2016-05-09T15:43:57.000Z
2016-05-09T15:43:57.000Z
.glyphicon { display: none; } .googleMapNg { position: relative; background-color: #fff; border: 1px solid #CCC; width: 550px; height: 600px; margin-bottom: 10px; margin-top: 10px; clear: both; overflow: hidden; } #default_search_header { width: 400px; padding-top: 10px; position: absolute; } #practice-list-info { min-height: 30px; } #practice-list-info input { max-width: 450px; } #practice-list-info h3 { font-size: 1.4em; margin-top: 10px; } .practice-header { cursor: pointer; } .nearby-practices-map { float: right; width: 550px; height: 0px; margin-top: -10px; overflow: hidden; } .nearby-practices-map #google-map { margin-bottom: 10px; } #table-container { height: 600px; overflow-y: scroll; } .nearby-practices-table { float: left; width: 45%; } .nearby-practices-table table { width: 100%; border-collapse: collapse; } .nearby-practices-table .header { position: relative; background-color: #02ae94; padding: 10px; color: #fff; } .nearby-practices-table td, .nearby-practices-table th { padding: 0; font-weight: normal; text-align: left; vertical-align: top; font-size: 16px; } #show-all-practices { padding: 23px 0 18px 0; } #show-all-practices a, a:visited, a:active, a:hover { color: #1d1dae; } #show-all-practices a, a:visited, a:active, a:hover { color: #2e3191; text-decoration: underline; font-size: 16px; } #show-all-practices a { cursor: pointer; } .highlight-address { background-color: #e6e6e6 } .highlight-header { background-color: #525252; position: relative; padding: 10px; color: #fff; }
14.948276
35
0.629758
3395fd2de2f0d52c09334efc6d7a3752b0b936cd
1,241
h
C
includes/led.h
PixelNut/PixelNutApp
75b2b1ffee82538beae6aa0f3795e647d9265aaf
[ "BSD-3-Clause" ]
null
null
null
includes/led.h
PixelNut/PixelNutApp
75b2b1ffee82538beae6aa0f3795e647d9265aaf
[ "BSD-3-Clause" ]
null
null
null
includes/led.h
PixelNut/PixelNutApp
75b2b1ffee82538beae6aa0f3795e647d9265aaf
[ "BSD-3-Clause" ]
null
null
null
// PixelNutApp LED Control // Uses single LED for error/status. //======================================================================================== /* Copyright (c) 2015-2020, Greg de Valois Software License Agreement (BSD License) See license.txt for the terms of this license. */ #if defined(DPIN_LED) #if defined(LED_ACTIVE_LOW) && LED_ACTIVE_LOW #define LED_ON LOW #define LED_OFF HIGH #else // default is active high #define LED_ON HIGH #define LED_OFF LOW #endif #define LED_TURN_ON digitalWrite(DPIN_LED, LED_ON) #define LED_TURN_OFF digitalWrite(DPIN_LED, LED_OFF) #endif void SetupLED(void) { #if defined(DPIN_LED) pinMode(DPIN_LED, OUTPUT); LED_TURN_ON; #endif } void BlinkStatusLED(uint16_t slow, uint16_t fast) { #if defined(DPIN_LED) LED_TURN_OFF; delay(250); if (slow) { for (int i = 0; i < slow; ++i) { LED_TURN_ON; delay(750); LED_TURN_OFF; delay(250); } if (fast) delay(250); } if (fast) { for (int i = 0; i < fast; ++i) { LED_TURN_ON; delay(150); LED_TURN_OFF; delay(250); } } delay(250); #endif } //========================================================================================
19.092308
90
0.549557
642f544b40b4e720e89c3e4592c46d35b032a261
1,514
py
Python
pymtl3/stdlib/ifcs/XcelMsg.py
mondO/pymtl3
9869dda28c01926cee6da94ebdeac2a210150c62
[ "BSD-3-Clause" ]
1
2022-01-03T06:22:11.000Z
2022-01-03T06:22:11.000Z
pymtl3/stdlib/ifcs/XcelMsg.py
mondO/pymtl3
9869dda28c01926cee6da94ebdeac2a210150c62
[ "BSD-3-Clause" ]
null
null
null
pymtl3/stdlib/ifcs/XcelMsg.py
mondO/pymtl3
9869dda28c01926cee6da94ebdeac2a210150c62
[ "BSD-3-Clause" ]
null
null
null
""" ======================================================================== XcelMsg.py ======================================================================== Accelerator message type implementation. Author : Yanghui Ou Date : June 3, 2019 """ from pymtl3 import * def mk_xcel_msg( addr, data ): return mk_xcel_req_msg( addr, data ), mk_xcel_resp_msg( data ) def mk_xcel_req_msg( addr, data ): AddrType = mk_bits( addr ) DataType = mk_bits( data ) cls_name = "XcelReqMsg_{}_{}".format( addr, data ) def req_to_str( self ): return "{}:{}:{}".format( "rd" if self.type_ == XcelMsgType.READ else "wr", AddrType( self.addr ), DataType( self.data ) if self.type_ != XcelMsgType.READ else " " * ( data//4 ), ) req_cls = mk_bitstruct( cls_name, { 'type_': Bits1, 'addr': AddrType, 'data': DataType, }, namespace = { '__str__' : req_to_str }) return req_cls def mk_xcel_resp_msg( data ): DataType = mk_bits( data ) cls_name = "XcelRespMsg_{}".format( data ) def resp_to_str( self ): return "{}:{}".format( "rd" if self.type_ == XcelMsgType.READ else "wr", DataType( self.data ) if self.type_ != XcelMsgType.WRITE else " " * ( data//4 ), ) resp_cls = mk_bitstruct( cls_name, { 'type_': Bits1, 'data': DataType, }, namespace = { '__str__' : resp_to_str }) return resp_cls class XcelMsgType: # TODO: figure out whether we want to use Bits1 here. READ = Bits1(0) WRITE = Bits1(1)
24.031746
72
0.557464
977bfdbf30454ba8362a54fe04170a9f625c814a
1,825
ts
TypeScript
packages/svg/src/icons/Iconpeach.ts
StringKe/IconPark
accda67be9ba31a4c07745eb6bc73e640df3e2be
[ "Apache-2.0" ]
null
null
null
packages/svg/src/icons/Iconpeach.ts
StringKe/IconPark
accda67be9ba31a4c07745eb6bc73e640df3e2be
[ "Apache-2.0" ]
null
null
null
packages/svg/src/icons/Iconpeach.ts
StringKe/IconPark
accda67be9ba31a4c07745eb6bc73e640df3e2be
[ "Apache-2.0" ]
null
null
null
/** * @file IconPeach 桃子 * @author Auto Generated by IconPark */ /* tslint:disable: max-line-length */ /* eslint-disable max-len */ import {ISvgIconProps, IconWrapper} from '../runtime'; export default IconWrapper('IconPeach', (props: ISvgIconProps) => ( '<?xml version="1.0" encoding="UTF-8"?>' + '<svg width="' + props.size + '" height="' + props.size + '" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">' + '<path d="M10.0772 13.4314C15.0471 7.86993 23.6868 10.3147 27 12C28.6566 11.368 33.1972 10.6426 36.1791 12.6649C39.9065 15.1929 44.6027 21.904 40.2542 31.3837C36.7753 38.9675 27.689 42.1574 24.3758 43C21.8909 41.9467 16.4303 39.8319 10.6066 34.5518C5.32574 29.7638 3.86498 20.3831 10.0772 13.4314Z" fill="' + props.colors[1] + '" stroke="' + props.colors[0] + '" stroke-width="' + props.strokeWidth + '" stroke-linejoin="' + props.strokeLinejoin + '"/>' + '<path d="M27 12C25.0761 12.75 21.2283 14.25 19.1295 18.75C16.8741 23.586 18.6048 27.75 19.1295 30" stroke="' + props.colors[0] + '" stroke-width="' + props.strokeWidth + '" stroke-linecap="' + props.strokeLinecap + '" stroke-linejoin="' + props.strokeLinejoin + '"/>' + '<path d="M21 4C21.3333 4.16667 23.5 4.5 24 6.5C24.4372 8.24895 23.6667 9.33333 23.5 10.5" stroke="' + props.colors[0] + '" stroke-width="' + props.strokeWidth + '" stroke-linecap="' + props.strokeLinecap + '"/>' + '<path d="M28.4787 11.3284C27.525 11.2954 26.8664 10.4549 27.0625 9.521C27.3328 8.23356 27.9452 6.47669 29.3292 5.39221C30.7133 4.30774 32.5656 4.13338 33.8803 4.17886C34.834 4.21185 35.4926 5.05238 35.2966 5.98629C35.0262 7.27373 34.4139 9.0306 33.0298 10.1151C31.6458 11.1995 29.7935 11.3739 28.4787 11.3284Z" stroke="' + props.colors[0] + '" stroke-width="' + props.strokeWidth + '"/>' + '</svg>' ));
96.052632
463
0.659726
cd24becf93495154c79148ac2c439a1abe252014
160
cs
C#
App/Interface/login/LineEdit_LoginUsername.cs
EnzoItaliano/Tamagotchi-LP
324ceeac966f616e3ec5c53a887effc68dfce10e
[ "MIT" ]
null
null
null
App/Interface/login/LineEdit_LoginUsername.cs
EnzoItaliano/Tamagotchi-LP
324ceeac966f616e3ec5c53a887effc68dfce10e
[ "MIT" ]
null
null
null
App/Interface/login/LineEdit_LoginUsername.cs
EnzoItaliano/Tamagotchi-LP
324ceeac966f616e3ec5c53a887effc68dfce10e
[ "MIT" ]
null
null
null
using Godot; using System; public class LineEdit_LoginUsername : LineEdit { public string get_LoginUsername_text() { return Convert.ToString(Text); } }
13.333333
48
0.75625
a7468ed1a74364aca311e6a00ca469d3ae7e21ad
163
sql
SQL
no-more-silos/data/mssql/b00_create_db_demo.sql
jwfbean/demo-scene
958f126d2225cd797e5b832daa9f45788243a751
[ "Apache-2.0" ]
1,150
2018-07-06T13:05:18.000Z
2022-03-31T19:56:24.000Z
no-more-silos/data/mssql/b00_create_db_demo.sql
jwfbean/demo-scene
958f126d2225cd797e5b832daa9f45788243a751
[ "Apache-2.0" ]
114
2018-08-21T16:55:24.000Z
2022-03-07T09:53:56.000Z
no-more-silos/data/mssql/b00_create_db_demo.sql
jwfbean/demo-scene
958f126d2225cd797e5b832daa9f45788243a751
[ "Apache-2.0" ]
732
2018-07-13T07:02:39.000Z
2022-03-29T17:58:58.000Z
USE [master] GO CREATE DATABASE demo; GO ALTER DATABASE [demo] SET CONTAINMENT = PARTIAL GO USE [demo] GO CREATE USER connect_user WITH PASSWORD = 'Asgard123'; GO
14.818182
53
0.766871
c6cc98b3103b159d79deac9bc44c5feef2963767
2,093
py
Python
Tools/disass/sample/apt1_cookiebag_parser.py
upxnoops/RE-Toolkit
4d1faecbe6c4498c9d2a0b607aaaeef393076062
[ "MIT" ]
null
null
null
Tools/disass/sample/apt1_cookiebag_parser.py
upxnoops/RE-Toolkit
4d1faecbe6c4498c9d2a0b607aaaeef393076062
[ "MIT" ]
null
null
null
Tools/disass/sample/apt1_cookiebag_parser.py
upxnoops/RE-Toolkit
4d1faecbe6c4498c9d2a0b607aaaeef393076062
[ "MIT" ]
null
null
null
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- ############################################################################# ## ## ## This file is part of Disass ## ## ## ## ## ## Copyright (C) 2013 Cassidian CyberSecurity SAS. All rights reserved. ## ## This document is the property of Cassidian CyberSecurity SAS, it may ## ## not be circulated without prior licence ## ## ## ## Author: Ivan Fontarensky <ivan.fontarensky@cassidian.com> ## ## ## ############################################################################# __author__ = 'ifontarensky' import sys import argparse from disass.Disass32 import Disass32 # Cookiebag # Tested on def reverse(path, verbose): disass = Disass32(path=path, verbose=verbose) disass.go_to_next_call('GetCommandLineA') disass.go_to_instruction('CALL') disass.go_to_instruction('CALL') disass.go_to_instruction('CALL') disass.go_to_instruction('CALL') if disass.go_to_next_call('memcpy'): address_mutex = disass.get_arguments(2) mutex = disass.get_string(address_mutex) print " C&C\t\t:", mutex if __name__ == '__main__': parser = argparse.ArgumentParser(description='sluegot_parser') parser.add_argument('--verbose', '-v', help='Do not output anything on the standard output.', action='store_true', default=False) parser.add_argument('path', help='path to analyze', nargs="*") args = parser.parse_args() if len(args.path) == 0: print "Usage : sluegot_parser.py sluegot.infected" sys.exit(1) for path in args.path: reverse(path=path, verbose=args.verbose)
36.086207
118
0.474439
ddba39222c72236f9588fed1c44a5b9592b1f68c
4,338
java
Java
litho-widget/src/main/java/com/facebook/litho/widget/CardSpec.java
leochuan/litho
e26c11e77f5e370afe21bde4c73d7459fa04dd86
[ "BSD-3-Clause" ]
4
2020-04-21T10:24:00.000Z
2020-04-21T11:22:30.000Z
litho-widget/src/main/java/com/facebook/litho/widget/CardSpec.java
leochuan/litho
e26c11e77f5e370afe21bde4c73d7459fa04dd86
[ "BSD-3-Clause" ]
null
null
null
litho-widget/src/main/java/com/facebook/litho/widget/CardSpec.java
leochuan/litho
e26c11e77f5e370afe21bde4c73d7459fa04dd86
[ "BSD-3-Clause" ]
1
2021-11-10T10:01:33.000Z
2021-11-10T10:01:33.000Z
/* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.litho.widget; import static com.facebook.litho.widget.CardShadowDrawable.getShadowBottom; import static com.facebook.litho.widget.CardShadowDrawable.getShadowHorizontal; import static com.facebook.litho.widget.CardShadowDrawable.getShadowTop; import static com.facebook.yoga.YogaEdge.ALL; import static com.facebook.yoga.YogaEdge.BOTTOM; import static com.facebook.yoga.YogaEdge.HORIZONTAL; import static com.facebook.yoga.YogaEdge.TOP; import static com.facebook.yoga.YogaPositionType.ABSOLUTE; import android.content.res.Resources; import android.graphics.Color; import com.facebook.litho.Column; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentLayout; import com.facebook.litho.annotations.LayoutSpec; import com.facebook.litho.annotations.OnCreateLayout; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; /** * A component that renders a given component into a card border with shadow. * * @prop cardBackgroundColor Background color for the card. * @prop clippingColor Color for corner clipping. * @prop shadowStartColor Start color for shadow drawn underneath the card. * @prop shadowEndColor End color for shadow drawn underneath the card. * @prop cornerRadius Corner radius for the card. * @prop elevation Elevation of the card. */ @LayoutSpec (isPureRender = true) class CardSpec { private static final int DEFAULT_CORNER_RADIUS_DP = 2; private static final int DEFAULT_SHADOW_SIZE_DP = 2; @PropDefault static final int cardBackgroundColor = Color.WHITE; @PropDefault static final int clippingColor = Color.WHITE; @PropDefault static final int shadowStartColor = 0x37000000; @PropDefault static final int shadowEndColor = 0x03000000; @PropDefault static final float cornerRadius = -1; @PropDefault static final float elevation = -1; private static float pixels(Resources resources, int dips) { final float scale = resources.getDisplayMetrics().density; return dips * scale + 0.5f; } @OnCreateLayout static ComponentLayout onCreateLayout( ComponentContext c, @Prop Component<?> content, @Prop(optional = true, resType = ResType.COLOR) int cardBackgroundColor, @Prop(optional = true, resType = ResType.COLOR) int clippingColor, @Prop(optional = true, resType = ResType.COLOR) int shadowStartColor, @Prop(optional = true, resType = ResType.COLOR) int shadowEndColor, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float cornerRadius, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float elevation) { final Resources resources = c.getResources(); if (cornerRadius == -1) { cornerRadius = pixels(resources, DEFAULT_CORNER_RADIUS_DP); } if (elevation == -1) { elevation = pixels(resources, DEFAULT_SHADOW_SIZE_DP); } final int shadowTop = getShadowTop(elevation); final int shadowBottom = getShadowBottom(elevation); final int shadowHorizontal = getShadowHorizontal(elevation); return Column.create(c) .child( Column.create(c) .marginPx(HORIZONTAL, shadowHorizontal) .marginPx(TOP, shadowTop) .marginPx(BOTTOM, shadowBottom) .backgroundColor(cardBackgroundColor) .child(content) .child( CardClip.create(c) .clippingColor(clippingColor) .cornerRadiusPx(cornerRadius) .positionType(ABSOLUTE) .positionPx(ALL, 0))) .child( CardShadow.create(c) .shadowStartColor(shadowStartColor) .shadowEndColor(shadowEndColor) .cornerRadiusPx(cornerRadius) .shadowSizePx(elevation) .positionType(ABSOLUTE) .positionPx(ALL, 0)) .build(); } }
39.081081
80
0.709313
fda9f141487e82e1ea3f54451410d234adc87f9e
7,771
css
CSS
Kairos/Perfil/PerfilEmpresa/assets/css/style.css
GabrielCoutz/Automa--es
91860ef080c7b0e0b925cdff72cc58ce5acb5d88
[ "MIT" ]
null
null
null
Kairos/Perfil/PerfilEmpresa/assets/css/style.css
GabrielCoutz/Automa--es
91860ef080c7b0e0b925cdff72cc58ce5acb5d88
[ "MIT" ]
null
null
null
Kairos/Perfil/PerfilEmpresa/assets/css/style.css
GabrielCoutz/Automa--es
91860ef080c7b0e0b925cdff72cc58ce5acb5d88
[ "MIT" ]
null
null
null
@font-face { font-family: "San Francisco"; font-weight: 400; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-regular-webfont.woff"); } #nomeEmpresaText, #FantasiaText, #cepEmpresaText,#numeroEmpresaText{ opacity: 0; display: none; transition: all 1s; } i#nomeEmpresaTip:hover ~ span#nomeEmpresaText, i#FantasiaTip:hover ~ span#FantasiaText, i#cepEmpresaTip:hover ~ span#cepEmpresaText, i#numeroEmpresaTip:hover ~ span#numeroEmpresaText{ border: #6e6e6e 1px dotted; padding: 10px; display: block !important; opacity: 1 !important; z-index: 100; margin: 10px; box-shadow: 10px 10px 7px -10px #bbbbbb; text-align: left; position: absolute; font-family: 'San Francisco'; font-weight: 700; font-size: 15px; color: #3a3a3a; text-decoration: none; border-radius: 10px; font-style: italic; background: white; } #cancelarbtn{ position: relative; color: #4E6EF1 !important; margin-left: 10px; background-color: white !important; border-color: #4E6EF1 !important; } p{ letter-spacing: 0.3px; } #editarbtn{ background: #4E6EF1 !important; } #btnsair{ cursor: pointer !important ; } #btnsair:hover{ color: red !important; } .close-layer{ display: none !important; } .alerta{ margin-top: -7px; margin-bottom: 3px; text-align: left; color: #ff0000; cursor: default; } lord-icon{ position: absolute !important; margin-top: -14px; right: 127px; } #btnfechar{ cursor: pointer !important; } .small-input { -moz-appearance: textfield; } .small-input::-webkit-inner-spin-button { display: none; } .small-input::-webkit-outer-spin-button, .small-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } button:hover{ box-shadow: 0px 6px 10px 1px rgb(0 0 0 / 31%) !important; transform: translateY(-0.10em); } button:active{ box-shadow: 0px 10px 15px -15px rgb(0 0 0) !important; transform: translateY(0em) !important; } button{ transition: 0.5s all !important; position: relative; overflow: hidden; border-color: transparent !important; } .btn { display: inline-block; overflow: hidden; font-weight: bold; color: #212529; text-align: center; vertical-align: middle; letter-spacing: 0.8px; font-family: 'San Francisco', sans-serif !important; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: transparent; border: 1px solid transparent; padding: 0.375rem 0.75rem; font-size: 14px !important; line-height: 1.5; border-radius: 0.25rem; transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; } button:disabled{ cursor: default; } #add_tel, #salvarbtn{ color: white; background: #20a837; } .vermei, .vermei:focus, .vermei:hover{ border: 1px solid red !important; } input, select{ max-width: 250px; font-family: 'San Francisco' !important; font-style: normal !important; } select{ height: 35px; } html, body{ max-width: 100% !important; overflow-x: hidden !important; } label{ color: #565656 !important; font-family: "San Francisco", sans-serif !important; } .content{ cursor: default; } input::-webkit-input-placeholder { color: black !important; opacity: 0.5 !important; } .text-secondary{ color: #6c757d!important; font-family: "Archivo Black", sans-serif !important; letter-spacing: 0.3px !important; } input, select{ transition: all 0.5s ease-in-out !important; border-radius:6px !important; border: 1px solid #ced6e0 !important; } input:focus, input:hover, select:focus, select:hover{ box-shadow: 0px 10px 20px -13px rgba(32, 56, 117, 0.35) !important; text-align: left !important; border-radius:6px !important; border-color: #3d9cff !important; outline: none !important; } #salvarbtn{ margin-left: 10px; } #ramo_input{ width: 100%; } #paginaInicial:hover, #suporte:hover { color: #3d9cff; } #btnsair-v{ background-color: white; color: red; border-color: red !important; width: 80px; height: 35px; } @media(min-width: 991px){ #btnfechar{ display: none; } #btnsair{ display: none; } #btnsair-v{ display: inline-block; } .nav-mobile-menu{ display: none !important; } } @media(max-width: 990px){ #btnsair{ display: block; } #btnsair-v{ display: none; } .nav-mobile-menu{ display: block !important; } } @media (max-width: 500px){ .alerta{ text-align: center; } button{ width: 100%; margin-bottom: 10px; } } #asdf{ cursor: default; } /*===== All Preloader Style =====*/ .preloader { /* Body Overlay */ position: fixed; top: 0; left: 0; display: table; height: 100%; width: 100%; /* Change Background Color */ background: #fff; z-index: 99999; } .preloader .loader { display: table-cell; vertical-align: middle; text-align: center; } .preloader .loader .spinner { position: absolute; left: 50%; top: 50%; width: 64px; margin-left: -32px; z-index: 18; pointer-events: none; } .preloader .loader .spinner .spinner-container { pointer-events: none; position: absolute; width: 100%; padding-bottom: 100%; top: 50%; left: 50%; margin-top: -50%; margin-left: -50%; animation: spinner-linspin 1568.2353ms linear infinite; } .preloader .loader .spinner .spinner-container .spinner-rotator { position: absolute; width: 100%; height: 100%; animation: spinner-easespin 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both; } .preloader .loader .spinner .spinner-container .spinner-rotator .spinner-left { position: absolute; top: 0; left: 0; bottom: 0; overflow: hidden; right: 50%; } .preloader .loader .spinner .spinner-container .spinner-rotator .spinner-right { position: absolute; top: 0; right: 0; bottom: 0; overflow: hidden; left: 50%; } .preloader .loader .spinner-circle { box-sizing: border-box; position: absolute; width: 200%; height: 100%; border-style: solid; /* Spinner Color */ border-color: #4E6EF1 #4E6EF1 #ddd; border-radius: 50%; border-width: 6px; } .preloader .loader .spinner-left .spinner-circle { left: 0; right: -100%; border-right-color: #ddd; animation: spinner-left-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both; } .preloader .loader .spinner-right .spinner-circle { left: -100%; right: 0; border-left-color: #ddd; animation: right-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both; } /* Preloader Animations */ @keyframes spinner-linspin { to { transform: rotate(360deg); } } @keyframes spinner-easespin { 12.5% { transform: rotate(135deg); } 25% { transform: rotate(270deg); } 37.5% { transform: rotate(405deg); } 50% { transform: rotate(540deg); } 62.5% { transform: rotate(675deg); } 75% { transform: rotate(810deg); } 87.5% { transform: rotate(945deg); } to { transform: rotate(1080deg); } } @keyframes spinner-left-spin { 0% { transform: rotate(130deg); } 50% { transform: rotate(-5deg); } to { transform: rotate(130deg); } } @keyframes right-spin { 0% { transform: rotate(-130deg); } 50% { transform: rotate(5deg); } to { transform: rotate(-130deg); } }
19.72335
183
0.630163
ef58696ea541a97f0fc88af8737659d8734206b7
1,975
go
Go
protocol/lz4stream.go
Blueprint-Marketing/syncthing
668b429615ad58cb74dc983834eaa0d1240a868a
[ "MIT" ]
null
null
null
protocol/lz4stream.go
Blueprint-Marketing/syncthing
668b429615ad58cb74dc983834eaa0d1240a868a
[ "MIT" ]
null
null
null
protocol/lz4stream.go
Blueprint-Marketing/syncthing
668b429615ad58cb74dc983834eaa0d1240a868a
[ "MIT" ]
1
2018-12-06T03:46:09.000Z
2018-12-06T03:46:09.000Z
package protocol import ( "bytes" "encoding/binary" "errors" "io" "sync" lz4 "github.com/bkaradzic/go-lz4" ) const lz4Magic = 0x5e63b278 type lz4Writer struct { wr io.Writer mut sync.Mutex buf []byte } func newLZ4Writer(w io.Writer) *lz4Writer { return &lz4Writer{wr: w} } func (w *lz4Writer) Write(bs []byte) (int, error) { w.mut.Lock() defer w.mut.Unlock() var err error w.buf, err = lz4.Encode(w.buf[:cap(w.buf)], bs) if err != nil { return 0, err } var hdr [8]byte binary.BigEndian.PutUint32(hdr[0:], lz4Magic) binary.BigEndian.PutUint32(hdr[4:], uint32(len(w.buf))) _, err = w.wr.Write(hdr[:]) if err != nil { return 0, err } _, err = w.wr.Write(w.buf) if err != nil { return 0, err } if debug { l.Debugf("lz4 write; %d / %d bytes", len(bs), 8+len(w.buf)) } return len(bs), nil } type lz4Reader struct { rd io.Reader mut sync.Mutex buf []byte ebuf []byte obuf *bytes.Buffer ibytes uint64 obytes uint64 } func newLZ4Reader(r io.Reader) *lz4Reader { return &lz4Reader{rd: r} } func (r *lz4Reader) Read(bs []byte) (int, error) { r.mut.Lock() defer r.mut.Unlock() if r.obuf == nil { r.obuf = bytes.NewBuffer(nil) } if r.obuf.Len() == 0 { if err := r.moreBits(); err != nil { return 0, err } } n, err := r.obuf.Read(bs) if debug { l.Debugf("lz4 read; %d bytes", n) } return n, err } func (r *lz4Reader) moreBits() error { var hdr [8]byte _, err := io.ReadFull(r.rd, hdr[:]) if binary.BigEndian.Uint32(hdr[0:]) != lz4Magic { return errors.New("bad magic") } ln := int(binary.BigEndian.Uint32(hdr[4:])) if len(r.buf) < ln { r.buf = make([]byte, int(ln)) } else { r.buf = r.buf[:ln] } _, err = io.ReadFull(r.rd, r.buf) if err != nil { return err } r.ebuf, err = lz4.Decode(r.ebuf[:cap(r.ebuf)], r.buf) if err != nil { return err } if debug { l.Debugf("lz4 moreBits: %d / %d bytes", ln+8, len(r.ebuf)) } _, err = r.obuf.Write(r.ebuf) return err }
16.458333
61
0.608608
0726b6125a543a0f4c694d98cd6b31b082ee5646
4,421
css
CSS
css/fail.css
JAIDEV123/Website
951bf8f3163c4664b9272554c19638f95bf21ea8
[ "MIT" ]
4
2018-08-25T09:03:56.000Z
2021-06-06T07:41:30.000Z
css/fail.css
JAIDEV123/Website
951bf8f3163c4664b9272554c19638f95bf21ea8
[ "MIT" ]
16
2018-08-25T13:28:35.000Z
2019-05-10T16:03:38.000Z
css/fail.css
JAIDEV123/Website
951bf8f3163c4664b9272554c19638f95bf21ea8
[ "MIT" ]
9
2018-08-25T05:44:42.000Z
2020-09-30T18:08:12.000Z
/* BEGIN CUSTOM DECLARATIONS */ @font-face { font-family: "Bebas Neue"; src: url("../assets/fonts/BebasNeueRegular.ttf"); } @font-face { font-family: "Norwester"; src: url("../assets/fonts/norwester.tff"), url("../fonts/norwester.eot"); } /* @import url('https://fonts.googleapis.com/css?family=Raleway:400,500'); */ @font-face { font-family: "Raleway"; src: url("../assets/fonts/raleway/Raleway-Medium.ttf"), url("../assets/fonts/raleway/Raleway-Regular.ttf"); } .bebas { font-family: 'Bebas Neue'; font-weight: lighter; } /* .raleway { font-family: 'Raleway'; } */ .norwester { font-family: 'Norwester'; } .verdana { font-family: Verdana, Geneva, Tahoma, sans-serif; } /* END CUSTOM DECLARATIONS */ a{ text-decoration: none; } html { scroll-behavior: smooth; font-size: 2vh; } /* #back-vid { height: 100vh; width:100%; overflow: hidden; } */ #landing { /* background: url('../assets/back/fail_back.gif'); */ background: url('../assets/back/fback.png'); background-size: contain; background-repeat: no-repeat; background-position: center; height: 100vh; width:100%; overflow: hidden; overflow: hidden; } .active { background-color: #ef2028; color: #1b1b1d; } .wrapper { display: flex; width:100%; align-items: stretch; } #sidebar { width: 25vw; position: fixed; top: 0; left: 0; min-height: 100vh; z-index: 999; background: #1b1b1d; color: #1b1b1d; transition: all 0.3s; } #sidebar.active{ margin-left:-25vw; } #sidebar .sidebar-header { padding: 20px; background: #1b1b1d; color: #ef2028; } #sidebar ul.components { padding: 20px 0px; /* border-bottom: 1px solid #; */ } #sidebar ul p { color: #ef2028; padding: 10px; } #sidebar ul li a { padding: 10px; font-size: 1.1em; display: block; } #sidebar ul li a:hover { color: #ef2028; background: #1b1b1d; } #sidebar ul li.active > a, a[aria-expanded="true"] { color: #1b1b1d; background: #ef2028; } #content { margin-left: 25vw; transition: all 0.3s; } ul ul a { font-size: 0.9em !important; padding-left: 30px !important; background: #1b1b1d; } a[data-toggle="collapse"] { position: relative; } .dropdown-toggle::after { display: block; position: absolute; top: 50%; right: 20px; transform: translateY(-50%); } #sidebar.active + #navbar + #content{ margin-left: 10vw; margin-right: 10vw; } #sidebar.active + #navbar{ margin-left: 0vw; } #navbar { /* height:10vh; margin-left: 25vw; */ position: fixed; transition: all 0.3s; z-index: 100; } .row.speaker { justify-content: center; align-items: center; } .row.speaker > div:first-child { text-align: center; } @media (max-width:768px) { .container-fluid { padding-left: 0; padding-right: 0; } html { font-size: 1rem; } #sidebar { width: 75vw; position: fixed; top: 0; left: 0; min-height: 100vh; z-index: 999; background: #1b1b1d; color: #ef2028; transition: all 0.3s; } #sidebar.active { margin-left: -75vw; } #sidebar.active + #navbar + #content { margin-left: 10vw; } #sidebar.active + #navbar{ margin-left: 0vw; } #navbar { margin-left: 75vw; z-index: 100; } } @media (max-width:768px) and (orientation: portrait) { html { font-size: 0.8rem; } } .section{ min-height: 100vh; display: flex; align-items: center; } @media (min-width:769px){ .section.container-fluid { padding-left: 3rem; padding-right: 3rem; } } body { font-family: 'Raleway'; } h1 { font-size: 8vh; color:#ef2028; padding: 4px; font-family: 'Bebas Neue'; } h2 { font-size: 4vh; color: #ef2028; } h3 { font-size: 2vh; color: #ef2028; padding: 4px; } .btn { background: #1b1b1d; color: #ef2028; } .speaker-image{ width: 100%; height: auto; position: center; } .collapse.list-unstyled { font-size: 0.9rem; } .container-fluid { min-height: 100vh; } #helper { width: 100%; background-color: white; position: absolute; bottom: 0; left: 0; text-align: center; }
16.253676
77
0.577245
1a9d4e12e1c16fc7494016bea0f92767f03c7d9b
3,504
py
Python
facebook_scraper.py
vaibhav-karnwal/facebook-scraping
e591a2fa525655e8398cc1d17240796b7f3e8c37
[ "MIT" ]
2
2020-12-21T22:48:33.000Z
2021-04-06T04:37:07.000Z
facebook_scraper.py
vaibhav-karnwal/facebook-scraping
e591a2fa525655e8398cc1d17240796b7f3e8c37
[ "MIT" ]
null
null
null
facebook_scraper.py
vaibhav-karnwal/facebook-scraping
e591a2fa525655e8398cc1d17240796b7f3e8c37
[ "MIT" ]
1
2022-01-08T11:02:34.000Z
2022-01-08T11:02:34.000Z
import argparse import time import json import csv import re import pandas as pd from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup from requests_html import HTMLSession, HTML from lxml.etree import ParserError from credential import username, password, email #list of elements to scrape post_links=[] post_ids=[] shares=[] dates=[] times=[] likes=[] comments=[] texts=[] #function to scroll from 0 position to end position def scroll_to_bottom(driver): old_position = 0 new_position = None while new_position != old_position: time.sleep(.5) # Get old scroll position old_position = driver.execute_script( ("return (window.pageYOffset !== undefined) ?" " window.pageYOffset : (document.documentElement ||" " document.body.parentNode || document.body);")) # Sleep and Scroll time.sleep(1) driver.execute_script(( "var scrollingElement = (document.scrollingElement ||" " document.body);scrollingElement.scrollTop =" " scrollingElement.scrollHeight;")) # Get new position new_position = driver.execute_script( ("return (window.pageYOffset !== undefined) ?" " window.pageYOffset : (document.documentElement ||" " document.body.parentNode || document.body);")) #calling chrome driver to login driver = webdriver.Chrome() driver.get(f"https://m.facebook.com/{username}/") driver.find_element_by_css_selector("a._4n43").click() time.sleep(2) driver.find_element_by_name("email").send_keys(email) driver.find_element_by_name("pass").send_keys(password) driver.find_element_by_name("login").click() time.sleep(1) scroll_to_bottom(driver) page_source = driver.page_source #scraping html page data soup = BeautifulSoup(page_source, 'lxml') section=soup.findAll('div',{'class':'_3drp'}) for a in section: #for scraping post link and id link=a.find('a',attrs={'class':'_5msj'}) post_link=link['href'] part = post_link.split('&')[0] post_id=part.split('=')[1] post_links.append(post_link) post_ids.append(post_id) #for scraping date and time of post post_date=a.find('abbr') post_data=post_date.get_text(strip=True).split('at') date=post_data[0] time=post_data[1] dates.append(date) times.append(time) #for scraping like of post like=a.find('div', attrs={'class':'_1g06'}) if(len(like) == 0): like ="0 likes" likes.append(like.get_text(strip=True)) #for scraping text of post text=a.find('div',{'class':'_5rgt _5nk5 _5msi'}) post_text=text.find('span') if(len(post_text)==0): post_text =" " texts.append(post_text.get_text(strip=True)) #for scraping comment and share of post comm_shar=a.findAll('span', attrs={'class':'_1j-c'}) comments.append(comm_shar[0].get_text(strip=True)) shares.append(comm_shar[1].get_text(strip=True)) #Appending all the list data to a pd dataframe df = pd.DataFrame({'dates':dates,'Time':times,'Post Links':post_links,'Post Ids':post_ids,'Text':texts,'like':likes,'Comment':comments ,'Shares':shares}) #converting pd raw data to csv file df.to_csv('facebook_scraped_post.csv', index=False, encoding='utf-16')
31.285714
154
0.649258
e0929a1f607b400412600c0013b817e484e6f5ce
2,309
c
C
apps/plugins/zxbox/interf.c
Rockbox-Chinese-Community/Rockbox-RCC
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
[ "BSD-3-Clause" ]
24
2015-03-10T08:43:56.000Z
2022-01-05T14:09:46.000Z
apps/plugins/zxbox/interf.c
Rockbox-Chinese-Community/Rockbox-RCC
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
[ "BSD-3-Clause" ]
4
2015-07-04T18:15:33.000Z
2018-05-18T05:33:33.000Z
apps/plugins/zxbox/interf.c
Rockbox-Chinese-Community/Rockbox-RCC
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
[ "BSD-3-Clause" ]
15
2015-01-21T13:58:13.000Z
2020-11-04T04:30:22.000Z
/* * Copyright (C) 1996-1998 Szeredi Miklos * Email: mszeredi@inf.bme.hu * * 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. See the file COPYING. * * 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 the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "zxconfig.h" #include "zxmisc.h" #include "interf.h" #include <stdio.h> #include <ctype.h> #define MAXMSGLEN 2048 char filenamebuf[MAXFILENAME]; char msgbuf[MAXMSGLEN]; char *spif_get_filename(void) { char *name=NULL; #if 0 /* should be implemented when adding ability */ /* to open snapshots from within zxbox */ char *name, *s; s = get_filename_line(); for(; *s && isspace((int) *s); s++); name = s; for(; *s && isgraph((int) *s); s++); *s = '\0'; if(name == s) { printf("Canceled!\n"); return NULL; } #endif return name; } char *spif_get_tape_fileinfo(int *startp, int *nump) { *startp=*nump=0; char *name=NULL; #if 0 /* should be implemented when adding ability */ /* to tapes snapshots from within zxbox */ char *name, *s; int res; s = get_filename_line(); for(; *s && isspace((int) *s); s++); name = s; for(; *s && isgraph((int) *s); s++); if(name != s) res = 1; else res = 0; if(*s) { *s = '\0'; s++; if(*s) { int r1; r1 = sscanf(s, "%d %d", startp, nump); if(r1 > 0) res += r1; } } if(res < 1) { printf("Canceled!\n"); return NULL; } if(res < 2) *startp = -1; if(res < 3) *nump = -1; #endif return name; } void put_msg(const char *msg) { #ifndef USE_GREY rb->splash (HZ/2, msg ); #else LOGF(msg); (void)msg; #endif } void put_tmp_msg(const char *msg) { #ifndef USE_GREY rb->splash (HZ/10, msg ); #else LOGF(msg); (void)msg; #endif }
19.735043
71
0.623647
391579e3a63bd450c8f0d522cff98b53313b897b
362
py
Python
Python/Algorithm/DateValidation.py
piovezan/SOpt
a5ec90796b7bdf98f0675457fc4bb99c8695bc40
[ "MIT" ]
148
2017-08-03T01:49:27.000Z
2022-03-26T10:39:30.000Z
Python/Algorithm/DateValidation.py
piovezan/SOpt
a5ec90796b7bdf98f0675457fc4bb99c8695bc40
[ "MIT" ]
3
2017-11-23T19:52:05.000Z
2020-04-01T00:44:40.000Z
Python/Algorithm/DateValidation.py
piovezan/SOpt
a5ec90796b7bdf98f0675457fc4bb99c8695bc40
[ "MIT" ]
59
2017-08-03T01:49:19.000Z
2022-03-31T23:24:38.000Z
from datetime import date def verificacaoData(): while True: dataForm = input('Digite a data atual no padrão dd/mm/aaaa: ') if date.today().strftime("%d/%m/%Y") != dataForm: print('Data informada difere da data atual.') else: print('Correto! Datas conferem!') break verificacaoData() #https://pt.stackoverflow.com/q/257108/101
24.133333
66
0.665746
81c332155a8500bdb596cee121342a49facf84b7
732
php
PHP
routes/web.php
Pablorth/voyage
106d15d1b61045e43633d2d316f5f1f4963cdbef
[ "MIT" ]
null
null
null
routes/web.php
Pablorth/voyage
106d15d1b61045e43633d2d316f5f1f4963cdbef
[ "MIT" ]
null
null
null
routes/web.php
Pablorth/voyage
106d15d1b61045e43633d2d316f5f1f4963cdbef
[ "MIT" ]
null
null
null
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // --acceuil Route::get('/', 'StaticController@index'); Route::get('/trips', 'StaticController@trips'); Route::get('/trip', 'StaticController@trip'); Route::get('/aboutus', function () { return view('about.aboutus'); }); Route::get('/contact', function () { return view('about.contact'); });
26.142857
75
0.54918
df6945259905b3750dfde3fd5eed6e8bbc33cf9c
162
cs
C#
TemporalTwist/Interfaces/IJobProcessor.cs
blacktau/temporaltwist
eabf1cd82d4714082e995133cb4072d86fafeee7
[ "BSD-3-Clause" ]
null
null
null
TemporalTwist/Interfaces/IJobProcessor.cs
blacktau/temporaltwist
eabf1cd82d4714082e995133cb4072d86fafeee7
[ "BSD-3-Clause" ]
null
null
null
TemporalTwist/Interfaces/IJobProcessor.cs
blacktau/temporaltwist
eabf1cd82d4714082e995133cb4072d86fafeee7
[ "BSD-3-Clause" ]
null
null
null
namespace TemporalTwist.Interfaces { using System; public interface IJobProcessor { void Cancel(); void RunAsync(IJob job); } }
14.727273
35
0.617284
fb040afa79906cc8ca3b59bf280b590cdb6591e8
1,769
h
C
Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NavigationHistory.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NavigationHistory.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NavigationHistory.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #if !defined(Q_MOC_RUN) #include <MCore/Source/StandardHeaders.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/StandardPluginsConfig.h> #include <QObject> #endif namespace EMStudio { class AnimGraphModel; // Handles history of the graph's navigation (back and forward) // The history affects the focus, every time focus changes, the new focus is added // to the history. Going back changes back the focus to the previous focus in the // history. // class NavigationHistory : public QObject { Q_OBJECT public: NavigationHistory(AnimGraphModel& animGrahModel); ~NavigationHistory(); bool CanStepBackward() const; bool CanStepForward() const; void StepBackward(); void StepForward(); signals: void ChangedSteppingLimits(); private slots: void OnFocusChanged(const QModelIndex& newFocusIndex, const QModelIndex& newFocusParent, const QModelIndex& oldFocusIndex, const QModelIndex& oldFocusParent); void OnRowsRemoved(const QModelIndex &parent, int first, int last); private: AnimGraphModel& m_animGraphModel; AZStd::vector<QPersistentModelIndex> m_navigationHistory; int m_navigationIndex; // Indicates if the focus was changed by stepping through history. // This is used to avoid processing the OnFocusChanged callback bool m_localStepping; static const size_t s_maxHistoryEntries = 256; }; } // namespace EMStudio
29.483333
166
0.701526
4374247bdf8181082864d1bff503ded21316496c
435
ts
TypeScript
projects/ng-material-multilevel-menu/src/lib/materials.module.ts
alexIslander/ng-material-multilevel-menu
d97d43b2ddfb1f11c304977b154d1625194243a4
[ "MIT" ]
98
2018-08-05T15:51:44.000Z
2021-12-07T08:02:44.000Z
projects/ng-material-multilevel-menu/src/lib/materials.module.ts
alexIslander/ng-material-multilevel-menu
d97d43b2ddfb1f11c304977b154d1625194243a4
[ "MIT" ]
140
2018-06-20T02:47:49.000Z
2022-03-24T07:17:42.000Z
projects/ng-material-multilevel-menu/src/lib/materials.module.ts
alexIslander/ng-material-multilevel-menu
d97d43b2ddfb1f11c304977b154d1625194243a4
[ "MIT" ]
63
2018-08-29T22:03:50.000Z
2021-12-21T07:53:44.000Z
import { NgModule } from '@angular/core'; import { MatRippleModule } from '@angular/material/core'; import { MatIconModule } from '@angular/material/icon'; import { MatListModule } from '@angular/material/list'; @NgModule({ imports: [ MatIconModule, MatListModule, MatRippleModule, ], declarations: [], exports: [ MatIconModule, MatListModule, MatRippleModule, ] }) export class MaterialsModule { }
20.714286
57
0.687356
da699e26b12052eaf2c879bf75bdbaad610a4616
1,314
swift
Swift
Sources/Core/Config/Environment.swift
OmnijarStudio/naamio
d8572f543c8454ea22f21552a203e3b63bd22938
[ "MIT" ]
null
null
null
Sources/Core/Config/Environment.swift
OmnijarStudio/naamio
d8572f543c8454ea22f21552a203e3b63bd22938
[ "MIT" ]
11
2016-09-17T12:26:11.000Z
2016-09-18T10:17:31.000Z
Sources/Core/Config/Environment.swift
OmnijarStudio/naamio
d8572f543c8454ea22f21552a203e3b63bd22938
[ "MIT" ]
null
null
null
import Foundation /// Gets the environment variable by name. public func getEnvironmentVar(_ name: String) -> String? { guard let rawValue = getenv(name) else { return nil } return String(utf8String: rawValue) } /// Sets or overrides the environment variable, specified by name. /// - Parameters: /// public func setEnvironmentVar(name: String, value: String, overwrite: Bool = true) { setenv(name, value, overwrite ? 1 : 0) } public class Environment { public static func readArgs() { let runModeEnv = getEnvironmentVar("NAAMIO_ENV") ?? "development" let portEnv = getEnvironmentVar("NAAMIO_PORT") ?? "8090" guard case Configuration.settings.mode = RunMode(rawValue: runModeEnv) else { Log.error("Run mode '\(runModeEnv)' not valid") return } Configuration.settings.logs = getEnvironmentVar("NAAMIO_LOGS") ?? "/var/log/naamio.log" Configuration.settings.web.templates = getEnvironmentVar("NAAMIO_TEMPLATES") ?? "_templates/leaf/" Configuration.settings.web.source = getEnvironmentVar("NAAMIO_SOURCE") ?? "public" guard case Configuration.settings.web.port = Int(portEnv) else { Log.error("Port number '\(portEnv)' not valid") return } } }
33.692308
106
0.653729
a928207ac985e6b66d37fd41b73e945535858f72
576
css
CSS
index.css
jratana1/bob-rpg
60ad04edf78653c55ea273bb491ba51e3a61cd93
[ "MIT" ]
null
null
null
index.css
jratana1/bob-rpg
60ad04edf78653c55ea273bb491ba51e3a61cd93
[ "MIT" ]
null
null
null
index.css
jratana1/bob-rpg
60ad04edf78653c55ea273bb491ba51e3a61cd93
[ "MIT" ]
null
null
null
.overlay { position: absolute; z-index: 1000; color: blue; background: rgba(189, 179, 179, 0.863); padding: 30px; visibility: hidden; width: 40rem; height: 3rem; top: 30rem; display: flex; left: 0; right: 0; margin-left: auto; margin-right: auto; border-radius: 25px } #game-containter{ position: relative; display: flex; justify-content: center; align-items: center; } canvas { padding-left: 0; padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
16.941176
43
0.590278
bc681f5ae31045f2388e6e172a7272c38fbd1b58
5,513
dart
Dart
lib/screens/event/event_log.dart
kzawadi/arrive
01a9393890059a0d245ce8f2e57d217c4c3bb2d1
[ "BSD-3-Clause" ]
null
null
null
lib/screens/event/event_log.dart
kzawadi/arrive
01a9393890059a0d245ce8f2e57d217c4c3bb2d1
[ "BSD-3-Clause" ]
null
null
null
lib/screens/event/event_log.dart
kzawadi/arrive
01a9393890059a0d245ce8f2e57d217c4c3bb2d1
[ "BSD-3-Clause" ]
null
null
null
import 'package:at_events_flutter/common_components/bottom_sheet.dart'; import 'package:at_events_flutter/models/event_notification.dart'; import 'package:at_events_flutter/screens/map_screen/events_collapsed_content.dart'; import 'package:at_events_flutter/services/event_key_stream_service.dart'; import 'package:at_events_flutter/services/home_event_service.dart'; import 'package:atsign_location_app/common_components/custom_appbar.dart'; import 'package:atsign_location_app/common_components/display_tile.dart'; import 'package:atsign_location_app/common_components/pop_button.dart'; import 'package:atsign_location_app/services/nav_service.dart'; import 'package:atsign_location_app/utils/constants/colors.dart'; import 'package:atsign_location_app/utils/constants/text_strings.dart'; import 'package:atsign_location_app/view_models/location_provider.dart'; import 'package:flutter/material.dart'; import 'package:at_common_flutter/services/size_config.dart'; import 'package:provider/provider.dart'; class EventLog extends StatefulWidget { @override _EventLogState createState() => _EventLogState(); } class _EventLogState extends State<EventLog> with SingleTickerProviderStateMixin { TabController _controller; @override void initState() { _controller = _controller = TabController(length: 2, vsync: this, initialIndex: 0); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: CustomAppBar( centerTitle: true, padding: true, title: TextStrings.events, action: PopButton(label: TextStrings.close), ), body: SafeArea( child: SingleChildScrollView( child: Container( height: SizeConfig().screenHeight - (80.toHeight), child: Column( children: <Widget>[ Container( height: 40, child: TabBar( indicatorColor: Theme.of(context).primaryColor, indicatorWeight: 3.toHeight, labelColor: Theme.of(context).primaryColor, unselectedLabelColor: AllColors().DARK_GREY, controller: _controller, tabs: [ Tab( child: Text( TextStrings.upcoming, style: TextStyle(fontSize: 16.toFont, letterSpacing: 1), ), ), Tab( child: Text(TextStrings.past, style: TextStyle( fontSize: 16.toFont, letterSpacing: 1)), ) ], ), ), Expanded( child: TabBarView( controller: _controller, children: [getUpcomingEvents(), getPastEvents()], )), ], ), ), ), ), ); } } Widget getUpcomingEvents() { var upcomingEvents = Provider.of<LocationProvider>( NavService.navKey.currentContext, listen: false) .allEventNotifications; return ListView.separated( scrollDirection: Axis.vertical, itemCount: upcomingEvents.length, separatorBuilder: (context, index) { return Divider(); }, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.only(right: 10.0, left: 10, top: 10), child: InkWell( onTap: () { HomeEventService().onEventModelTap( upcomingEvents[index].eventNotificationModel, upcomingEvents[index].haveResponded); }, child: DisplayTile( title: upcomingEvents[index].eventNotificationModel.title, atsignCreator: upcomingEvents[index].eventNotificationModel.atsignCreator, subTitle: '${TextStrings.eventOn} ${dateToString(upcomingEvents[index].eventNotificationModel.event.date)}', invitedBy: '${TextStrings.invitedBy} ${upcomingEvents[index].eventNotificationModel.atsignCreator}', ), ), ); }, ); } Widget getPastEvents() { var pastEvents = EventKeyStreamService() .allPastEventNotifications .map((e) => e.eventNotificationModel) .toList(); return ListView.separated( scrollDirection: Axis.vertical, itemCount: pastEvents.length, separatorBuilder: (context, index) { return Divider(); }, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.only(right: 10.0, left: 10, top: 10), child: InkWell( onTap: () { bottomSheet( context, EventsCollapsedContent( pastEvents[index], key: UniqueKey(), isStatic: true, ), 300, onSheetCLosed: () {}, ); }, child: DisplayTile( title: pastEvents[index].title, atsignCreator: pastEvents[index].atsignCreator, subTitle: '${TextStrings.eventOn} ${dateToString(pastEvents[index].event.date)}', invitedBy: '${TextStrings.invitedBy} ${pastEvents[index].atsignCreator}', ), ), ); }, ); }
34.242236
114
0.582623
3b1a1b9b9e110b91051c4254157d1ae04562e1e3
6,026
dart
Dart
lib/main.dart
GreenAppers/cruzweb
37ce55ff3b3faa9ef674607b21e49ab087cdf1a8
[ "MIT" ]
2
2019-08-09T07:33:17.000Z
2020-02-13T16:02:43.000Z
lib/main.dart
GreenAppers/cruzweb
37ce55ff3b3faa9ef674607b21e49ab087cdf1a8
[ "MIT" ]
null
null
null
lib/main.dart
GreenAppers/cruzweb
37ce55ff3b3faa9ef674607b21e49ab087cdf1a8
[ "MIT" ]
null
null
null
// Copyright 2019 cruzweb developers // Use of this source code is governed by a MIT-style license that can be found in the LICENSE file. import 'dart:html'; import 'package:flutter/material.dart'; import 'package:clippy/browser.dart' as clippy; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:intl/intl.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:sembast/sembast_memory.dart'; import 'package:cruzawl/currency.dart'; import 'package:cruzawl/http.dart'; import 'package:cruzawl/network.dart'; import 'package:cruzawl/preferences.dart'; import 'package:cruzawl/util.dart'; import 'package:cruzawl/wallet.dart'; import 'package:cruzawl_ui/explorer/cruzbase.dart'; import 'package:cruzawl_ui/localization.dart'; import 'package:cruzawl_ui/model.dart'; import 'package:cruzawl_ui/routes.dart'; import 'package:cruzawl_ui/ui.dart'; class CruzWebLoading extends StatelessWidget { final PeerNetwork network; CruzWebLoading(this.network); @override Widget build(BuildContext context) { final Cruzawl appState = ScopedModel.of<Cruzawl>(context, rebuildOnChange: true); if (network.peerState != PeerState.disconnected) { return SimpleScaffold(Center(child: CircularProgressIndicator()), title: "Loading..."); } else { String url = 'https' + network.peerAddress.substring(3); return SimpleScaffold( Container( padding: EdgeInsets.all(32), child: Column( children: <Widget>[ Text('If this is a new browser session, visit:', style: appState.theme.labelStyle), GestureDetector( child: Text(url, style: appState.theme.linkStyle), onTap: () => window.open(url, url), ), Text('Accept the certificate and refresh the page.', style: appState.theme.labelStyle), ], ), ), title: 'Error'); } } } class CruzWebApp extends StatelessWidget { final Cruzawl appState; CruzWebApp(this.appState); @override Widget build(BuildContext context) { final double maxWidth = 700; final AppTheme theme = themes[appState.preferences.theme] ?? themes['teal']; return ScopedModel<SimpleScaffoldActions>( model: SimpleScaffoldActions(<Widget>[ (PopupMenuBuilder() ..addItem( icon: Icons.settings, text: 'Settings', onSelected: () => window.location.hash = '/settings', ) ..addItem( icon: Icons.vpn_lock, text: 'Network', onSelected: () => window.location.hash = '/network', ) /*..addItem( icon: Icons.settings_input_svideo, text: 'Console', onSelected: () => window.location.hash = '/console', )*/ ..addItem( icon: Icons.redeem, text: 'Donations', onSelected: () => window.location.hash = '/address/RWEgB+NQs/T83EkmIFNVJG+xK64Hm90GmQgrdR2V7BI=', )) .build( icon: Icon(Icons.more_vert), ), ], searchBar: true), child: MaterialApp( theme: theme.data, debugShowCheckedModeBanner: false, locale: appState.localeOverride, localizationsDelegates: [ LocalizationDelegate(title: 'cruzbase'), GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate ], supportedLocales: Localization.supportedLocales, onGenerateTitle: (BuildContext context) => Localization.of(context).title, onGenerateRoute: CruzawlRoutes( appState, maxWidth: maxWidth, loadingWidget: CruzWebLoading(appState.network), defaultRoute: MaterialPageRoute( builder: (BuildContext context) => ScopedModelDescendant<WalletModel>( builder: (context, child, model) => CruzbaseWidget( appState.network, wideStyle: useWideStyle(context, maxWidth)), ), ), ).onGenerateRoute, ), ); } } String assetPath(String asset) => asset; void setClipboardText(BuildContext context, String text) async => await clippy.write(text); Future<String> getClipboardText() async => 'unused'; void launchUrl(BuildContext context, String url) => window.open(url, url); void main() async { debugPrint('Main ' + Uri.base.toString()); Cruzawl appState = Cruzawl( assetPath, launchUrl, setClipboardText, getClipboardText, databaseFactoryMemoryFs, CruzawlPreferences( await databaseFactoryMemoryFs.openDatabase('settings.db'), () => NumberFormat.currency().currencyName), '/', NullFileSystem(), httpClient: HttpClientImpl(), packageInfo: PackageInfo('CruzWeb', 'com.greenappers.cruzweb', '1.1.1', '21')); Currency currency = Currency.fromJson('CRUZ'); appState.addWallet( Wallet.fromPublicKeyList( databaseFactoryMemoryFs, appState.fileSystem, 'empty.cruzall', 'Empty wallet', findPeerNetworkForCurrency(appState.networks, currency), Seed(randBytes(64)), <PublicAddress>[currency.nullAddress], appState.preferences, debugPrint, appState.openedWallet), store: false); appState.network.autoReconnectSeconds = null; appState.connectPeers(currency); runApp( ScopedModel<Cruzawl>( model: appState, child: ScopedModel<WalletModel>( model: appState.wallet, child: ScopedModelDescendant<Cruzawl>( builder: (context, child, model) => CruzWebApp(appState)), ), ), ); }
32.572973
100
0.615334
731ff060d1a1b37307743e75f20a1d05a6722c91
7,698
lua
Lua
libraries/AceSerializer-3.0/AceSerializer-3.0.lua
delirius325/SpeedyMount-BCC
60b402d6f61320424fa50579c2207591cc64ee64
[ "MIT" ]
1
2021-07-17T14:46:19.000Z
2021-07-17T14:46:19.000Z
libraries/AceSerializer-3.0/AceSerializer-3.0.lua
delirius325/SpeedyMount-BCC
60b402d6f61320424fa50579c2207591cc64ee64
[ "MIT" ]
2
2021-11-01T04:31:20.000Z
2021-11-01T04:31:53.000Z
libraries/AceSerializer-3.0/AceSerializer-3.0.lua
delirius325/SpeedyMount-BCC
60b402d6f61320424fa50579c2207591cc64ee64
[ "MIT" ]
null
null
null
--[[ $Id: AceSerializer-3.0.lua 494 2008-02-03 13:03:56Z nevcairiel $ ]] local MAJOR,MINOR = "AceSerializer-3.0", 2 local AceSerializer, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceSerializer then return end local strbyte = string.byte local strchar = string.char local tconcat = table.concat local gsub = string.gsub local gmatch = string.gmatch local pcall = pcall local format = string.format local type = type local tostring, tonumber = tostring, tonumber local select = select -- quick copies of string representations of wonky numbers local serNaN = tostring(0/0) local serInf = tostring(1/0) local serNegInf = tostring(-1/0) ----------------------------------------------------------------------- -- Serialization functions local function SerializeStringHelper(ch) -- Used by SerializeValue for strings -- We use \126 ("~") as an escape character for all nonprints plus a few more local n = strbyte(ch) if n<=32 then -- nonprint + space return "\126"..strchar(n+64) elseif n==94 then -- value separator return "\126\125" elseif n==126 then -- our own escape character return "\126\124" elseif n==127 then -- nonprint (DEL) return "\126\123" else assert(false) -- can't be reached if caller uses a sane regex end end local function SerializeValue(v, res, nres) -- We use "^" as a value separator, followed by one byte for type indicator local t=type(v) if t=="string" then -- ^S = string (escaped to remove nonprints, "^"s, etc) res[nres+1] = "^S" res[nres+2] = gsub(v,"[%c \94\126\127]", SerializeStringHelper) nres=nres+2 elseif t=="number" then -- ^N = number (just tostring()ed) or ^F (float components) local str = tostring(v) if tonumber(str)==v or str==serNaN or str==serInf or str==serNegInf then -- translates just fine, transmit as-is res[nres+1] = "^N" res[nres+2] = str nres=nres+2 else local m,e = frexp(v) res[nres+1] = "^F" res[nres+2] = format("%.0f",m*2^53) -- force mantissa to become integer (it's originally 0.5--0.9999) res[nres+3] = "^f" res[nres+4] = tostring(e-53) -- adjust exponent to counteract mantissa manipulation nres=nres+4 end elseif t=="table" then -- ^T...^t = table (list of key,value pairs) nres=nres+1 res[nres] = "^T" for k,v in pairs(v) do nres = SerializeValue(k, res, nres) nres = SerializeValue(v, res, nres) end nres=nres+1 res[nres] = "^t" elseif t=="boolean" then -- ^B = true, ^b = false nres=nres+1 if v then res[nres] = "^B" -- true else res[nres] = "^b" -- false end elseif t=="nil" then -- ^Z = nil (zero, "N" was taken :P) nres=nres+1 res[nres] = "^Z" else error(MAJOR..": Cannot serialize a value of type '"..t.."'") -- can't produce error on right level, this is wildly recursive end return nres end ----------------------------------------------------------------------- -- API Serialize(...) -- -- Takes a list of values (strings, numbers, booleans, nils, tables) -- and returns it in serialized form (a string). -- May throw errors on invalid data types. -- local serializeTbl = { "^1" } -- "^1" = Hi, I'm data serialized by AceSerializer protocol rev 1 function AceSerializer:Serialize(...) local nres = 1 for i=1,select("#", ...) do local v = select(i, ...) nres = SerializeValue(v, serializeTbl, nres) end serializeTbl[nres+1] = "^^" -- "^^" = End of serialized data return tconcat(serializeTbl, "", 1, nres+1) end ----------------------------------------------------------------------- -- Deserialization functions local function DeserializeStringHelper(escape) if escape<"~\123" then return strchar(strbyte(escape,2,2)-64) elseif escape=="~\123" then return "\127" elseif escape=="~\124" then return "\126" elseif escape=="~\125" then return "\94" end error("DeserializeStringHelper got called for '"..escape.."'?!?") -- can't be reached unless regex is screwed up end local function DeserializeNumberHelper(number) if number == serNaN then return 0/0 elseif number == serNegInf then return -1/0 elseif number == serInf then return 1/0 else return tonumber(number) end end -- DeserializeValue: worker function for :Deserialize() -- It works in two modes: -- Main (top-level) mode: Deserialize a list of values and return them all -- Recursive (table) mode: Deserialize only a single value (_may_ of course be another table with lots of subvalues in it) -- -- The function _always_ works recursively due to having to build a list of values to return -- -- Callers are expected to pcall(DeserializeValue) to trap errors local function DeserializeValue(iter,single,ctl,data) if not single then ctl,data = iter() end if not ctl then error("Supplied data misses AceSerializer terminator ('^^')") end if ctl=="^^" then -- ignore extraneous data return end local res if ctl=="^S" then res = gsub(data, "~.", DeserializeStringHelper) elseif ctl=="^N" then res = DeserializeNumberHelper(data) if not res then error("Invalid serialized number: '"..tostring(data).."'") end elseif ctl=="^F" then -- ^F<mantissa>^f<exponent> local ctl2,e = iter() if ctl2~="^f" then error("Invalid serialized floating-point number, expected '^f', not '"..tostring(ctl2).."'") end local m=tonumber(data) e=tonumber(e) if not (m and e) then error("Invalid serialized floating-point number, expected mantissa and exponent, got '"..tostring(m).."' and '"..tostring(e).."'") end res = m*(2^e) elseif ctl=="^B" then -- yeah yeah ignore data portion res = true elseif ctl=="^b" then -- yeah yeah ignore data portion res = false elseif ctl=="^Z" then -- yeah yeah ignore data portion res = nil elseif ctl=="^T" then -- ignore ^T's data, future extensibility? res = {} local k,v while true do ctl,data = iter() if ctl=="^t" then break end -- ignore ^t's data k = DeserializeValue(iter,true,ctl,data) if k==nil then error("Invalid AceSerializer table format (no table end marker)") end ctl,data = iter() v = DeserializeValue(iter,true,ctl,data) if v==nil then error("Invalid AceSerializer table format (no table end marker)") end res[k]=v end else error("Invalid AceSerializer control code '"..ctl.."'") end if not single then return res,DeserializeValue(iter) else return res end end ----------------------------------------------------------------------- -- API Deserialize(str) -- -- Accepts serialized data, ignoring all control characters and whitespace. -- -- Returns true followed by a list of values, OR false followed by a message -- function AceSerializer:Deserialize(str) str = gsub(str, "[%c ]", "") -- ignore all control characters; nice for embedding in email and stuff local iter = gmatch(str, "(^.)([^^]*)") -- Any ^x followed by string of non-^ local ctl,data = iter() if not ctl or ctl~="^1" then -- we purposefully ignore the data portion of the start code, it can be used as an extension mechanism return false, "Supplied data is not AceSerializer data (rev 1)" end return pcall(DeserializeValue, iter) end ---------------------------------------- -- Base library stuff ---------------------------------------- AceSerializer.internals = { -- for test scripts SerializeValue = SerializeValue, SerializeStringHelper = SerializeStringHelper, } local mixins = { "Serialize", "Deserialize", } AceSerializer.embeds = AceSerializer.embeds or {} function AceSerializer:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end -- Update embeds for target, v in pairs(AceSerializer.embeds) do AceSerializer:Embed(target) end
27.492857
133
0.647961
cdbd3516407b9c9bfb09ff0dae2befeda76a07d2
9,722
cs
C#
Oracle.NoSQL.SDK/src/DataModel/DoubleValue.cs
oracle/nosql-dotnet-sdk
b28eec3c61bb4c4e1ffbc8740bedd4a5543c5430
[ "UPL-1.0", "MIT" ]
1
2022-03-03T09:08:10.000Z
2022-03-03T09:08:10.000Z
Oracle.NoSQL.SDK/src/DataModel/DoubleValue.cs
oracle/nosql-dotnet-sdk
b28eec3c61bb4c4e1ffbc8740bedd4a5543c5430
[ "UPL-1.0", "MIT" ]
3
2021-12-10T21:45:01.000Z
2022-03-17T02:13:25.000Z
Oracle.NoSQL.SDK/src/DataModel/DoubleValue.cs
oracle/nosql-dotnet-sdk
b28eec3c61bb4c4e1ffbc8740bedd4a5543c5430
[ "UPL-1.0", "MIT" ]
2
2022-02-18T01:23:36.000Z
2022-03-03T09:08:14.000Z
/*- * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl/ */ namespace Oracle.NoSQL.SDK { using System; using System.Globalization; using System.Text.Json; using static SizeOf; /// <summary> /// Represents a double precision floating point value. /// </summary> /// <remarks> /// <para> /// This class is used to represent values of NoSQL data types /// <em>Double</em> and <em>Float</em>. This value is represented /// by a C# type <c>double</c>. /// </para> /// <para> /// Note that when converted to JSON, instances of /// <see cref="DoubleValue"/> that contain special values such as /// <see cref = "Double.PositiveInfinity" />, /// <see cref = "Double.NegativeInfinity" /> and /// <see cref="Double.NaN"/> will be represented by strings "Infinity", /// "-Infinity" and "NaN" respectively and thus cannot be converted back /// from JSON to instances of <see cref="DoubleValue"/>. /// </para> /// </remarks> /// <seealso cref="FieldValue"/> public class DoubleValue : FieldValue { private double value; /// <summary> /// Initializes a new instance of the <see cref="DoubleValue"/> with /// the specified <c>double</c> value. /// </summary> /// <param name="value">The value which this instance will represent. /// </param> public DoubleValue(double value) { this.value = value; } /// <inheritdoc cref="FieldValue.DbType" path="summary"/> /// <value> /// <see cref="SDK.DbType.Double"/> /// </value> public override DbType DbType => DbType.Double; /// <summary> /// Gets the value of this instance as <c>double</c>. /// </summary> /// <value> /// The <c>double</c> value that this instance represents. /// </value> public override double AsDouble => value; /// <summary> /// Converts the value represented by this instance to a 32-bit signed /// integer. /// </summary> /// <remarks> /// This method performs the same conversion as /// <see cref="Convert.ToInt32(double)"/>. /// </remarks> /// <returns>The value rounded to the nearest 32-bit signed integer. /// </returns> /// <exception cref="OverflowException">If this /// instance represents value less than <see cref="Int32.MinValue"/> /// or greater than <see cref="Int32.MaxValue"/></exception> /// <seealso cref="Convert.ToInt32(double)"/> public override int ToInt32() => Convert.ToInt32(value); /// <summary> /// Converts the value represented by this instance to a 64-bit signed /// integer. /// </summary> /// <remarks> /// This method performs the same conversion as /// <see cref="Convert.ToInt64(double)"/>. /// </remarks> /// <returns>The value rounded to the nearest 64-bit signed integer. /// </returns> /// <exception cref="OverflowException">If this /// instance represents value less than <see cref="Int64.MinValue"/> /// or greater than <see cref="Int64.MaxValue"/></exception> /// <seealso cref="Convert.ToInt64(double)"/> public override long ToInt64() => Convert.ToInt64(value); /// <summary> /// Converts the value represented by this instance to a decimal /// number. /// </summary> /// <remarks> /// This method performs the same conversion as /// <see cref="Convert.ToDecimal(double)"/>. /// </remarks> /// <returns>A decimal number equivalent to the value represented by /// this instance.</returns> /// <exception cref="OverflowException">If this /// instance represents value less than <see cref="Decimal.MinValue"/> /// or greater than <see cref="Decimal.MaxValue"/></exception> /// <seealso cref="Convert.ToDecimal(double)"/> public override decimal ToDecimal() => Convert.ToDecimal(value); /// <inheritdoc/> public override void SerializeAsJson(Utf8JsonWriter writer, JsonOutputOptions options = null) { if (double.IsFinite(value)) { writer.WriteNumberValue(value); } else { writer.WriteStringValue(value.ToString( CultureInfo.InvariantCulture)); } } internal override bool IsNumeric => true; internal override int QueryCompare(FieldValue other, int nullRank) { switch (other.DbType) { case DbType.Double: case DbType.Integer: case DbType.Long: return AsDouble.CompareTo(other.ToDouble()); case DbType.Number: return -NumberValue.CompareDecimalDouble(other.AsDecimal, AsDouble); case DbType.Boolean: case DbType.String: case DbType.Timestamp: return -1; case DbType.Null: case DbType.JsonNull: case DbType.Empty: return -nullRank; default: throw ComparisonNotSupported(other); } } internal override bool QueryEquals(FieldValue other) { switch (other.DbType) { case DbType.Double: case DbType.Long: case DbType.Integer: return AsDouble.Equals(other.ToDouble()); case DbType.Number: return NumberValue.DecimalDoubleEquals(other.AsDecimal, AsDouble); default: return false; } } internal static int QueryHashCode(double value) { var longValue = unchecked((long)value); return value.Equals(longValue) ? LongValue.QueryHashCode(longValue) : value.GetHashCode(); } internal override int QueryHashCode() => QueryHashCode(value); internal override long GetMemorySize() => GetObjectSize(sizeof(double)); internal override FieldValue QueryAdd(FieldValue other) { switch (other.DbType) { case DbType.Long: case DbType.Integer: case DbType.Double: value += other.ToDouble(); return this; case DbType.Number: try { return new NumberValue( (decimal)value + other.AsDecimal); } catch (OverflowException) { goto case DbType.Double; } default: throw other.NonNumericOperand(AdditionOp); } } internal override FieldValue QuerySubtract(FieldValue other) { switch (other.DbType) { case DbType.Long: case DbType.Integer: case DbType.Double: value -= other.ToDouble(); return this; case DbType.Number: try { return new NumberValue( (decimal)value - other.AsDecimal); } catch (OverflowException) { goto case DbType.Double; } default: throw other.NonNumericOperand(SubtractionOp); } } internal override FieldValue QueryMultiply(FieldValue other) { switch (other.DbType) { case DbType.Long: case DbType.Integer: case DbType.Double: value *= other.ToDouble(); return this; case DbType.Number: try { return new NumberValue( (decimal)value * other.AsDecimal); } catch (OverflowException) { goto case DbType.Double; } default: throw other.NonNumericOperand(MultiplicationOp); } } internal override FieldValue QueryDivide(FieldValue other, bool isFloating) { switch (other.DbType) { case DbType.Long: case DbType.Integer: case DbType.Double: value /= other.ToDouble(); return this; case DbType.Number: try { return new NumberValue( (decimal)value / other.AsDecimal); } catch (OverflowException) { goto case DbType.Double; } default: throw other.NonNumericOperand(DivisionOp); } } } }
34.475177
78
0.495783
a3d16d9c15afde5a7f7c03c82a6dc0d4f84b72b7
376
java
Java
spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java
zeesh49/tutorials
a93f2ca39ab76ef4439e11ced78d1a6f1b3bf0b2
[ "MIT" ]
6
2019-01-15T03:43:54.000Z
2022-03-30T01:44:31.000Z
spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java
zeesh49/tutorials
a93f2ca39ab76ef4439e11ced78d1a6f1b3bf0b2
[ "MIT" ]
3
2021-01-21T01:26:55.000Z
2021-12-09T22:31:33.000Z
spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java
zeesh49/tutorials
a93f2ca39ab76ef4439e11ced78d1a6f1b3bf0b2
[ "MIT" ]
8
2018-11-12T13:49:40.000Z
2021-11-11T10:06:22.000Z
package org.baeldung.persistence.service; import org.baeldung.persistence.IOperations; import org.baeldung.persistence.model.Foo; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface IFooService extends IOperations<Foo> { Foo retrieveByName(String name); Page<Foo> findPaginated(Pageable pageable); }
25.066667
55
0.800532
c3dbd4a79079f5461a60b02b24431c1af221fd7c
1,250
cs
C#
EncodingNormalizer.UnitTest/ArgTest.cs
lindexi/EncodingNormalior
179089e58b0bc3edefb91755bb4c081bae8afbb5
[ "MIT" ]
39
2018-06-26T01:51:03.000Z
2022-03-10T07:02:53.000Z
EncodingNormalizer.UnitTest/ArgTest.cs
dotnet-campus/EncodingNormalior
179089e58b0bc3edefb91755bb4c081bae8afbb5
[ "MIT" ]
12
2018-06-15T09:03:16.000Z
2022-01-05T00:37:25.000Z
EncodingNormalizer.UnitTest/ArgTest.cs
lindexi/EncodingNormalior
179089e58b0bc3edefb91755bb4c081bae8afbb5
[ "MIT" ]
10
2018-04-17T07:01:12.000Z
2022-03-26T07:36:04.000Z
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EncodingNormalizer.UnitTest { [TestClass] public class ArgTest { [TestMethod] public void NoFolderArgTest() { //没有存在文件夹arg string[] arg = new[] { "-f", //"E:\\程序\\ethylene156\\EncodingNormalior" }; try { EncodingNormalior.Program.Main(arg); } catch (Exception e) { Assert.AreEqual(e.GetType(), typeof(ArgumentException)); Assert.AreEqual(e.Message, EncodingNormalior.Program.NoFolderArgException); } } [TestMethod] public void NotFoundFolderArgTest() { //没有存在文件夹 string[] arg = new[] { "-f", "E:\\不存在" }; try { EncodingNormalior.Program.Main(arg); } catch (Exception e) { Assert.AreEqual(e.GetType(), typeof(ArgumentException)); Assert.AreEqual(e.Message.Contains("不存在文件夹"), true); } } } }
24.509804
91
0.4536
03fc24efae991f3c8933fd4bd298cce2fc29f01c
2,269
swift
Swift
ImageMetalling-13/ImageMetalling-13/AppDelegate.swift
dnevera/ImageMetalling
d16b31f44a221dd37ca721a0ff8a84bbf2b04209
[ "MIT" ]
37
2015-11-01T06:16:35.000Z
2022-02-12T22:44:28.000Z
ImageMetalling-13/ImageMetalling-13/AppDelegate.swift
dnevera/ImageMetalling
d16b31f44a221dd37ca721a0ff8a84bbf2b04209
[ "MIT" ]
1
2021-07-12T22:10:00.000Z
2021-07-12T22:10:00.000Z
ImageMetalling-12/ImageMetalling-12/AppDelegate.swift
dnevera/ImageMetalling
d16b31f44a221dd37ca721a0ff8a84bbf2b04209
[ "MIT" ]
5
2017-06-14T10:30:42.000Z
2018-10-22T21:57:47.000Z
// // AppDelegate.swift // ImageMetalling-12 // // Created by denis svinarchuk on 12.06.16. // Copyright © 2016 ImageMetalling. All rights reserved. // import Cocoa import IMProcessing import simd enum IMPPrefs{ struct colors { static let background = float4(x:0.1,y:0.1,z:0.1,w:1.0) static let toolbarColor = float4(x:0.1,y:0.1,z:0.1,w:1.0) static let indentColor = float4(x:0.3,y:0.3,z:0.3,w:1.0) } } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSToolbarDelegate{ func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application for w in NSApp.windows{ w.backgroundColor = IMPColor(color: IMPPrefs.colors.background) } IMPDocument.sharedInstance.openRecentMenu = openRecentMenu } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBOutlet weak var openRecentMenu: NSMenu! @IBAction func clearOpenRecent(sender: AnyObject) { IMPDocument.sharedInstance.clearRecent() } @IBAction func chooseMenuItem(sender: AnyObject) { IMPMenuHandler.sharedInstance.currentMenuItem = sender as? NSMenuItem } @IBAction func openFile(sender: AnyObject) { IMPDocument.sharedInstance.openFilePanel(["jpg", "jpeg"]) } @IBAction func saveFile(sender: NSMenuItem) { let savePanel = NSSavePanel() savePanel.extensionHidden = false; savePanel.allowedFileTypes = ["jpg"] let dateFormat = NSDateFormatter() dateFormat.dateFormat = "yyyy-MM-dd-HH_mm_ss" dateFormat.stringFromDate(NSDate()) savePanel.nameFieldStringValue = String(format: "improcessing-result-\(dateFormat.stringFromDate(NSDate())).jpg") let result = savePanel.runModal() if result == NSModalResponseOK { IMPDocument.sharedInstance.saveCurrent((savePanel.URL?.path)!) } else { print("\(result)") } } func openRecentHandler(sender:NSMenuItem){ IMPDocument.sharedInstance.currentFile = sender.title } }
29.467532
121
0.653151
6863f488e27741e029f196e796e416b155d35843
6,487
asm
Assembly
Transynther/x86/_processed/AVXALIGN/_zr_/i9-9900K_12_0xa0_notsx.log_21829_345.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/AVXALIGN/_zr_/i9-9900K_12_0xa0_notsx.log_21829_345.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/AVXALIGN/_zr_/i9-9900K_12_0xa0_notsx.log_21829_345.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x740f, %rsi lea addresses_D_ht+0xb1cb, %rdi clflush (%rsi) nop nop dec %r10 mov $89, %rcx rep movsq nop nop nop add %rdi, %rdi lea addresses_WT_ht+0x1643f, %rbx nop nop nop cmp %rsi, %rsi mov (%rbx), %ebp nop nop dec %rcx lea addresses_normal_ht+0x1e62d, %r10 nop nop xor $16048, %rbp mov $0x6162636465666768, %rcx movq %rcx, %xmm0 vmovups %ymm0, (%r10) nop nop nop nop sub %rbx, %rbx lea addresses_normal_ht+0x14dcb, %rsi nop nop dec %r14 movb (%rsi), %bl add %rbp, %rbp lea addresses_WC_ht+0x10ecb, %rsi lea addresses_WT_ht+0x12dcb, %rdi nop nop nop nop dec %rax mov $50, %rcx rep movsb inc %r14 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %r8 push %rax push %rdx push %rsi // Store mov $0x18b, %r15 clflush (%r15) nop nop nop nop nop inc %r10 mov $0x5152535455565758, %rsi movq %rsi, %xmm1 vmovups %ymm1, (%r15) nop nop nop nop nop add %rsi, %rsi // Store lea addresses_D+0x12e43, %r14 nop nop nop add $20791, %rax movw $0x5152, (%r14) nop nop sub $43447, %r15 // Store lea addresses_US+0x71cb, %rax clflush (%rax) nop nop cmp $53285, %r10 mov $0x5152535455565758, %r8 movq %r8, %xmm7 vmovups %ymm7, (%rax) nop cmp $54105, %r10 // Store lea addresses_PSE+0x268f, %r8 xor $13417, %rdx movb $0x51, (%r8) nop nop nop nop nop add %rdx, %rdx // Store lea addresses_A+0x1bb9b, %rsi nop nop nop sub %rax, %rax mov $0x5152535455565758, %r14 movq %r14, %xmm1 movups %xmm1, (%rsi) nop nop nop nop and %r10, %r10 // Faulty Load lea addresses_US+0x1fdcb, %r10 dec %r14 mov (%r10), %r8d lea oracles, %r10 and $0xff, %r8 shlq $12, %r8 mov (%r10,%r8,1), %r8 pop %rsi pop %rdx pop %rax pop %r8 pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 2, 'NT': True, 'same': False, 'congruent': 2}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 2}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 4}} [Faulty Load] {'src': {'type': 'addresses_US', 'AVXalign': True, 'size': 4, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}} {'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 10}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': True}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
35.064865
2,999
0.656081
9b570010be25242282cc6f641cb7335ab92a815b
2,248
sql
SQL
Module 2/module_2.sql
snalahi/SQL-for-Data-Science
e3c970a136df8db071be6e936fb5e5792c3112af
[ "MIT" ]
1
2021-06-02T10:56:49.000Z
2021-06-02T10:56:49.000Z
Module 2/module_2.sql
snalahi/SQL-for-Data-Science
e3c970a136df8db071be6e936fb5e5792c3112af
[ "MIT" ]
null
null
null
Module 2/module_2.sql
snalahi/SQL-for-Data-Science
e3c970a136df8db071be6e936fb5e5792c3112af
[ "MIT" ]
null
null
null
-- Query 1 -- Find all the tracks that have a length of 5,000,000 milliseconds or more. -- How many tracks are returned? Select Milliseconds, count(TrackId) AS Tracks From Tracks Where Milliseconds >= 5000000 -- Query 2 -- Find all the invoices whose total is between $5 and $15 dollars. -- How many total records are there? Select count(InvoiceId) as Invoice_count, Total From Invoices Where Total Between 5 and 15 -- Query 3 -- Find all the customers from the following States: RJ, DF, AB, BC, CA, WA, NY. -- What company does Jack Smith work for? Select FirstName, LastName, State, Company From Customers Where State in ('RJ', 'DF', 'AB', 'BC', 'CA', 'WA', 'NY') -- Query 4 -- Find all the invoices for customer 56 and 58 where the total was between $1.00 and $5.00. -- What was the invoice date for invoice ID 315? Select CustomerId, InvoiceId, InvoiceDate, Total From Invoices Where (CustomerId Between 56 and 58) and (Total Between 1.00 and 5.00) -- Query 5 -- Find all the tracks whose name starts with 'All'. -- How many total records are there? Select count(TrackId) as Tracks_count, Name From Tracks Where Name Like 'All%' -- Query 6 -- Find all the customer emails that start with "J" and are from gmail.com. -- What is the one email address returned? Select Email From Customers Where Email Like 'j%gmail.com' -- Query 7 -- Find all the invoices from the billing city Brasília, Edmonton, and Vancouver and sort in descending order by invoice ID. -- What is the total invoice amount of the first record returned? Select InvoiceId, BillingCity, Total From Invoices Where BillingCity in ('Brasília', 'Edmonton', 'Vancouver' ) Order By InvoiceId DESC -- Query 8 -- Show the number of orders placed by each customer (hint: this is found in the invoices table) and sort the result by the -- number of orders in descending order. -- What is the number of items placed for the 8th person on this list? Select count(CustomerId) as Order_count, InvoiceId, CustomerId From Invoices Group By CustomerId Order By Order_count DESC -- Query 9 -- Find the albums with 12 or more tracks. -- How many total records are there? Select count(TrackId) as Tracks_Count, TrackId, AlbumId From Tracks Group By AlbumId Having Tracks_Count >= 12
24.977778
124
0.746886
443697ff5e4be043883b688450f81a4e8c093f19
268
py
Python
PythonExecicios/ex045.2.py
lucasohara98/Python_CursoemVideo
e5266abaf67ef3e27fe8928458b3860feb0ed46d
[ "MIT" ]
null
null
null
PythonExecicios/ex045.2.py
lucasohara98/Python_CursoemVideo
e5266abaf67ef3e27fe8928458b3860feb0ed46d
[ "MIT" ]
null
null
null
PythonExecicios/ex045.2.py
lucasohara98/Python_CursoemVideo
e5266abaf67ef3e27fe8928458b3860feb0ed46d
[ "MIT" ]
null
null
null
from random import randint itens = ('Pedra', 'Papel', 'Tesoura') computador = randint(0,2) print(f'O computador escolheu {itens[computador]}') jogador=(int(input('Qual é a sua jogada:'))) print('jogador jogou:') print(f'o computador jogou:{itens[computador]}')
33.5
52
0.701493
30894087a4739340a3a49c14524a3c817a868b1b
1,405
lua
Lua
modfiles/data/migrations/migration_1_1_5.lua
RSBat/FactoryPlanner
475513572772ded16188f1231409e0c3d1625a4a
[ "MIT" ]
49
2019-05-31T18:36:00.000Z
2022-03-19T18:16:28.000Z
modfiles/data/migrations/migration_1_1_5.lua
RSBat/FactoryPlanner
475513572772ded16188f1231409e0c3d1625a4a
[ "MIT" ]
8
2019-11-20T19:44:41.000Z
2021-10-02T19:35:07.000Z
modfiles/data/migrations/migration_1_1_5.lua
RSBat/FactoryPlanner
475513572772ded16188f1231409e0c3d1625a4a
[ "MIT" ]
27
2019-06-26T18:22:55.000Z
2022-03-30T10:57:41.000Z
local migration = {} function migration.global() end function migration.player_table(player_table) player_table.ui_state.view_states = player_table.ui_state.view_state player_table.preferences.toggle_column = false end function migration.subfactory(subfactory) for _, floor in pairs(Subfactory.get_all_floors(subfactory)) do if floor.level > 1 then floor.defining_line = floor.Line.datasets[1] end for _, line in pairs(Floor.get_in_order(floor, "Line")) do if not line.subfloor then line.machine.effects_tooltip = "" for _, module in pairs(Machine.get_in_order(line.machine, "Module")) do module.effects_tooltip = "" end line.active = true end if line.beacon then line.beacon.effects_tooltip = "" line.beacon.module.effects_tooltip = "" -- not strictly necessary yet end end end end function migration.packed_subfactory(packed_subfactory) local function update_lines(floor) for _, packed_line in ipairs(floor.Line.objects) do if packed_line.subfloor then update_lines(packed_line.subfloor) else packed_line.active = true end end end update_lines(packed_subfactory.top_floor) end return migration
29.893617
87
0.634875
edc2965edf2de920df47297679357a448d3e1355
106
sql
SQL
5.2.3/Database/Indexes/AFW_23_DETL_RESLT_RECHR_FK1.sql
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
1
2017-07-06T14:53:28.000Z
2017-07-06T14:53:28.000Z
5.2.3/Database/Indexes/AFW_23_DETL_RESLT_RECHR_FK1.sql
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
null
null
null
5.2.3/Database/Indexes/AFW_23_DETL_RESLT_RECHR_FK1.sql
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
null
null
null
SET DEFINE OFF; CREATE INDEX AFW_23_DETL_RESLT_RECHR_FK1 ON AFW_23_DETL_RESLT_RECHR (REF_RECHR) LOGGING /
17.666667
67
0.858491
43cb55cf722f92758b02d6840d040b315510ea12
2,727
ts
TypeScript
client/src/components/create-broadcast/steps/configure/hooks/useTestCall.ts
sonhoangci/twilio-voice-notification-app
3cf360c31e9b89b94c0909531172aa9dff8d5e06
[ "Apache-2.0" ]
20
2020-06-26T17:54:24.000Z
2021-12-30T12:24:38.000Z
client/src/components/create-broadcast/steps/configure/hooks/useTestCall.ts
craigsdennis/twilio-voice-notification-app
7de6e41289b58905843cf71d4cf43ac6faf779e7
[ "Apache-2.0" ]
28
2020-06-29T08:35:05.000Z
2021-05-10T03:14:47.000Z
client/src/components/create-broadcast/steps/configure/hooks/useTestCall.ts
craigsdennis/twilio-voice-notification-app
7de6e41289b58905843cf71d4cf43ac6faf779e7
[ "Apache-2.0" ]
21
2020-06-28T00:04:59.000Z
2022-01-04T18:53:53.000Z
import { useCallback, useState, useMemo } from 'react'; import isEmpty from 'lodash.isempty'; import useFetch from 'use-http'; import { CallStatus } from '@/types'; import socketIOClient from 'socket.io-client'; const wasCallSuccesful = (callStatus: CallStatus) => { return [ CallStatus.COMPLETED, CallStatus.BUSY, CallStatus.NO_ANSWER, CallStatus.CANCELED, ].includes(callStatus); }; export const useTestCall = (from: string, to: string, message: string) => { const [request, response] = useFetch(); const [cancelRequest] = useFetch(); const [callStatus, setCallStatus] = useState('initiating'); const [isTestCallOngoing, setIsTestCallOngoing] = useState(false); const [callSid, setCallSid] = useState(''); const isCancelLoading = useMemo(() => cancelRequest.loading, [cancelRequest]); const isCancelAvailable = useMemo(() => !isEmpty(callSid), [callSid]); const cancelTestCall = useCallback(async () => { await cancelRequest.get(`/test-call/cancel/${callSid}`); }, [callSid, cancelRequest]); const makeTestCall = useCallback(() => { return new Promise(async (resolve, reject) => { try { setCallStatus('initiating'); setIsTestCallOngoing(true); console.log( 'making a test call to: %s, from: %s with the message: %s', to, from, message ); await request.post('/test-call', { message, to, from, }); if (!response.ok) { setIsTestCallOngoing(false); setCallStatus(CallStatus.FAILED); reject(); } console.log('response %i', response.status); console.log('callSid %s', response.data?.callSid); setCallSid(response.data?.callSid); const socket = socketIOClient(window.location.origin); socket.on('update', (value: any) => { console.log('document updated: ', value); console.log('status: ', value.status); setCallStatus(value.status); if (wasCallSuccesful(value.status)) { setCallSid(''); setIsTestCallOngoing(false); socket.disconnect(); resolve(value.status); } if (value.status === CallStatus.FAILED) { setIsTestCallOngoing(false); socket.disconnect(); reject(); } }); } catch (error) { console.log('second error', error); reject(error); } }); }, [to, from, message, request, response.ok, response.status, response.data]); return { makeTestCall, cancelTestCall, isCancelLoading, isCancelAvailable, callStatus, isTestCallOngoing, }; };
28.705263
80
0.599927
c986c5a4659043b4d6dd937ebc53ecf71c559d8d
1,005
tsx
TypeScript
docs/src/docs/demos/core/Burger/burger.configurator.tsx
Rouby/mantine
b96200071f2bc4bff940a2a6cb8ed610c39545b2
[ "MIT" ]
null
null
null
docs/src/docs/demos/core/Burger/burger.configurator.tsx
Rouby/mantine
b96200071f2bc4bff940a2a6cb8ed610c39545b2
[ "MIT" ]
null
null
null
docs/src/docs/demos/core/Burger/burger.configurator.tsx
Rouby/mantine
b96200071f2bc4bff940a2a6cb8ed610c39545b2
[ "MIT" ]
null
null
null
import React, { useState } from 'react'; import { Burger, ElementsGroup } from '@mantine/core'; import Configurator from '../../../../components/Configurator/Configurator'; function BurgerWrapper(props: React.ComponentPropsWithoutRef<typeof Burger>) { const [opened, setOpened] = useState(false); const title = opened ? 'Open navigation' : 'Close navigation'; return ( <ElementsGroup position="center"> <Burger title={title} aria-label={title} opened={opened} onClick={() => setOpened((o) => !o)} {...props} /> </ElementsGroup> ); } const codeTemplate = (props: string) => `<Burger${props} />`; export function BurgerConfigurator() { return ( <Configurator component={BurgerWrapper} codeTemplate={codeTemplate} props={[ { name: 'color', type: 'color', initialValue: 'gray', defaultValue: 'gray' }, { name: 'size', type: 'size', initialValue: 'md', defaultValue: 'md' }, ]} /> ); }
27.916667
85
0.610945
253507f13c200c815cf6c0d6a963f2c1164fd50e
1,558
rb
Ruby
spec/plantmatters/gbif/species_matches_spec.rb
kspurgin/plantmatters
bd029e75d306f82f593c8357947a46dfc532e073
[ "MIT" ]
null
null
null
spec/plantmatters/gbif/species_matches_spec.rb
kspurgin/plantmatters
bd029e75d306f82f593c8357947a46dfc532e073
[ "MIT" ]
null
null
null
spec/plantmatters/gbif/species_matches_spec.rb
kspurgin/plantmatters
bd029e75d306f82f593c8357947a46dfc532e073
[ "MIT" ]
null
null
null
# frozen_string_literal: true RSpec.describe Plantmatters::GBIF::SpeciesMatches do let(:matches) { described_class.new(name: binomial) } cc_vcr_opt = {cassette_name: 'matches_cercis_canadensis'} as_vcr_opt = {cassette_name: 'matches_andropogon_scoparius'} ds_vcr_opt = {cassette_name: 'matches_dicentra_spectabilis'} uu_vcr_opt = {cassette_name: 'matches_unknown_umbellifer'} context 'when Cercis canadensis', vcr: cc_vcr_opt do let(:binomial) { 'Cercis canadensis' } it 'returns 16 matches' do expect(matches.results.length).to eq(16) end it 'returns expected species key' do expect(matches.species_key).to eq(5353583) end end context 'when Andropogon scoparius', vcr: as_vcr_opt do let(:binomial) { 'Andropogon scoparius' } it 'returns 28 matches' do expect(matches.results.length).to eq(28) end it 'returns expected species key' do expect(matches.species_key).to eq(2704432) end end context 'when Dicentra spectabilis', vcr: ds_vcr_opt do let(:binomial) { 'Dicentra spectabilis' } it 'returns 1 match' do expect(matches.results.length).to eq(1) end it 'returns expected species key' do expect(matches.species_key).to eq(2888564) end end context 'when Unknown umbellifer', vcr: uu_vcr_opt do let(:binomial) { 'Unknown umbellifer' } it 'returns 0 matches' do expect(matches.results.length).to eq(0) end it 'returns expected species key' do expect(matches.species_key).to be_nil end end end
27.821429
62
0.70154
3dce9e1b5bcc57e2837e4d4697728703f3dad1b8
886
lua
Lua
test/tests/text escaping.lua
Reuh/anselme
10af596a582f9b1d69495385469d092c1b7c95b9
[ "0BSD" ]
null
null
null
test/tests/text escaping.lua
Reuh/anselme
10af596a582f9b1d69495385469d092c1b7c95b9
[ "0BSD" ]
null
null
null
test/tests/text escaping.lua
Reuh/anselme
10af596a582f9b1d69495385469d092c1b7c95b9
[ "0BSD" ]
null
null
null
local _={} _[21]={} _[20]={} _[19]={} _[18]={} _[17]={} _[16]={text="sub [text]",tags=_[21]} _[15]={text="decorators # tag ~ condition $ fn",tags=_[20]} _[14]={text="other codes \n \\ \9",tags=_[19]} _[13]={text="quote \"",tags=_[18]} _[12]={text="expression {a}",tags=_[17]} _[11]={_[16]} _[10]={_[15]} _[9]={_[14]} _[8]={_[13]} _[7]={_[12]} _[6]={"return"} _[5]={"text",_[11]} _[4]={"text",_[10]} _[3]={"text",_[9]} _[2]={"text",_[8]} _[1]={"text",_[7]} return {_[1],_[2],_[3],_[4],_[5],_[6]} --[[ { "text", { { tags = {}, text = "expression {a}" } } } { "text", { { tags = {}, text = 'quote "' } } } { "text", { { tags = {}, text = "other codes \n \\ \t" } } } { "text", { { tags = {}, text = "decorators # tag ~ condition $ fn" } } } { "text", { { tags = {}, text = "sub [text]" } } } { "return" } ]]--
19.26087
59
0.417607
459e9c054a5b2d79b7932fe12e1c9017fe4d3bd3
1,116
sql
SQL
02-comparacao-char-varchar.sql
thiago-castilho/estudando-banco-de-dados
c8256dc011b373d274ad712f7ab0e50bd21b4291
[ "Apache-2.0" ]
null
null
null
02-comparacao-char-varchar.sql
thiago-castilho/estudando-banco-de-dados
c8256dc011b373d274ad712f7ab0e50bd21b4291
[ "Apache-2.0" ]
null
null
null
02-comparacao-char-varchar.sql
thiago-castilho/estudando-banco-de-dados
c8256dc011b373d274ad712f7ab0e50bd21b4291
[ "Apache-2.0" ]
null
null
null
/* TIPAGEM DE TABELAS DE BANDO DE DADOS */ -- Caracteres literais: CHAR e VARCHAR -- Números: FLOAT e INT -- Fotos e documentos: BLOB -- Textos extensos: TEXT -- VAR de VARCHAR vem da palavra variant, ou seja, VARCHAR é dinâmico. /* Dado CHAR(10) e VARCHAR(10), ambos preenchidos com joao. Os tamanhos serão, respectivamente, 10 bytes e 4 bytes. Os 6 campos restantes em CHAR, serão preenchidos com espaços. Ou seja, mais dados serão trafegados, tornando o banco menos performático. Já o VARHAR, ele varia de acordo com o tamanho do dado, dispensando os campos restantes. OBS.: Isso não significa que devemos sempre utilizar VARCHAR. CHAR é ligeiramente mais performático que VARCHAR, isso porquê ele não tem que ficar variando seu tamanho conforme o dado. Então, quando usar CHAR? Devemos usar CHAR quando o número de caracteres da coluna nunca for variante. Por exemplo: Unidade Federativa: SP; RJ; MS; utiliza-se sempre 2 dígitos (ou 2 bytes). Sexo: M para masculino e F para feminino. utiliza-se sempre 1 dígito (ou 1 byte). Verdadeiro ou falso: podemos utilizar 1 ou 0, sendo utilizado apenas 1 byte.*/
44.64
136
0.766129
b1828d3d2f9dc303c239282b62a2bc18139f293a
20,528
lua
Lua
builder/builder.lua
Anujan/opus-apps
be42cf74cd9d8a9bd405943dcfe35fc14c6984d4
[ "MIT" ]
null
null
null
builder/builder.lua
Anujan/opus-apps
be42cf74cd9d8a9bd405943dcfe35fc14c6984d4
[ "MIT" ]
null
null
null
builder/builder.lua
Anujan/opus-apps
be42cf74cd9d8a9bd405943dcfe35fc14c6984d4
[ "MIT" ]
null
null
null
if not _G.turtle and not _G.commands then error('Must be run on a turtle or a command computer') end local Adapter = require('core.inventoryAdapter') local Event = require('opus.event') local GPS = require('opus.gps') local itemDB = require('core.itemDB') local Schematic = require('builder.schematic') local TableDB = require('core.tableDB') local UI = require('opus.ui') local Util = require('opus.util') local colors = _G.colors local fs = _G.fs local BUILDER_DIR = 'usr/builder' local substitutionPage local Builder if _G.commands then Builder = require('builder.commands') else Builder = require('builder.turtle') end Builder = Builder() Builder.schematic = Schematic() local function convertSingleBack(item) if item then item.id = item.name item.dmg = item.damage item.qty = item.count item.max_size = item.maxCount item.display_name = item.displayName end return item end local function convertBack(t) for _,v in pairs(t) do convertSingleBack(v) end return t end --[[-- SubDB --]]-- local subDB = TableDB({ fileName = fs.combine(BUILDER_DIR, 'sub.db'), }) function subDB:load() if fs.exists(self.fileName) then TableDB.load(self) elseif not Builder.isCommandComputer then self:seedDB() end end function subDB:seedDB() self.data = { [ "minecraft:redstone_wire:0" ] = "minecraft:redstone:0", [ "minecraft:wall_sign:0" ] = "minecraft:sign:0", [ "minecraft:standing_sign:0" ] = "minecraft:sign:0", [ "minecraft:potatoes:0" ] = "minecraft:potato:0", [ "minecraft:unlit_redstone_torch:0" ] = "minecraft:redstone_torch:0", [ "minecraft:powered_repeater:0" ] = "minecraft:repeater:0", [ "minecraft:unpowered_repeater:0" ] = "minecraft:repeater:0", [ "minecraft:carrots:0" ] = "minecraft:carrot:0", [ "minecraft:cocoa:0" ] = "minecraft:dye:3", [ "minecraft:unpowered_comparator:0" ] = "minecraft:comparator:0", [ "minecraft:powered_comparator:0" ] = "minecraft:comparator:0", [ "minecraft:piston_head:0" ] = "minecraft:air:0", [ "minecraft:piston_extension:0" ] = "minecraft:air:0", [ "minecraft:portal:0" ] = "minecraft:air:0", [ "minecraft:double_wooden_slab:0" ] = "minecraft:planks:0", [ "minecraft:double_wooden_slab:1" ] = "minecraft:planks:1", [ "minecraft:double_wooden_slab:2" ] = "minecraft:planks:2", [ "minecraft:double_wooden_slab:3" ] = "minecraft:planks:3", [ "minecraft:double_wooden_slab:4" ] = "minecraft:planks:4", [ "minecraft:double_wooden_slab:5" ] = "minecraft:planks:5", [ "minecraft:lit_redstone_lamp:0" ] = "minecraft:redstone_lamp:0", [ "minecraft:double_stone_slab:1" ] = "minecraft:sandstone:0", [ "minecraft:double_stone_slab:2" ] = "minecraft:planks:0", [ "minecraft:double_stone_slab:3" ] = "minecraft:cobblestone:0", [ "minecraft:double_stone_slab:4" ] = "minecraft:brick_block:0", [ "minecraft:double_stone_slab:5" ] = "minecraft:stonebrick:0", [ "minecraft:double_stone_slab:6" ] = "minecraft:nether_brick:0", [ "minecraft:double_stone_slab:7" ] = "minecraft:quartz_block:0", [ "minecraft:double_stone_slab:9" ] = "minecraft:sandstone:2", [ "minecraft:double_stone_slab2:0" ] = "minecraft:sandstone:0", [ "minecraft:stone_slab:2" ] = "minecraft:wooden_slab:0", [ "minecraft:wheat:0" ] = "minecraft:wheat_seeds:0", [ "minecraft:flowing_water:0" ] = "minecraft:air:0", [ "minecraft:lit_furnace:0" ] = "minecraft:furnace:0", [ "minecraft:wall_banner:0" ] = "minecraft:banner:0", [ "minecraft:standing_banner:0" ] = "minecraft:banner:0", [ "minecraft:tripwire:0" ] = "minecraft:string:0", [ "minecraft:pumpkin_stem:0" ] = "minecraft:pumpkin_seeds:0", } self.dirty = true self:flush() end function subDB:add(s) TableDB.add(self, { s.id, s.dmg }, table.concat({ s.sid, s.sdmg }, ':')) self:flush() end function subDB:remove(s) -- TODO: tableDB.remove should take table key TableDB.remove(self, s.id .. ':' .. s.dmg) self:flush() end function subDB:extract(s) local id, dmg = s:match('(.+):(%d+)') return id, tonumber(dmg) end function subDB:getSubstitutedItem(id, dmg) local sub = TableDB.get(self, { id, dmg }) if sub then id, dmg = self:extract(sub) end return { id = id, dmg = dmg } end function subDB:lookupBlocksForSub(sid, sdmg) local t = { } for k,v in pairs(self.data) do local id, dmg = self:extract(v) if id == sid and dmg == sdmg then id, dmg = self:extract(k) t[k] = { id = id, dmg = dmg, sid = sid, sdmg = sdmg } end end return t end --[[-- blankPage --]]-- local blankPage = UI.Page() function blankPage:draw() self:clear(colors.black) self:setCursorPos(1, 1) end function blankPage:enable() self:sync() UI.Page.enable(self) end --[[-- selectSubstitutionPage --]]-- local selectSubstitutionPage = UI.Page({ titleBar = UI.TitleBar({ title = 'Select a substitution', previousPage = 'listing' }), grid = UI.ScrollingGrid({ columns = { { heading = 'id', key = 'id' }, { heading = 'dmg', key = 'dmg' }, }, sortColumn = 'id', height = UI.term.height-1, autospace = true, y = 2, }), }) function selectSubstitutionPage:enable() self.grid:adjustWidth() self.grid:setIndex(1) UI.Page.enable(self) end function selectSubstitutionPage:eventHandler(event) if event.type == 'grid_select' then substitutionPage.sub = event.selected UI:setPage(substitutionPage) elseif event.type == 'key' and event.key == 'q' then UI:setPreviousPage() else return UI.Page.eventHandler(self, event) end return true end --[[-- substitutionPage --]]-- substitutionPage = UI.Page { titleBar = UI.TitleBar { previousPage = true, title = 'Substitute a block' }, menuBar = UI.MenuBar { y = 2, buttons = { { text = 'Accept', event = 'accept', help = 'Accept' }, { text = 'Revert', event = 'revert', help = 'Restore to original' }, { text = 'Air', event = 'air', help = 'Air' }, }, }, info = UI.Window { y = 4, width = UI.term.width, height = 3 }, grid = UI.ScrollingGrid { columns = { { heading = 'Name', key = 'display_name', width = UI.term.width-9 }, { heading = 'Qty', key = 'fQty', width = 5 }, }, sortColumn = 'display_name', height = UI.term.height-7, y = 7, }, throttle = UI.Throttle { }, statusBar = UI.StatusBar { } } substitutionPage.menuBar:add({ filterLabel = UI.Text({ value = 'Search', x = UI.term.width-14, }), filter = UI.TextEntry({ x = UI.term.width-7, width = 7, }) }) function substitutionPage.info:draw() local sub = self.parent.sub local inName = itemDB:getName({ name = sub.id, damage = sub.dmg }) local outName = '' if sub.sid then outName = itemDB:getName({ name = sub.sid, damage = sub.sdmg }) end self:clear() self:print(' Replace ' .. inName .. '\n' .. ' With ' .. outName) end function substitutionPage:enable() self.allItems = convertBack(Builder.itemAdapter:refresh()) self.grid.values = self.allItems for _,item in pairs(self.grid.values) do item.key = item.id .. ':' .. item.dmg item.lname = string.lower(item.display_name) item.fQty = Util.toBytes(item.qty) end self.grid:update() self.menuBar.filter:reset() self:setFocus(self.menuBar.filter) UI.Page.enable(self) end function substitutionPage:applySubstitute(id, dmg) self.sub.sid = id self.sub.sdmg = dmg end function substitutionPage:eventHandler(event) if event.type == 'grid_focus_row' then local s = string.format('%s:%d', event.selected.id, event.selected.dmg) self.statusBar:setStatus(s) self.statusBar:draw() elseif event.type == 'grid_select' then self:applySubstitute(event.selected.id, event.selected.dmg) self.info:draw() elseif event.type == 'text_change' then local text = event.text or '' if #text == 0 then self.grid.values = self.allItems else self.grid.values = { } for _,item in pairs(self.allItems) do if string.find(item.lname, text) then table.insert(self.grid.values, item) end end end self.grid:update() self.grid:setIndex(1) self.grid:draw() elseif event.type == 'accept' or event.type == 'air' or event.type == 'revert' then self.statusBar:setStatus('Saving changes...') self.statusBar:draw() self:sync() if event.type == 'air' then self:applySubstitute('minecraft:air', 0) end if event.type == 'revert' then subDB:remove(self.sub) elseif not self.sub.sid then self.statusBar:setStatus('Select a substition') self.statusBar:draw() return UI.Page.eventHandler(self, event) else subDB:add(self.sub) end self.throttle:enable() Builder:reloadSchematic(function() self.throttle:update() end) self.throttle:disable() UI:setPage('listing') elseif event.type == 'cancel' then UI:setPreviousPage() end return UI.Page.eventHandler(self, event) end --[[-- ListingPage --]]-- local listingPage = UI.Page({ titleBar = UI.TitleBar({ title = 'Supply List', previousPage = 'start' }), menuBar = UI.MenuBar({ y = 2, buttons = { { text = 'Craft', event = 'craft', help = 'Request crafting' }, { text = 'Refresh', event = 'refresh', help = 'Refresh inventory' }, { text = 'Toggle', event = 'toggle', help = 'Toggles needed blocks' }, { text = 'Substitute', event = 'edit', help = 'Substitute a block' }, } }), grid = UI.ScrollingGrid({ columns = { { heading = 'Name', key = 'display_name', width = UI.term.width - 14 }, { heading = 'Need', key = 'need', width = 5 }, { heading = 'Have', key = 'qty', width = 5 }, }, sortColumn = 'display_name', y = 3, height = UI.term.height-3, help = 'Set a block type or pick a substitute block' }), accelerators = { q = 'menu', c = 'craft', r = 'refresh', t = 'toggle', }, statusBar = UI.StatusBar(), fullList = true }) function listingPage:enable(throttle) listingPage:refresh(throttle) UI.Page.enable(self) end function listingPage:eventHandler(event) if event.type == 'craft' then local s = self.grid:getSelected() local item = convertSingleBack(Builder.itemAdapter:getItemInfo({ name = s.id, damage = s.dmg, nbtHash = s.nbt_hash, })) if item and item.is_craftable then local qty = math.max(0, s.need - item.qty) if item and Builder.itemAdapter.craftItems then Builder.itemAdapter:craftItems({{ name = s.id, damage = s.dmg, nbtHash = s.nbt_hash, count = qty }}) local name = s.display_name or s.id self.statusBar:timedStatus('Requested ' .. qty .. ' ' .. name, 3) end else self.statusBar:timedStatus('Unable to craft') end elseif event.type == 'grid_focus_row' then self.statusBar:setStatus(event.selected.id .. ':' .. event.selected.dmg) self.statusBar:draw() elseif event.type == 'refresh' then self:refresh() self:draw() self.statusBar:timedStatus('Refreshed ', 3) elseif event.type == 'toggle' then self.fullList = not self.fullList self:refresh() self:draw() elseif event.type == 'menu' then UI:setPage('start') elseif event.type == 'edit' or event.type == 'grid_select' then self:manageBlock(self.grid:getSelected()) elseif event.type == 'focus_change' then if event.focused.help then self.statusBar:timedStatus(event.focused.help, 3) end end return UI.Page.eventHandler(self, event) end function listingPage.grid:getDisplayValues(row) row = Util.shallowCopy(row) row.need = Util.toBytes(row.need) row.qty = Util.toBytes(row.qty) return row end function listingPage.grid:getRowTextColor(row, selected) if row.is_craftable then return colors.yellow end return UI.Grid:getRowTextColor(row, selected) end function listingPage:refresh(throttle) local supplyList = Builder:getBlockCounts() Builder.itemAdapter:refresh(throttle) for _,b in pairs(supplyList) do if b.need > 0 then local item = convertSingleBack(Builder.itemAdapter:getItemInfo({ name = b.id, damage = b.dmg, nbtHash = b.nbt_hash, })) if item then b.display_name = item.display_name b.qty = item.qty b.is_craftable = item.is_craftable else b.display_name = itemDB:getName({ name = b.id, damage = b.dmg }) end end if throttle then throttle() end end if self.fullList then self.grid:setValues(supplyList) else local t = {} for _,b in pairs(supplyList) do if self.fullList or b.qty < b.need then table.insert(t, b) end end self.grid:setValues(t) end self.grid:setIndex(1) end function listingPage:manageBlock(selected) local substitutes = subDB:lookupBlocksForSub(selected.id, selected.dmg) if Util.empty(substitutes) then substitutionPage.sub = { id = selected.id, dmg = selected.dmg } UI:setPage(substitutionPage) elseif Util.size(substitutes) == 1 then local _,sub = next(substitutes) substitutionPage.sub = sub UI:setPage(substitutionPage) else selectSubstitutionPage.selected = selected selectSubstitutionPage.grid:setValues(substitutes) UI:setPage(selectSubstitutionPage) end end --[[-- startPage --]]-- local wy = 2 local my = 3 if UI.term.width < 30 then wy = 9 my = 2 end local startPage = UI.Page { window = UI.Window { x = UI.term.width-16, y = wy, width = 16, height = 9, backgroundColor = colors.gray, grid = UI.Grid { columns = { { heading = 'Name', key = 'name', width = 6 }, { heading = 'Value', key = 'value', width = 7 }, }, disableHeader = true, x = 1, y = 2, width = 16, height = 9, inactive = true, backgroundColor = colors.gray }, }, menu = UI.Menu { x = 2, y = my, height = 7, backgroundColor = UI.Page.defaults.backgroundColor, menuItems = { { prompt = 'Set starting level', event = 'startLevel' }, { prompt = 'Set starting block', event = 'startBlock' }, { prompt = 'Set starting point', event = 'startPoint' }, { prompt = 'Supply list', event = 'assignBlocks' }, { prompt = 'Toggle mode', event = 'toggleMode' }, { prompt = 'Begin', event = 'begin' }, { prompt = 'Quit', event = 'quit' } } }, startLevel = UI.Dialog { title = 'Enter Starting Level', height = 7, form = UI.Form { y = 3, x = 2, height = 4, event = 'setStartLevel', cancelEvent = 'slide_hide', text = UI.Text { x = 5, y = 1, width = 10, textColor = colors.gray, }, textEntry = UI.TextEntry { formKey = 'level', x = 15, y = 1, width = 7, }, }, statusBar = UI.StatusBar(), }, startBlock = UI.Dialog { title = 'Enter Block Number', height = 7, form = UI.Form { y = 3, x = 2, height = 4, event = 'setStartBlock', cancelEvent = 'slide_hide', text = UI.Text { x = 2, y = 1, width = 13, textColor = colors.gray, }, textEntry = UI.TextEntry { x = 16, y = 1, width = 10, limit = 8, }, }, statusBar = UI.StatusBar(), }, startPoint = UI.Dialog { title = 'Set starting point', height = 11, form = UI.Form { y = 2, x = 2, ey = -2, cancelEvent = 'slide_hide', text1 = UI.Text { x = 1, y = 2, value = 'Turtle location' }, xLoc = UI.TextEntry { x = 1, y = 3, formKey = 'x', width = 7, limit = 16, shadowText = 'x', required = true }, yLoc = UI.TextEntry { x = 9, y = 3, formKey = 'y', width = 7, limit = 16, shadowText = 'y', required = true }, zLoc = UI.TextEntry { x = 17, y = 3, formKey = 'z', width = 7, limit = 16, shadowText = 'z', required = true }, text2 = UI.Text { x = 1, y = 5, value = 'Starting Point' }, xrLoc = UI.TextEntry { x = 1, y = 6, formKey = 'rx', width = 7, limit = 16, shadowText = 'x', required = true }, yrLoc = UI.TextEntry { x = 9, y = 6, formKey = 'ry', width = 7, limit = 16, shadowText = 'y', required = true }, zrLoc = UI.TextEntry { x = 17, y = 6, formKey = 'rz', width = 7, limit = 16, shadowText = 'z', required = true }, revert = UI.Button { x = 1, y = -2, text = 'Revert', event = 'revert' }, accelerators = { form_cancel = 'slide_hide', }, }, statusBar = UI.StatusBar({ values = 'Optional start point'}), }, throttle = UI.Throttle { }, accelerators = { x = 'test', [ 'control-q' ] = 'quit' } } function startPage:draw() local t = { { name = 'mode', value = Builder.mode }, { name = 'start', value = Builder.index }, { name = 'blocks', value = #Builder.schematic.blocks }, { name = 'length', value = Builder.schematic.length }, { name = 'width', value = Builder.schematic.width }, { name = 'height', value = Builder.schematic.height }, } self.window.grid:setValues(t) UI.Page.draw(self) end function startPage:enable() self:setFocus(self.menu) UI.Page.enable(self) end function startPage.startPoint:eventHandler(event) if event.type == 'form_complete' then for k,v in pairs(event.values) do Builder.loc[k] = tonumber(v) end Builder:saveProgress(Builder.index) self:hide() elseif event.type == 'revert' then Builder.loc = { } Builder:saveProgress(Builder.index) self:hide() elseif event.type == 'form_invalid' then self.statusBar:setStatus(event.message) elseif event.type == 'form_cancel' or event.type == 'cancel' then self:hide() else return UI.Dialog.eventHandler(self, event) end return true end function startPage:eventHandler(event) if event.type == 'startLevel' then self.startLevel.form.text.value = '0 - ' .. Builder.schematic.height self.startLevel:show() elseif event.type == 'setStartLevel' then local l = tonumber(self.startLevel.form.textEntry.value) if l and l < Builder.schematic.height and l >= 0 then for k,v in pairs(Builder.schematic.blocks) do if v.y >= l then Builder.index = k Builder:saveProgress(Builder.index) break end end self.startLevel:hide() self:draw() else self.startLevel.statusBar:setStatus('Invalid start level') end elseif event.type == 'startBlock' then self.startBlock.form.text.value = '1 - ' .. #Builder.schematic.blocks self.startBlock.form.textEntry.value = tostring(Builder.index) self.startBlock:show() elseif event.type == 'setStartBlock' then local bn = tonumber(self.startBlock.form.textEntry.value) if bn and bn < #Builder.schematic.blocks and bn >= 0 then Builder.index = bn Builder:saveProgress(Builder.index) self.startBlock:hide() self:draw() else self.startLevel.statusBar:setStatus('Invalid start block') end elseif event.type == 'startPoint' then local loc = Util.shallowCopy(Builder.loc) if not loc.x then if _G.turtle then local pt = GPS.getPoint() if pt then loc.x = pt.x loc.y = pt.y loc.z = pt.z end elseif _G.commands then loc.x, loc.y, loc.z = _G.commands.getBlockPosition() end end self.startPoint.form:setValues(loc) self.startPoint:show() elseif event.type == 'assignBlocks' then -- this might be an approximation of the blocks needed -- as the current level's route may or may not have been -- computed Builder:dumpInventory() UI:setPage('listing', function() self.throttle:update() end) self.throttle:disable() elseif event.type == 'toggleMode' then if Builder.mode == 'build' then if Builder.index == 1 then Builder.index = #Builder.schematic.blocks end Builder.mode = 'destroy' else if Builder.index == #Builder.schematic.blocks then Builder.index = 1 end Builder.mode = 'build' end self:draw() elseif event.type == 'begin' then UI:setPage('blank') self:sync() print('Reloading schematic') Builder:reloadSchematic(Util.throttle()) Builder:begin() elseif event.type == 'quit' then UI:quit() end return UI.Page.eventHandler(self, event) end --[[-- startup logic --]]-- local args = {...} if #args < 1 then error('supply file name or URL') end Builder.itemAdapter = Adapter.wrap({ side = 'bottom', direction = 'up' }) if not Builder.itemAdapter then error('test A chest or ME interface must be below turtle') end subDB:load() UI.term:reset() print('Loading schematic') Builder.schematic:load(args[1]) print('Substituting blocks') Builder.subDB = subDB Builder:substituteBlocks(Util.throttle()) if not fs.exists(BUILDER_DIR) then fs.makeDir(BUILDER_DIR) end Builder:loadProgress(Builder.schematic.filename .. '.progress') Event.on('build', function() Builder:build() end) UI:setPages({ listing = listingPage, start = startPage, blank = blankPage }) UI:setPage('start') UI:start()
26.590674
104
0.649308
ed0905643418bd45d1a67cf3fce12e5ae262ce92
18,183
h
C
platforms/xtensa-lx106-elf/lib/gcc/xtensa-lx106-elf/4.8.2/include/xcc/g++/stl_algobase.h
arielscarpinelli/tuya-esp8266
a514d624fc99b9471e910356d6cce9afc8345a50
[ "BSD-3-Clause" ]
39
2019-04-24T13:40:02.000Z
2022-02-21T08:30:22.000Z
platforms/xtensa-lx106-elf/lib/gcc/xtensa-lx106-elf/4.8.2/include/xcc/g++/stl_algobase.h
arielscarpinelli/tuya-esp8266
a514d624fc99b9471e910356d6cce9afc8345a50
[ "BSD-3-Clause" ]
2
2020-02-11T23:29:47.000Z
2020-06-05T17:29:41.000Z
platforms/xtensa-lx106-elf/lib/gcc/xtensa-lx106-elf/4.8.2/include/xcc/g++/stl_algobase.h
arielscarpinelli/tuya-esp8266
a514d624fc99b9471e910356d6cce9afc8345a50
[ "BSD-3-Clause" ]
31
2019-07-07T06:17:49.000Z
2022-03-05T18:17:00.000Z
/* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /* NOTE: This is an internal header file, included by other STL headers. * You should not attempt to use it directly. */ #ifndef __SGI_STL_INTERNAL_ALGOBASE_H #define __SGI_STL_INTERNAL_ALGOBASE_H #ifndef __STL_CONFIG_H #include <stl_config.h> #endif #ifndef __SGI_STL_INTERNAL_RELOPS #include <stl_relops.h> #endif #ifndef __SGI_STL_INTERNAL_PAIR_H #include <stl_pair.h> #endif #ifndef __TYPE_TRAITS_H_ #include <type_traits.h> #endif #include <string.h> #include <limits.h> #include <stdlib.h> #include <stddef.h> #include <new.h> #include <iostream.h> #ifndef __SGI_STL_INTERNAL_ITERATOR_H #include <stl_iterator.h> #endif __STL_BEGIN_NAMESPACE // swap and iter_swap template <class _ForwardIter1, class _ForwardIter2, class _Tp> inline void __iter_swap(_ForwardIter1 __a, _ForwardIter2 __b, _Tp*) { _Tp __tmp = *__a; *__a = *__b; *__b = __tmp; } template <class _ForwardIter1, class _ForwardIter2> inline void iter_swap(_ForwardIter1 __a, _ForwardIter2 __b) { __iter_swap(__a, __b, __VALUE_TYPE(__a)); } template <class _Tp> inline void swap(_Tp& __a, _Tp& __b) { _Tp __tmp = __a; __a = __b; __b = __tmp; } //-------------------------------------------------- // min and max #ifndef __BORLANDC__ #undef min #undef max template <class _Tp> inline const _Tp& min(const _Tp& __a, const _Tp& __b) { return __b < __a ? __b : __a; } template <class _Tp> inline const _Tp& max(const _Tp& __a, const _Tp& __b) { return __a < __b ? __b : __a; } #endif /* __BORLANDC__ */ template <class _Tp, class _Compare> inline const _Tp& min(const _Tp& __a, const _Tp& __b, _Compare __comp) { return __comp(__b, __a) ? __b : __a; } template <class _Tp, class _Compare> inline const _Tp& max(const _Tp& __a, const _Tp& __b, _Compare __comp) { return __comp(__a, __b) ? __b : __a; } //-------------------------------------------------- // copy // All of these auxiliary functions serve two purposes. (1) Replace // calls to copy with memmove whenever possible. (Memmove, not memcpy, // because the input and output ranges are permitted to overlap.) // (2) If we're using random access iterators, then write the loop as // a for loop with an explicit count. The auxiliary class __copy_dispatch // is a workaround for compilers that don't support partial ordering of // function templates. template <class _InputIter, class _OutputIter, class _Distance> inline _OutputIter __copy(_InputIter __first, _InputIter __last, _OutputIter __result, input_iterator_tag, _Distance*) { for ( ; __first != __last; ++__result, ++__first) *__result = *__first; return __result; } template <class _RandomAccessIter, class _OutputIter, class _Distance> inline _OutputIter __copy(_RandomAccessIter __first, _RandomAccessIter __last, _OutputIter __result, random_access_iterator_tag, _Distance*) { for (_Distance __n = __last - __first; __n > 0; --__n) { *__result = *__first; ++__first; ++__result; } return __result; } template <class _Tp> inline _Tp* __copy_trivial(const _Tp* __first, const _Tp* __last, _Tp* __result) { memmove(__result, __first, sizeof(_Tp) * (__last - __first)); return __result + (__last - __first); } #ifdef __STL_CLASS_PARTIAL_SPECIALIZATION template <class _InputIter, class _OutputIter, class _BoolType> struct __copy_dispatch { static _OutputIter copy(_InputIter __first, _InputIter __last, _OutputIter __result) { typedef typename iterator_traits<_InputIter>::iterator_category _Category; typedef typename iterator_traits<_InputIter>::difference_type _Distance; return __copy(__first, __last, __result, _Category(), (_Distance*) 0); } }; template <class _Tp> struct __copy_dispatch<_Tp*, _Tp*, __true_type> { static _Tp* copy(const _Tp* __first, const _Tp* __last, _Tp* __result) { return __copy_trivial(__first, __last, __result); } }; template <class _Tp> struct __copy_dispatch<const _Tp*, _Tp*, __true_type> { static _Tp* copy(const _Tp* __first, const _Tp* __last, _Tp* __result) { return __copy_trivial(__first, __last, __result); } }; template <class _InputIter, class _OutputIter> inline _OutputIter copy(_InputIter __first, _InputIter __last, _OutputIter __result) { typedef typename iterator_traits<_InputIter>::value_type _Tp; typedef typename __type_traits<_Tp>::has_trivial_assignment_operator _Trivial; return __copy_dispatch<_InputIter, _OutputIter, _Trivial> ::copy(__first, __last, __result); } #else /* __STL_CLASS_PARTIAL_SPECIALIZATION */ template <class _InputIter, class _OutputIter> inline _OutputIter copy(_InputIter __first, _InputIter __last, _OutputIter __result) { return __copy(__first, __last, __result, __ITERATOR_CATEGORY(__first), __DISTANCE_TYPE(__first)); } inline char* copy(const char* __first, const char* __last, char* __result) { memmove(__result, __first, __last - __first); return __result + (__last - __first); } inline wchar_t* copy(const wchar_t* __first, const wchar_t* __last, wchar_t* __result) { memmove(__result, __first, sizeof(wchar_t) * (__last - __first)); return __result + (__last - __first); } #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ //-------------------------------------------------- // copy_backward template <class _BidirectionalIter1, class _BidirectionalIter2, class _Distance> inline _BidirectionalIter2 __copy_backward(_BidirectionalIter1 __first, _BidirectionalIter1 __last, _BidirectionalIter2 __result, bidirectional_iterator_tag, _Distance*) { while (__first != __last) *--__result = *--__last; return __result; } template <class _RandomAccessIter, class _BidirectionalIter, class _Distance> inline _BidirectionalIter __copy_backward(_RandomAccessIter __first, _RandomAccessIter __last, _BidirectionalIter __result, random_access_iterator_tag, _Distance*) { for (_Distance __n = __last - __first; __n > 0; --__n) *--__result = *--__last; return __result; } #ifdef __STL_CLASS_PARTIAL_SPECIALIZATION // This dispatch class is a workaround for compilers that do not // have partial ordering of function templates. All we're doing is // creating a specialization so that we can turn a call to copy_backward // into a memmove whenever possible. template <class _BidirectionalIter1, class _BidirectionalIter2, class _BoolType> struct __copy_backward_dispatch { typedef typename iterator_traits<_BidirectionalIter1>::iterator_category _Cat; typedef typename iterator_traits<_BidirectionalIter1>::difference_type _Distance; static _BidirectionalIter2 copy(_BidirectionalIter1 __first, _BidirectionalIter1 __last, _BidirectionalIter2 __result) { return __copy_backward(__first, __last, __result, _Cat(), (_Distance*) 0); } }; template <class _Tp> struct __copy_backward_dispatch<_Tp*, _Tp*, __true_type> { static _Tp* copy(const _Tp* __first, const _Tp* __last, _Tp* __result) { const ptrdiff_t _Num = __last - __first; memmove(__result - _Num, __first, sizeof(_Tp) * _Num); return __result - _Num; } }; template <class _Tp> struct __copy_backward_dispatch<const _Tp*, _Tp*, __true_type> { static _Tp* copy(const _Tp* __first, const _Tp* __last, _Tp* __result) { return __copy_backward_dispatch<_Tp*, _Tp*, __true_type> ::copy(__first, __last, __result); } }; template <class _BI1, class _BI2> inline _BI2 copy_backward(_BI1 __first, _BI1 __last, _BI2 __result) { typedef typename __type_traits<typename iterator_traits<_BI2>::value_type> ::has_trivial_assignment_operator _Trivial; return __copy_backward_dispatch<_BI1, _BI2, _Trivial> ::copy(__first, __last, __result); } #else /* __STL_CLASS_PARTIAL_SPECIALIZATION */ template <class _BI1, class _BI2> inline _BI2 copy_backward(_BI1 __first, _BI1 __last, _BI2 __result) { return __copy_backward(__first, __last, __result, __ITERATOR_CATEGORY(__first), __DISTANCE_TYPE(__first)); } #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ //-------------------------------------------------- // copy_n (not part of the C++ standard) template <class _InputIter, class _Size, class _OutputIter> pair<_InputIter, _OutputIter> __copy_n(_InputIter __first, _Size __count, _OutputIter __result, input_iterator_tag) { for ( ; __count > 0; --__count) { *__result = *__first; ++__first; ++__result; } return pair<_InputIter, _OutputIter>(__first, __result); } template <class _RAIter, class _Size, class _OutputIter> inline pair<_RAIter, _OutputIter> __copy_n(_RAIter __first, _Size __count, _OutputIter __result, random_access_iterator_tag) { _RAIter __last = __first + __count; return pair<_RAIter, _OutputIter>(__last, copy(__first, __last, __result)); } template <class _InputIter, class _Size, class _OutputIter> inline pair<_InputIter, _OutputIter> __copy_n(_InputIter __first, _Size __count, _OutputIter __result) { return __copy_n(__first, __count, __result, __ITERATOR_CATEGORY(__first)); } template <class _InputIter, class _Size, class _OutputIter> inline pair<_InputIter, _OutputIter> copy_n(_InputIter __first, _Size __count, _OutputIter __result) { return __copy_n(__first, __count, __result); } //-------------------------------------------------- // fill and fill_n template <class _ForwardIter, class _Tp> void fill(_ForwardIter __first, _ForwardIter __last, const _Tp& __value) { for ( ; __first != __last; ++__first) *__first = __value; } template <class _OutputIter, class _Size, class _Tp> _OutputIter fill_n(_OutputIter __first, _Size __n, const _Tp& __value) { for ( ; __n > 0; --__n, ++__first) *__first = __value; return __first; } //-------------------------------------------------- // equal and mismatch template <class _InputIter1, class _InputIter2> pair<_InputIter1, _InputIter2> mismatch(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2) { while (__first1 != __last1 && *__first1 == *__first2) { ++__first1; ++__first2; } return pair<_InputIter1, _InputIter2>(__first1, __first2); } template <class _InputIter1, class _InputIter2, class _BinaryPredicate> pair<_InputIter1, _InputIter2> mismatch(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2, _BinaryPredicate __binary_pred) { while (__first1 != __last1 && __binary_pred(*__first1, *__first2)) { ++__first1; ++__first2; } return pair<_InputIter1, _InputIter2>(__first1, __first2); } template <class _InputIter1, class _InputIter2> inline bool equal(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2) { for ( ; __first1 != __last1; ++__first1, ++__first2) if (*__first1 != *__first2) return false; return true; } template <class _InputIter1, class _InputIter2, class _BinaryPredicate> inline bool equal(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2, _BinaryPredicate __binary_pred) { for ( ; __first1 != __last1; ++__first1, ++__first2) if (!__binary_pred(*__first1, *__first2)) return false; return true; } //-------------------------------------------------- // lexicographical_compare and lexicographical_compare_3way. // (the latter is not part of the C++ standard.) template <class _InputIter1, class _InputIter2> bool lexicographical_compare(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2, _InputIter2 __last2) { for ( ; __first1 != __last1 && __first2 != __last2 ; ++__first1, ++__first2) { if (*__first1 < *__first2) return true; if (*__first2 < *__first1) return false; } return __first1 == __last1 && __first2 != __last2; } template <class _InputIter1, class _InputIter2, class _Compare> bool lexicographical_compare(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2, _InputIter2 __last2, _Compare __comp) { for ( ; __first1 != __last1 && __first2 != __last2 ; ++__first1, ++__first2) { if (__comp(*__first1, *__first2)) return true; if (__comp(*__first2, *__first1)) return false; } return __first1 == __last1 && __first2 != __last2; } inline bool lexicographical_compare(const unsigned char* __first1, const unsigned char* __last1, const unsigned char* __first2, const unsigned char* __last2) { const size_t __len1 = __last1 - __first1; const size_t __len2 = __last2 - __first2; const int __result = memcmp(__first1, __first2, min(__len1, __len2)); return __result != 0 ? __result < 0 : __len1 < __len2; } inline bool lexicographical_compare(const char* __first1, const char* __last1, const char* __first2, const char* __last2) { #if CHAR_MAX == SCHAR_MAX return lexicographical_compare((const signed char*) __first1, (const signed char*) __last1, (const signed char*) __first2, (const signed char*) __last2); #else /* CHAR_MAX == SCHAR_MAX */ return lexicographical_compare((const unsigned char*) __first1, (const unsigned char*) __last1, (const unsigned char*) __first2, (const unsigned char*) __last2); #endif /* CHAR_MAX == SCHAR_MAX */ } template <class _InputIter1, class _InputIter2> int __lexicographical_compare_3way(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2, _InputIter2 __last2) { while (__first1 != __last1 && __first2 != __last2) { if (*__first1 < *__first2) return -1; if (*__first2 < *__first1) return 1; ++__first1; ++__first2; } if (__first2 == __last2) { return !(__first1 == __last1); } else { return -1; } } inline int __lexicographical_compare_3way(const unsigned char* __first1, const unsigned char* __last1, const unsigned char* __first2, const unsigned char* __last2) { const ptrdiff_t __len1 = __last1 - __first1; const ptrdiff_t __len2 = __last2 - __first2; const int __result = memcmp(__first1, __first2, min(__len1, __len2)); return __result != 0 ? __result : (__len1 == __len2 ? 0 : (__len1 < __len2 ? -1 : 1)); } inline int __lexicographical_compare_3way(const char* __first1, const char* __last1, const char* __first2, const char* __last2) { #if CHAR_MAX == SCHAR_MAX return __lexicographical_compare_3way( (const signed char*) __first1, (const signed char*) __last1, (const signed char*) __first2, (const signed char*) __last2); #else return __lexicographical_compare_3way((const unsigned char*) __first1, (const unsigned char*) __last1, (const unsigned char*) __first2, (const unsigned char*) __last2); #endif } template <class _InputIter1, class _InputIter2> int lexicographical_compare_3way(_InputIter1 __first1, _InputIter1 __last1, _InputIter2 __first2, _InputIter2 __last2) { return __lexicographical_compare_3way(__first1, __last1, __first2, __last2); } __STL_END_NAMESPACE #endif /* __SGI_STL_INTERNAL_ALGOBASE_H */ // Local Variables: // mode:C++ // End:
34.502846
79
0.632844
628752bec6cb380b3a1bb6a8fc5fc307f721c727
254
sql
SQL
backend/sql/columns.sql
praveenweb/data-dictionary
589d0d9740c268203f36e7d99398082a56d5d13e
[ "MIT" ]
82
2020-11-24T13:38:33.000Z
2022-02-20T07:47:50.000Z
backend/sql/columns.sql
praveenweb/data-dictionary
589d0d9740c268203f36e7d99398082a56d5d13e
[ "MIT" ]
7
2020-11-24T15:12:13.000Z
2021-04-08T17:48:55.000Z
backend/sql/columns.sql
praveenweb/data-dictionary
589d0d9740c268203f36e7d99398082a56d5d13e
[ "MIT" ]
4
2020-11-25T20:52:10.000Z
2021-06-27T18:13:21.000Z
select table_schema, table_name, column_name, column_default, is_nullable::bool, data_type, udt_name from information_schema.columns where columns.table_schema not in ('pg_catalog', 'information_schema', 'hdb_catalog')
21.166667
83
0.716535
277f3015659fe8fa6e7c68d93aedbbe72dcc374b
3,180
kt
Kotlin
domain/src/test/java/com/telen/easylineup/domain/GetTeamCreationNextStepTests.kt
kaygenzo/EasyLineUp
3941fb10aee593332bc942f96734971ab3e68600
[ "Apache-2.0" ]
null
null
null
domain/src/test/java/com/telen/easylineup/domain/GetTeamCreationNextStepTests.kt
kaygenzo/EasyLineUp
3941fb10aee593332bc942f96734971ab3e68600
[ "Apache-2.0" ]
null
null
null
domain/src/test/java/com/telen/easylineup/domain/GetTeamCreationNextStepTests.kt
kaygenzo/EasyLineUp
3941fb10aee593332bc942f96734971ab3e68600
[ "Apache-2.0" ]
1
2020-05-26T11:36:03.000Z
2020-05-26T11:36:03.000Z
package com.telen.easylineup.domain import android.view.View import com.telen.easylineup.domain.model.TeamCreationStep import com.telen.easylineup.domain.usecases.GetTeamCreationNextStep import com.telen.easylineup.domain.usecases.GetTeamCreationStep import io.reactivex.observers.TestObserver import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.MockitoAnnotations import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) internal class GetTeamCreationNextStepTests { lateinit var mGetTeamCreationNextStep: GetTeamCreationNextStep @Before fun init() { MockitoAnnotations.initMocks(this) mGetTeamCreationNextStep = GetTeamCreationNextStep() } @Test fun shouldTriggerAnExceptionIfStepNotManaged() { val observer = TestObserver<GetTeamCreationStep.ResponseValue>() mGetTeamCreationNextStep.executeUseCase(GetTeamCreationStep.RequestValues(TeamCreationStep.FINISH)).subscribe(observer) observer.await() observer.assertError(IllegalArgumentException::class.java) } // Team -> Type @Test fun shouldReturnNextScreenTypeIfCurrentIsTeam() { val observer = TestObserver<GetTeamCreationStep.ResponseValue>() mGetTeamCreationNextStep.executeUseCase(GetTeamCreationStep.RequestValues(TeamCreationStep.TEAM)).subscribe(observer) observer.await() observer.assertComplete() Assert.assertEquals(TeamCreationStep.TYPE, observer.values().first().config.nextStep) Assert.assertEquals(true, observer.values().first().config.nextButtonEnabled) Assert.assertEquals(R.string.team_creation_label_finish, observer.values().first().config.nextButtonLabel) Assert.assertEquals(View.VISIBLE, observer.values().first().config.nextButtonVisibility) Assert.assertEquals(true, observer.values().first().config.previousButtonEnabled) Assert.assertEquals(R.string.team_creation_label_previous, observer.values().first().config.previousButtonLabel) Assert.assertEquals(View.VISIBLE, observer.values().first().config.nextButtonVisibility) } // Type -> Finish @Test fun shouldReturnNextScreenFinishIfCurrentIsType() { val observer = TestObserver<GetTeamCreationStep.ResponseValue>() mGetTeamCreationNextStep.executeUseCase(GetTeamCreationStep.RequestValues(TeamCreationStep.TYPE)).subscribe(observer) observer.await() observer.assertComplete() Assert.assertEquals(TeamCreationStep.FINISH, observer.values().first().config.nextStep) Assert.assertEquals(false, observer.values().first().config.nextButtonEnabled) Assert.assertEquals(0, observer.values().first().config.nextButtonLabel) Assert.assertEquals(View.INVISIBLE, observer.values().first().config.nextButtonVisibility) Assert.assertEquals(false, observer.values().first().config.previousButtonEnabled) Assert.assertEquals(0, observer.values().first().config.previousButtonLabel) Assert.assertEquals(View.INVISIBLE, observer.values().first().config.previousButtonVisibility) } }
47.462687
127
0.769497
9a58cb9b6ebc9ccd2f865f3f79e9d1e8440571cb
484
rb
Ruby
test/unit/converge/db/table/base_test.rb
azanar/converge
7f18fc2ee9ead1d9df10f9f7fda87c3804614c49
[ "MIT" ]
null
null
null
test/unit/converge/db/table/base_test.rb
azanar/converge
7f18fc2ee9ead1d9df10f9f7fda87c3804614c49
[ "MIT" ]
null
null
null
test/unit/converge/db/table/base_test.rb
azanar/converge
7f18fc2ee9ead1d9df10f9f7fda87c3804614c49
[ "MIT" ]
null
null
null
require File.expand_path('../../../../test_helper', __FILE__) require 'converge/db/table/target' class Converge::DB::Table::BaseTest < Test::Unit::TestCase setup do @mock_model = mock @base = Class.new do include Converge::DB::Table::Base end @table = @base.new(@mock_model) end test '#name' do mock_columns = mock @mock_model.expects(:columns).returns(mock_columns) res = @table.columns assert_equal res, mock_columns end end
19.36
61
0.659091
8da9b9f785de5ecc7c33c40620c477f7e083848d
3,626
js
JavaScript
resources/js/Pages/Dashboard/Services/components/ServicesForm.js
aminlahiani/maccar_technologie
b50d59bfd08cca3247b53fa48279c5932825362c
[ "MIT" ]
null
null
null
resources/js/Pages/Dashboard/Services/components/ServicesForm.js
aminlahiani/maccar_technologie
b50d59bfd08cca3247b53fa48279c5932825362c
[ "MIT" ]
null
null
null
resources/js/Pages/Dashboard/Services/components/ServicesForm.js
aminlahiani/maccar_technologie
b50d59bfd08cca3247b53fa48279c5932825362c
[ "MIT" ]
null
null
null
import React from "react"; import Button from "@/Components/Button"; import Input from "@/Components/Input"; import Label from "@/Components/Label"; import ValidationErrors from "@/Components/ValidationErrors"; import { Link, useForm } from "@inertiajs/inertia-react"; export default function ServicesForm() { const { data, setData, post, processing, errors, reset } = useForm({ name: "", description: "", price: "", }); const onHandleChange = (event) => { setData(event.target.name, event.target.value); }; const submit = (e) => { e.preventDefault(); post(route("services-create")); }; return ( <> <ValidationErrors errors={errors} /> <form onSubmit={submit}> <div className="shadow overflow-hidden sm:rounded-md"> <div className="px-4 py-5 bg-white sm:p-6"> <div className="grid grid-cols-6 gap-6"> <div className="col-span-6 sm:col-span-3"> <Label forInput="name" value="Nom de Service" /> <Input type="text" name="name" value={data.name} className="mt-1 block w-full" autoComplete="name" isFocused={true} handleChange={onHandleChange} required /> </div> <div className="col-span-6 sm:col-span-3"> <Label forInput="price" value="Prix" /> <Input type="number" name="price" value={data.price} className="mt-1 block w-full" autoComplete="username" handleChange={onHandleChange} required /> </div> <div className="col-span-6 sm:col-span-6"> <Label forInput="description" value="Description" /> <Input type="text" name="description" value={data.description} className="mt-1 block w-full" autoComplete="username" handleChange={onHandleChange} required /> </div> </div> <div className="flex items-center justify-end mt-4"> <Button className="ml-4 bg-tahiti-900 hover:bg-tahiti-800 " processing={processing} > creation d'Un Service </Button> </div> </div> </div> </form> </> ); }
38.989247
84
0.351351
38be8d41e1e994fb4af69820e1c52820f796a488
8,947
php
PHP
application/models/Entries_model.php
er-ashish-chauhan/JobManagement
3cb0e6b67ccec1e13fcf8cf25daf89bcb42fc321
[ "MIT" ]
null
null
null
application/models/Entries_model.php
er-ashish-chauhan/JobManagement
3cb0e6b67ccec1e13fcf8cf25daf89bcb42fc321
[ "MIT" ]
null
null
null
application/models/Entries_model.php
er-ashish-chauhan/JobManagement
3cb0e6b67ccec1e13fcf8cf25daf89bcb42fc321
[ "MIT" ]
null
null
null
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Entries_model extends CI_Model { private $table_users; private $table_states; public function __construct() { parent::__construct(); $this->table = 'admin'; $this->table_users = 'users'; $this->table_video = 'videos'; } // get all user details for listing public function entries_list($postData = null) { $response = array(); ## Reading post values $draw = $postData['draw']; $start = $postData['start']; $rowperpage = $postData['length']; // Rows display per page $columnIndex = $postData['order'][0]['column']; // Column index $columnName = $postData['columns'][$columnIndex]['name']; // Column name $columnSortOrder = $postData['order'][0]['dir']; // asc or desc $searchValue = $postData['search']['value']; // Search value ## variable to store data for searching. $searchQuery = ""; if ($searchValue != '') { if ($searchValue == 'Active') { $searchValue = 'Enabled'; } if ($searchValue == 'Inactive') { $searchValue = 'Disabled'; } $searchQuery = " (j.job_name like '%" . $searchValue . "%' or f.firm_name like '%" . $searchValue . "%' or u.firstName like '%" . $searchValue . "%' or u.lastName like '%" . $searchValue . "%') "; } ## Total number of records without filtering $this->db->select('count(*) as allcount'); $this->db->from("jobMeta"); $this->db->where("status", 1); // echo $this->db->last_query(); $query = $this->db->get(); $records = $query->result(); // echo '<pre>'; print_r($records); echo '</pre>'; $totalRecords = $records[0]->allcount; ## Total number of record with filtering $this->db->select('count(*) as allcount'); $this->db->from("jobMeta"); $this->db->where("status", 1); if ($searchQuery != '') { $this->db->where($searchQuery); } $query = $this->db->get(); $records = $query->result(); $totalRecordwithFilter = $records[0]->allcount; ## Fetch records $this->db->select("jobMeta.id, jobMeta.previousSlip, jobMeta.currentSlip,jobMeta.bill, jobMeta.currentSlipNo, jobMeta.firmId, jobMeta.commodityId, jobMeta.entryType, jobMeta.deliveryType, jobMeta.created,commodities.commodity, firm.firm_name, jobMeta.cNetWeight"); $this->db->from("jobMeta"); $this->db->where('jobMeta.status', 1); $this->db->join('firm', 'firm.id = jobMeta.firmId', 'left'); $this->db->join('commodities', 'commodities.id = jobMeta.commodityId', 'left'); if ($searchQuery != '') { $this->db->where($searchQuery); } // if (!empty($columnName)) { // $this->db->order_by($columnName, $columnSortOrder); // } else { $this->db->order_by('jobMeta.id', 'DESC'); // } if ($rowperpage != -1) { $this->db->limit($rowperpage, $start); } $query = $this->db->get(); $records = $query->result(); $data = array(); $i = $start + 1; // loop to iterate and storing data into array accordingly that is going to display. foreach ($records as $record) { $id = $record->id; $actionLinks = "<a href='" . base_url('admin/entries/view_entries?id=') . encode($id) . " ' class='btn btn-sm btn-flat btn-primary' title='View Entry'>View</a>"; $actionLinks .= " <a data-id='" . $id . "' id='showentrymodel' href='javascript:void(0)' class='btn btn-sm btn-flat btn-primary' data-toggle='modal' data-target='#entriesModal ' title='Approve'>Approve</a> "; $actionLinks .= "<a data-id='" . $id . "' id='rejectEntry' href='javascript:void(0)' class='btn btn-sm btn-flat btn-danger' title='Reject'>Reject</a> "; $actionLinks .= "<a href='" . base_url('admin/entries/manage_bargain_detail?id=') . encode($id) . " ' class='btn btn-sm btn-flat btn-primary' title='Edit Bargain' >Make Bargain</a>"; $previousSlip = "<a class='previous_img' data-imageurl='" . str_replace("JobManagement/", "", base_url()) . $record->previousSlip . "' href='javascript:void(0)'><Image alt='Previous Slip' class='entryImage' src='" . str_replace("JobManagement/", "", base_url()) . $record->previousSlip . "' /></a>"; $currentSlip = "<a class='previous_img' data-imageurl='" . str_replace("JobManagement/", "", base_url()) . $record->currentSlip . "' href='javascript:void(0)'><Image alt='Current Slip' class='entryImage' src='" . str_replace("JobManagement/", "", base_url()) . $record->currentSlip . "' /></a>"; $bill = "<a class='previous_img' data-imageurl='" . str_replace("JobManagement/", "", base_url()) . $record->bill . "' href='javascript:void(0)'><Image alt='Bill Slip' class='entryImage' src='" . str_replace("JobManagement/", "", base_url()) . $record->bill . "' /></a>"; $data[] = array( $i++, $actionLinks, $record->firm_name, $record->commodity, $record->currentSlipNo, // $previousSlip, // $currentSlip, // $bill, $record->entryType, $record->deliveryType, $record->cNetWeight, $record->created, ); } ## Response $response = array( "draw" => intval($draw), "iTotalRecords" => $totalRecords, "iTotalDisplayRecords" => $totalRecordwithFilter, "aaData" => $data, "detail" => [$columnName, $columnSortOrder], "detail" => [$columnName, $columnSortOrder], "search_query" => $searchQuery, "last_query" => $this->db->last_query() ); // pr($response,1); return $response; } public function getJobByEntryDetails($entryId) { $this->db->select("job.id as jobId"); $this->db->from("jobMeta"); $this->db->where("jobMeta.id", $entryId); $this->db->join("job", "job.firmId = jobMeta.firmId AND job.commodityId = jobMeta.commodityId", "left"); $result = $this->db->get(); if ($result->num_rows() > 0) { return $result->row(); } else { return null; } } public function getjobById($where) { $this->db->select("*"); $this->db->from("job"); $this->db->where($where); $result = $this->db->get(); if ($result->num_rows() > 0) { return $result->row(); } else { return null; } } public function getEntryById($where) { $this->db->select("*"); $this->db->from("jobMeta"); $this->db->where($where); $result = $this->db->get(); if ($result->num_rows() > 0) { return $result->row(); } else { return null; } } public function updateJob($jobId, $data) { $this->db->where('id', $jobId); $this->db->update('job', $data); $afftectedRow = $this->db->affected_rows(); return $afftectedRow; } public function updatedJobMeta($entryId, $data) { $this->db->where('id', $entryId); $this->db->update('jobMeta', $data); $afftectedRow = $this->db->affected_rows(); return $afftectedRow; } public function insertBargain($data) { $this->db->insert('job', $data); // $afftectedRow = $this->db->affected_rows(); return $this->db->insert_id(); } public function viewEntriesDetail($id) { $this->db->select("jobMeta.*,commodities.commodity, firm.firm_name, jobMeta.cNetWeight"); $this->db->from("jobMeta"); $this->db->where('jobMeta.id', $id); $this->db->join('firm', 'firm.id = jobMeta.firmId', 'left'); $this->db->join('commodities', 'commodities.id = jobMeta.commodityId', 'left'); return $this->db->get()->row(); } public function updateEditEntries($data, $id) { $this->db->where('id', $id); return $this->db->update('jobMeta', $data); } public function add_entries($data) { $this->db->insert('jobMeta', $data); return $this->db->insert_id(); } public function getBrokers() { $this->db->select("*"); $this->db->from("brokers"); $result = $this->db->get(); if ($result->num_rows() > 0) { return $result->result(); } else { return null; } } }
36.81893
208
0.527663
f2167268765ffe76e761cc6761bc607ce690351d
7,801
cpp
C++
src/nnfusion/core/operators/generic_op/generic_op_define/MaxPool.cpp
nox-410/nnfusion
0777e297299c4e7a5071dc2ee97b87adcd22840e
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/operators/generic_op/generic_op_define/MaxPool.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/operators/generic_op/generic_op_define/MaxPool.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "nnfusion/core/operators/generic_op/generic_op.hpp" REGISTER_OP(MaxPool) .infershape(nnfusion::op::infershape::unimplemented_and_not_used) /* .translate([](std::shared_ptr<graph::GNode> curr) -> std::string { auto _op = static_pointer_cast<nnfusion::op::MaxPool>(curr->get_op_ptr()); NNFUSION_CHECK_NOT_NULLPTR(_op) << "Node type is not " << curr->get_op_ptr()->get_op_type(); const auto& kernel = _op->get_window_shape(); const auto& stride = _op->get_window_movement_strides(); const auto& padding_below = _op->get_padding_below(); const auto& padding_above = _op->get_padding_above(); uint64_t padding[] = { padding_below[1], padding_below[0], padding_above[1], padding_above[0]}; return op::create_code_from_template( R"( - input("input0", @input_shape@); output(@output_shape@, topi=topi.nn.pool(args("input0"), kernel=@kernel@, stride=@stride@, padding=@padding@, pool_type="max")); )", {{"input_shape", vector_to_string(curr->get_input_shape(0))}, {"output_shape", vector_to_string(curr->get_output_shape(0))}, {"kernel", vector_to_string(kernel)}, {"stride", vector_to_string(stride)}, {"padding", vector_to_string(padding)}}); }) */ .translate_v2([](std::shared_ptr<graph::GNode> curr) -> std::string { auto _op = static_pointer_cast<nnfusion::op::MaxPool>(curr->get_op_ptr()); auto& input_shape = curr->get_input_shape(0); auto& output_shape = curr->get_output_shape(0); auto& dtype = curr->get_element_type(); bool is_1d = (output_shape.size() == 3); const bool is_nchw = _op->get_data_format() == "NCHW" ? true : false; auto& m_strides = _op->get_window_movement_strides(); auto& strides = _op->get_window_shape(); auto& padding_below = _op->get_padding_below(); auto& padding_above = _op->get_padding_above(); if (!(padding_below.size() == padding_above.size())) { return std::string(); } if (!(padding_below.size() >= 1)) { return std::string(); } if (!is_1d) { if (!(padding_below.size() == 2)) { return std::string(); } } auto expression_template = R"( @output0@@output0_layout@ >=! @input0@@input0_layout@@conditions@; )"; std::string conditions; std::string when_condition; std::string where_condition; auto output_layout = std::vector<std::string>{"N"}; auto input_layout = std::vector<std::string>{"N"}; if (is_nchw) { output_layout.push_back("C"); input_layout.push_back("C"); output_layout.push_back("HO"); input_layout.push_back("HO * " + to_string(m_strides[0]) + " + KH - " + to_string(padding_below[0])); if (padding_below[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] + " >=0"; } if (padding_above[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] + " < " + to_string(input_shape[2]); } where_condition += (where_condition.empty() ? "" : " , ") + output_layout[2] + " in " + to_string(output_shape[2]) + ", KH in " + to_string(strides[0]); if (!is_1d) { output_layout.push_back("WO"); input_layout.push_back("WO * " + to_string(m_strides[1]) + " + KW - " + to_string(padding_below[1])); if (padding_below[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[3] + " >=0"; } if (padding_above[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[3] + " < " + to_string(input_shape[3]); } where_condition += (where_condition.empty() ? "" : " , ") + output_layout[3] + " in " + to_string(output_shape[3]) + ", KW in " + to_string(strides[1]); } } else { output_layout.push_back("HO"); input_layout.push_back("HO * " + to_string(m_strides[0]) + " + KH - " + to_string(padding_below[0])); if (padding_below[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[1] + " >=0"; } if (padding_above[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[1] + " < " + to_string(input_shape[1]); } where_condition += (where_condition.empty() ? "" : " , ") + output_layout[1] + " in " + to_string(output_shape[1]) + ", KH in " + to_string(strides[0]); if (!is_1d) { output_layout.push_back("WO"); input_layout.push_back("WO * " + to_string(m_strides[1]) + " + KW - " + to_string(padding_below[1])); if (padding_below[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] + " >=0"; } if (padding_above[0] > 0) { when_condition += (when_condition.empty() ? "" : " , ") + input_layout[2] + " < " + to_string(input_shape[2]); } where_condition += (where_condition.empty() ? "" : " , ") + output_layout[2] + " in " + to_string(output_shape[2]) + ", KW in " + to_string(strides[1]); } output_layout.push_back("C"); input_layout.push_back("C"); } if (!when_condition.empty()) { std::string min_value; if (dtype == nnfusion::element::f32) { min_value = "-3.4e38"; } else if (dtype == nnfusion::element::f16) { min_value = "-6.55e4"; } else if (dtype == nnfusion::element::i8) { min_value = "-128"; } else { NNFUSION_LOG(INFO) << "not support padding with data type " << dtype << " yet, fallback"; return std::string(); } when_condition = ".when([" + when_condition + "], " + min_value + ")"; } if (!where_condition.empty()) { where_condition = " where " + where_condition; } conditions = when_condition + where_condition; op::OpConfig::any config; config["conditions"] = conditions; config["output0_layout"] = vector_to_string<std::vector<std::string>>(output_layout); config["input0_layout"] = vector_to_string<std::vector<std::string>>(input_layout); auto expression_code = op::create_code_from_template(expression_template, config); return expression_code; });
43.099448
182
0.483912
a42a84dcec57347bf5c1bacad673db2f488aeab8
446
php
PHP
resources/views/layouts/_footer.blade.php
MonsterEdward/larabbs
149be43565218a92f3e47b54e7eefb12394c2d61
[ "MIT" ]
null
null
null
resources/views/layouts/_footer.blade.php
MonsterEdward/larabbs
149be43565218a92f3e47b54e7eefb12394c2d61
[ "MIT" ]
null
null
null
resources/views/layouts/_footer.blade.php
MonsterEdward/larabbs
149be43565218a92f3e47b54e7eefb12394c2d61
[ "MIT" ]
null
null
null
<footer class="footer"> <div class="container"> <p class="pull-left"> <a href="https://lihuang.monsteredward.com" target="_blank">My try</a> </p> {{--<p class="pull-right"><a href="mailto:edwardvewen@163.com">Contact to me</a></p> --}} <p class="pull-right"><a href="mailto:{{ setting('contact_email') }}">联系我们</a></p> {{-- Administrator自带一个辅助函数setting(), setting($key, $default = '', $setting_name = 'site') --}} </div> </footer>
40.545455
96
0.623318
f42e5118666c0479404782a0ba18c316df9926af
216
cs
C#
POEditor.Net.Shared/Body/TermsListResponse.cs
roju-ai/POEditor.Net
a4de6768f7ad4162cb58e21a3183c805e8d4d181
[ "MIT" ]
null
null
null
POEditor.Net.Shared/Body/TermsListResponse.cs
roju-ai/POEditor.Net
a4de6768f7ad4162cb58e21a3183c805e8d4d181
[ "MIT" ]
null
null
null
POEditor.Net.Shared/Body/TermsListResponse.cs
roju-ai/POEditor.Net
a4de6768f7ad4162cb58e21a3183c805e8d4d181
[ "MIT" ]
null
null
null
using POEditor.Model; using System; using System.Collections.Generic; using System.Text; namespace POEditor.Body { public class TermsListResponse : BaseResponseWithResult<TermsListResponseResult> { } }
18
84
0.773148
02e25c9d7fb909ac840c45dff9a8a2c89b458ed1
703
rs
Rust
testing/jormungandr-scenario-tests/src/programs.rs
eugene-babichenko/jormungandr
75151bdcb77567597e2161dac17656b2a8fcd962
[ "Apache-2.0", "MIT" ]
403
2019-01-10T11:45:16.000Z
2022-03-27T07:23:30.000Z
testing/jormungandr-scenario-tests/src/programs.rs
eugene-babichenko/jormungandr
75151bdcb77567597e2161dac17656b2a8fcd962
[ "Apache-2.0", "MIT" ]
2,186
2019-01-07T14:57:01.000Z
2022-03-31T00:40:26.000Z
testing/jormungandr-scenario-tests/src/programs.rs
eugene-babichenko/jormungandr
75151bdcb77567597e2161dac17656b2a8fcd962
[ "Apache-2.0", "MIT" ]
179
2019-01-10T13:17:08.000Z
2022-02-08T11:31:14.000Z
use std::path::{Path, PathBuf}; use std::process::Command; /// internal function to prepare an executable path name for `jormungandr` and `jcli` /// /// if the program could not be found in the $PATH or the current path then this /// function will panic so the tests are not executed. pub fn prepare_command(exe: impl Into<PathBuf>) -> PathBuf { let exe = exe.into(); check_command_version(&exe); exe } fn check_command_version(exe: &Path) { let mut cmd = Command::new(exe); cmd.arg("--version"); let exit_status = cmd.spawn().unwrap().wait().unwrap(); assert!( exit_status.success(), "cannot execute the command successfully: {:?}", cmd ); }
27.038462
85
0.651494
e1d10d2f53f500f6db24559a07930fa5357c0ac1
60,851
cs
C#
DXInfo.DataTables/Editor.cs
zhenghua75/FairiesMemberManage
aee597086ab1016c406f630ac4edd5c329b248b1
[ "Apache-2.0" ]
null
null
null
DXInfo.DataTables/Editor.cs
zhenghua75/FairiesMemberManage
aee597086ab1016c406f630ac4edd5c329b248b1
[ "Apache-2.0" ]
null
null
null
DXInfo.DataTables/Editor.cs
zhenghua75/FairiesMemberManage
aee597086ab1016c406f630ac4edd5c329b248b1
[ "Apache-2.0" ]
null
null
null
// <copyright>Copyright (c) 2014-2015 SpryMedia Ltd - All Rights Reserved</copyright> // // <summary> // Editor class for reading tables as well as creating, editing and deleting rows // </summary> using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text.RegularExpressions; using System.Reflection; using System.Web; using System.Web.Configuration; using DataTables.EditorUtil; using System.Data; namespace DataTables { /// <summary> /// DataTables Editor base class for creating editable tables. /// /// Editor class instances are capable of servicing all of the requests that /// DataTables and Editor will make from the client-side - specifically: /// /// * Get data /// * Create new record /// * Edit existing record /// * Delete existing records /// /// The Editor instance is configured with information regarding the /// database table fields that you which to make editable, and other information /// needed to read and write to the database (table name for example!). /// /// This documentation is very much focused on describing the API presented /// by these DataTables Editor classes. For a more general overview of how /// the Editor class is used, and how to install Editor on your server, please /// refer to the Editor manual ( https://editor.datatables.net/manual ). /// </summary> public class Editor { /// <summary> /// Version string /// </summary> public const string Version = "1.5.4"; /// <summary> /// Create a new Editor instance /// </summary> /// <param name="db">An instance of the DataTables Database class that we can use for the DB connection. Can also be set with the <code>Db()</code> method.</param> /// <param name="table">The table name in the database to read and write information from and to. Can also be set with the <code>Table()</code> method.</param> /// <param name="pkey">Primary key column name in the table given. Can also be set with the <code>PKey()</code> method.</param> public Editor(Database db = null, string table = null, string pkey = null) { if (db != null) { Db(db); } if (table != null) { Table(table); } if (pkey != null) { Pkey(pkey); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public events */ /// <summary> /// Event which is triggered immediately prior to a row being created. /// Note that for multi-row creation it is triggered for each row /// indivudally. /// </summary> public event EventHandler<PreCreateEventArgs> PreCreate; /// <summary> /// Event which is triggered immediately after a row has been created. /// Note that for multi-row creation it is triggered for each row /// indivudally. /// </summary> public event EventHandler<PostCreateEventArgs> PostCreate; /// <summary> /// Event which is triggered immediately prior to a row being edited. /// Note that for multi-row editing, it is triggered for each row /// individually. /// </summary> public event EventHandler<PreEditEventArgs> PreEdit; /// <summary> /// Event which is triggered immediately after a row being edited. /// Note that for multi-row editing, it is triggered for each row /// individually. /// </summary> public event EventHandler<PostEditEventArgs> PostEdit; /// <summary> /// Event which is triggered immediately prior to a row being deleted. /// Note that for multi-row deletion, it is triggered for each row /// individually. /// </summary> public event EventHandler<PreRemoveEventArgs> PreRemove; /// <summary> /// Event which is triggered immediately after a row being deleted. /// Note that for multi-row deletion, it is triggered for each row /// individually. /// </summary> public event EventHandler<PostRemoveEventArgs> PostRemove; /// <summary> /// /// </summary> public event EventHandler<PreSelectEventArgs> PreSelect; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private parameters */ private Database _db; private readonly List<Field> _field = new List<Field>(); private readonly List<Field> _groupField = new List<Field>(); private string _idPrefix = "row_"; private DtRequest _processData; private Dictionary<string, object> _formData; private Type _userModelT; private string _pkey = "id"; private readonly List<string> _table = new List<string>(); private bool _transaction = true; private readonly List<WhereCondition> _where = new List<WhereCondition>(); private readonly List<LeftJoin> _leftJoin = new List<LeftJoin>(); private readonly DtResponse _out = new DtResponse(); private readonly List<MJoin> _mJoin = new List<MJoin>(); private HttpRequest _request; private readonly Dictionary<string, List<Delegate>> _events = new Dictionary<string, List<Delegate>>(); private bool _tryCatch = true; private int _userId = 1; private bool _isBatch = true; private bool _isLocator = true; private bool _isShelfLife = true; private bool _scrapVouchVerify = true; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods */ /// <summary> /// Get the response object that has been created by this instance. This /// is only useful after <code>process()</code> has been called. /// </summary> /// <returns>The response object as populated by this instance</returns> public DtResponse Data() { return _out; } /// <summary> /// Get the database instance used by this instance /// </summary> /// <returns>Database connection instance</returns> public Database Db() { return _db; } /// <summary> /// Set the database connection instance /// </summary> /// <param name="db">Connection instance to set</param> /// <returns>Self for chaining</returns> public Editor Db(Database db) { _db = db; return this; } /// <summary> /// get user id /// </summary> /// <returns></returns> public int UserId() { return _userId; } /// <summary> /// set user id /// </summary> /// <param name="userId"></param> /// <returns></returns> public Editor UserId(int userId) { _userId = userId; return this; } /// <summary> /// 批号 /// </summary> /// <returns></returns> public bool IsBatch() { return _isBatch; } /// <summary> /// 批号 /// </summary> /// <param name="isBatch"></param> /// <returns></returns> public Editor IsBatch(bool isBatch) { _isBatch = isBatch; return this; } /// <summary> /// 货位 /// </summary> /// <returns></returns> public bool IsLocator() { return _isLocator; } /// <summary> /// 货位 /// </summary> /// <param name="isLocator"></param> /// <returns></returns> public Editor IsLocator(bool isLocator) { _isLocator = isLocator; return this; } /// <summary> /// 保质期 /// </summary> /// <returns></returns> public bool IsShelfLife() { return _isShelfLife; } /// <summary> /// 保质期 /// </summary> /// <param name="isShelfLife"></param> /// <returns></returns> public Editor IsShelfLife(bool isShelfLife) { _isShelfLife = isShelfLife; return this; } /// <summary> /// 获取不合格品记录单是否审核 /// </summary> /// <returns></returns> public bool ScrapVouchVerify() { return _scrapVouchVerify; } /// <summary> /// 设置不合格品记录单是否审核 /// </summary> /// <param name="scrapVouchVerify"></param> /// <returns></returns> public Editor ScrapVouchVerify(bool scrapVouchVerify) { _scrapVouchVerify = scrapVouchVerify; return this; } /// <summary> /// Get the fields that have been configured for this instance /// </summary> /// <returns>List of fields</returns> public List<Field> Field() { return _field; } /// <summary> /// Get a field instance that has already been added /// </summary> /// <param name="f">Field name to select</param> /// <returns>Field instance</returns> public Field Field(string f) { for (var i = 0; i < _field.Count(); i++) { if (_field[i].Name() == f) { return _field[i]; } } throw new Exception("Unknown field: " + f); } /// <summary> /// Add a new field to this instance /// </summary> /// <param name="f">New field to add</param> /// <returns>Self for chaining</returns> public Editor Field(Field f) { _field.Add(f); return this; } /// <summary> /// Add multiple fields too this instance /// </summary> /// <param name="fields">Collection of fields to add</param> /// <returns>Self for chaining</returns> public Editor Field(IEnumerable<Field> fields) { foreach (var f in fields) { _field.Add(f); } return this; } /// <summary> /// /// </summary> /// <param name="f"></param> /// <returns></returns> public Editor GroupField(Field f) { _groupField.Add(f); return this; } /// <summary> /// /// </summary> /// <param name="fields"></param> /// <returns></returns> public Editor GroupField(IEnumerable<Field> fields) { foreach (var f in fields) { _groupField.Add(f); } return this; } /// <summary> /// Get the DOM prefix. /// /// Typically primary keys are numeric and this is not a valid ID value in an /// HTML document - is also increases the likelihood of an ID clash if multiple /// tables are used on a single page. As such, a prefix is assigned to the /// primary key value for each row, and this is used as the DOM ID, so Editor /// can track individual rows. /// </summary> /// <returns>DOM prefix</returns> public string IdPrefix() { return _idPrefix; } /// <summary> /// Set the DOM prefix. /// /// Typically primary keys are numeric and this is not a valid ID value in an /// HTML document - is also increases the likelihood of an ID clash if multiple /// tables are used on a single page. As such, a prefix is assigned to the /// primary key value for each row, and this is used as the DOM ID, so Editor /// can track individual rows. /// </summary> /// <param name="prefix">Prefix to set</param> /// <returns>Self for chaining</returns> public Editor IdPrefix(string prefix) { _idPrefix = prefix; return this; } /// <summary> /// Get the data that is being processed by the Editor instance. This is only /// useful once the <code>Process()</code> method has been called, and /// is available for use in validation and formatter methods. /// </summary> /// <returns>Data given to <code>Process()</code></returns> public DtRequest InData() { return _processData; } /// <summary> /// Add a left join condition to the Editor instance, allowing it to operate /// over multiple tables. Multiple <code>leftJoin()</code> calls can be made for a /// single Editor instance to join multiple tables. /// /// A left join is the most common type of join that is used with Editor /// so this method is provided to make its use very easy to configure. Its /// parameters are basically the same as writing an SQL left join statement, /// but in this case Editor will handle the create, update and remove /// requirements of the join for you: /// /// * Create - On create Editor will insert the data into the primary table /// and then into the joined tables - selecting the required data for each /// table. /// * Edit - On edit Editor will update the main table, and then either /// update the existing rows in the joined table that match the join and /// edit conditions, or insert a new row into the joined table if required. /// * Remove - On delete Editor will remove the main row and then loop over /// each of the joined tables and remove the joined data matching the join /// link from the main table. /// /// Please note that when using join tables, Editor requires that you fully /// qualify each field with the field's table name. SQL can result table /// names for ambiguous field names, but for Editor to provide its full CRUD /// options, the table name must also be given. For example the field /// <code>first_name</code> in the table <code>users</code> would be given /// as <code>users.first_name</code>. /// </summary> /// <param name="table">Table name to do a join onto</param> /// <param name="field1">Field from the parent table to use as the join link</param> /// <param name="op">Join condition (`=`, '&lt;`, etc)</param> /// <param name="field2">Field from the child table to use as the join link</param> /// <returns>Self for chaining</returns> public Editor LeftJoin(string table, string field1, string op, string field2) { _leftJoin.Add(new LeftJoin(table, field1, op, field2)); return this; } /// <summary> /// /// </summary> /// <param name="table"></param> /// <param name="condition"></param> /// <returns></returns> public Editor LeftJoin(string table,string condition) { _leftJoin.Add(new LeftJoin(table, condition)); return this; } /// <summary> /// Add a 1-to-many ("mjoin") join to the Editor instance. The way the /// join operates is defined by the MJoin class /// </summary> /// <param name="join">MJoin link to use</param> /// <returns>Self for chaining</returns> public Editor MJoin(MJoin join) { _mJoin.Add(join); return this; } /// <summary> /// Set a model to use. /// /// In keeping with the MVC style of coding, you can define the fields /// and their types that you wish to get from the database in a simple /// class. Editor will automatically add fields from the model. /// /// Note that fields that are defined in the model can also be defined /// as <code>Field</code> instances should you wish to add additional /// options to a specific field such as formatters or validation. /// </summary> /// <typeparam name="T">Model to use</typeparam> /// <returns>Self for chaining</returns> public Editor Model<T>() { _userModelT = typeof(T); return this; } /// <summary> /// Add an event listener. The `Editor` class will trigger an number of /// events that some action can be taken on. /// </summary> /// <param name="name">Event name</param> /// <param name="callback"> /// Callback function to execute when the event occurs /// </param> /// <returns>Self for chaining</returns> public Editor On(string name, Delegate callback) { if (!_events.ContainsKey(name)) { _events.Add(name, new List<Delegate>()); } _events[name].Add(callback); return this; } /// <summary> /// Get the database table name this Editor instance will use /// </summary> /// <returns>Table name</returns> public List<string> Table() { return _table; } /// <summary> /// Set the database table name this Editor instance will use /// </summary> /// <param name="t">Table name</param> /// <returns>Self for chaining</returns> public Editor Table(string t) { _table.Add(t); return this; } /// <summary> /// Add multiple tables to the Editor instance /// </summary> /// <param name="tables">Collection of tables to add</param> /// <returns>Self for chaining</returns> public Editor Table(IEnumerable<string> tables) { foreach (var t in tables) { _table.Add(t); } return this; } /// <summary> /// Get the transaction state for this instance. /// /// When enabled (which it is by default) Editor will use an SQL transaction /// to ensure data integrity while it is performing operations on the table. /// This can be optionally disabled using this method, if required by your /// database configuration. /// </summary> /// <returns>The current transaction value/state</returns> public bool Transaction() { return _transaction; } /// <summary> /// Set the transaction state for this instance. /// </summary> /// <param name="set">Value to set - true to enable transactions, false to disabled.</param> /// <returns>Editor instance for chaining</returns> public Editor Transaction(bool set) { _transaction = set; return this; } /// <summary> /// Enable (default) / disable the error catching that Editor performs when /// processing the data from the client. When enabled any errors will be presented /// in a format that can be presented to the end user, but it makes debugging /// much more difficult if an error should occur inside the DataTables dll. /// Disabling the try / catch makes it much easier to see exactly where the error /// is occuring. /// </summary> /// <param name="set">Enable - true, or disable - false</param> /// <returns>Editor instance for chaining</returns> public Editor TryCatch(bool set) { _tryCatch = set; return this; } /// <summary> /// Get the primary key field that has been configured. /// /// The primary key must be known to Editor so it will know which rows are being /// edited / deleted upon those actions. The default value is 'id'. /// </summary> /// <returns>Primary key</returns> public string Pkey() { return _pkey; } /// <summary> /// Set the primary key field to use. Please note that at this time /// Editor does not support composite primary keys in a table, only a /// single field primary key is supported. /// /// The primary key must be known to Editor so it will know which rows are being /// edited / deleted upon those actions. The default value is 'id'. /// </summary> /// <param name="id">Primary key column name</param> /// <returns>Self for chaining</returns> public Editor Pkey(string id) { _pkey = id; return this; } /// <summary> /// Process a request from the Editor client-side to get / set data. /// </summary> /// <param name="data">Data sent from the client-side</param> /// <returns>Self for chaining</returns> public Editor Process(DtRequest data) { if (_tryCatch) { try { _Process(data); } catch (Exception e) { _out.error = e.Message; if (_transaction) { _db.Rollback(); } } } else { _Process(data); } return this; } /// <summary> /// Process a request from the Editor client-side to get / set data. /// For use with WebAPI's 'FormDataCollection' collection /// </summary> /// <param name="data">Data sent from the client-side</param> /// <returns>Self for chaining</returns> public Editor Process(IEnumerable<KeyValuePair<string, string>> data = null) { return Process(new DtRequest(data)); } /// <summary> /// Process a request from the Editor client-side to get / set data. /// For use with MVC's 'Request.Form' collection /// </summary> /// <param name="data">Data sent from the client-side</param> /// <returns>Self for chaining</returns> public Editor Process(NameValueCollection data = null) { var list = new List<KeyValuePair<string, string>>(); if (data != null) { foreach (var key in data.AllKeys) { list.Add(new KeyValuePair<string, string>(key, data[key])); } } return Process(new DtRequest(list)); } /// <summary> /// Get DtRequest /// </summary> /// <param name="request"></param> /// <returns></returns> public DtRequest GetDtRequest(HttpRequest request) { return GetDtRequest(request.Form); } /// <summary> /// Get DtRequest /// </summary> /// <param name="data"></param> /// <returns></returns> public DtRequest GetDtRequest(NameValueCollection data = null) { var list = new List<KeyValuePair<string, string>>(); if (data != null) { foreach (var key in data.AllKeys) { list.Add(new KeyValuePair<string, string>(key, data[key])); } } return new DtRequest(list); } /// <summary> /// Process a request from the Editor client-side to get / set data. /// For use with an HttpRequest object /// </summary> /// <param name="request">Data sent from the client-side</param> /// <returns>Self for chaining</returns> public Editor Process(HttpRequest request) { _request = request; return Process(request.Form); } /// <summary> /// Perform validation on a data set. /// /// Note that validation is performed on data only when the action is /// 'create' or 'edit'. Additionally, validation is performed on the _wire /// data_ - i.e. that which is submitted from the client, without formatting. /// Any formatting required by <code>setFormatter</code> is performed after /// the data from the client has been validated. /// </summary> /// <param name="response">DataTables response object</param> /// <param name="request">DataTables request object</param> /// <returns>`true` if the data is valid, `false` if not.</returns> public bool Validate(DtResponse response, DtRequest request) { // Validation is only performed on create and edit if (request.RequestType != DtRequest.RequestTypes.EditorCreate && request.RequestType != DtRequest.RequestTypes.EditorEdit) { return true; } foreach (var pair in request.Data) { var values = pair.Value as Dictionary<string, object>; foreach (var field in _field) { var validation = field.Validate(values, this, string.IsNullOrEmpty(_idPrefix)?"":pair.Key.Replace(_idPrefix, "")); if (validation != null) { response.fieldErrors.Add(new DtResponse.FieldError { name = field.Name(), status = validation }); } } // MJoin validation foreach (var mjoin in _mJoin) { mjoin.Validate(response, this, values); } } return !response.fieldErrors.Any(); } /// <summary> /// Where condition to add to the query used to get data from the database. /// Multiple conditions can be added if required. /// /// Can be used in two different ways: /// /// * Simple case: `where( field, value, operator )` /// * Complex: `where( fn )` /// /// The simple case is fairly self explanatory, a condition is applied to the /// data that looks like `field operator value` (e.g. `name = 'Allan'`). The /// complex case allows full control over the query conditions by providing a /// closure function that has access to the database Query that Editor is /// using, so you can use the `where()`, `or_where()`, `and_where()` and /// `where_group()` methods as you require. /// /// Please be very careful when using this method! If an edit made by a user /// using Editor removes the row from the where condition, the result is /// undefined (since Editor expects the row to still be available, but the /// condition removes it from the result set). /// </summary> /// <param name="fn">Delegate to execute adding where conditions to the table</param> /// <returns>Self for chaining</returns> public Editor Where(Action<Query> fn) { _where.Add(new WhereCondition { Custom = fn }); return this; } /// <summary> /// Where condition to add to the query used to get data from the database. /// Multiple conditions can be added if required. /// /// Can be used in two different ways: /// /// * Simple case: `where( field, value, operator )` /// * Complex: `where( fn )` /// /// The simple case is fairly self explanatory, a condition is applied to the /// data that looks like `field operator value` (e.g. `name = 'Allan'`). The /// complex case allows full control over the query conditions by providing a /// closure function that has access to the database Query that Editor is /// using, so you can use the `where()`, `or_where()`, `and_where()` and /// `where_group()` methods as you require. /// /// Please be very careful when using this method! If an edit made by a user /// using Editor removes the row from the where condition, the result is /// undefined (since Editor expects the row to still be available, but the /// condition removes it from the result set). /// </summary> /// <param name="key">Database column name to perform the condition on</param> /// <param name="value">Value to use for the condition</param> /// <param name="op">Conditional operator</param> /// <returns>Self for chaining</returns> public Editor Where(string key, object value, string op = "=") { _where.Add(new WhereCondition { Key = key, Value = value, Operator = op }); return this; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Internal methods */ /// <summary> /// Get the request object used for this instance /// </summary> /// <returns>HTTP request object</returns> internal HttpRequest Request() { return _request; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods */ private void _Process(DtRequest data) { _processData = data; _formData = data.Data; if (_transaction) { _db.Transaction(); } _PrepJoin(); _PrepModel(); if (data.RequestType == DtRequest.RequestTypes.DataTablesGet || data.RequestType == DtRequest.RequestTypes.DataTablesSsp) { // DataTable get request _out.Merge(_Get(null, data)); } else if (data.RequestType == DtRequest.RequestTypes.EditorUpload) { // File upload _Upload(data); } else if (data.RequestType == DtRequest.RequestTypes.EditorRemove) { // Remove rows _Remove(data); _FileClean(); } else { // Create or edit // Trigger pre events before validation, so validation could be added foreach (var pair in data.Data) { if (data.RequestType == DtRequest.RequestTypes.EditorCreate) { if (PreCreate != null) { PreCreate(this, new PreCreateEventArgs { Editor = this, Values = pair.Value as Dictionary<string, object> }); } } else { if (PreEdit != null) { PreEdit(this, new PreEditEventArgs { Editor = this, Id = string.IsNullOrEmpty(_idPrefix)?pair.Key:pair.Key.Replace(_idPrefix, ""), Values = pair.Value as Dictionary<string, object> }); } } } // Validate var valid = Validate(_out, data); // Global validation - if you want global validation - do it here // _Out.Error = ""; if (valid) { foreach (var pair in data.Data) { var d = data.RequestType == DtRequest.RequestTypes.EditorCreate ? _Insert(pair.Value as Dictionary<string, object>) : _Update(pair.Key, pair.Value as Dictionary<string, object>); if (d != null) { _out.data.Add(d); } } } _FileClean(); } if (_transaction) { _db.Commit(); } } private void _PrepModel() { // Add fields which are defined in the model, but not in the _Field list if (_userModelT != null) { _FieldFromModel(_userModelT); } } private void _FieldFromModel(Type model, string parent = "") { // Add the properties foreach (var pi in model.GetProperties()) { var field = _FindField(parent + pi.Name, "name"); // If the field doesn't exist yet, create it if (field == null) { field = new Field(parent + pi.Name); Field(field); } // Then assign the information from the model field.Type(pi.PropertyType); if (pi.IsDefined(typeof(EditorTypeErrorAttribute))) { var err = pi.GetCustomAttribute<EditorTypeErrorAttribute>(); field.TypeError(err.Msg); } if (pi.IsDefined(typeof(EditorHttpNameAttribute))) { var name = pi.GetCustomAttribute<EditorHttpNameAttribute>(); field.Name(name.Name); } } // Add any nested classes and their properties var nested = model.GetNestedTypes(BindingFlags.Public | BindingFlags.Instance); foreach (var t in nested) { _FieldFromModel(t, parent + t.Name + "."); } } private DtResponse _Get(object id = null, DtRequest http = null) { if (PreSelect != null) { PreSelect(this, new PreSelectEventArgs { Editor = this, Http = http }); } Query query = _db .Query("select") .Table(_table) .Get(_pkey); // Add all fields that we need to get from the database foreach (var field in _field) { if (field.Apply("get") && field.GetValue() == null && field.DbField()!=_pkey) { query.Get(field.DbField()+" as "+field.Name()); } } _GetGroup(query); _GetWhere(query); _PerformLeftJoin(query); var ssp = _SspQuery(query, http); if (id != null) { query.Where(_pkey, id); } var res = query.Exec(); Dictionary<string, object> row; var dtData = new DtResponse(); while ((row = res.Fetch()) != null) { var inner = new Dictionary<string, object> { { "DT_RowId", _idPrefix + row[_pkey] } }; foreach (var field in _field) { if (field.Apply("get")) { field.Write(inner, row); } } dtData.data.Add(inner); } // Field options foreach (var field in _field) { var opts = field.OptionsExec(_db); if (opts != null) { dtData.options.Add(field.Name(), opts); } } // Row based joins foreach (var mjoin in _mJoin) { mjoin.Data(this, dtData); } // Uploaded files dtData.files = _FileData(); return dtData.Merge(ssp); } private Dictionary<string, object> _Insert(Dictionary<string, object> values) { // Insert the new row var id = _InsertOrUpdate(null, values); // Was the primary key sent? Unusual, but it is possible var pkeyField = _FindField(_pkey, "name"); if (pkeyField != null && pkeyField.Apply("create", values)) { id = pkeyField.Val("set", values); } // Row based joins foreach (var mjoin in _mJoin) { mjoin.Insert(this, id, values); } // Full data set for the created row var row = _Get(id); var rowData = row.data.Any() ? row.data[0] : null; // _Trigger("postCreate", id, values, row); if (PostCreate != null) { PostCreate(this, new PostCreateEventArgs { Editor = this, Values = values, Data = rowData, Id = id }); } return rowData; } private Dictionary<string, object> _Update(string id, Dictionary<string, object> values) { id = string.IsNullOrEmpty(_idPrefix)?id:id.Replace(_idPrefix, ""); // Update or insert the rows for the parent table and the left joined // tables _InsertOrUpdate(id, values); // Row based joins foreach (var mjoin in _mJoin) { mjoin.Update(this, id, values); } // Was the primary key altered as part of the edit? Unusual, but it is // possible var pkeyField = _FindField(_pkey, "name"); var getId = pkeyField != null && pkeyField.Apply("edit", values) ? pkeyField.Val("set", values) : id; // Full data set for the modified row var row = _Get(getId); var rowData = row.data.Any() ? row.data[0] : null; if (PostEdit != null) { PostEdit(this, new PostEditEventArgs { Editor = this, Id = id, Data = rowData, Values = values }); } return rowData; } private void _Remove(DtRequest data) { // Strip the ID prefix that the client-side sends back var ids = new List<string>(); foreach (var pair in data.Data) { var id = pair.Key.Replace(_idPrefix, ""); if (PreRemove != null) { PreRemove(this, new PreRemoveEventArgs { Editor = this, Id = id, Values = pair.Value as Dictionary<string, object> }); } ids.Add(id); } if (!ids.Any()) { throw new Exception("No ids submitted for the delete"); } // Row based joins - remove first as the host row will be removed which is // a dependency foreach (var mjoin in _mJoin) { mjoin.Remove(this, ids); } // Remove from the left join tables for (int i = 0, ien = _leftJoin.Count(); i < ien; i++) { var join = _leftJoin[i]; string parentLink; string childLink; // which side of the join refers to the parent table? if (join.Field1.IndexOf(join.Table) == 0) { parentLink = join.Field2; childLink = join.Field1; } else { parentLink = join.Field1; childLink = join.Field2; } // Only delete on the primary key, since that is what the ids refer // to - otherwise we'd be deleting on random data! if (parentLink == _pkey) { _RemoveTable(join.Table, ids, childLink); } } // Remove from the primary tables for (int i = 0, ien = _table.Count(); i < ien; i++) { _RemoveTable(_table[i], ids); } foreach (var pair in data.Data) { var id = pair.Key.Replace(_idPrefix, ""); if (PostRemove != null) { PostRemove(this, new PostRemoveEventArgs { Editor = this, Id = id, Values = pair.Value as Dictionary<string, object> }); } } } private void _Upload(DtRequest data) { if (_request == null) { throw new Exception("File upload requires that 'Process' be called with an HttpRequest object"); } var field = _FindField(data.UploadField, "name"); var fieldName = ""; if (field == null) { // Perhaps it in a join instance for (var i = 0; i < _mJoin.Count(); i++) { var join = _mJoin[i]; foreach (var joinField in join.Fields()) { var name = join.Name() + "[]." + joinField.Name(); if (name == data.UploadField) { field = joinField; fieldName = name; } } } } else { fieldName = field.Name(); } if (field == null) { throw new Exception("Unknown upload field name submitted"); } var upload = field.Upload(); if (upload == null) { throw new Exception("File uploaded to a field that does not have upload options configured"); } object res = upload.Exec(this); if (res is Boolean && (Boolean)res == false) { _out.fieldErrors.Add(new DtResponse.FieldError { name = fieldName, status = upload.Error() }); } else { _out.files = _FileData(upload.Table()); _out.upload.id = res; } } private Dictionary<string, Dictionary<string, Dictionary<string, object>>> _FileData(string limitTable = null) { var files = new Dictionary<string, Dictionary<string, Dictionary<string, object>>>(); // The fields in this instance _FileDataFields(files, _field, limitTable); // From joined tables foreach (var join in _mJoin) { _FileDataFields(files, join.Fields(), limitTable); } return files; } private void _FileDataFields(IDictionary<string, Dictionary<string, Dictionary<string, object>>> @files, IEnumerable<Field> fields, string limitTable) { foreach (var field in fields) { var upload = field.Upload(); if (upload == null) { continue; } var table = upload.Table(); if (table == null) { continue; } if (limitTable != null && table != limitTable) { continue; } if (files.ContainsKey(table)) { continue; } var fileData = upload.Data(_db); if (fileData != null) { files.Add(table, fileData); } } } private void _FileClean() { foreach (var field in _field) { var upload = field.Upload(); if (upload != null) { upload.DbCleanExec(this, field); } } foreach (var join in _mJoin) { foreach (var field in join.Fields()) { var upload = field.Upload(); if (upload != null) { upload.DbCleanExec(this, field); } } } } private void _RemoveTable(string table, IEnumerable<string> ids, string pkey = null) { if (pkey == null) { pkey = _pkey; } // Check that there is a field which has a set option for this table var count = _field.Count( field => !field.DbField().Contains(".") || ( _Part(field.DbField()) == table && field.Set() != DataTables.Field.SetType.None ) ); if (count > 0) { _db.Query("delete") .Table(table) .OrWhere(pkey, ids) .Exec(); } } private void _PrepJoin() { if (!_leftJoin.Any()) { return; } // Check if the primary key has a table identifier - if not, add one if (!_pkey.Contains('.')) { _pkey = _Alias(_table[0]) + '.' + _pkey; } // Check that all the fields have a table selector, orhterwise, we'd need to // know the structure of the tables, to know which fields belong in // which. This extra requirement on the fields removed that foreach (var field in _field) { var name = field.DbField(); if (name != "''" && !name.Contains('.')) { throw new Exception("Table part of the field '" + name + "' was not found. " + "In Editor instance that use a join, all the fields must have the " + "database table set explicity." ); } } } private Field _FindField(string name, string type) { for (int i = 0, ien = _field.Count(); i < ien; i++) { var field = _field[i]; if (type == "name" && field.Name() == name) { return field; } if (type == "db" && field.DbField() == name) { return field; } } return null; } private void _GetGroup(Query query) { foreach (var groupField in _groupField) { query.Group(groupField.DbField()); } } private void _GetWhere(Query query) { foreach (var where in _where) { if (where.Custom != null) { where.Custom(query); } else { query.Where(where.Key, where.Value, where.Operator,false); } } } private DtResponse _SspQuery(Query query, DtRequest http) { var ssp = new DtResponse(); if (http == null || http.RequestType == DtRequest.RequestTypes.DataTablesGet) { return ssp; } // Add the server-side processing conditions _SspLimit(query, http); _SspSort(query, http); _SspFilter(query, http); // Get the nuber of rows in the result set string dork = _groupField.Count > 0 ? "DISTINCT COUNT(1) OVER() as cnt " : "COUNT( " + _pkey + " ) as cnt"; var setCount = _db .Query("select") .Table(_table) .Get(dork); _GetWhere(setCount); _GetGroup(setCount); _SspFilter(setCount, http); //if (_where.Any()|| _groupField.Count > 0) //{ _PerformLeftJoin(setCount); //} var count1 = setCount.Exec().Fetch(); var setCounted = 0; if (count1 != null) { setCounted = Convert.ToInt32(count1["cnt"]); } // Get the number of rows in the full set var fullCount = _db .Query("select") .Table(_table) .Get(dork); _GetWhere(fullCount); _GetGroup(fullCount); // A left join is only needed if there is a where condition, incase the // conditional items are the ones being joined in if (_where.Any()|| _groupField.Count > 0) { _PerformLeftJoin(fullCount); } var count2 = fullCount.Exec().Fetch(); var fullCounted = 0; if (count2 != null) { fullCounted = Convert.ToInt32(count2["cnt"]); } ssp.recordsTotal = fullCounted; ssp.recordsFiltered = setCounted; ssp.draw = http.Draw; return ssp; } private string _SspField(DtRequest http, int index) { var name = http.Columns[index].Data; var field = _FindField(name, "name"); if (field != null) { if (field.DbField() == "''") { return field.Name(); } return field.DbField(); } // Is it the primary key? if (name == "DT_RowId") { return _pkey; } throw new Exception("Unknown field: " + name + " (index " + index + ")"); } private void _SspSort(Query query, DtRequest http) { for (int i = 0, ien = http.Order.Count(); i < ien; i++) { var order = http.Order[i]; query.Order( _SspField(http, order.Column) + " " + (order.Dir == "asc" ? "asc" : "desc") ); } } private void _SspFilter(Query query, DtRequest http) { // Global search, add a ( ... or ... ) set of filters for each column // in the table (not the fields, just the columns submitted) if (http.Search.Value != "") { query.Where(delegate(Query q) { for (int i = 0, ien = http.Columns.Count(); i < ien; i++) { if (!http.Columns[i].Searchable) { continue; } var field = _SspField(http, i); if (field != null) { q.OrWhere(field, http.Search.Value, "", false); //if (http.Columns[i].Search.NotLike) //{ // q.OrWhere(field, http.Search.Value, "NotLike",false); //} //else //{ // q.OrWhere(field, "%" + http.Search.Value + "%", "like"); //} } } }); } // Column filters for (int i = 0, ien = http.Columns.Count(); i < ien; i++) { var column = http.Columns[i]; var search = column.Search.Value; if (search != "" && column.Searchable) { query.Where(_SspField(http, i), search, "", false); //if (column.Search.NotLike) //{ // query.Where(_SspField(http, i), search, "NotLike",false); //} //else //{ // query.Where(_SspField(http, i), "%" + search + "%", "like"); //} } } } private void _SspLimit(Query query, DtRequest http) { // -1 is "show all" in DataTables, so there would be no limit at that point if (http.Length != -1) { query .Offset(http.Start) .Limit(http.Length); } } private object _InsertOrUpdate(object id, Dictionary<string, object> values) { // Loop over all tables in _Table, doing the insert of update as needed for (int i = 0, ien = _table.Count(); i < ien; i++) { var res = _InsertOrUpdateTable( _table[i], values, id == null ? null : new Dictionary<string, object> { { _pkey, id } } ); // If we don't have an id yet, then the first insert will return // the id we want. if (id == null) { id = res.InsertId(); } } // And for the left join tables as well foreach (var join in _leftJoin) { string parentLink; string childLink; var where = new Dictionary<string, object>(); object whereValue; // Which side of the join refers to the parent table? var joinTable = _Alias(join.Table); var tablePart = _Part(join.Field1); if (_Part(join.Field1, "db") != null) { tablePart = _Part(join.Field1, "db") + "." + tablePart; } if (tablePart == joinTable) { parentLink = join.Field2; childLink = join.Field1; } else { parentLink = join.Field1; childLink = join.Field2; } if (parentLink == _pkey) { whereValue = id; } else { // We need submitted information about the joined data to be // submitted as well as the new value. We first check if the // host field was submitted var field = _FindField(parentLink, "db"); if (field == null || !field.Apply("set", values)) { // If not, then check if the child id was submitted field = _FindField(childLink, "db"); // No data available, so we can't do anything if (field == null || !field.Apply("set", values)) { continue; } } whereValue = field.Val("set", values); } where.Add(_Part(childLink, "field"), whereValue); _InsertOrUpdateTable(join.Table, values, where); } return id; } private Result _InsertOrUpdateTable(string table, Dictionary<string, object> values, Dictionary<string, object> where) { var set = new Dictionary<string, object>(); var action = where == null ? "create" : "edit"; var tableAlias = _Alias(table); foreach (var field in _field) { var tablePart = _Part(field.DbField()); if (_Part(field.DbField(), "db") != null) { tablePart = _Part(field.DbField(), "db") + "." + tablePart; } // Does this field apply to this table (only check when a join is // being used) if (_leftJoin.Any() && tablePart != tableAlias) { continue; } // /Check if this field should be set, based on the options and // submitted data if (!field.Apply(action, values)) { continue; } // Some db's (specifically postgres) don't like having the table // name prefixing the column name. var fieldPart = _Part(field.DbField(), "field"); set.Add(fieldPart, field.Val("set", values)); } // If nothing to do, then do nothing! if (!set.Any()) { return null; } // Insert or update return action == "create" ? _db.Insert(table, set) : _db.Push(table, set, @where); } private void _PerformLeftJoin(Query q) { if (_leftJoin.Count() != 0) { foreach (var join in _leftJoin) { if (join.isCondition) { q.Join(join.Table, join.Condition, "LEFT"); } else { q.Join(join.Table, join.Field1 + " " + join.Operator + " " + join.Field2, "LEFT"); } } } } private string _Alias(string name, string type = "alias") { if (name.IndexOf(" as ", StringComparison.OrdinalIgnoreCase) < 0) { return name; } var a = Regex.Split(name, " as ", RegexOptions.IgnoreCase); return type == "alias" ? a[1] : a[0]; } private string _Part(string name, string type = "table") { string db = null; string table = null; string column = null; if (name.Contains(".")) { var a = name.Split('.'); if (a.Count() == 3) { db = a[0]; table = a[1]; column = a[2]; } else if (a.Count() == 2) { table = a[0]; column = a[1]; } } else { column = name; } switch (type) { case "db": return db; case "table": return table; default: return column; } } } }
32.892432
171
0.46466
e5962ef4a53bc8d4edb691eb6874d8488b682888
1,094
swift
Swift
Sources/App/Config+Setup.swift
vkoskiv/NoMansCanvas
5dca49ea5e396130739d8808a6fa1f118909c02b
[ "MIT" ]
5
2022-02-01T19:48:14.000Z
2022-02-04T11:39:45.000Z
Sources/App/Config+Setup.swift
vkoskiv/NoMansCanvas
5dca49ea5e396130739d8808a6fa1f118909c02b
[ "MIT" ]
1
2022-02-01T17:26:28.000Z
2022-02-01T17:26:28.000Z
Sources/App/Config+Setup.swift
vkoskiv/NoMansCanvas
5dca49ea5e396130739d8808a6fa1f118909c02b
[ "MIT" ]
null
null
null
import FluentProvider import MySQLProvider import Glibc extension Config { public func setup() throws { setbuf(stdout, nil) // allow fuzzy conversions for these types // (add your own types here) Node.fuzzy = [Row.self, JSON.self, Node.self] try setupProviders() try setupPreparations() } /// Configure providers private func setupProviders() throws { try addProvider(FluentProvider.Provider.self) //macOS requires workaround with MAMP: ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock try addProvider(MySQLProvider.Provider.self) } /// Add all models that should have their /// schemas prepared before the app boots private func setupPreparations() throws { preparations.append(Post.self) preparations.append(Tile.self) preparations.append(User.self) preparations.append(UserModify.self) preparations.append(UserModify2.self) preparations.append(WhyDoIKeepForgettingThese.self) preparations.append(TileModify.self) preparations.append(UserModify4.self) } }
30.388889
102
0.714808
da8a14f8e4e72c5b04d4e4b17f6b68f955bee82d
1,454
php
PHP
src/MathInterface.php
autonomous411/php-expressions
4dc7c3a4bb3f335a04cb05b0d41871529cfc9b73
[ "MIT" ]
5
2018-09-12T13:00:41.000Z
2022-02-17T14:02:25.000Z
src/MathInterface.php
autonomous411/php-expressions
4dc7c3a4bb3f335a04cb05b0d41871529cfc9b73
[ "MIT" ]
2
2021-02-01T09:04:48.000Z
2021-02-01T10:14:59.000Z
src/MathInterface.php
autonomous411/php-expressions
4dc7c3a4bb3f335a04cb05b0d41871529cfc9b73
[ "MIT" ]
3
2018-09-12T13:10:24.000Z
2020-08-13T13:05:51.000Z
<?php /** * @file */ namespace Xylemical\Expressions; /** * Class MathInterface * * @package Xylemical\Expressions */ interface MathInterface { /** * Add $a to $b. * * @param string $a * @param string $b * @param int $decimals * * @return string */ public function add($a, $b, $decimals = 0); /** * Subtract $b from $a. * * @param string $a * @param string $b * @param int $decimals * * @return string */ public function subtract($a, $b, $decimals = 0); /** * @param string $a * @param string $b * @param int $decimals * * @return string */ public function multiply($a, $b, $decimals = 0); /** * Divide $a by $b. * * @param string $a * @param string $b * @param int $decimals * * @return string */ public function divide($a, $b, $decimals = 0); /** * Get the modulus of $a from $b. * * @param string $a * @param string $b * * @return string */ public function modulus($a, $b); /** * Compare $a to $b. * * @param string $a * @param string $b * @param int $decimals * * @return int */ public function compare($a, $b, $decimals = 0); /** * Gets the PHP native version of the value. * * @return int|float */ public function native($value); }
16.906977
52
0.488996