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
3c58c2923df187536af97da1aad18767aadbfcdf
2,260
lua
Lua
lua/aerial/layout.lua
eddiebergman/aerial.nvim
4ce6499dbf92cdce9460c23e9660cdfcb511f5b9
[ "MIT" ]
null
null
null
lua/aerial/layout.lua
eddiebergman/aerial.nvim
4ce6499dbf92cdce9460c23e9660cdfcb511f5b9
[ "MIT" ]
null
null
null
lua/aerial/layout.lua
eddiebergman/aerial.nvim
4ce6499dbf92cdce9460c23e9660cdfcb511f5b9
[ "MIT" ]
null
null
null
local M = {} local function is_float(value) local _, p = math.modf(value) return p ~= 0 end local function calc_float(value, max_value) if value and is_float(value) then return math.min(max_value, value * max_value) else return value end end local function calc_list(values, max_value, aggregator, limit) local ret = limit if type(values) == "table" then for _, v in ipairs(values) do ret = aggregator(ret, calc_float(v, max_value)) end return ret else ret = aggregator(ret, calc_float(values, max_value)) end return ret end local function calculate_dim(desired_size, size, min_size, max_size, total_size) local ret = calc_float(size, total_size) local min_val = calc_list(min_size, total_size, math.max, 1) local max_val = calc_list(max_size, total_size, math.min, total_size) if not ret then if not desired_size then ret = (min_val + max_val) / 2 else ret = calc_float(desired_size, total_size) end end ret = math.min(ret, max_val) ret = math.max(ret, min_val) return math.floor(ret) end local function get_max_width(relative, winid) if relative == "editor" then return vim.o.columns else return vim.api.nvim_win_get_width(winid or 0) end end local function get_max_height(relative, winid) if relative == "editor" then return vim.o.lines - vim.o.cmdheight else return vim.api.nvim_win_get_height(winid or 0) end end M.calculate_col = function(relative, width, winid) if relative == "cursor" then return 1 else return math.floor((get_max_width(relative, winid) - width) / 2) end end M.calculate_row = function(relative, height, winid) if relative == "cursor" then return 1 else return math.floor((get_max_height(relative, winid) - height) / 2) end end M.calculate_width = function(relative, desired_width, config, winid) return calculate_dim( desired_width, config.width, config.min_width, config.max_width, get_max_width(relative, winid) ) end M.calculate_height = function(relative, desired_height, config, winid) return calculate_dim( desired_height, config.height, config.min_height, config.max_height, get_max_height(relative, winid) ) end return M
23.061224
80
0.708407
86ef49ac7c89b9f589818f073c8d889e413e088e
852
swift
Swift
HappyZoo/HappyZoo/CustomTableViewCell.swift
Donny8028/Swift-Applications
e212d3cafb9b9466ce1a97e3b7d43f2158e7673a
[ "MIT" ]
null
null
null
HappyZoo/HappyZoo/CustomTableViewCell.swift
Donny8028/Swift-Applications
e212d3cafb9b9466ce1a97e3b7d43f2158e7673a
[ "MIT" ]
null
null
null
HappyZoo/HappyZoo/CustomTableViewCell.swift
Donny8028/Swift-Applications
e212d3cafb9b9466ce1a97e3b7d43f2158e7673a
[ "MIT" ]
null
null
null
// // CustomTableViewCell.swift // HappyZoo // // Created by 賢瑭 何 on 2016/6/13. // Copyright © 2016年 Donny. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var thumbnail: UIImageView! @IBOutlet weak var chName: UILabel! @IBOutlet weak var engName: UILabel! var animalImage: UIImage? { didSet{ if let image = animalImage { if let view = thumbnail { view.image = image } } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.780488
63
0.577465
d057c93496238efb2aa1e600d5f0e4f155840a37
1,508
sql
SQL
src/main/resources/data.sql
theFaustus/employee-locator
a9657cf31f1af0cfc0bf61dea08a1c6776b9615d
[ "MIT" ]
null
null
null
src/main/resources/data.sql
theFaustus/employee-locator
a9657cf31f1af0cfc0bf61dea08a1c6776b9615d
[ "MIT" ]
null
null
null
src/main/resources/data.sql
theFaustus/employee-locator
a9657cf31f1af0cfc0bf61dea08a1c6776b9615d
[ "MIT" ]
1
2022-01-28T14:26:49.000Z
2022-01-28T14:26:49.000Z
INSERT INTO public.employees (id, email, first_name, job_position, last_name, password, role, username, country, city, street, geo_processed) VALUES (1,'dtugdar@evil-inc.com','Dorin','MEDIOR','Tugdar','$2a$10UfZidY.e.miCC','USER','dtugdar','USA','Washington','1600 Pennsylvania Ave', false), (2,'iparagam@evil-inc.com','Ion','MEDIOR','Paragam','$2a$10N86mg7oNV8F9r7S5CP4','ADMIN','iparagam','Vatican City','Citta del Vaticano','Saint Martha House', false), (3,'iblorpam@evil-inc.com','Ion','MEDIOR','Blorpam','$2a$10VKVCTepBLVpjY..K','USER','iblorpam','USA','Charlottesville','931 Thomas Jefferson Parkway', false), (4,'adalbam@evil-inc.com','Andrei','SENIOR','Dalbam','$2a$107zmMRnMOHLJBAaKxJePsG5y','USER','adalbam','Netherlands','Amsterdam','Prinsengracht 263', false), (5,'sander.stas@evil-inc.com','Stanislav','SENIOR','Sander','$2a$10CfUdiU3gqs0q0K','USER','ssander','USA','Los Olivos','5225 Figueroa Mountain Road', false), (6,'vdeleban@evil-inc.com','Vladislav','JUNIOR','Deleban','$2a$10ta4IKzVW0UYKTd7z2','USER','vdeleban','UK','London','10 Downing St', false), (7,'vbargus@evil-inc.com','Vladislav','JUNIOR','Bargus','$2a$10w.N1E1HIxoe','USER','vbargus','USA','Hartford','351 Farmington Ave', false), (8,'abafaram@evil-inc.com','Andrei','JUNIOR','Bafaram','$2a$10JcpVzlG.D/K3u','USER','abafaram','USA','Los Angeles','10236 Charing Cross Rd', false), (9,'rmecerco@evil-inc.com','Radu','JUNIOR','Mecerco','$2a$10xxaDSUca5y5mw6e.','USER','rmecerco','UK','Stratford-upon-Avon','Henley Street', false);
150.8
164
0.712865
75a807d8029a9531a0d56ecf9feb3d2bf8aede74
7,095
rs
Rust
crates/starlight/src/heap/precise_allocation.rs
RDambrosio016/starlight
60b8bdc8fa8cb479c3fe66138681f779e3d02701
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
crates/starlight/src/heap/precise_allocation.rs
RDambrosio016/starlight
60b8bdc8fa8cb479c3fe66138681f779e3d02701
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
crates/starlight/src/heap/precise_allocation.rs
RDambrosio016/starlight
60b8bdc8fa8cb479c3fe66138681f779e3d02701
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
use super::{addr::Address, cell::*}; use std::alloc::{alloc, dealloc, Layout}; use std::sync::atomic::{AtomicBool, Ordering}; //intrusive_adapter!(pub PreciseAllocationNode = UnsafeRef<PreciseAllocation> : PreciseAllocation {link: LinkedListLink}); /// Precise allocation used for large objects (>= LARGE_CUTOFF). /// Wafflelink uses GlobalAlloc that already knows what to do for large allocations. The GC shouldn't /// have to think about such things. That's where PreciseAllocation comes in. We will allocate large /// objects directly using malloc, and put the PreciseAllocation header just before them. We can detect /// when a *mut Object is a PreciseAllocation because it will have the ATOM_SIZE / 2 bit set. #[repr(C)] pub struct PreciseAllocation { //pub link: LinkedListLink, /// allocation request size pub cell_size: usize, /// Is this allocation marked by GC? pub is_marked: bool, /// index in precise_allocations pub index_in_space: u32, /// Is alignment adjusted? //pub is_newly_allocated: bool, pub adjusted_alignment: bool, /// Is this even valid allocation? pub has_valid_cell: bool, } impl PreciseAllocation { /// Return atomic reference to `is_marked` pub fn mark_atomic(&self) -> &AtomicBool { unsafe { &*(&self.is_marked as *const bool as *const AtomicBool) } } /// Alignment of allocation. pub const ALIGNMENT: usize = 16; /// Alignment of pointer returned by `Self::cell`. pub const HALF_ALIGNMENT: usize = Self::ALIGNMENT / 2; /// Check if raw_ptr is precisely allocated. pub fn is_precise(raw_ptr: *mut ()) -> bool { (raw_ptr as usize & Self::HALF_ALIGNMENT) != 0 } /// Create PreciseAllocation from pointer pub fn from_cell(ptr: *mut Header) -> *mut Self { unsafe { ptr.cast::<u8>() .offset(-(Self::header_size() as isize)) .cast() } } /// Return base pointer #[inline] pub fn base_pointer(&self) -> *mut () { if self.adjusted_alignment { ((self as *const Self as isize) - (Self::HALF_ALIGNMENT as isize)) as *mut () } else { self as *const Self as *mut () } } /// Set `is_marked` to false pub fn clear_marked(&mut self) { self.is_marked = false; //self.is_marked.store(false, Ordering::Relaxed); } /// Return `is_marked` pub fn is_marked(&self) -> bool { self.mark_atomic().load(Ordering::Relaxed) } /// Test and set marked. Will return true /// if it is already marked. pub fn test_and_set_marked(&self) -> bool { if self.is_marked() { return true; } self.mark_atomic() .compare_exchange(false, true, Ordering::Release, Ordering::Relaxed) .is_ok() } /// Test and set marked without synchronization. pub fn test_and_set_marked_unsync(&mut self) -> bool { if self.is_marked { return true; } self.is_marked = true; false } /// Return cell address, it is always aligned to `Self::HALF_ALIGNMENT`. pub fn cell(&self) -> *mut Header { let addr = Address::from_ptr(self).offset(Self::header_size()); addr.to_mut_ptr() } /// Return true if raw_ptr is above lower bound pub fn above_lower_bound(&self, raw_ptr: *mut ()) -> bool { let ptr = raw_ptr; let begin = self.cell() as *mut (); ptr >= begin } /// Return true if raw_ptr below upper bound pub fn below_upper_bound(&self, raw_ptr: *mut ()) -> bool { let ptr = raw_ptr; let begin = self.cell() as *mut (); let end = (begin as usize + self.cell_size) as *mut (); ptr <= (end as usize + 8) as *mut () } /// Returns header size + required alignment to make cell be aligned to 8. pub const fn header_size() -> usize { ((core::mem::size_of::<PreciseAllocation>() + Self::HALF_ALIGNMENT - 1) & !(Self::HALF_ALIGNMENT - 1)) | Self::HALF_ALIGNMENT } /// Does this allocation contains raw_ptr? pub fn contains(&self, raw_ptr: *mut ()) -> bool { self.above_lower_bound(raw_ptr) && self.below_upper_bound(raw_ptr) } /// Is this allocation live? pub fn is_live(&self) -> bool { self.is_marked() //|| self.is_newly_allocated } /// Clear mark bit pub fn flip(&mut self) { self.clear_marked(); } /// Is this marked? pub fn is_empty(&self) -> bool { !self.is_marked() //&& !self.is_newly_allocated } /// Derop cell if this allocation is not marked. pub fn sweep(&mut self) { if self.has_valid_cell && !self.is_live() { unsafe { let cell = self.cell(); std::ptr::drop_in_place((*cell).get_dyn()); } self.has_valid_cell = false; } } /// Try to create precise allocation (no way that it will return null for now). pub fn try_create(size: usize, index_in_space: u32) -> *mut Self { let adjusted_alignment_allocation_size = Self::header_size() + size + Self::HALF_ALIGNMENT; unsafe { let mut space = alloc( Layout::from_size_align(adjusted_alignment_allocation_size, Self::HALF_ALIGNMENT) .unwrap(), ); //let mut space = libc::malloc(adjusted_alignment_allocation_size); let mut adjusted_alignment = false; if !is_aligned_for_precise_allocation(space) { space = space.add(Self::HALF_ALIGNMENT); adjusted_alignment = true; assert!(is_aligned_for_precise_allocation(space)); } assert!(size != 0); space.cast::<Self>().write(Self { //link: LinkedListLink::new(), adjusted_alignment, is_marked: false, //is_newly_allocated: true, has_valid_cell: true, cell_size: size, index_in_space, }); assert!((&*(&*space.cast::<Self>()).cell()).is_precise_allocation()); space.cast() } } /// return cell size pub fn cell_size(&self) -> usize { self.cell_size } /// Destroy this allocation pub fn destroy(&mut self) { let adjusted_alignment_allocation_size = Self::header_size() + self.cell_size + Self::HALF_ALIGNMENT; let base = self.base_pointer(); unsafe { let cell = self.cell(); core::ptr::drop_in_place((*cell).get_dyn()); dealloc( base.cast(), Layout::from_size_align(adjusted_alignment_allocation_size, Self::ALIGNMENT) .unwrap(), ); } } } /// Check if `mem` is aligned for precise allocation pub fn is_aligned_for_precise_allocation(mem: *mut u8) -> bool { let allocable_ptr = mem as usize; (allocable_ptr & (PreciseAllocation::ALIGNMENT - 1)) == 0 }
37.539683
122
0.58957
9e871dc3c156ce0db9521c55dd5bdd61eb681327
72
sql
SQL
services/hasura/migrations/1630785352979_alter_table_public_dashboards_alter_column_team_id/up.sql
em3ndez/mlcraft
4e42bf8ffeace1b09397e4d1a806cefae6800678
[ "Apache-2.0", "MIT" ]
336
2021-06-20T19:55:43.000Z
2022-03-25T14:15:45.000Z
services/hasura/migrations/1630785352979_alter_table_public_dashboards_alter_column_team_id/up.sql
em3ndez/mlcraft
4e42bf8ffeace1b09397e4d1a806cefae6800678
[ "Apache-2.0", "MIT" ]
13
2021-06-21T13:09:50.000Z
2022-03-07T07:54:58.000Z
services/hasura/migrations/1630785352979_alter_table_public_dashboards_alter_column_team_id/up.sql
em3ndez/mlcraft
4e42bf8ffeace1b09397e4d1a806cefae6800678
[ "Apache-2.0", "MIT" ]
15
2021-06-21T08:41:37.000Z
2022-01-26T12:52:01.000Z
alter table "public"."dashboards" alter column "team_id" drop not null;
36
71
0.763889
743040b45b2ed57c51f5e2390f2106a07a473685
58,789
c
C
VoltammetricBipotentiostatApp_350.c
aidanmurfie/PhD_Thesis
55d5f80149509ab79e3d1871aa6fbc28496898e4
[ "MIT" ]
null
null
null
VoltammetricBipotentiostatApp_350.c
aidanmurfie/PhD_Thesis
55d5f80149509ab79e3d1871aa6fbc28496898e4
[ "MIT" ]
null
null
null
VoltammetricBipotentiostatApp_350.c
aidanmurfie/PhD_Thesis
55d5f80149509ab79e3d1871aa6fbc28496898e4
[ "MIT" ]
null
null
null
/********************************************************************************* Copyright (c) 2014 Analog Devices, Inc. All Rights Reserved. This software is proprietary to Analog Devices, Inc. and its licensors. By using this software you agree to the terms of the associated Analog Devices Software License Agreement. *********************************************************************************/ /***************************************************************************** * @file: AmperometricMeasurement.c * @brief: Amperometric measurement example. *****************************************************************************/ /* Apply ADI MISRA Suppressions */ #define ASSERT_ADI_MISRA_SUPPRESSIONS #include "misra.h" #include <stddef.h> /* for 'NULL' */ #include <stdio.h> #include <string.h> /* for strlen */ #include "test_common.h" #include "afe.h" #include "afe_lib.h" #include "uart.h" #include "spi.h" #include "gpio.h" /* Macro to enable the returning of AFE data using the UART */ /* 1 = return AFE data on UART */ /* 0 = return AFE data on SW (Std Output) */ #define USE_UART_FOR_DATA (1) /* Helper macro for printing strings to UART or Std. Output */ #define PRINT(s) test_print(s) /****************************************************************************/ /* <----------- DURL1 -----------><----------- DURL2 -----------> */ /* <-- DURIVS1 --><-- DURIVS2 --> */ /* _______________________________ <--- VL2 */ /* | */ /* ______________________________| <--- VL1 */ /* */ /* <---- dur1 ----><--- dur2 ---><---- dur3 ----><---- dur4 ----> */ /****************************************************************************/ /* DC Level 1 voltage in mV (range: -0.8V to 0.8V) */ #define VL1 (200) /* DC Level 2 voltage in mV (range: -0.8V to 0.8V) */ #define VL2 (200) /* DC Step Size in mv */ #define VL_STEP (10) /* The duration (in us) of DC Level 1 voltage */ /* #define DURL1 ((uint32_t)(2500000)) */ /* value set to achieve 2 ADC samples 2250 */ #define DURL1 ((uint32_t)(2250)) /* The duration (in us) of DC Level 2 voltage */ /* #define DURL2 ((uint32_t)(2500000)) */ /* value set to achieve 2 ADC samples */ #define DURL2 ((uint32_t)(2250)) /* The duration (in us) which the IVS switch should remain closed (to shunt */ /* switching current) before changing the DC level. */ #define DURIVS1 ((uint32_t)(100)) /* The duration (in us) which the IVS switch should remain closed (to shunt */ /* switching current) after changing the DC level. */ #define DURIVS2 ((uint32_t)(100)) /* Is shunting of the switching current required? Required: 1, Not required: 0 */ #define SHUNTREQD (1) /* RCAL value, in ohms */ /* Default value on ADuCM350 Switch Mux Config Board Rev.0 is 1k */ #define RCAL (998000) /* RTIA value, in ohms */ /* Default value on ADuCM350 Switch Mux Config Board Rev.0 is 7.5k */ #define RTIA (10000000) /* DO NOT EDIT: DAC LSB size in mV, before attenuator (1.6V / (2^12 - 1))(0.39072) */ #define DAC_LSB_SIZE (0.39072) /* DO NOT EDIT: DC Level 1 in DAC codes */ #define DACL1 ((uint32_t)(((float)VL1 / (float)DAC_LSB_SIZE) + 0x800)) /* DO NOT EDIT: DC Level 2 in DAC codes */ #define DACL2 ((uint32_t)(((float)VL2 / (float)DAC_LSB_SIZE) + 0x800)) /* DAC_STEP */ #define DAC_STEP ((uint32_t)(((float)VL_STEP / (float)DAC_LSB_SIZE))) /* DO NOT EDIT: Number of samples to be transferred by DMA, based on the duration of */ /* the sequence. */ /* SAMPLE_COUNT = (Level 1 Duration + Level 2 Duration)us * (160k/178)samples/s */ /*#define SAMPLE_COUNT (uint32_t)((2 * (DURL1 + DURL2)) / 2225) */ #define SAMPLE_COUNT (uint32_t)(1) /* Size limit for each DMA transfer (max 1024) */ #define DMA_BUFFER_SIZE ( 300u) /* DO NOT EDIT: Maximum printed message length. Used for printing only. */ #define MSG_MAXLEN (50) #pragma location="volatile_ram" uint16_t dmaBuffer[DMA_BUFFER_SIZE * 2]; /* Sequence for Amperometric measurement */ uint32_t seq_afe_ampmeas_we8[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - **AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF** = 0 (do not bypass) */ 0x86006678, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ //0x00003200, /* 8 - Wait: 0.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000000, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ //0x00090880, /* 12 - Wait: 37ms for LPF settling */ //0x00080E80, /* 12 - Wait: 33ms for LPF settling (It just works to this point) */ 0x00090880, /* 12 - Wait: 37ms for LPF settling (It just works to this point) */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86016678, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x00000000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86006678, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; /* Sequence for Amperometric measurement */ uint32_t seq_afe_ampmeas_we7[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - **AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF** = 0 (do not bypass) */ 0x86005578, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ //0x00003200, /* 8 - Wait: 0.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000000, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ //0x00090880, /* 12 - Wait: 37ms for LPF settling */ //0x00080E80, /* 12 - Wait: 33ms for LPF settling (It just works to this point) */ 0x00090880, /* 12 - Wait: 37ms for LPF settling (It just works to this point) */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86015578, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x00000000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86005578, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; /* Sequence for Amperometric measurement */ uint32_t seq_afe_ampmeas_we6[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - **AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF** = 0 (do not bypass) */ 0x86004478, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ //0x00003200, /* 8 - Wait: 0.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000000, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ //0x00090880, /* 12 - Wait: 37ms for LPF settling */ //0x00080E80, /* 12 - Wait: 33ms for LPF settling (It just works to this point) */ 0x00090880, /* 12 - Wait: 37ms for LPF settling (It just works to this point) */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86014478, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x00000000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86004478, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; /* Sequence for Amperometric measurement */ uint32_t seq_afe_ampmeas_we5[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - **AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF** = 0 (do not bypass) */ 0x86003378, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ //0x00003200, /* 8 - Wait: 0.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000000, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ //0x00090880, /* 12 - Wait: 37ms for LPF settling */ //0x00080E80, /* 12 - Wait: 33ms for LPF settling (It just works to this point) */ 0x00090880, /* 12 - Wait: 37ms for LPF settling (It just works to this point) */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86013378, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x00000000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86003378, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; /* Sequence for Amperometric measurement */ uint32_t seq_afe_ampmeas_we4[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - **AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF** = 0 (do not bypass) */ 0x86002278, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ //0x00003200, /* 8 - Wait: 0.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000000, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ //0x00090880, /* 12 - Wait: 37ms for LPF settling */ //0x00080E80, /* 12 - Wait: 33ms for LPF settling (It just works to this point) */ 0x00090880, /* 12 - Wait: 37ms for LPF settling (It just works to this point) */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86012278, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x00000000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86002278, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; /* Sequence for Amperometric measurement */ uint32_t seq_afe_ampmeas_we3[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - **AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF** = 0 (do not bypass) */ 0x86001178, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ //0x00003200, /* 8 - Wait: 0.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000000, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ //0x00090880, /* 12 - Wait: 37ms for LPF settling */ //0x00080E80, /* 12 - Wait: 33ms for LPF settling (It just works to this point) */ 0x00090880, /* 12 - Wait: 37ms for LPF settling (It just works to this point) */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86011178, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x00000000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86001178, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; //sequence for voltage warm up uint32_t seq_warm_afe_ampmeas[] = { 0x00150065, /* 0 - Safety Word, Command Count = 15, CRC = 0x1C */ 0x84007818, /* 1 - AFE_FIFO_CFG: DATA_FIFO_SOURCE_SEL = 0b11 (LPF) */ 0x8A000030, /* 2 - AFE_WG_CFG: TYPE_SEL = 0b00 */ 0x88000F00, /* 3 - AFE_DAC_CFG: DAC_ATTEN_EN = 0 (disable DAC attenuator) */ 0xAA000800, /* 4 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 1 placeholder, user programmable) */ 0xA0000002, /* 5 - AFE_ADC_CFG: MUX_SEL = 0b00010, GAIN_OFFS_SEL = 0b00 (TIA) */ 0xA2000000, /* 6 - AFE_SUPPLY_LPF_CFG: BYPASS_SUPPLY_LPF = 0 (do not bypass) */ 0x86001288, /* 7 - DMUX_STATE = 5, PMUX_STATE = 5, NMUX_STATE = 6, TMUX_STATE = 6 */ 0x0001A900, /* 8 - Wait: 6.8ms (based on load RC = 6.8kOhm * 1uF) */ 0x80024EF0, /* 9 - AFE_CFG: WG_EN = 1 */ 0x00000C80, /* 10 - Wait: 200us */ 0x80034FF0, /* 11 - AFE_CFG: ADC_CONV_EN = 1, SUPPLY_LPF_EN = 1 */ 0x00090880, /* 12 - Wait: 37ms for LPF settling */ 0x00000000, /* 13 - Wait: (DAC Level 1 duration - IVS duration 1) (placeholder, user programmable) */ 0x86011288, /* 14 - IVS_STATE = 1 (close IVS switch, user programmable) */ 0x00000000, /* 15 - Wait: IVS duration 1 (placeholder, user programmable) */ 0xAA000800, /* 16 - AFE_WG_DAC_CODE: DAC_CODE = 0x800 (DAC Level 2 placeholder, user programmable) */ 0x1E1A3000, /* 17 - Wait: IVS duration 2 (placeholder, user programmable) */ 0x86001288, /* 18 - IVS_STATE = 0 (open IVS switch) */ 0x00000000, /* 19 - Wait: (DAC Level 2 duration - IVS duration 2) (placeholder, user programmable) */ 0x80020EF0, /* 20 - AFE_CFG: WAVEGEN_EN = 0, ADC_CONV_EN = 0, SUPPLY_LPF_EN = 0 */ 0x82000002, /* 21 - AFE_SEQ_CFG: SEQ_EN = 0 */ }; /* Variables and functions needed for data output through UART */ ADI_UART_HANDLE hUartDevice = NULL; /* Function prototypes */ void test_print (char *pBuffer); ADI_UART_RESULT_TYPE uart_Init (void); ADI_UART_RESULT_TYPE uart_UnInit (void); extern int32_t adi_initpinmux (void); void RxDmaCB (void *hAfeDevice, uint32_t length, void *pBuffer); //GPIO PINS typedef struct { ADI_GPIO_PORT_TYPE Port; ADI_GPIO_MUX_TYPE Muxing; ADI_GPIO_DATA_TYPE Pins; } PinMap; #define INTERRUPT_ID EINT0_IRQn PinMap Blue = { ADI_GPIO_PORT_4, (ADI_GPIO_P40), (ADI_GPIO_PIN_0) }; PinMap Red = { ADI_GPIO_PORT_4, (ADI_GPIO_P41), (ADI_GPIO_PIN_1) }; PinMap Green = { ADI_GPIO_PORT_4, (ADI_GPIO_P42), (ADI_GPIO_PIN_2) }; /* Size of Tx and Rx buffers */ #define BUFFER_SIZE 27 /* Rx and Tx buffers */ static uint8_t RxBuffer[BUFFER_SIZE]; static uint8_t TxBuffer[BUFFER_SIZE]; //static uint8_t dataBuffer[25]; static uint8_t dataBuffer[27]; int main(void) { ADI_AFE_DEV_HANDLE hAfeDevice; uint32_t dur1; uint32_t dur2; uint32_t dur3; uint32_t dur4; printf("scaic"); /* UART return code */ ADI_UART_RESULT_TYPE uartResult; ADI_UART_INIT_DATA initData; ADI_UART_GENERIC_SETTINGS_TYPE Settings; int16_t rxSize; int16_t txSize; int16_t count = 0; uint32_t SWV_AMP_pkpk = 0; /* Initialize system */ SystemInit(); /* Change the system clock source to HFXTAL and change clock frequency to 16MHz */ /* Requirement for AFE (ACLK) */ SystemTransitionClocks(ADI_SYS_CLOCK_TRIGGER_MEASUREMENT_ON); /* SPLL with 32MHz used, need to divide by 2 */ SetSystemClockDivider(ADI_SYS_CLOCK_UART, 2); /* Test initialization */ test_Init(); //GPIO SETUP if (adi_GPIO_Init()) { FAIL("main: adi_GPIO_Init failed"); } if (adi_GPIO_SetOutputEnable(Blue.Port, Blue.Pins, true)) { FAIL("main: adi_GPIO_SetOutputEnable failed"); } if (adi_GPIO_SetOutputEnable(Red.Port, Red.Pins, true)) { FAIL("main: adi_GPIO_SetOutputEnable failed"); } if (adi_GPIO_SetOutputEnable(Green.Port, Green.Pins, true)) { FAIL("main: adi_GPIO_SetOutputEnable failed"); } /////////////////////GPIO LIGHTS//////////////////////////////////////////////// /* Set outputs high */ if (adi_GPIO_SetHigh(Blue.Port, Blue.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed");} /* Set outputs high */ if (adi_GPIO_SetLow(Red.Port, Red.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed"); } if (adi_GPIO_SetHigh(Green.Port, Green.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed"); } /* initialize static pinmuxing */ adi_initpinmux(); /* Initialize the UART for transferring measurement data out */ if (ADI_UART_SUCCESS != uart_Init()) { FAIL("uart_Init"); } /* Initialize the AFE API */ if (ADI_AFE_SUCCESS != adi_AFE_Init(&hAfeDevice)) { FAIL("Init"); } /* Set RCAL Value */ if (ADI_AFE_SUCCESS != adi_AFE_SetRcal(hAfeDevice, RCAL)) { FAIL("Set RCAL"); } /* Set RTIA Value */ if (ADI_AFE_SUCCESS != adi_AFE_SetRtia(hAfeDevice, RTIA)) { FAIL("Set RTIA"); } /* AFE power up */ if (ADI_AFE_SUCCESS != adi_AFE_PowerUp(hAfeDevice)) { FAIL("PowerUp"); } /* Excitation Channel Power-Up */ if (ADI_AFE_SUCCESS != adi_AFE_ExciteChanPowerUp(hAfeDevice)) { FAIL("ExciteChanCalAtten"); } /* TIA Channel Calibration */ if (ADI_AFE_SUCCESS != adi_AFE_TiaChanCal(hAfeDevice)) { FAIL("TiaChanCal"); } /* Excitation Channel (no attenuation) Calibration */ if (ADI_AFE_SUCCESS != adi_AFE_ExciteChanCalNoAtten(hAfeDevice)) { FAIL("adi_AFE_ExciteChanCalNoAtten"); } /* Amperometric Measurement */ /* Set the user programmable portions of the sequence */ /* Set the duration values */ if (SHUNTREQD) { dur1 = DURL1 - DURIVS1; dur2 = DURIVS1; dur3 = DURIVS2; dur4 = DURL2 - DURIVS2; } else { dur1 = DURL1; dur2 = 0; dur3 = 0; dur4 = DURL2; } /////////////////////////////////////WARM UP VOLTAGE SETTINGS////////////////////////////////////////////////////// // define duration of warm up voltage in microseconds uint32_t durw =2000000 - 46450; /* Set duration of warm up voltage */ seq_warm_afe_ampmeas[19] = durw * 16; // define and set warmup voltage float VLwarm = -200; uint32_t DACLwarm= ((uint32_t)(((float)VLwarm / (float)DAC_LSB_SIZE) + 0x800)); seq_warm_afe_ampmeas[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACLwarm); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////scan rate calculations///////////////////////////////////////////////////////////////////// uint32_t scan_r = 100; uint32_t delay_sr = 0; //printf("Enter CV Scan rate"); //scanf("%u" , &scan_r); //setting scan rate delay in microseconds delay_sr = (uint32_t)(((9.8765432/scan_r)-0.0485)*1000000); seq_afe_ampmeas_we3[10] = delay_sr * 16; seq_afe_ampmeas_we4[10] = delay_sr * 16; seq_afe_ampmeas_we5[10] = delay_sr * 16; seq_afe_ampmeas_we6[10] = delay_sr * 16; seq_afe_ampmeas_we7[10] = delay_sr * 16; seq_afe_ampmeas_we8[10] = delay_sr * 16; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Set durations in ACLK periods */ seq_afe_ampmeas_we3[13] = dur1 * 16; seq_afe_ampmeas_we4[13] = dur1 * 16; seq_afe_ampmeas_we5[13] = dur1 * 16; seq_afe_ampmeas_we6[13] = dur1 * 16; seq_afe_ampmeas_we7[13] = dur1 * 16; seq_afe_ampmeas_we8[13] = dur1 * 16; seq_afe_ampmeas_we3[15] = dur2 * 16; seq_afe_ampmeas_we4[15] = dur2 * 16; seq_afe_ampmeas_we5[15] = dur2 * 16; seq_afe_ampmeas_we6[15] = dur2 * 16; seq_afe_ampmeas_we7[15] = dur2 * 16; seq_afe_ampmeas_we8[15] = dur2 * 16; seq_afe_ampmeas_we3[17] = dur3 * 16; seq_afe_ampmeas_we4[17] = dur3 * 16; seq_afe_ampmeas_we5[17] = dur3 * 16; seq_afe_ampmeas_we6[17] = dur3 * 16; seq_afe_ampmeas_we7[17] = dur3 * 16; seq_afe_ampmeas_we8[17] = dur3 * 16; seq_afe_ampmeas_we3[19] = dur4 * 16; seq_afe_ampmeas_we4[19] = dur4 * 16; seq_afe_ampmeas_we5[19] = dur4 * 16; seq_afe_ampmeas_we6[19] = dur4 * 16; seq_afe_ampmeas_we7[19] = dur4 * 16; seq_afe_ampmeas_we8[19] = dur4 * 16; /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL1); seq_afe_ampmeas_we4[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL1); seq_afe_ampmeas_we5[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL1); seq_afe_ampmeas_we6[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL1); seq_afe_ampmeas_we7[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL1); seq_afe_ampmeas_we8[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL1); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL2); seq_afe_ampmeas_we4[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL2); seq_afe_ampmeas_we5[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL2); seq_afe_ampmeas_we6[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL2); seq_afe_ampmeas_we7[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL2); seq_afe_ampmeas_we8[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL2); if (!SHUNTREQD) { /* IVS switch remains open */ seq_afe_ampmeas_we3[14] &= 0xFFFEFFFF; seq_afe_ampmeas_we4[14] &= 0xFFFEFFFF; seq_afe_ampmeas_we5[14] &= 0xFFFEFFFF; seq_afe_ampmeas_we6[14] &= 0xFFFEFFFF; seq_afe_ampmeas_we7[14] &= 0xFFFEFFFF; seq_afe_ampmeas_we8[14] &= 0xFFFEFFFF; } #if (ADI_AFE_CFG_ENABLE_RX_DMA_DUAL_BUFFER_SUPPORT == 1) /* Set the Rx DMA buffer sizes */ if (ADI_AFE_SUCCESS != adi_AFE_SetDmaRxBufferMaxSize(hAfeDevice, DMA_BUFFER_SIZE, DMA_BUFFER_SIZE)) { FAIL("adi_AFE_SetDmaRxBufferMaxSize"); } #endif /* ADI_AFE_CFG_ENABLE_RX_DMA_DUAL_BUFFER_SUPPORT == 1 */ /* Register Rx DMA Callback */ if (ADI_AFE_SUCCESS != adi_AFE_RegisterCallbackOnReceiveDMA(hAfeDevice, RxDmaCB, 0)) { FAIL("adi_AFE_RegisterCallbackOnReceiveDMA"); } /* Recalculate CRC in software for the amperometric measurement */ adi_AFE_EnableSoftwareCRC(hAfeDevice, true); /* Perform the Amperometric measurement(s) */ //!! Run the WARMUP VOLTAGE /* if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_warm_afe_ampmeas, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); }*/ openSPIH(); ////////////////////////////////user defined values mode/////////////////////////////////////////// uint16_t terminate = 0; //defaults int V_Init = 200; int V_Final = -600; int V_Fin = 600; int no_step = 160; int V_Step = 10; uint32_t V_WE2 = 0; int SWV_AMP = 50; int V_DAC_Water = 0; char chem_test = 'a'; char clean_electrode = 'n'; while (terminate == 0) { ///////////////////////////////test initialisation mode///////////////////////////////////////////// rxSize = 1; txSize = 1; /* Read a character */ uartResult = adi_UART_BufRx(hUartDevice, RxBuffer, &rxSize); if (ADI_UART_SUCCESS != uartResult) { test_Fail("adi_UART_BufRx() failed"); } if(RxBuffer[0] == 'n') { rxSize = 27; txSize = 27; //rxSize = 25; //txSize = 25; //recieve data packet for all 350 configurations uartResult = adi_UART_BufRx(hUartDevice, RxBuffer, &rxSize); if (ADI_UART_SUCCESS != uartResult) { test_Fail("adi_UART_BufRx() failed"); } //////////////////////////////////processing input data////////////////////////////////// //------------------------------test type--------------------------------------// chem_test = RxBuffer[0]; //a is CV //b is SWV //c is GCCV //d is GCSWV //------------------------------Initial Voltage--------------------------------------// //lowest-1.1 //1 is +- int Vdec1 = RxBuffer[2] - '0'; //3 is decimal point int Vpt1 = RxBuffer[4] - '0'; int Vpt2 = RxBuffer[5] - '0'; V_Init = (Vdec1*1000) + (Vpt1*100) + (Vpt2*10); //------------------------------Final Voltage--------------------------------------// //max1.1 //6 is +- Vdec1 = RxBuffer[7] - '0'; //8 is decimal point Vpt1 = RxBuffer[9] - '0'; Vpt2 = RxBuffer[10] - '0'; V_Final = (Vdec1*1000) + (Vpt1*100) + (Vpt2*10); //------------------------------Voltage Steps------------------------------------// //1-100mV int Vdec3 = RxBuffer[11] - '0'; int Vdec2 = RxBuffer[12] - '0'; Vdec1 = RxBuffer[13] - '0'; V_Step = (Vdec3*100) + (Vdec2*10) + Vdec1; //------------------------------Scan Rate--------------------------------------// //max 200 Vdec3 = RxBuffer[14] - '0'; Vdec2 = RxBuffer[15] - '0'; Vdec1 = RxBuffer[16] - '0'; int Scan_Rate = (uint32_t)((Vdec3*100) + (Vdec2*10) + Vdec1); ///////////////VSTEP/10 allows sequence time to change accordingly//////////////// // We recieve a scan rate value from the app for swv :) //------------------------------SWV Amplitude--------------------------------------// //max 200 Vdec3 = RxBuffer[17] - '0'; Vdec2 = RxBuffer[18] - '0'; Vdec1 = RxBuffer[19] - '0'; SWV_AMP = (Vdec3*100) + (Vdec2*10) + Vdec1; SWV_AMP_pkpk = SWV_AMP*2; //------------------------------WE2 Voltage--------------------------------------// //max1.1 //6 is +- Vdec1 = RxBuffer[21] - '0'; //8 is decimal point Vpt1 = RxBuffer[23] - '0'; Vpt2 = RxBuffer[24] - '0'; V_WE2 = (uint32_t)((Vdec1*1000) + (Vpt1*100) + (Vpt2*10)); V_DAC_Water = (float)V_WE2; // RxBuffer[25] is Sweep dir clean_electrode = RxBuffer[26]; //account for negative sign if necessary if (RxBuffer[1] == '-') { V_Init = V_Init*(-1); } if (RxBuffer[6] == '-') { V_Final = V_Final*(-1); } if (RxBuffer[20] == '-') { V_WE2 = 1100 - V_WE2 - V_Init; } else { V_WE2 = 1100 + V_WE2 - V_Init; } // V_WE2 = 200; no_step = 2*((V_Final - V_Init)/V_Step); //uint32_t delay_scanr = (uint32_t)((((V_Step/10)*((9.8765432/Scan_Rate)))-0.0485)*1000000); uint32_t delay_scanr = (uint32_t)(((((2*(V_Final - V_Init))/Scan_Rate)/(no_step+2))-0.0485)*1000000);//mVs (required duration of each voltage point)-(manditory 350 delay at every point) seq_afe_ampmeas_we3[10] = delay_scanr * 16; seq_afe_ampmeas_we4[10] = delay_scanr * 16; seq_afe_ampmeas_we5[10] = delay_scanr * 16; seq_afe_ampmeas_we6[10] = delay_scanr * 16; seq_afe_ampmeas_we7[10] = delay_scanr * 16; seq_afe_ampmeas_we8[10] = delay_scanr * 16; V_Fin = V_Final; // - to make it wrt we instead of actual ce voltage //no need to do this for v final since we just count up from vinit V_Init = V_Init*(-1); V_Final = V_Final*(-1); } ///////////// kills 350////////// else if(RxBuffer[0] == 'e') { terminate = 1; } //////////////////initialise test////////////////////// else if (RxBuffer[0] == ' ') { //////////////////// //gpio lights///////////////////////////////////////////////// if (adi_GPIO_SetHigh(Red.Port, Red.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed"); } if (adi_GPIO_SetLow(Green.Port, Green.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed"); } if (clean_electrode == 'y') //////////////////////////cleans electrode at V-- /////////////////////// { AD5683R_WE2_Voltage(V_WE2); int VL3 = V_Init; int VL4 = V_Init; uint32_t DAC_STEP_loop = ((uint32_t)((V_Step / (float)DAC_LSB_SIZE))); uint32_t DACL5= ((uint32_t)(((float)VL3 / (float)DAC_LSB_SIZE) + 0x800)); uint32_t DACL3= ((uint32_t)(((float)VL4 / (float)DAC_LSB_SIZE) + 0x800)); for (int loop =0; loop <(30); loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } /* Update DAC Level settings */ DACL3 = DACL5; if (loop >(79)) //DACL5 += DAC_STEP_loop; DACL3 = DACL5; else //DACL5 -= DAC_STEP_loop; DACL3 = DACL5; /* Set DAC Level 1 */ seq_afe_ampmeas_we4[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we4[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); } } /* loop the Amperometric measurement */ //float VL3 = -200; //float VL4 = -200; if (chem_test == 'a' || chem_test == 'c') //////////////////////////initialisation phase////////////////////////////////////// { AD5683R_WE2_Voltage(V_WE2); int VL3 = 0; int VL4 = 0; uint32_t DAC_STEP_loop = ((uint32_t)((V_Step / DAC_LSB_SIZE))); uint32_t DACL5= ((uint32_t)(((float)VL3 / (float)DAC_LSB_SIZE) + 0x800)); uint32_t DACL3= ((uint32_t)(((float)VL4 / (float)DAC_LSB_SIZE) + 0x800)); for (int loop =0; loop <(10); loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we4, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } /* Update DAC Level settings */ DACL3 = DACL5; if (loop >(79)) //DACL5 += DAC_STEP_loop; DACL3 = DACL5; else //DACL5 -= DAC_STEP_loop; DACL3 = DACL5; /* Set DAC Level 1 */ seq_afe_ampmeas_we4[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we4[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); } /*End loop*/ ///////////////////////////////CG_CV//////////////////////////////////// if(RxBuffer[25] == 'n') { VL3 = V_Init; VL4 = V_Init; } if(RxBuffer[25] == 'p') { VL3 = V_Final; VL4 = V_Final; //vdacwater user inputted vwe2 V_WE2 = 1100 - V_DAC_Water -V_Fin; } DAC_STEP_loop = ((uint32_t)((V_Step / DAC_LSB_SIZE))); //DACL5= ((uint32_t)(((float)V_Init / (float)DAC_LSB_SIZE) + 0x800)); //DACL3= ((uint32_t)(((float)V_Init / (float)DAC_LSB_SIZE) + 0x800)); DACL5= (uint32_t)((VL3 / DAC_LSB_SIZE) + 0x800); DACL3= (uint32_t)((VL3 / DAC_LSB_SIZE) + 0x800); //Initialise SPI in 350 /*Set WE2 Voltage wrt WE1*/ //uint32_t WE2 = -200; int v = VL3; DACL3= (uint32_t)((v / DAC_LSB_SIZE) + 0x800); /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); AD5683R_WE2_Voltage(1100); for (int loop =0; loop < no_step +1 ; loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } AD5683R_WE2_Voltage(V_WE2); /* Update DAC Level settings */ DACL3 = DACL5; if(RxBuffer[25] == 'n') { if (loop <(no_step/2)) { v -= V_Step; V_WE2 -= (uint32_t)V_Step; } else { v += V_Step; V_WE2 += (uint32_t)V_Step; } } if(RxBuffer[25] == 'p') { if (loop >(no_step/2)) { v -= V_Step; V_WE2 -= (uint32_t)V_Step; } else { v += V_Step; V_WE2 += (uint32_t)V_Step; } } DACL3= (uint32_t)((v / DAC_LSB_SIZE) + 0x800); /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); } /*End loop*/ } /////////////////////////SWV////////////////////////////// else if (chem_test == 'b'|| chem_test == 'd') { AD5683R_WE2_Voltage(1100); float VL3 = 0; float VL4 = 0; uint32_t DAC_STEP_loop = ((uint32_t)((V_Step / (float)DAC_LSB_SIZE))); uint32_t DACL5= ((uint32_t)(((float)VL3 / (float)DAC_LSB_SIZE) + 0x800)); uint32_t DACL3= ((uint32_t)(((float)VL4 / (float)DAC_LSB_SIZE) + 0x800)); for (int loop =0; loop <(10); loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } /* Update DAC Level settings */ DACL3 = DACL5; if (loop >(79)) //DACL5 += DAC_STEP_loop; DACL3 = DACL5; else //DACL5 -= DAC_STEP_loop; DACL3 = DACL5; /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); } /*End loop*/ ///////////////////////////////CG_SWV//////////////////////////////////// int v =0; if(RxBuffer[25] == 'n') { v = V_Init; } if(RxBuffer[25] == 'p') { v = V_Final; //vdacwater user inputted vwe2 V_WE2 = 1100 - V_DAC_Water -V_Fin; } //Initialise SPI in 350 uint32_t DACL7= (uint32_t)(((v+SWV_AMP) / DAC_LSB_SIZE) + 0x800); //nominal voltage - swv amp /*Set WE2 Voltage wrt WE1*/ //uint32_t WE2 = -200; /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL7); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL7); for (int loop =0; loop < (no_step/2) + 1; loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } AD5683R_WE2_Voltage(V_WE2); //uint32_t DACL6= (uint32_t)(((v-(SWV_AMP_pkpk/2)) / DAC_LSB_SIZE) + 0x800); uint32_t DACL6= (uint32_t)((((v-SWV_AMP)) / DAC_LSB_SIZE) + 0x800); /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL6); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL6); if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } if(RxBuffer[25] == 'n') { v -= V_Step; V_WE2 -= V_Step; } if(RxBuffer[25] == 'p') { v += V_Step; V_WE2 += V_Step; } // DACL7= (uint32_t)(((v+(SWV_AMP_pkpk/2)) / DAC_LSB_SIZE) + 0x800); DACL7= (uint32_t)(((v+SWV_AMP) / DAC_LSB_SIZE) + 0x800); /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL7); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL7); } /*End loop*/ } AD5683R_WE2_Voltage(1100); if (chem_test == 'w') //////////////////////////initialisation phase////////////////////////////////////// { AD5683R_WE2_Voltage(V_WE2); float VL3 = 0; float VL4 = 0; uint32_t DAC_STEP_loop = ((uint32_t)((V_Step / (float)DAC_LSB_SIZE))); uint32_t DACL5= ((uint32_t)(((float)VL3 / (float)DAC_LSB_SIZE) + 0x800)); uint32_t DACL3= ((uint32_t)(((float)VL4 / (float)DAC_LSB_SIZE) + 0x800)); for (int loop =0; loop <(10); loop++){ /* Set DAC Level 1 */ seq_afe_ampmeas_we4[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we4[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we4, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } /* Update DAC Level settings */ DACL3 = DACL5; if (loop >(79)) //DACL5 += DAC_STEP_loop; DACL3 = DACL5; else //DACL5 -= DAC_STEP_loop; DACL3 = DACL5; /* Set DAC Level 1 */ seq_afe_ampmeas_we4[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we4[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); } ///////////////////////////////Ians_Water Test//////////////////////////////////// if(RxBuffer[25] == 'n') { VL3 = V_Init; //-0.7 VL4 = V_Init; float V_350 = -1*(V_DAC_Water); //0.4 //float V_350 = -400; uint32_t V_DAC = (1100 -(uint32_t)V_Init) - (uint32_t)V_DAC_Water; DAC_STEP_loop = ((uint32_t)(((float)V_Step / (float)DAC_LSB_SIZE))); //DACL5= ((uint32_t)(((float)V_Init / (float)DAC_LSB_SIZE) + 0x800)); //DACL3= ((uint32_t)(((float)V_Init / (float)DAC_LSB_SIZE) + 0x800)); DACL5= (uint32_t)((V_350 / DAC_LSB_SIZE) + 0x800); DACL3= (uint32_t)((V_350 / DAC_LSB_SIZE) + 0x800); //Initialise SPI in 350 AD5683R_WE2_Voltage(1100); for (float loop =0; loop < no_step + 1; loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } AD5683R_WE2_Voltage(V_DAC); /* Update DAC Level settings */ DACL3 = DACL5; if (loop >((no_step/2)-1)) { V_DAC -= (uint32_t)V_Step; } else { V_DAC += (uint32_t)V_Step; } /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); } /*End loop*/ } //if(RxBuffer[25] == 'p') if(RxBuffer[25] == 'p') { VL3 = V_Init; VL4 = V_Init; float V_350 = -1*(V_DAC_Water); //0.4 uint32_t V_DAC = (1100 +(uint32_t)V_Fin) - (uint32_t)V_DAC_Water; //uint32_t V_DAC = 1900; DAC_STEP_loop = ((uint32_t)(((float)V_Step / (float)DAC_LSB_SIZE))); //DACL5= ((uint32_t)(((float)V_Init / (float)DAC_LSB_SIZE) + 0x800)); //DACL3= ((uint32_t)(((float)V_Init / (float)DAC_LSB_SIZE) + 0x800)); DACL5= (uint32_t)((V_350 / DAC_LSB_SIZE) + 0x800); DACL3= (uint32_t)((V_350 / DAC_LSB_SIZE) + 0x800); //Initialise SPI in 350 AD5683R_WE2_Voltage(1100); for (float loop =0; loop < no_step + 1; loop++){ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hAfeDevice, seq_afe_ampmeas_we3, (uint16_t *) dmaBuffer, SAMPLE_COUNT)) { FAIL("adi_AFE_RunSequence"); } AD5683R_WE2_Voltage(V_DAC); /* Update DAC Level settings */ DACL3 = DACL5; if (loop >((no_step/2)-1)) { V_DAC += (uint32_t)V_Step; // change step orientation } else { V_DAC -= (uint32_t)V_Step; // change step orientation } /* Set DAC Level 1 */ seq_afe_ampmeas_we3[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL3); /* Set DAC Level 2 */ seq_afe_ampmeas_we3[16] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_DAC_CODE, DACL5); } /*End loop*/ } } /////////////////////GPIO LIGHTS//////////////////////////////////////////////// /* Set outputs high */ if (adi_GPIO_SetHigh(Blue.Port, Blue.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed");} /* Set outputs high */ if (adi_GPIO_SetLow(Red.Port, Red.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed"); } if (adi_GPIO_SetHigh(Green.Port, Green.Pins)) { FAIL("Test_GPIO_Polling: adi_GPIO_SetHigh failed"); } } AD5683R_WE2_Voltage(1100); } /* Restore to using default CRC stored with the sequence */ adi_AFE_EnableSoftwareCRC(hAfeDevice, false); /* AFE Power Down */ if (ADI_AFE_SUCCESS != adi_AFE_PowerDown(hAfeDevice)) { FAIL("adi_AFE_PowerDown"); } /* Unregister Rx DMA Callback */ if (ADI_AFE_SUCCESS != adi_AFE_RegisterCallbackOnReceiveDMA(hAfeDevice, NULL, 0)) { FAIL("adi_AFE_RegisterCallbackOnReceiveDMA (unregister)"); } /* Uninitialize the AFE API */ if (ADI_AFE_SUCCESS != adi_AFE_UnInit(hAfeDevice)) { FAIL("adi_AFE_UnInit"); } /* Uninitialize the UART */ adi_UART_UnInit(hUartDevice); PASS(); } /*! * @brief AFE Rx DMA Callback Function. * * @param[in] hAfeDevice Device handle obtained from adi_AFE_Init() * length Number of U16 samples received from the DMA * pBuffer Pointer to the buffer containing the LPF results * * * @details 16-bit results are converted to bytes and transferred using the UART * */ void RxDmaCB(void *hAfeDevice, uint32_t length, void *pBuffer) { #if (1 == USE_UART_FOR_DATA) char msg[MSG_MAXLEN]; uint32_t i; uint16_t *ppBuffer = (uint16_t*)pBuffer; //float current; /* Check if there are samples to be sent */ if (length) { for (i = 0; i < length; i++) { //int jj = 0 ; /**ppBuffer = (*ppBuffer-32768);*/ //current = (float)*ppBuffer; //current = (current - 32768.0); // sprintf(msg, "%f\r\n", current++); sprintf(msg, "%u ", *ppBuffer++); PRINT(msg); //for (jj = 0; jj < 10000; jj++); } } #elif (0 == USE_UART_FOR_DATA) FAIL("Std. Output is too slow for ADC/LPF data. Use UART instead."); #endif /* USE_UART_FOR_DATA */ } /* Helper function for printing a string to UART or Std. Output */ void test_print (char *pBuffer) { #if (1 == USE_UART_FOR_DATA) int16_t size; /* Print to UART */ size = strlen(pBuffer); adi_UART_BufTx(hUartDevice, pBuffer, &size); #elif (0 == USE_UART_FOR_DATA) /* Print to console */ printf(pBuffer); #endif /* USE_UART_FOR_DATA */ } /* Initialize the UART, set the baud rate and enable */ ADI_UART_RESULT_TYPE uart_Init (void) { ADI_UART_RESULT_TYPE result = ADI_UART_SUCCESS; /* Open UART in blocking, non-intrrpt mode by supplying no internal buffs */ if (ADI_UART_SUCCESS != (result = adi_UART_Init(ADI_UART_DEVID_0, &hUartDevice, NULL))) { return result; } /* Set UART baud rate to 115200 */ if (ADI_UART_SUCCESS != (result = adi_UART_SetBaudRate(hUartDevice, ADI_UART_BAUD_9600))) { return result; } /* Enable UART */ if (ADI_UART_SUCCESS != (result = adi_UART_Enable(hUartDevice,true))) { return result; } return result; } /* Uninitialize the UART */ ADI_UART_RESULT_TYPE uart_UnInit (void) { ADI_UART_RESULT_TYPE result = ADI_UART_SUCCESS; /* Uninitialize the UART API */ if (ADI_UART_SUCCESS != (result = adi_UART_UnInit(hUartDevice))) { return result; } return result; }
41.783227
191
0.47878
40b0a1dfb43202165653f8f95ad61ca6a8f8fe82
2,136
py
Python
statsSend/teamCity/teamCityStatisticsSender.py
luigiberrettini/build-deploy-stats
52a0bf5aeb8d2f8ef62e4e836eb0b9874dea500d
[ "MIT" ]
2
2017-07-04T14:30:35.000Z
2017-07-04T16:04:53.000Z
statsSend/teamCity/teamCityStatisticsSender.py
luigiberrettini/build-deploy-stats
52a0bf5aeb8d2f8ef62e4e836eb0b9874dea500d
[ "MIT" ]
null
null
null
statsSend/teamCity/teamCityStatisticsSender.py
luigiberrettini/build-deploy-stats
52a0bf5aeb8d2f8ef62e4e836eb0b9874dea500d
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from dateutil import parser from statsSend.session import Session from statsSend.utils import print_exception from statsSend.urlBuilder import UrlBuilder from statsSend.teamCity.teamCityProject import TeamCityProject class TeamCityStatisticsSender: def __init__(self, settings, reporter): page_size = int(settings['page_size']) url_builder = UrlBuilder(settings['server_url'], settings['api_url_prefix'], '', page_size) headers = { 'Accept': 'application/json'} user = settings['user'] password = settings['password'] self.session_factory = lambda: Session(url_builder, headers, user, password) self.project_id = settings['project_id'] self.since_timestamp = parser.parse(settings['since_timestamp']).strftime('%Y%m%dT%H%M%S%z') self.reporter = reporter async def send(self): if ("report_categories" in dir(self.reporter)): async with self.session_factory() as session: try: project = TeamCityProject(session, self.project_id) categories = [build_configuration.to_category() async for build_configuration in project.retrieve_build_configurations()] self.reporter.report_categories(categories) except Exception as err: print_exception('Error sending categories') async with self.session_factory() as session: try: project = TeamCityProject(session, self.project_id) async for build_configuration in project.retrieve_build_configurations(): async for build_run in build_configuration.retrieve_build_runs_since_timestamp(self.since_timestamp): try: activity = build_run.to_activity() self.reporter.report_activity(activity) except Exception as err: print_exception('Error reporting activity') except Exception as err: print_exception('Error reporting activities')
49.674419
141
0.644195
0a5db0663c34e5537f2666534e394ce3c501400a
1,832
kt
Kotlin
Project/app/src/main/java/org/ionproject/android/common/workers/ProgrammeOfferWorker.kt
i-on-project/android
c18e940a10b9bcc4e3511ca7fa2c647be5db9ff2
[ "Apache-2.0" ]
7
2020-03-05T19:05:27.000Z
2022-01-25T20:28:55.000Z
Project/app/src/main/java/org/ionproject/android/common/workers/ProgrammeOfferWorker.kt
i-on-project/android
c18e940a10b9bcc4e3511ca7fa2c647be5db9ff2
[ "Apache-2.0" ]
54
2020-03-05T19:06:31.000Z
2021-05-24T13:17:26.000Z
Project/app/src/main/java/org/ionproject/android/common/workers/ProgrammeOfferWorker.kt
i-on-project/android
c18e940a10b9bcc4e3511ca7fa2c647be5db9ff2
[ "Apache-2.0" ]
1
2020-09-11T11:57:47.000Z
2020-09-11T11:57:47.000Z
package org.ionproject.android.common.workers import android.content.Context import androidx.work.WorkerParameters import org.ionproject.android.common.IonApplication import org.ionproject.android.common.dto.SirenEntity import org.ionproject.android.programmes.toProgrammeOffer import java.net.URI class ProgrammeOfferWorker( context: Context, params: WorkerParameters ) : NumberedWorker(context, params) { private val programmeOfferDao by lazy(LazyThreadSafetyMode.NONE) { IonApplication.db.programmeOfferDao() } private val ionWebAPI by lazy(LazyThreadSafetyMode.NONE) { IonApplication.ionWebAPI } private val programmeOfferId by lazy(LazyThreadSafetyMode.NONE) { inputData.getInt(PROGRAMME_OFFER_ID_KEY, -1) } private val programmeOfferUri by lazy(LazyThreadSafetyMode.NONE) { inputData.getString(RESOURCE_URI_KEY) ?: "" } override suspend fun job(): Boolean { if (programmeOfferId != -1 && programmeOfferUri != "") { val programmeOfferLocal = programmeOfferDao.getProgrammeOfferById(programmeOfferId) if (programmeOfferLocal != null) { val programmeOfferServer = ionWebAPI.getFromURI(URI(programmeOfferUri), SirenEntity::class.java) .toProgrammeOffer(programmeOfferLocal.courseID) programmeOfferDao.updateProgrammeOffer(programmeOfferServer) if (programmeOfferLocal != programmeOfferServer) { programmeOfferDao.updateProgrammeOffer(programmeOfferServer) } } return true } return false } override suspend fun lastJob() { if (programmeOfferId != -1) programmeOfferDao.deleteProgrammeOfferById(programmeOfferId) } }
35.230769
95
0.68941
f096f12672dc8cc406412f4e784d59f039d3b8f1
4,800
js
JavaScript
flow-types/types/notify_vx.x.x/flow_v0.25.x-/notify.js
goodmind/FlowDefinitelyTyped
9b2bf8af438bf10f6a375f441301109be02ef876
[ "MIT" ]
15
2019-02-09T07:05:17.000Z
2021-04-04T14:30:00.000Z
flow-types/types/notify_vx.x.x/flow_v0.25.x-/notify.js
goodmind/FlowDefinitelyTyped
9b2bf8af438bf10f6a375f441301109be02ef876
[ "MIT" ]
1
2021-05-08T04:00:43.000Z
2021-05-08T04:00:43.000Z
flow-types/types/notify_vx.x.x/flow_v0.25.x-/notify.js
goodmind/FlowDefinitelyTyped
9b2bf8af438bf10f6a375f441301109be02ef876
[ "MIT" ]
4
2019-03-21T14:39:18.000Z
2020-11-04T07:42:28.000Z
declare module "notify" { declare interface Notify$Options { /** * Whether to hide the notification on click. Default is true. */ clickToHide?: boolean; /** * Whether to auto-hide the notification (after autoHideDelay milliseconds). Default is true. */ autoHide?: boolean; /** * If autoHide, hide after milliseconds. Default is 5000. */ autoHideDelay?: number; /** * Show the arrow pointing at the element. Default is true. */ arrowShow?: boolean; /** * Arrow size in pixels. Default is 5. */ arrowSize?: number; /** * Position of the notification when created relative to an element. Default is 'bottom left'. */ elementPosition?: string; /** * Position of the notification when created globally. Default is 'top right'. */ globalPosition?: string; /** * Style of the notification. Default is 'bootstrap'. * * For more information on styles, refer to Notify.StyleDefinition. */ style?: string; /** * Class of the notification (string or [string]). Default is 'error'. * * Notify looks through the classes defined in the given style and will apply the CSS * attributes of that style. Additionally, a CSS class of "notifyjs-<style name>-<class name>" * will be applied. */ className?: string; /** * Animation when notification is shown. Default is 'slideDown'. */ showAnimation?: string; /** * Duration show animation, in milliseconds. Default is 400. */ showDuration?: number; /** * Animation when notification is hidden. Default is 'slideUp'. */ hideAnimation?: string; /** * Duration for hide animation, in milliseconds. Default is 200. */ hideDuration?: number; /** * Padding in px between element and notification. Deafult is 2. */ gap?: number; } /** * Notifications created with a specified class will have CSS properties applied to that * notification. This interface defines what properties and their values to apply for a given class. * Keys should be CSS property names, and values their values. */ declare interface Notify$ClassCSS { [propertyName: string]: string; } declare interface Notify$StyleDefinition { /** * Defines the HTML wrapping the notification. * * If you only have HTML element that you need to modify per notification then you should give * this element an attribute of data-notify-text or data-notify-html. Use data-notify-html if * you wish to display arbitrary HTML inside the notification, otherwise, use data-notify-text * as it is more secure. * For more complex notifications, you may give a value to the data-notify-text/data-notify-html * attribute on an element, such as <div data-notify-html="propertyName"></div>. You may then * pass a javasript Object with a "propertyName" key to the notify method, whose value will be * the text/html that the element is populated with. */ html: string; /** * Defines the available classes in this style. The "base" property will be applied to every * notification with this style. */ classes?: { [className: string]: Notify$ClassCSS, base?: Notify$ClassCSS }; /** * All notifications will have this CSS applied to it. */ css?: string; } declare interface Notify$JQueryStatic { /** * Create a global notification. */ (text: string, className?: string): void; (text: string, options?: Notify$Options): void; (data: any, className?: string): void; (data: any, options?: Notify$Options): void; /** * Create a notification positioned relative to the given element. */ (element: JQuery, text: string, className?: string): void; (element: JQuery, text: string, options?: Notify$Options): void; (element: JQuery, data: any, className?: string): void; (element: JQuery, data: any, options?: Notify$Options): void; /** * Define a style for Notify to use. */ addStyle(styleName: string, styleDefinition: Notify$StyleDefinition): void; /** * Specify the default options for all notifications. */ defaults(options: Notify$Options): void; } declare interface JQueryStatic { notify: Notify$Notify$JQueryStatic; } declare interface JQuery { /** * Create a notification positioned relative to the currently selected element. */ notify(text: string, className?: string): void; notify(text: string, options?: Notify$Notify$Options): void; notify(data: any, className?: string): void; notify(data: any, options?: Notify$Notify$Options): void; } }
30.188679
102
0.647083
27eadd147dcbff915d66cd6d1d6039977ffc4963
6,771
swift
Swift
test/Sema/availability_refinement_contexts.swift
goingreen/swift
13966657128f4b3e663a9085ea7be5de93cdaa96
[ "Apache-2.0" ]
null
null
null
test/Sema/availability_refinement_contexts.swift
goingreen/swift
13966657128f4b3e663a9085ea7be5de93cdaa96
[ "Apache-2.0" ]
null
null
null
test/Sema/availability_refinement_contexts.swift
goingreen/swift
13966657128f4b3e663a9085ea7be5de93cdaa96
[ "Apache-2.0" ]
null
null
null
// RUN: %target-swift-frontend -typecheck -dump-type-refinement-contexts %s > %t.dump 2>&1 // RUN: %FileCheck --strict-whitespace %s < %t.dump // REQUIRES: OS=macosx // CHECK: {{^}}(root versions=[10.{{[0-9]+}}.0,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=SomeClass // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someMethod() // CHECK-NEXT: {{^}} (decl versions=[10.53,+Inf) decl=someInnerFunc() // CHECK-NEXT: {{^}} (decl versions=[10.53,+Inf) decl=InnerClass // CHECK-NEXT: {{^}} (decl versions=[10.54,+Inf) decl=innerClassMethod // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someStaticProperty // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someComputedProperty // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someOtherMethod() @available(OSX 10.51, *) class SomeClass { @available(OSX 10.52, *) func someMethod() { @available(OSX 10.53, *) func someInnerFunc() { } @available(OSX 10.53, *) class InnerClass { @available(OSX 10.54, *) func innerClassMethod() { } } } func someUnrefinedMethod() { } @available(OSX 10.52, *) static var someStaticProperty: Int = 7 @available(OSX 10.52, *) var someComputedProperty: Int { get { } set(v) { } } @available(OSX 10.52, *) func someOtherMethod() { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=someFunction() @available(OSX 10.51, *) func someFunction() { } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=SomeProtocol // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=protoMethod() // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=protoProperty @available(OSX 10.51, *) protocol SomeProtocol { @available(OSX 10.52, *) func protoMethod() -> Int @available(OSX 10.52, *) var protoProperty: Int { get } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=extension.SomeClass // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someExtensionFunction() @available(OSX 10.51, *) extension SomeClass { @available(OSX 10.52, *) func someExtensionFunction() { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithStmtCondition // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.54,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.54,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.55,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.55,+Inf) decl=funcInGuardElse() // CHECK-NEXT: {{^}} (guard_fallthrough versions=[10.55,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.56,+Inf) // CHECK-NEXT: {{^}} (guard_fallthrough versions=[10.56,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.57,+Inf) decl=funcInInnerIfElse() @available(OSX 10.51, *) func functionWithStmtCondition() { if #available(OSX 10.52, *), let x = (nil as Int?), #available(OSX 10.53, *) { if #available(OSX 10.54, *) { guard #available(OSX 10.55, *) else { @available(OSX 10.55, *) func funcInGuardElse() { } } guard #available(OSX 10.56, *) else { } } else { @available(OSX 10.57, *) func funcInInnerIfElse() { } } } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithUnnecessaryStmtCondition // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.54,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.54,+Inf) @available(OSX 10.51, *) func functionWithUnnecessaryStmtCondition() { // Shouldn't introduce refinement context for then branch when unnecessary if #available(OSX 10.51, *) { } if #available(OSX 10.9, *) { } // Nested in conjunctive statement condition if #available(OSX 10.53, *), let x = (nil as Int?), #available(OSX 10.52, *) { } if #available(OSX 10.54, *), #available(OSX 10.54, *) { } // Wildcard is same as minimum deployment target if #available(iOS 7.0, *) { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithUnnecessaryStmtConditionsHavingElseBranch // CHECK-NEXT: {{^}} (if_else versions=empty // CHECK-NEXT: {{^}} (decl versions=empty decl=funcInInnerIfElse() // CHECK-NEXT: {{^}} (if_else versions=empty // CHECK-NEXT: {{^}} (guard_else versions=empty // CHECK-NEXT: {{^}} (guard_else versions=empty // CHECK-NEXT: {{^}} (if_else versions=empty @available(OSX 10.51, *) func functionWithUnnecessaryStmtConditionsHavingElseBranch(p: Int?) { // Else branch context version is bottom when check is unnecessary if #available(OSX 10.51, *) { } else { if #available(OSX 10.52, *) { } @available(OSX 10.52, *) func funcInInnerIfElse() { } if #available(iOS 7.0, *) { } else { } } if #available(iOS 7.0, *) { } else { } guard #available(iOS 8.0, *) else { } // Else branch will execute if p is nil, so it is not dead. if #available(iOS 7.0, *), let x = p { } else { } if #available(iOS 7.0, *), let x = p, #available(iOS 7.0, *) { } else { } // Else branch is dead guard #available(iOS 7.0, *), #available(iOS 8.0, *) else { } if #available(OSX 10.51, *), #available(OSX 10.51, *) { } else { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithWhile() // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (while_body versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.54,+Inf) decl=funcInWhileBody() @available(OSX 10.51, *) func functionWithWhile() { while #available(OSX 10.52, *), let x = (nil as Int?) { @available(OSX 10.54, *) func funcInWhileBody() { } } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=SomeEnum // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=availableOn1052 // CHECK-NEXT: {{^}} (decl versions=[10.53,+Inf) decl=availableOn1053 // CHECK-NEXT: {{^}} (case_body versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (case_body versions=[10.53,+Inf) @available(OSX 10.51, *) enum SomeEnum { case unrestricted @available(OSX 10.52, *) case availableOn1052 @available(OSX 10.53, *) case availableOn1053 var availableVersion: Int? { switch self { case .unrestricted: return nil case .availableOn1052: return 1052 case .availableOn1053: return 1053 } } }
30.777273
108
0.615123
1f1e5631cae402414c4ad290ad4887e1c32e8e71
5,208
kts
Kotlin
app/build.gradle.kts
WiMank/Playlist-Export-For-Spotify
8a2b55851849ec639b2dbde64970c4e11a55ec48
[ "Apache-2.0" ]
2
2020-10-10T11:30:52.000Z
2021-02-02T14:16:24.000Z
app/build.gradle.kts
WiMank/Playlist-Export-For-Spotify
8a2b55851849ec639b2dbde64970c4e11a55ec48
[ "Apache-2.0" ]
null
null
null
app/build.gradle.kts
WiMank/Playlist-Export-For-Spotify
8a2b55851849ec639b2dbde64970c4e11a55ec48
[ "Apache-2.0" ]
1
2020-09-13T13:57:57.000Z
2020-09-13T13:57:57.000Z
import com.android.build.gradle.internal.dsl.BuildType import java.io.FileInputStream import java.util.* plugins { id(Plugins.androidApplication) kotlin(Plugins.android) kotlin(Plugins.androidExtensions) kotlin(Plugins.kapt) id(Plugins.hiltPlugin) id(Plugins.safeargsKotlinPlugin) id(Plugins.junit5Plugin) } val secretsPropertiesFile = rootProject.file("secrets.properties") val secretProperties = Properties() if (secretsPropertiesFile.exists()) { secretProperties.load(FileInputStream(secretsPropertiesFile)) } else { secretProperties.setProperty("client_id", System.getenv("client_id")) secretProperties.setProperty("redirect_uri", System.getenv("redirect_uri")) } android { compileSdkVersion(App.compileSdkVersion) buildToolsVersion(App.buildToolsVersion) defaultConfig { applicationId = App.applicationId minSdkVersion(App.minSdkVersion) targetSdkVersion(App.targetSdkVersion) versionCode = App.versionCode versionName = App.versionName testInstrumentationRunner = App.testInstrumentationRunner } buildTypes { getByName("release") { buildClientId() buildRedirectUri() isMinifyEnabled = true isShrinkResources = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } getByName("debug") { buildClientId() buildRedirectUri() isMinifyEnabled = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } kapt { correctErrorTypes = true } buildFeatures { dataBinding = true } } dependencies { implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) implementation(Dependencies.kotlinStdlib) implementation(Dependencies.coreKtx) //Test testImplementation(Dependencies.junit) testImplementation(Dependencies.junitJupiterApi) testRuntimeOnly(Dependencies.junitJupiterEngine) testImplementation(Dependencies.junitJupiterParams) testImplementation(Dependencies.mockk) testImplementation(Dependencies.coroutinesTest) testImplementation(Dependencies.truth) testImplementation(Dependencies.mockWebServer) debugImplementation(Dependencies.fragmentTesting) kaptAndroidTest(Dependencies.hiltAndroidCompiler) //Android test androidTestImplementation(Dependencies.workTesting) androidTestImplementation(Dependencies.androidxJunit) androidTestImplementation(Dependencies.espressoCore) androidTestImplementation(Dependencies.mockkAndroid) androidTestImplementation(Dependencies.daggerHiltTesting) androidTestImplementation(Dependencies.truth) //Activity, Fragment, etc. implementation(Dependencies.appcompat) implementation(Dependencies.constraintlayout) implementation(Dependencies.activityKtx) implementation(Dependencies.fragmentKtx) //Room implementation(Dependencies.room) implementation(Dependencies.roomKtx) kapt(Dependencies.roomCompiler) //Dagger implementation(Dependencies.daggerHilt) kapt(Dependencies.hiltAndroidCompiler) //Dagger Lifecycle implementation(Dependencies.daggerHiltLifecycle) kapt(Dependencies.daggerAndroidxHiltCompiler) //Dagger Work Manager implementation(Dependencies.daggerHiltWork) //Navigation implementation(Dependencies.navigationComponent) implementation(Dependencies.navigationComponentKtx) //ViewModel implementation(Dependencies.viewModelKtx) implementation(Dependencies.lifecycleExtensions) implementation(Dependencies.liveDataKtx) //Coroutines implementation(Dependencies.coroutines) //Moshi implementation(Dependencies.moshi) kapt(Dependencies.moshiCodegen) //Retrofit implementation(Dependencies.retrofit) implementation(Dependencies.retrofitConverterMoshi) //OkHttp implementation(Dependencies.okHttp) implementation(Dependencies.loggingInterceptor) //Glide implementation(Dependencies.glide) kapt(Dependencies.glideCompiler) //Timber implementation(Dependencies.timber) //AppAuth implementation(Dependencies.appAuth) //Shimmer implementation(Dependencies.shimmer) //Work Manager implementation(Dependencies.workManager) //KotlinxHtml implementation(Dependencies.kotlinxHtml) //Material components implementation(Dependencies.material) //ZtZip implementation(Dependencies.ztZip) } fun BuildType.buildClientId() { buildConfigField( "String", "clientId", "\"${secretProperties.getProperty("client_id")}\"" ) } fun BuildType.buildRedirectUri() { buildConfigField( "String", "redirectUri", "\"${secretProperties.getProperty("redirect_uri")}\"" ) }
27.555556
93
0.723118
313f74a853ff3fef83b97d63570c19607fab4487
1,121
swift
Swift
Sources/Networking/NetworkingClient.swift
clementleroy/EQSNetworking
3a48ccc00489e4ab915b82b049d265870f3940a7
[ "MIT" ]
null
null
null
Sources/Networking/NetworkingClient.swift
clementleroy/EQSNetworking
3a48ccc00489e4ab915b82b049d265870f3940a7
[ "MIT" ]
null
null
null
Sources/Networking/NetworkingClient.swift
clementleroy/EQSNetworking
3a48ccc00489e4ab915b82b049d265870f3940a7
[ "MIT" ]
null
null
null
import Foundation import Combine public class NetworkingClient { /** Instead of using the same keypath for every call eg: "collection", this enables to use a default keypath for parsing collections. This is overidden by the per-request keypath if present. */ public var defaultCollectionParsingKeyPath: String? public var baseURL: String public var headers = [String: String]() public var parameterEncoding = ParameterEncoding.urlEncoded /** Prints network calls to the console. Values Available are .None, Calls and CallsAndResponses. Default is None */ public var logLevels: NetworkingLogLevel { get { return logger.logLevels } set { logger.logLevels = newValue } } public var logHandler: NetworkingLogFunction { get { return logger.logHandler } set { logger.logHandler = newValue } } var logger = NetworkingLogger() public init(baseURL: String) { self.baseURL = baseURL } } public typealias NetworkingLogFunction = (_ message: String) -> Void
27.341463
74
0.662801
e2d300d8e4e121b06dc29366489ac410c8633131
120
kt
Kotlin
cortex-console/src/main/kotlin/com/hileco/cortex/console/graphics/TableColumn.kt
SkPhilipp/cortex
5e45e4a3659d4fd7167ae31a58bee7785a869993
[ "MIT" ]
6
2021-11-02T18:28:01.000Z
2022-02-04T11:18:08.000Z
cortex-console/src/main/kotlin/com/hileco/cortex/console/graphics/TableColumn.kt
SkPhilipp/cortex
5e45e4a3659d4fd7167ae31a58bee7785a869993
[ "MIT" ]
null
null
null
cortex-console/src/main/kotlin/com/hileco/cortex/console/graphics/TableColumn.kt
SkPhilipp/cortex
5e45e4a3659d4fd7167ae31a58bee7785a869993
[ "MIT" ]
1
2021-11-02T18:33:11.000Z
2021-11-02T18:33:11.000Z
package com.hileco.cortex.console.graphics data class TableColumn( val title: String, val width: Int )
17.142857
42
0.683333
d9afe57d9052560a17fd4cac6c92b496ea3304fc
1,821
rs
Rust
fenris-solid/tests/unit_tests/gravity_source.rs
Andlon/fenris
297a9e9e09efb1f524cd439c8e88d6248aa500a6
[ "Apache-2.0", "MIT" ]
28
2021-10-08T23:42:25.000Z
2022-03-18T15:50:05.000Z
fenris-solid/tests/unit_tests/gravity_source.rs
Andlon/fenris
297a9e9e09efb1f524cd439c8e88d6248aa500a6
[ "Apache-2.0", "MIT" ]
3
2021-11-03T15:20:21.000Z
2021-11-15T15:12:16.000Z
fenris-solid/tests/unit_tests/gravity_source.rs
Andlon/fenris
297a9e9e09efb1f524cd439c8e88d6248aa500a6
[ "Apache-2.0", "MIT" ]
6
2021-11-03T15:09:58.000Z
2022-02-21T17:06:43.000Z
use fenris::assembly::global::{CsrAssembler, VectorAssembler}; use fenris::assembly::local::{Density, ElementMassAssembler, ElementSourceAssemblerBuilder, UniformQuadratureTable}; use fenris::mesh::procedural::create_unit_square_uniform_quad_mesh_2d; use fenris::mesh::QuadMesh2d; use fenris::nalgebra; use fenris::nalgebra::{vector, DVector}; use fenris::quadrature; use fenris_solid::GravitySource; use matrixcompare::assert_matrix_eq; use std::iter::repeat; #[test] fn gravity_source_agrees_with_mass_matrix_vector_product_quad4() { // Test that the gravity force f_g = M g, // where g = [ 0.0, -9.81, 0.0, -9.81, ... ] // (when using the same quadrature rule or otherwise an exact quadrature) let mesh: QuadMesh2d<f64> = create_unit_square_uniform_quad_mesh_2d(4); let quadrature = quadrature::tensor::quadrilateral_gauss(2); let mass_quadrature = UniformQuadratureTable::from_quadrature_and_uniform_data(quadrature, Density(2.0)); let mass_assembler = ElementMassAssembler::with_solution_dim(2) .with_quadrature_table(&mass_quadrature) .with_space(&mesh); let mass_matrix = CsrAssembler::default().assemble(&mass_assembler).unwrap(); let gravity_source = GravitySource::from_acceleration(vector![0.0, -9.81]); let gravity_assembler = ElementSourceAssemblerBuilder::new() .with_source(&gravity_source) .with_quadrature_table(&mass_quadrature) .with_finite_element_space(&mesh) .build(); let f_gravity = VectorAssembler::default() .assemble_vector(&gravity_assembler) .unwrap(); let num_nodes = mesh.vertices().len(); let g = DVector::from_iterator(2 * num_nodes, repeat([0.0, -9.81]).take(num_nodes).flatten()); let mg = mass_matrix * &g; assert_matrix_eq!(f_gravity, mg, comp = float); }
44.414634
116
0.731466
a88a354411ee92ceecd52db21aa75e5c37db8781
3,195
swift
Swift
FZClosureScrollView/Classes/CollectionView/FZCollectionViewManager.swift
FranZhou/FZClosureScrollView
64b0fea766279b6fe7a93b360b29d1bc5e5906a6
[ "MIT" ]
null
null
null
FZClosureScrollView/Classes/CollectionView/FZCollectionViewManager.swift
FranZhou/FZClosureScrollView
64b0fea766279b6fe7a93b360b29d1bc5e5906a6
[ "MIT" ]
null
null
null
FZClosureScrollView/Classes/CollectionView/FZCollectionViewManager.swift
FranZhou/FZClosureScrollView
64b0fea766279b6fe7a93b360b29d1bc5e5906a6
[ "MIT" ]
null
null
null
// // FZCollectionViewManager.swift // FZClosureScrollView // // Created by Fan Zhou on 2021/7/2. // import UIKit public class FZCollectionViewManager: FZScrollViewManager { // MARK: - property /// /// The assignment will override the FZScrollViewManager's delegateDecorator property public var collectionViewDelegateDecorator: FZCollectionViewDelegateDecorator? { didSet { super.delegateDecorator = collectionViewDelegateDecorator } } public var dataSourceDecorator: FZCollectionViewDataSourceDecorator? public var prefetchDataSourceDecorator: FZCollectionViewPrefetchDataSourceDecorator? private var _dragDelegateDecorator: Any? @available(iOS 11.0, *) public var dragDelegateDecorator: FZCollectionViewDragDelegateDecorator? { get { return _dragDelegateDecorator as? FZCollectionViewDragDelegateDecorator } set { _dragDelegateDecorator = newValue } } private var _dropDelegateDecorator: Any? @available(iOS 11.0, *) public var dropDelegateDecorator: FZCollectionViewDropDelegateDecorator? { get { return _dropDelegateDecorator as? FZCollectionViewDropDelegateDecorator } set { _dropDelegateDecorator = newValue } } // MARK: - override public override func responds(to aSelector: Selector!) -> Bool { if shouldCheckResponds(to: aSelector) { return checkResponds(to: aSelector) } return super.responds(to: aSelector) } } // MARK: - optional method check extension FZCollectionViewManager { /// Whether the selector is an optional method /// - Parameter selector: selector /// - Returns: Returns true to indicate that the selector is optional private func shouldCheckResponds(to selector: Selector) -> Bool { if isDelegateSelector(selector) || isDataSourceSelector(selector) || isPrefetchDataSourceSelector(selector) { return true } if #available(iOS 11.0, *) { if isDragDelegateSelector(selector) || isDropDelegateSelector(selector) { return true } } return false } /// Check whether the optional method can actually be called /// - Parameter selector: selector /// - Returns: Return true to indicate that the optional method can be called private func checkResponds(to selector: Selector) -> Bool { if isDelegateSelector(selector) { return checkDelegateResponds(to: selector) } else if isDataSourceSelector(selector) { return checkDataSourceResponds(to: selector) } else if isPrefetchDataSourceSelector(selector) { return checkPrefetchDataSourceResponds(to: selector) } if #available(iOS 11.0, *) { if isDragDelegateSelector(selector) { return checkDragDelegateResponds(to: selector) } else if isDropDelegateSelector(selector) { return checkDropDelegateResponds(to: selector) } } return false } }
31.323529
93
0.655086
6caf02f0c40a8f69f2c8e9eaac50c13f5959e536
3,868
go
Go
pool/conn.go
santiment/clickhouse_sinker
beb622520db706e26fc6beb519aeeb29b25d3675
[ "Apache-2.0" ]
null
null
null
pool/conn.go
santiment/clickhouse_sinker
beb622520db706e26fc6beb519aeeb29b25d3675
[ "Apache-2.0" ]
null
null
null
pool/conn.go
santiment/clickhouse_sinker
beb622520db706e26fc6beb519aeeb29b25d3675
[ "Apache-2.0" ]
null
null
null
/* Copyright [2019] housepower Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package pool // Clickhouse connection pool import ( "database/sql" "fmt" "strings" "sync" "time" "github.com/heptiolabs/healthcheck" "github.com/housepower/clickhouse_sinker/health" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "github.com/sundy-li/go_commons/utils" ) const ( BlockSize = 1 << 21 //2097152, two times of the default value ) var ( lock sync.Mutex poolMaps map[string]*ClusterConnections ) // Connection a datastructure for storing the clickhouse connection type Connection struct { *sql.DB dsn string } type ClusterConnections struct { connections []*Connection ref int } // ReConnect used for restablishing connection with server func (c *Connection) ReConnect() error { sqlDB, err := sql.Open("clickhouse", c.dsn) if err != nil { log.Info("reconnect to ", c.dsn, err.Error()) return err } log.Info("reconnect success to ", c.dsn) c.DB = sqlDB return nil } func InitConn(name, hosts string, port int, db, username, password, dsnParams string) (err error) { var ips, ips2, dsnArr []string var sqlDB *sql.DB lock.Lock() if poolMaps == nil { poolMaps = make(map[string]*ClusterConnections) } if cc, ok := poolMaps[name]; ok { cc.ref++ lock.Unlock() return } lock.Unlock() // if contains ',', that means it's a ip list if strings.Contains(hosts, ",") { ips = strings.Split(strings.TrimSpace(hosts), ",") } else { ips = []string{hosts} } for _, ip := range ips { if ips2, err = utils.GetIp4Byname(ip); err != nil { // fallback to ip err = nil } else { ip = ips2[0] } dsn := fmt.Sprintf("tcp://%s:%d?database=%s&username=%s&password=%s&block_size=%d", ip, port, db, username, password, BlockSize) if dsnParams != "" { dsn += "&" + dsnParams } dsnArr = append(dsnArr, dsn) } log.Infof("clickhouse dsn of %s: %+v", name, dsnArr) var cc ClusterConnections cc.ref = 1 for _, dsn := range dsnArr { if sqlDB, err = sql.Open("clickhouse", dsn); err != nil { err = errors.Wrapf(err, "") return } health.Health.AddReadinessCheck(dsn, healthcheck.DatabasePingCheck(sqlDB, 10*time.Second)) cc.connections = append(cc.connections, &Connection{sqlDB, dsn}) } lock.Lock() defer lock.Unlock() if cc2, ok := poolMaps[name]; ok { cc2.ref++ return } poolMaps[name] = &cc return nil } func FreeConn(name string) { lock.Lock() defer lock.Unlock() if cc, ok := poolMaps[name]; ok { cc.ref-- if cc.ref <= 0 { delete(poolMaps, name) } } } func GetTotalConn() (cnt int) { lock.Lock() defer lock.Unlock() for _, cc := range poolMaps { cnt += cc.ref * len(cc.connections) } return } // GetNumConn get number of connections for the given name func GetNumConn(name string) (numConn int) { lock.Lock() defer lock.Unlock() if ps, ok := poolMaps[name]; ok { numConn = len(ps.connections) } return } // GetConn select a clickhouse node from the cluster based on batchNum func GetConn(name string, batchNum int64) (con *Connection) { lock.Lock() defer lock.Unlock() cc, ok := poolMaps[name] if !ok { return } con = cc.connections[batchNum%int64(len(cc.connections))] return } // CloseAll closed all connection and destroys the pool func CloseAll() { for _, cc := range poolMaps { for _, c := range cc.connections { _ = c.Close() } } }
22.229885
99
0.682006
90c66f306ace4cd14ae1c24b98e171c582f66964
459
py
Python
ML_EVR/common/models.py
IcouldEsmileof/Diplomna
75f343d38e2352211eb60fcd011d334ac7509da8
[ "MIT" ]
null
null
null
ML_EVR/common/models.py
IcouldEsmileof/Diplomna
75f343d38e2352211eb60fcd011d334ac7509da8
[ "MIT" ]
null
null
null
ML_EVR/common/models.py
IcouldEsmileof/Diplomna
75f343d38e2352211eb60fcd011d334ac7509da8
[ "MIT" ]
null
null
null
from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.models import Sequential class SimpleModel(object): @staticmethod def build_model(observation, actions, name=None): return Sequential([ Flatten(input_shape=(1, observation)), Dense(observation * 8, activation='relu'), Dense(observation * 4, activation='relu'), Dense(actions, activation='linear'), ], name=name)
32.785714
54
0.657952
39bd084478222d27821e03e09730508d04e23ba2
1,918
js
JavaScript
server/server.js
frozenfroggie/Nightlife
da50f321aa7b52d4f844459726a03595d84f8ed2
[ "MIT" ]
1
2019-09-01T00:06:09.000Z
2019-09-01T00:06:09.000Z
server/server.js
frozenfroggie/Nightlife
da50f321aa7b52d4f844459726a03595d84f8ed2
[ "MIT" ]
null
null
null
server/server.js
frozenfroggie/Nightlife
da50f321aa7b52d4f844459726a03595d84f8ed2
[ "MIT" ]
null
null
null
require('./config/config'); const path = require('path'); const express = require('express'); // const morgan = require('morgan'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const helmet = require('helmet') const session = require('express-session'); const MongoStore = require('connect-mongo')(session); const fileUpload = require('express-fileupload'); require('isomorphic-fetch'); const searchRoutes = require('./routes/search'); const usersRoutes = require('./routes/users'); const socialAuthRoutes = require('./routes/socialAuth'); const auth = require('./passport/auth.js'); const githubAuth = require('./passport/strategies/githubAuth.js'); const googleAuth = require('./passport/strategies/googleAuth.js'); const facebookAuth = require('./passport/strategies/facebookAuth.js'); const publicPath = path.join(__dirname, '../dist'); const app = express(); app.use(helmet()); app.use(fileUpload()); console.log(process.env.MONGODB_URI); mongoose.connect(process.env.MONGODB_URI); app.use(session({ store: new MongoStore({mongooseConnection: mongoose.connection}), secret: 'keyboard cat', resave: false, saveUninitialized: false })); app.use(bodyParser.json()) // app.use(morgan('dev')); app.use('/', express.static(publicPath)); auth(app); githubAuth(); facebookAuth(); googleAuth(); app.use('/search', searchRoutes); app.use('/users', usersRoutes); app.use('/socialAuth', socialAuthRoutes); app.use( (req,res,next) => { const error = new Error('Not found'); error.status = 404; next(error); }); app.use( (error,req,res,next) => { if(process.env.NODE_ENV === 'dev') { res.status(error.status || 500); res.json({ error: { message: error.message } }); } else { res.sendFile(publicPath + '/error.html'); } }); const port = process.env.PORT || 8000; app.listen(port); module.exports = app;
25.236842
70
0.682482
f4dd05996828059c2c5a6acfa2ceda1cef8730cd
1,928
go
Go
utils/pubsub.go
rudderlabs/rudder-utils
11847bfa8fd535865fe917c99bc3648c2c9a8b39
[ "MIT" ]
null
null
null
utils/pubsub.go
rudderlabs/rudder-utils
11847bfa8fd535865fe917c99bc3648c2c9a8b39
[ "MIT" ]
null
null
null
utils/pubsub.go
rudderlabs/rudder-utils
11847bfa8fd535865fe917c99bc3648c2c9a8b39
[ "MIT" ]
1
2022-03-27T06:56:21.000Z
2022-03-27T06:56:21.000Z
//go:generate mockgen -destination=../mocks/utils/mock_pubsub.go -package=utils github.com/rudderlabs/rudder-server/utils PublishSubscriber package utils import ( "sync" ) type DataEvent struct { Data interface{} Topic string } // DataChannel is a channel which can accept an DataEvent type DataChannel chan DataEvent // DataChannelSlice is a slice of DataChannels type DataChannelSlice []DataChannel type PublishSubscriber interface { Publish(topic string, data interface{}) PublishToChannel(channel DataChannel, topic string, data interface{}) Subscribe(topic string, ch DataChannel) } // EventBus stores the information about subscribers interested for a particular topic type EventBus struct { subscribers map[string]DataChannelSlice rm sync.RWMutex } func (eb *EventBus) Publish(topic string, data interface{}) { eb.rm.RLock() if chans, found := eb.subscribers[topic]; found { // this is done because the slices refer to same array even though they are passed by value // thus we are creating a new slice with our elements thus preserve locking correctly. // special thanks for /u/freesid who pointed it out channels := append(DataChannelSlice{}, chans...) go func(data DataEvent, dataChannelSlices DataChannelSlice) { for _, ch := range dataChannelSlices { ch <- data } }(DataEvent{Data: data, Topic: topic}, channels) } eb.rm.RUnlock() } func (eb *EventBus) PublishToChannel(channel DataChannel, topic string, data interface{}) { eb.rm.RLock() go func() { channel <- DataEvent{Data: data, Topic: topic} }() eb.rm.RUnlock() } func (eb *EventBus) Subscribe(topic string, ch DataChannel) { eb.rm.Lock() if prev, found := eb.subscribers[topic]; found { eb.subscribers[topic] = append(prev, ch) } else { if eb.subscribers == nil { eb.subscribers = map[string]DataChannelSlice{} } eb.subscribers[topic] = append([]DataChannel{}, ch) } eb.rm.Unlock() }
28.776119
139
0.731328
95de38f0b3691ac4986c095f48e7f29db3057f86
16,514
css
CSS
frontend/web/themes/senluo/css/aboutus.css
ChisWill/Yii2-Origin
bb1964261a923f6d1ad3660c20a0cfb1ccb11ca4
[ "BSD-3-Clause" ]
1
2021-05-07T13:14:21.000Z
2021-05-07T13:14:21.000Z
frontend/web/themes/senluo/css/aboutus.css
ChisWill/yii2-origin
bb1964261a923f6d1ad3660c20a0cfb1ccb11ca4
[ "BSD-3-Clause" ]
null
null
null
frontend/web/themes/senluo/css/aboutus.css
ChisWill/yii2-origin
bb1964261a923f6d1ad3660c20a0cfb1ccb11ca4
[ "BSD-3-Clause" ]
null
null
null
body { overflow-x: hidden; } .aboutusCenter{ width: 100%; } .image-slider { width: 12rem; height: 6rem; margin: 1.3rem auto; background: url(../images/bg.png) no-repeat; padding: 14px 16px 0px 16px; box-sizing: border-box; position: relative; } .image-slider-back, .image-slider-forward { float: left; width: 0.6rem; height: 0.6rem; color: white; position: absolute; top: 1.8rem; cursor: pointer; } .image-slider-back { left: 0; background: url(../images/left-active.png) center center no-repeat; background-size: 100% 100%; } .image-slider-forward { right: 0; background: url(../images/right-active.png) center center no-repeat; background-size: 100% 100%; } .image-slider-contents{ width: 10rem; height: 4.5rem; margin: 0 0.85rem; float: left; position: relative; overflow: hidden; } .image-slider-contents .contents-wrapper{ position: absolute; padding-top: 18px; } .image-slider-contents .outer{ background-color: #fff; float: left; width: 3rem; height: 4rem; margin: 0px 0.16rem; cursor: pointer; position: relative; padding-bottom: 0.12rem; } .spic{ position: relative; width: 100%; height: 100%; text-align: center; color: #333; float: left; padding-top: 10px; } .spic>img{ position: absolute; right: -20px; top: -20px; } /*.image-slider-contents img{ width:120px; height:120px; margin:0 auto; }*/ .spic>a{ display: block; text-align: center; margin: 0.1rem 0; color: #8b8989; font-size: 0.24rem; } .spic>a:nth-of-type(2){ font-size: 0.18rem; } .hidden{ display:none; } .visible{ display:block; } .thumbnail-active{ filter: alpha(opacity=100); opacity: 1.0; cursor: pointer; } .thumbnail-inactive{ filter: alpha(opacity=20); opacity: 0.2; cursor: pointer; } .preview{ position: absolute; top: -0.5rem; left: 50%; margin-left: -2.5rem; width: 5rem; height: auto; background-color: White; padding: 0.3rem; text-align: center; border: solid 1px #eee; box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.13); } .preview .img-large{ width:3.3rem; z-index:1000; margin:0 auto; } .preview .img-large .left{ position:absolute; left: 0.32rem; top: 2.34rem; width: 0.3rem; height: 0.4rem; z-index: 1000; background: url(../images/arrow_21.png); background-repeat: no-repeat; cursor: pointer; } .preview .img-large .right{ position: absolute; right: 0.22rem; top: 2.3rem; z-index: 1000; width: 0.3rem; height: 0.4rem; background: url(../images/arrow_24.png); background-repeat: no-repeat; cursor: pointer; } .preview .close{ position: absolute; left: 4.34rem; top: -16px; width: 32px; height: 34px; background: url(../images/close.png); float: right; cursor: pointer; z-index: 2000; } .preview .img-large img{ width: 3.3rem; height: 3.3rem; } .preview .label{ width: 80%; line-height: 30px; float: left; padding: 8px; background-color: white; text-align: left; font-weight: bold; font-size: 13px; text-align: center; margin-left: 10%; } .preview .label:nth-of-type(2){ color: #c33435; font-size: 0.3rem; } .preview .label:nth-of-type(3) { font-weight: normal; font-size: 0.24rem; color: #343535; } .preview .label:nth-of-type(4){ padding-top: 0.16rem; border-top: 3px solid #c33435; font-size: 0.24rem; font-weight: normal; } .outer{ border:solid 1px #eee; box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.13); } .spic-back{ width: 95%; padding: 0.12rem 0; margin: 0 auto; background-image: url('../images/zoom2.png'); background-repeat: no-repeat; background-size: 60% 90%; background-position: 1.52rem 1.06rem; background-color: #e3e7ea; } /*分割线*/ body { visibility: hidden; background: #fff; } .background{ width: 100%; height: 7.3rem; background-size: 100% 100%; } .aboutus{ position:absolute; left: 50%; width: 12rem; height: 6.6rem; margin-top: -1.1rem; margin-left: -6rem; padding: 0.3rem; box-sizing:border-box; background: rgba(0,0,0,0); border: 1px solid #fff; } .aboutus-content{ padding: 0.78rem 0.7rem; background: #fff; z-index: 1000; box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.13); } .con-top{ text-align: center; } .con-top>div{ font-size: 0.3rem; } .con-top>div:nth-of-type(2){ font-size: 0.2rem; } .con-top>div>span{ font-weight: bold; color: #4c4c4c; } .con-bottom{ padding-top: 0.4rem; overflow: hidden; } .con-bottom>div:nth-of-type(1){ float: left; width: 4rem; margin-right: 1rem; } .con-bottom>div:nth-of-type(1)>img{ float: left; width: 2rem; height: 2rem; } .con-bottom img{ width: 100%; } .company{ font-weight: bold; font-size: 0.26rem; color: #c33435; margin-bottom: 0.2rem; } .introduce{ font-size: 0.2rem; color: #545455; } .idea{ position: relative; width: 12rem; height: 4.6rem; background-repeat: no-repeat; background-size: 100% 100%; margin: 1.3rem auto; margin-top: 6.3rem; } .idea>div{ position: absolute; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.4); text-align: center; } .idea-title{ width: 1.6rem; height: 0.6rem; line-height: 0.6rem; text-align: center; font-size: 0.26rem; color: #fff; margin: 0.7rem auto; font-weight: bold; border: 1px solid #fff; } .idea-intro{ font-size: 0.22rem; width: 10.5rem; margin: 0 auto; color: #fff; line-height: 0.46rem; } .our-culture{ width: 12rem; margin: 0 auto; } .our-culture>div:nth-of-type(1){ font-size: 0.26rem; } .our-culture>div:nth-of-type(1)>span:nth-of-type(1){ color: #c33435; font-weight: bold; margin-right: 0.16rem; } .culture-box{ position: relative; width: 8.7rem; height: 3.4rem; margin: 0.7rem 0; background-color: #f6f4f5; padding-top: 0.6rem; box-sizing: border-box; } .culture-box>img{ position: absolute; top: -0.67rem; right: -2.86rem; } .culture-content{ width: 4.6rem; margin: 0 0.6rem; font-size: 0.22rem; line-height: 0.43rem; color: #545455; } .culture-foot{ display: flex; justify-content: space-between; margin: 1.3rem 0; } .culture-foot>div{ font-size: 0.38rem; } .culture-foot>div>h5{ display: inline-block; font-size: 0.26rem; color: #7a7a7a; font-weight: bold; } .culture-foot>div.active{ margin-top: 0.24rem; color: #7a7a7a; } .our-team{ text-align: center; } .our-team>div:nth-of-type(1){ font-size: 0.3rem; } .our-team>div:nth-of-type(1)>span{ color: #4c4c4c; font-weight: bold; } .our-team>div:nth-of-type(2){ display: flex; justify-content:space-between; font-size: 0.2rem; } .our-team>div:nth-of-type(2)>div.active{ width: 42%; height: 3px; background-color: #cdcdcd; margin-top: 0.16rem; } /*面包屑*/ .breadcrumbs{ width: 100%; padding: 0.16rem 0.86rem!important; box-sizing:border-box; background-color: #f1f3f4; display: flex; } /*外壳*/ .con-center{ width: 100%; } .spic-back img { width: calc(100% - 0.24rem); height: 2.5rem; } .main-crumbs { width: auto; padding: 0 0.15rem; } /*手机ipad样式统一处理*/ @media screen and (max-width: 1200px) { .image-slider { width: 100%; } .spic-back img { width: 100%; height: 2.1rem; } .aboutus{ margin-top: -0.69rem; margin-left: -44%; width: 90%; height: 4.15rem; } .aboutus-content{ padding: 0.49rem 0.44rem; background: #fff; box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.13); } .con-bottom{ padding-top: 0.25rem; } .con-bottom>div:nth-of-type(1){ margin-right: 0.4rem; width: 1.2rem; margin-top: 0.2rem; } .con-bottom>div:nth-of-type(1)>img{ display: block; width: 1.26rem; height: 1.26rem; } .con-bottom>div:nth-of-type(1)>img:nth-of-type(1){ margin-bottom: 0.315rem; margin-top: 0.1rem; } .con-bottom>div:nth-of-type(2) { width:3.6rem; } .con-bottom>div{ float: left; } .company{ font-weight: bold; font-size: 0.35rem; color: #c33435; margin-bottom: 0.08rem; } .introduce{ font-size: 0.22rem; color: #545455; } .idea{ position: relative; width: 100%; height: 2.89rem; background-repeat: no-repeat; background-size: 100% 100%; margin: 0.819rem auto; margin-top: 7.5rem; } .idea>div{ position: absolute; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.4); text-align: center; } .idea-title{ width: 1.6rem; height: 0.6rem; line-height: 0.6rem; text-align: center; font-size: 0.26rem; color: #fff; margin: 0.2rem auto; font-weight: bold; border: 1px solid #fff; } .idea-intro{ font-size: 0.22rem; width: 100%; margin: 0 auto; color: #fff; line-height: 0.46rem; } .our-culture{ width: 86%; margin: 0 auto; } .our-culture>div:nth-of-type(1){ font-size: 0.26rem; } .our-culture>div:nth-of-type(1)>span:nth-of-type(1){ color: #c33435; font-weight: bold; margin-right: 0.16rem; } .culture-box{ position: relative; width: 100%; height: 2.14rem; margin: 0.44rem 0; background-color: #f6f4f5; padding-top: 0.1rem; box-sizing: border-box; } .culture-box>img{ position: absolute; width: 2.5rem; top: 0.1rem; right: -6%; } .culture-content{ width: 60%; margin: 0 0.378rem; font-size: 0.22rem; line-height: 0.4rem; color: #545455; } .culture-foot{ margin: 0.82rem 0; } .culture-foot img{ width: 0.68rem; } .culture-foot>div{ font-size: 0.38rem; } .culture-foot>div>span{ font-size: 0.26rem; color: #7a7a7a; font-weight: bold; } .culture-foot>div.active{ margin-top: 0rem; color: #7a7a7a; } .our-team>div:nth-of-type(2)>div.active{ height: 1px; } /*手机轮播图*/ .image-slider{ height: 4.78rem; margin: 0.82rem auto; background: url(../images/bg.png) no-repeat; padding: 14px 16px 0px 16px; box-sizing: border-box; position: relative; } .image-slider-back, .image-slider-forward{ float:left; width:0.6rem; height:0.6rem; color:white; position:absolute; top:1.8rem; cursor:pointer; background-size: 100% 100%; } .image-slider-back{ width:0.378rem; height:0.378rem; left: 0rem; top: 2rem; } .image-slider-forward{ position: absolute; width: 0.378rem; height: 0.378rem; right: 0rem; top: 2rem; } .image-slider-contents{ overflow: hidden; width: 6.3rem; height: 2.835rem; padding-bottom: 1.2rem; left: 50%; margin-left: -3.15rem; } .image-slider-contents .contents-wrapper{ padding-top:0.1rem; } .image-slider-contents .outer{ background-color:#fff; float:left; width: 2.8rem; height: 3.52rem; background-size: cover; margin: 0px 0.166rem; cursor:pointer; position:relative; padding-bottom: 0.0756rem; } .spic>img{ position: absolute; right: -5px; top: -8px; width: 0.315rem; } .spic-back{ width: 95%; padding: 0.12rem 0; margin: 0 auto; background-image: url('../images/zoom2.png'); background-repeat: no-repeat; background-size: 60% 90%; background-position: 1.52rem 1.06rem; background-color: #e3e7ea; } .spic-back>img{ width: 90%; } .preview{ position: absolute; top: -0.378rem; left: 25%; margin-left: 0px; width: 50%; height: auto; background-color: White; padding-top: 0.1rem; padding-bottom: 0.2rem; text-align: center; border: solid 1px #eee; box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.13); } .preview .img-large{ width:2rem; z-index:1000; margin:0.3rem auto; } .preview .img-large .left{ background-size: 100% 100%; } .preview .img-large .right{ position:absolute; right:0.32rem; top: 2.36rem; background-size: 100% 100% } .preview .close{ position:absolute; left:2.73rem; top:-16px; width:32px; height:34px; background:url(../images/close.png); float:right; cursor:pointer; z-index:2000; } .preview .img-large img{ width: 2rem; height: 2rem; } .preview .label{ width:2.73rem; line-height:30px; float:left; padding:8px; background-color:White; font-weight:bold; margin-left: 0.5rem; text-align:center; } .preview .label:nth-of-type(2){ color: #c33435; font-size: 0.3rem; } .preview .label:nth-of-type(3) { font-weight: normal; font-size: 0.24rem; color: #343535; } .preview .label:nth-of-type(4){ padding-top: 0.16rem; border-top: 3px solid #c33435; font-size: 0.24rem; font-weight: normal; } } @media screen and (max-width: 414px){ .con-bottom>div:nth-of-type(2) { width: 3rem; } } @media screen and (max-width: 320px) { .image-slider{ width: 6rem; } .image-slider-contents{ width: 5.3rem; } .image-slider-contents .outer{ width: 2.44rem; } .con-bottom>div:nth-of-type(1)>img { display: block; width: 1rem; height: 1rem; } .con-bottom>div:nth-of-type(1) { margin-right: 0.2rem; } .aboutus-content { padding: 0.49rem 0.44rem 0.8rem; } .con-bottom>div:nth-of-type(2) { width: 2.6rem; } .preview { width: 3rem; } .preview .label { margin-left: 0rem; } .preview .img-large .right { left: 3.2rem; } } /*适配手机样式*/ @media screen and (max-width: 640px) { .preview { left: 10%; margin-left: 0px; width: 80%; padding: 0px; } .preview .label { width: 80%; } .preview .img-large { margin-top: 0.3rem; } } /*适配ipad*/ @media screen and (max-width: 1025px) and (min-width: 768px) { .image-slider-contents { width: 700px; left: 50%; margin-left: -350px; } .image-slider-contents .outer { width: 200px; } .image-slider-back { left: 0.2rem; top: 1.7rem; } .image-slider-forward { right: 0.2rem; top: 1.7rem; } .spic-back img { height: 1.8rem; } .image-slider-contents .outer { height: 3rem; } }
21.530639
73
0.524646
868215458d5e330fe6b627bca4f6c97d02b1593d
951
kt
Kotlin
app/src/main/java/com/android/amit/instaclone/view/story/AddStoryViewModel.kt
amit7127/Instagram-Clone
80a94147e538c821db2730ae80a449013d616eb4
[ "Apache-2.0" ]
2
2020-07-04T04:15:25.000Z
2020-08-05T08:59:58.000Z
app/src/main/java/com/android/amit/instaclone/view/story/AddStoryViewModel.kt
amit7127/Instagram-Clone
80a94147e538c821db2730ae80a449013d616eb4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/android/amit/instaclone/view/story/AddStoryViewModel.kt
amit7127/Instagram-Clone
80a94147e538c821db2730ae80a449013d616eb4
[ "Apache-2.0" ]
null
null
null
package com.android.amit.instaclone.view.story import android.net.Uri import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.android.amit.instaclone.data.Resource import com.android.amit.instaclone.data.StoryModel import com.android.amit.instaclone.repo.Repository import com.android.amit.instaclone.util.Constants /** * File created at 27/05/2020 * Author : Amit Kumar Sahoo * email: amit.sahoo@mindfiresolutions.com * About file : Add Story view model */ class AddStoryViewModel : ViewModel() { var repo: Repository = Repository() /** * Post story */ fun postStory(imageUri: Uri): MutableLiveData<Resource<Unit>> { val story = StoryModel() story.timeStart = System.currentTimeMillis() story.timeEnd = System.currentTimeMillis() + Constants.STORY_END_INTERVAL story.userId = repo.getCurrentUserId() return repo.postStory(imageUri, story) } }
30.677419
81
0.736067
40a567b8546ff055f32c27faa0a6a26e1dcbe0b3
4,903
py
Python
src/expositor/cli/host.py
secretuminc/expositor
b68b56433d312d86869be9581d45116be433ee06
[ "MIT" ]
1
2021-06-23T17:40:39.000Z
2021-06-23T17:40:39.000Z
src/expositor/cli/host.py
secretuminc/expositor
b68b56433d312d86869be9581d45116be433ee06
[ "MIT" ]
null
null
null
src/expositor/cli/host.py
secretuminc/expositor
b68b56433d312d86869be9581d45116be433ee06
[ "MIT" ]
null
null
null
# Helper methods for printing `host` information to the terminal. import quo from expositor.helpers import get_ip def host_print_pretty(host, history=False): """Show the host information in a user-friendly way and try to include as much relevant information as possible.""" # General info quo.echo(quo.style(get_ip(host), fg='green')) if len(host['hostnames']) > 0: quo.echo(u'{:25s}{}'.format('Hostnames:', ';'.join(host['hostnames']))) if 'city' in host and host['city']: quo.echo(u'{:25s}{}'.format('City:', host['city'])) if 'country_name' in host and host['country_name']: quo.echo(u'{:25s}{}'.format('Country:', host['country_name'])) if 'os' in host and host['os']: quo.echo(u'{:25s}{}'.format('Operating System:', host['os'])) if 'org' in host and host['org']: quo.echo(u'{:25s}{}'.format('Organization:', host['org'])) if 'last_update' in host and host['last_update']: quo.echo('{:25s}{}'.format('Updated:', host['last_update'])) quo.echo('{:25s}{}'.format('Number of open ports:', len(host['ports']))) # Output the vulnerabilities the host has if 'vulns' in host and len(host['vulns']) > 0: vulns = [] for vuln in host['vulns']: if vuln.startswith('!'): continue if vuln.upper() == 'CVE-2014-0160': vulns.append(quo.flair(f'Heartbleed', fg="vred")) else: vulns.append(quo.flair(vuln, fg='red')) if len(vulns) > 0: quo.echo('{:25s}'.format('Vulnerabilities:'), nl=False) for vuln in vulns: quo.echo(vuln + '\t', nl=False) quo.echo('') quo.echo('') # If the user doesn't have access to SSL/ Telnet results then we need # to pad the host['data'] property with empty banners so they still see # the port listed as open. (#63) if len(host['ports']) != len(host['data']): # Find the ports the user can't see the data for ports = host['ports'] for banner in host['data']: if banner['port'] in ports: ports.remove(banner['port']) # Add the placeholder banners for port in ports: banner = { 'port': port, 'transport': 'tcp', # All the filtered services use TCP 'timestamp': host['data'][-1]['timestamp'], # Use the timestamp of the oldest banner 'placeholder': True, # Don't store this banner when the file is saved } host['data'].append(banner) quo.echo('Ports:') for banner in sorted(host['data'], key=lambda k: k['port']): product = '' version = '' if 'product' in banner and banner['product']: product = banner['product'] if 'version' in banner and banner['version']: version = '({})'.format(banner['version']) quo.flair(f'{:>7d}'.format(banner['port']), fg='cyan'), nl=False) if 'transport' in banner: quo.echo('/', nl=False) quo.flair(f'{} '.format(banner['transport']), fg='vyellow'), nl=False) quo.echo('{} {}'.format(product, version), nl=False) if history: # Format the timestamp to only show the year-month-day date = banner['timestamp'][:10] quo.flair(f'\t\t({})'.format(date), fg='white', dim=True, nl=False) quo.echo('') # Show optional ssl info if 'ssl' in banner: if 'versions' in banner['ssl'] and banner['ssl']['versions']: quo.echo('\t|-- SSL Versions: {}'.format(', '.join([item for item in sorted(banner['ssl']['versions']) if not version.startswith('-')]))) if 'dhparams' in banner['ssl'] and banner['ssl']['dhparams']: quo.echo('\t|-- Diffie-Hellman Parameters:') quo.echo('\t\t{:15s}{}\n\t\t{:15s}{}'.format('Bits:', banner['ssl']['dhparams']['bits'], 'Generator:', banner['ssl']['dhparams']['generator'])) if 'fingerprint' in banner['ssl']['dhparams']: quo.echo('\t\t{:15s}{}'.format('Fingerprint:', banner['ssl']['dhparams']['fingerprint'])) def host_print_tsv(host, history=False): """Show the host information in a succinct, grep-friendly manner.""" for banner in sorted(host['data'], key=lambda k: k['port']): quo.flair(f'{:>7d}'.format(banner['port']), fg='cyan', nl=False) quo.echo('\t', nl=False) quo.flair(f'{} '.format(banner['transport']), fg='yellow' nl=False) if history: # Format the timestamp to only show the year-month-day date = banner['timestamp'][:10] quo.flair(f'\t({})'.format(date), fg='white', dim=True, nl=False) quo.flair(f'') HOST_PRINT = { 'pretty': host_print_pretty, 'tsv': host_print_tsv, }
39.861789
159
0.555782
6c7d8c4999186a691df5958d7892d1b65bc10a03
63
go
Go
hide_stub.go
11ib/twitchpipe
caffad99240b6dfbd58c166279a46281cd185605
[ "MIT" ]
27
2019-11-08T21:17:21.000Z
2021-08-15T04:52:35.000Z
hide_stub.go
11ib/twitchpipe
caffad99240b6dfbd58c166279a46281cd185605
[ "MIT" ]
16
2019-11-12T15:06:34.000Z
2020-12-24T21:12:36.000Z
hide_stub.go
11ib/twitchpipe
caffad99240b6dfbd58c166279a46281cd185605
[ "MIT" ]
3
2019-11-28T20:01:39.000Z
2021-05-28T12:41:34.000Z
// +build !windows package main func hideWindow() {} // Stub
10.5
28
0.650794
07fc811d241183b12b05cd7cb522bd5031dc0eee
231
sql
SQL
src/main/resources/db/migration/data/R__4_45__OFFENDER_RESTRICTIONS.sql
ministryofjustice/nomis-prisoner-deletion-service
529aceeec26869234c9629d7074b5a44f0aa5d85
[ "MIT" ]
1
2022-03-10T13:20:20.000Z
2022-03-10T13:20:20.000Z
src/main/resources/db/migration/data/R__4_45__OFFENDER_RESTRICTIONS.sql
ministryofjustice/nomis-prisoner-deletion-service
529aceeec26869234c9629d7074b5a44f0aa5d85
[ "MIT" ]
1
2022-03-14T09:54:49.000Z
2022-03-14T09:54:49.000Z
src/main/resources/db/migration/data/R__4_45__OFFENDER_RESTRICTIONS.sql
ministryofjustice/nomis-prisoner-deletion-service
529aceeec26869234c9629d7074b5a44f0aa5d85
[ "MIT" ]
null
null
null
INSERT INTO OFFENDER_RESTRICTIONS (OFFENDER_RESTRICTION_ID,OFFENDER_BOOK_ID,RESTRICTION_TYPE,EFFECTIVE_DATE,ENTERED_STAFF_ID,COMMENT_TEXT) VALUES (-1,-1,'RESTRICTION',TIMESTAMP '2001-01-01 00:00:00.000000',-1,'Some Comment Text');
77
138
0.831169
e26d73c55be05185b45abbb4cc2e471a16661fd1
2,219
sql
SQL
backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5510759_sys_gh1134webui_AD_Table_Process_more_fields_DDL.sql
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5510759_sys_gh1134webui_AD_Table_Process_more_fields_DDL.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5510759_sys_gh1134webui_AD_Table_Process_more_fields_DDL.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
-- note that our postgres 9.5. does not yet have "ADD COLUMN IF NOT EXISTS" DO $$ BEGIN -- 2019-01-25T12:25:13.098 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator /* DDL */ ALTER TABLE public.AD_Table_Process ADD COLUMN AD_Tab_ID NUMERIC(10) ; EXCEPTION WHEN SQLSTATE '42701' THEN RAISE NOTICE 'At least one column already existed; Ignoring; Error-Code %, Message=%', SQLSTATE, SQLERRM; END $$; DO $$ BEGIN -- 2019-01-25T12:35:15.496 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator /* DDL */ ALTER TABLE public.AD_Table_Process ADD COLUMN WEBUI_DocumentAction CHAR(1) DEFAULT 'Y' CHECK (WEBUI_DocumentAction IN ('Y','N')) NOT NULL ; EXCEPTION WHEN SQLSTATE '42701' THEN RAISE NOTICE 'At least one column already existed; Ignoring; Error-Code %, Message=%', SQLSTATE, SQLERRM; END $$; DO $$ BEGIN -- 2019-01-25T12:35:35.377 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator /* DDL */ ALTER TABLE public.AD_Table_Process ADD COLUMN WEBUI_ViewAction CHAR(1) DEFAULT 'Y' CHECK (WEBUI_ViewAction IN ('Y','N')) NOT NULL ; EXCEPTION WHEN SQLSTATE '42701' THEN RAISE NOTICE 'At least one column already existed; Ignoring; Error-Code %, Message=%', SQLSTATE, SQLERRM; END $$; DO $$ BEGIN -- 2019-01-25T12:35:54.124 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator /* DDL */ ALTER TABLE public.AD_Table_Process ADD COLUMN WEBUI_IncludedTabTopAction CHAR(1) DEFAULT 'N' CHECK (WEBUI_IncludedTabTopAction IN ('Y','N')) NOT NULL ; EXCEPTION WHEN SQLSTATE '42701' THEN RAISE NOTICE 'At least one column already existed; Ignoring; Error-Code %, Message=%', SQLSTATE, SQLERRM; END $$; DO $$ BEGIN alter table AD_Table_Process rename WEBUI_QuickAction to WEBUI_ViewQuickAction; EXCEPTION WHEN SQLSTATE '42703' THEN RAISE NOTICE 'column doesn''t exist, so we assume it was already renamed; Ignoring; Error-Code %, Message=%', SQLSTATE, SQLERRM; END $$; DO $$ BEGIN alter table AD_Table_Process rename WEBUI_QuickAction_Default to WEBUI_ViewQuickAction_Default; EXCEPTION WHEN SQLSTATE '42703' THEN RAISE NOTICE 'column doesn''t exist, so we assume it was already renamed; Ignoring; Error-Code %, Message=%', SQLSTATE, SQLERRM; END $$;
34.138462
160
0.749887
a7b7a613811deac59917de76d78bce49e20270b5
1,596
kt
Kotlin
src/main/kotlin/me/melijn/melijnbot/commands/administration/SetVerificationPasswordCommand.kt
zeroeightysix/Melijn
acf17564244c0c62fba2b85e143d83c6c00c1a86
[ "MIT" ]
87
2019-01-09T12:19:50.000Z
2022-03-30T18:59:21.000Z
src/main/kotlin/me/melijn/melijnbot/commands/administration/SetVerificationPasswordCommand.kt
zeroeightysix/Melijn
acf17564244c0c62fba2b85e143d83c6c00c1a86
[ "MIT" ]
51
2018-07-27T14:52:29.000Z
2022-02-15T17:41:36.000Z
src/main/kotlin/me/melijn/melijnbot/commands/administration/SetVerificationPasswordCommand.kt
zeroeightysix/Melijn
acf17564244c0c62fba2b85e143d83c6c00c1a86
[ "MIT" ]
31
2018-06-16T12:01:49.000Z
2022-03-19T23:30:11.000Z
package me.melijn.melijnbot.commands.administration import me.melijn.melijnbot.internals.command.AbstractCommand import me.melijn.melijnbot.internals.command.CommandCategory import me.melijn.melijnbot.internals.command.ICommandContext import me.melijn.melijnbot.internals.translation.PLACEHOLDER_ARG import me.melijn.melijnbot.internals.utils.message.sendRsp import me.melijn.melijnbot.internals.utils.withVariable class SetVerificationPasswordCommand : AbstractCommand("command.setverificationpassword") { init { id = 42 name = "setVerificationPassword" aliases = arrayOf("svp") commandCategory = CommandCategory.ADMINISTRATION } override suspend fun execute(context: ICommandContext) { val wrapper = context.daoManager.verificationPasswordWrapper if (context.args.isEmpty()) { val password = wrapper.getPassword(context.guildId) val part = if (password.isBlank()) { "unset" } else { "set" } val msg = context.getTranslation("$root.show.$part") .withVariable("password", password) sendRsp(context, msg) return } val msg = if (context.rawArg == "null") { wrapper.remove(context.guildId) context.getTranslation("$root.unset") } else { wrapper.set(context.guildId, context.rawArg) context.getTranslation("$root.set") .withVariable(PLACEHOLDER_ARG, context.rawArg) } sendRsp(context, msg) } }
34.695652
91
0.651629
c7ef7543a536a00201fe56bf6826fb52e73e5f45
1,137
java
Java
ses-app/ses-web-delivery/src/main/java/com/redescooter/ses/web/delivery/service/base/impl/CorTenantScooterServiceImpl.java
moutainhigh/ses-server
e1ee6ac34499950ef4b1b97efa0aaf4c4fec67c5
[ "MIT" ]
null
null
null
ses-app/ses-web-delivery/src/main/java/com/redescooter/ses/web/delivery/service/base/impl/CorTenantScooterServiceImpl.java
moutainhigh/ses-server
e1ee6ac34499950ef4b1b97efa0aaf4c4fec67c5
[ "MIT" ]
null
null
null
ses-app/ses-web-delivery/src/main/java/com/redescooter/ses/web/delivery/service/base/impl/CorTenantScooterServiceImpl.java
moutainhigh/ses-server
e1ee6ac34499950ef4b1b97efa0aaf4c4fec67c5
[ "MIT" ]
2
2021-08-31T07:59:28.000Z
2021-10-16T10:55:44.000Z
package com.redescooter.ses.web.delivery.service.base.impl; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import java.util.List; import com.redescooter.ses.web.delivery.dao.base.CorTenantScooterMapper; import com.redescooter.ses.web.delivery.dm.CorTenantScooter; import com.redescooter.ses.web.delivery.service.base.CorTenantScooterService; @Service public class CorTenantScooterServiceImpl extends ServiceImpl<CorTenantScooterMapper, CorTenantScooter> implements CorTenantScooterService{ @Override public int updateBatch(List<CorTenantScooter> list) { return baseMapper.updateBatch(list); } @Override public int batchInsert(List<CorTenantScooter> list) { return baseMapper.batchInsert(list); } @Override public int insertOrUpdate(CorTenantScooter record) { return baseMapper.insertOrUpdate(record); } @Override public int insertOrUpdateSelective(CorTenantScooter record) { return baseMapper.insertOrUpdateSelective(record); } }
36.677419
138
0.78628
291a38f780b055b857defa7947a54b1f8d85c16a
4,241
py
Python
sklearn/classifiers1.py
gnublet/py_explorations
328ba7c5340537f8e83b3695c24e1afea284402f
[ "MIT" ]
null
null
null
sklearn/classifiers1.py
gnublet/py_explorations
328ba7c5340537f8e83b3695c24e1afea284402f
[ "MIT" ]
null
null
null
sklearn/classifiers1.py
gnublet/py_explorations
328ba7c5340537f8e83b3695c24e1afea284402f
[ "MIT" ]
null
null
null
#AUTHOR: Kevin ## CHALLENGE - create 3 more classifiers... #1 Random Forest #2 Multi-layer Perceptron #3 Support Vector Machine #comparison #Try cross validation since we have a small dataset from sklearn.model_selection import cross_val_score #enable preprocessing (for MLP) under cross-validation from sklearn.pipeline import make_pipeline from sklearn import preprocessing from sklearn import tree#decision tree from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from sklearn import svm #Data: [height, weight, shoe_size] X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40], [190, 90, 47], [175, 64, 39], [177, 70, 40], [159, 55, 37], [171, 75, 42], [181, 85, 43]] Y = ['male', 'male', 'female', 'female', 'male', 'male', 'female', 'female', 'female', 'male', 'male'] #mytest = [165,54,40]#me mytest = [190,70,43] #CHALLENGE - ...and train them on our data #Decision Tree nfolds = 5 myscores = {} clf_DT = tree.DecisionTreeClassifier() #do k=5 fold crossvalidation scores_DT = cross_val_score(clf_DT, X,Y, cv = nfolds)#cv = number of folds (how to choose?) # I was thinking i want to maximize the number of folds since our dataset is so small print("Decision Tree scores: ",scores_DT) print("Accuracy: %0.2f (+/- %0.2f)" %(scores_DT.mean(), scores_DT.std()*2)) myscores['DT'] = scores_DT.mean() #Random Forest #using the same training data clf_RF = RandomForestClassifier(n_estimators = 10)#how to choose n_estimators? #cv scores_RF = cross_val_score(clf_RF, X,Y, cv = nfolds) print("Random Forest scores: ",scores_RF) print("Accuracy: %0.2f (+/- %0.2f)" %(scores_RF.mean(), scores_RF.std()*2)) myscores['RF'] = scores_RF.mean() #Multi-layer perceptron #MLP is sensitive to feature scaling on the data so lets standardize clf_MLP = make_pipeline(preprocessing.StandardScaler(), MLPClassifier(solver= 'lbfgs', alpha = 1e-5, hidden_layer_sizes=(5,2), random_state=1)) scores_MLP = cross_val_score(clf_MLP, X, Y, cv = nfolds) print("Multilayer Perceptron scores: ",scores_MLP) print("Accuracy: %0.2f (+/- %0.2f)" %(scores_MLP.mean(), scores_MLP.std()*2)) myscores['MLP'] = scores_MLP.mean() #Support Vector Machine clf_SVM = svm.SVC() scores_SVM = cross_val_score(clf_SVM, X,Y,cv = nfolds) print("SVM scores: ",scores_SVM) print("Accuracy: %0.2f (+/- %0.2f)" %(scores_SVM.mean(), scores_SVM.std()*2)) myscores['SVM'] = scores_SVM.mean() ######## print('') #Special Case: ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (I'm a skinny guy) #Decision Tree predictions clf_DT = clf_DT.fit(X, Y) prediction_DT = clf_DT.predict([mytest]) #prediction = clf_DT.predict([[165, 54, 40]]) #CHALLENGE compare their results and print the best one! print("The decision tree classifier predicts {} to be {}.".format(mytest, prediction_DT)) #Random Forest predictions clf_RF = clf_RF.fit(X,Y) prediction_RF = clf_RF.predict([mytest]) print("The random forest classifier predicts {} to be {}.".format(mytest, prediction_RF)) #MLP predictions #clf_MLP = clf_MLP.fit(X,Y) #prediction_MLP = clf_MLP.predict([mytest]) #print("The multi-layer perceptron classifier predicts {} to be {}.".format(mytest, prediction_MLP)) y_test = ['male'] scaler = preprocessing.StandardScaler().fit(X)#Scale X X_transformed = scaler.transform(X) clf_MLP = clf_MLP.fit(X_transformed, Y) X_test_transformed = scaler.transform([mytest]) #print(clf_MLP.score(X_test_transformed, y_test)) prediction_MLP = clf_MLP.predict(X_test_transformed) print("The multilayer perceptron classifier predicts {} to be {}.".format(mytest, prediction_MLP)) #SVM predictions clf_SVM = clf_SVM.fit(X,Y) prediction_SVM = clf_SVM.predict([mytest]) print("The support vector classifier predicts {} to be {}.".format(mytest, prediction_SVM)) #print("SVM support vectors:\n", clf_SVM.support_vectors_) #print("SVM support indices:", clf_SVM.support_) #print("number of support vectors for each class:", clf_SVM.n_support_) #print(mytest, X_test_transformed) #which is most accurate? print('') mymax = 0 mymodel = '' for k in myscores: if myscores[k]>=mymax: mymax = myscores[k] mymodel = k #print(k, myscores[k]) print("The most accurate model is {} with an accuracy of {}".format(mymodel, mymax))
35.940678
143
0.719642
5df8f6953a74a56f94523fecea68c3d9b40a4a9c
4,676
lua
Lua
assets/preload/data/ballistic-(beta-mix)/script.lua
RaidenAlfares13/Psych-Engine-0.4.2-Android-Port
787adb7558a65fa3eefde2610967e5065368419a
[ "Apache-2.0" ]
null
null
null
assets/preload/data/ballistic-(beta-mix)/script.lua
RaidenAlfares13/Psych-Engine-0.4.2-Android-Port
787adb7558a65fa3eefde2610967e5065368419a
[ "Apache-2.0" ]
null
null
null
assets/preload/data/ballistic-(beta-mix)/script.lua
RaidenAlfares13/Psych-Engine-0.4.2-Android-Port
787adb7558a65fa3eefde2610967e5065368419a
[ "Apache-2.0" ]
null
null
null
local resetHideHud = false function onCreatePost() if not lowQuality then addLuaScript('epicScripts/infishake') addLuaScript('epicScripts/cam') end addCharacterToList('bf-jam-car', 'boyfriend'); -- this is probably really bad practice but oh well resetHideHud = not hideHud; if resetHideHud then setPropertyFromClass('ClientPrefs', 'hideHud', true); -- disable debug keys SORRY ;( -- exiting with these will fuck up your hide HUD setting -- if you wanna use em enable hide hud first!!!! setProperty('debugKeysChart', null); setProperty('debugKeysCharacter', null); end precacheImage('hqr/slamratings/shit'); precacheImage('hqr/slamratings/bad'); precacheImage('hqr/slamratings/good'); precacheImage('hqr/slamratings/sick'); precacheImage('hqr/slamratings/go'); -- TODO: replace "go" graphic (how???) -- TODO: replace ratings (how ?????????) end function onCountdownTick(swagCounter) if swagCounter == 3 then makeLuaSprite('slamGo', 'hqr/slamratings/go', screenWidth / 2 - 279, screenHeight / 2 - 215); setObjectCamera('slamGo','hud'); doTweenAlpha('slamGoAlpha', 'slamGo', 0, crochet / 1000, 'cubeInOut'); setProperty('countdownGo.visible', false); addLuaSprite('slamGo', true); end end function onTweenCompleted(tag) if tag == 'slamGoAlpha' then removeLuaSprite('slamGo', true); end end function goodNoteHit(id, direction, noteType, isSustainNote) -- slammin ratings!!! if not isSustainNote and resetHideHud then --structure strumTime = getPropertyFromGroup('notes', id, 'strumTime'); local rating = getRating(strumTime - getSongPosition() + getPropertyFromClass('ClientPrefs','ratingOffset')); -- sorry no comboOffset!! -- only gonna have one at a time cuz fuck managing multiple instances local middlescrolloffset = 0; if middlescroll then middlescrolloffset = 250; end makeLuaSprite('lastRating', 'hqr/slamratings/' .. rating, screenWidth * 0.35 - 75 - middlescrolloffset, screenHeight / 2 - 60); setObjectCamera('lastRating','hud'); setProperty('lastRating.velocity.y', math.random(-140, -175)); setProperty('lastRating.velocity.x', math.random(-10)); setProperty('lastRating.acceleration.y', 550); runTimer('lastRatingTimer', crochet / 1000); setScrollFactor('lastRating', 1, 1); scaleObject('lastRating', 0.7, 0.7); updateHitbox('lastRating'); addLuaSprite('lastRating', true); -- BRING BACK THE COMBO COUNTER LOL!!!! local combo = getProperty('combo'); if combo >= 10 then for i=2,0,-1 do local tag = 'combodigit' .. i; makeLuaSprite(tag, 'num' .. math.floor(combo / 10 ^ i % 10), screenWidth * 0.35 - 60 - middlescrolloffset - i * 43, screenHeight / 2 + 80); setObjectCamera(tag,'hud'); setProperty(tag .. '.velocity.y', math.random(-140, -160)); setProperty(tag .. '.velocity.x', math.random(-5, 5)); setProperty(tag .. '.acceleration.y', math.random(200, 300)); runTimer(tag .. 'Timer', crochet / 500); setScrollFactor(tag, 1, 1); scaleObject(tag, 0.5, 0.5); updateHitbox(tag); addLuaSprite(tag, true); end end end end function getRating(diff) diff = math.abs(diff); if diff <= getPropertyFromClass('ClientPrefs', 'badWindow') then if diff <= getPropertyFromClass('ClientPrefs', 'goodWindow') then if diff <= getPropertyFromClass('ClientPrefs', 'sickWindow') then return 'sick'; end return 'good'; end return 'bad'; end return 'shit'; end function onTimerCompleted(tag, loops, loopsLeft) if tag == 'lastRatingTimer' then doTweenAlpha('lastRatingAlpha', 'lastRating', 0, 0.2); elseif tag == 'combodigit0Timer' then doTweenAlpha('combodigit0Alpha', 'combodigit0', 0, 0.2); elseif tag == 'combodigit1Timer' then doTweenAlpha('combodigit1Alpha', 'combodigit1', 0, 0.2); elseif tag == 'combodigit2Timer' then doTweenAlpha('combodigit2Alpha', 'combodigit2', 0, 0.2); end end -- there is no hook for playstate closing so i have to cover all exiting options!!! -- closing the game dont matter cuz this doesnt save the pref to save data anyway -- the ONLY WAY this fucks up to my knowledge is if u use chart/character debug key -- to exit playstate so those are disabled now. if u wanna use em, enable hide hud! function onGameOver() if resetHideHud then setPropertyFromClass('ClientPrefs', 'hideHud', false); end end function onEndSong() if resetHideHud then setPropertyFromClass('ClientPrefs', 'hideHud', false); end end function onPause() if resetHideHud then setPropertyFromClass('ClientPrefs', 'hideHud', false); end end function onResume() -- lol put it back on if resetHideHud then setPropertyFromClass('ClientPrefs', 'hideHud', true); end end
30.966887
143
0.711933
a5ee01e42f330735d81e8c7924a988219321f1b8
11,735
kt
Kotlin
mobile/src/main/java/uk/co/appsbystudio/geoshare/base/MainActivity.kt
STUDIO-apps/GeoSharer_Android
f66aa94d7f44c8dbf81a6a67a4e0504bbf7e2d32
[ "Apache-2.0" ]
2
2016-04-10T01:43:47.000Z
2017-09-12T01:07:46.000Z
mobile/src/main/java/uk/co/appsbystudio/geoshare/base/MainActivity.kt
STUDIO-apps/GeoSharer_Android
f66aa94d7f44c8dbf81a6a67a4e0504bbf7e2d32
[ "Apache-2.0" ]
43
2017-09-01T21:39:54.000Z
2018-07-30T16:11:43.000Z
mobile/src/main/java/uk/co/appsbystudio/geoshare/base/MainActivity.kt
STUDIO-apps/GeoSharer_Android
f66aa94d7f44c8dbf81a6a67a4e0504bbf7e2d32
[ "Apache-2.0" ]
null
null
null
package uk.co.appsbystudio.geoshare.base import android.app.Activity import android.app.DialogFragment import android.content.Context import android.content.Intent import android.os.Bundle import android.preference.PreferenceManager import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.view.View import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.header_layout.view.* import uk.co.appsbystudio.geoshare.R import uk.co.appsbystudio.geoshare.authentication.AuthActivity import uk.co.appsbystudio.geoshare.base.adapters.FriendsNavAdapter import uk.co.appsbystudio.geoshare.friends.manager.FriendsManager import uk.co.appsbystudio.geoshare.maps.MapsFragment import uk.co.appsbystudio.geoshare.utils.ProfileSelectionResult import uk.co.appsbystudio.geoshare.utils.SettingsPreferencesHelper import uk.co.appsbystudio.geoshare.utils.ShowMarkerPreferencesHelper import uk.co.appsbystudio.geoshare.utils.TrackingPreferencesHelper import uk.co.appsbystudio.geoshare.utils.dialog.ProfilePictureOptions import uk.co.appsbystudio.geoshare.utils.dialog.ShareOptions import uk.co.appsbystudio.geoshare.utils.services.TrackingService import uk.co.appsbystudio.geoshare.utils.ui.SettingsActivity class MainActivity : AppCompatActivity(), MainView, FriendsNavAdapter.Callback { private var presenter: MainPresenter? = null private lateinit var authStateListener: FirebaseAuth.AuthStateListener private var header: View? = null private var friendsNavAdapter: FriendsNavAdapter? = null private var mapsFragment: MapsFragment = MapsFragment() private val hasTracking = HashMap<String, Boolean>() private val friendsMap = LinkedHashMap<String, String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) presenter = MainPresenterImpl(this, ShowMarkerPreferencesHelper(getSharedPreferences("showOnMap", Context.MODE_PRIVATE)), TrackingPreferencesHelper(getSharedPreferences("tracking", Context.MODE_PRIVATE)), SettingsPreferencesHelper(PreferenceManager.getDefaultSharedPreferences(applicationContext)), MainInteractorImpl(cacheDir.toString())) presenter?.setTrackingService() /* HANDLES FOR VARIOUS VIEWS */ if (savedInstanceState == null) { supportFragmentManager.beginTransaction().replace(R.id.frame_content_map_main, mapsFragment, "maps_fragment").commit() } else { mapsFragment = supportFragmentManager.findFragmentByTag("maps_fragment") as MapsFragment presenter?.swapFragment(mapsFragment) } var navItemSelected = false var checkedItem = 0 drawer_left_nav_main.setNavigationItemSelectedListener { item -> navItemSelected = true drawer_layout?.closeDrawers() when (item.itemId) { R.id.maps -> checkedItem = R.id.maps R.id.friends -> checkedItem = R.id.friends R.id.settings -> checkedItem = R.id.settings R.id.logout -> checkedItem = R.id.logout R.id.feedback -> checkedItem = R.id.feedback } false } val drawerListener = object : DrawerLayout.DrawerListener { override fun onDrawerStateChanged(newState: Int) {} override fun onDrawerSlide(drawerView: View, slideOffset: Float) {} override fun onDrawerOpened(drawerView: View) {} override fun onDrawerClosed(drawerView: View) { if (navItemSelected) { navItemSelected = false presenter?.run { when (checkedItem) { R.id.maps -> swapFragment(mapsFragment) R.id.friends -> friends() R.id.settings -> settings() R.id.logout -> logout() R.id.feedback -> feedback() else -> showError("Hmm... Looks like something has gone wrong") } } } } } drawer_layout.addDrawerListener(drawerListener) header = drawer_left_nav_main.getHeaderView(0) recycler_right_nav_main?.setHasFixedSize(true) recycler_right_nav_main?.layoutManager = LinearLayoutManager(this@MainActivity) //Get friends and populate right nav drawer presenter?.run { getFriends() getFriendsTrackingState() updatedProfileListener() } friendsNavAdapter = FriendsNavAdapter(this@MainActivity, recycler_right_nav_main, friendsMap, hasTracking, this) recycler_right_nav_main.adapter = friendsNavAdapter /* POPULATE LEFT NAV DRAWER HEADER FIELDS */ header?.profile_image?.setOnClickListener { presenter?.openDialog(ProfilePictureOptions(), "") } presenter?.run { updateNavProfilePicture(header?.profile_image, this@MainActivity.cacheDir.toString()) updateNavDisplayName() setMarkerVisibilityState() } switch_markers_main.setOnCheckedChangeListener { buttonView, isChecked -> mapsFragment.setAllMarkersVisibility(isChecked) } authStateListener = FirebaseAuth.AuthStateListener { firebaseAuth -> val currentUser = firebaseAuth.currentUser if (currentUser == null) { presenter?.run { clearSharedPreferences() stopTrackingService() auth() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { if (requestCode == 213) { mapsFragment.setup() } else { ProfileSelectionResult(main = this).profilePictureResult(this@MainActivity, requestCode, resultCode, data, FirebaseAuth.getInstance().currentUser?.uid) } } } override fun onStart() { super.onStart() FirebaseAuth.getInstance().addAuthStateListener(authStateListener) } override fun onResume() { super.onResume() presenter?.updateNavDisplayName() presenter?.updateNavProfilePicture(header?.profile_image, this@MainActivity.cacheDir.toString()) } override fun onStop() { super.onStop() FirebaseAuth.getInstance().removeAuthStateListener(authStateListener) } override fun onDestroy() { super.onDestroy() presenter?.stop() friendsMap.clear() } override fun updateFriendsList(uid: String?, name: String?) { if (uid != null && name != null) { friendsMap[uid] = name add_friends.visibility = View.GONE } friendsNavAdapter?.notifyDataSetChanged() } override fun removeFromFriendList(uid: String?) { friendsMap.remove(uid) friendsNavAdapter?.notifyDataSetChanged() if (friendsMap.isEmpty()) add_friends.visibility = View.VISIBLE } override fun updateTrackingState(uid: String?, trackingState: Boolean?) { if (uid != null && trackingState != null) hasTracking[uid] = trackingState friendsNavAdapter?.notifyDataSetChanged() } override fun removeTrackingState(uid: String?) { hasTracking.remove(uid) friendsNavAdapter?.notifyDataSetChanged() } override fun showFragment(fragment: Fragment) { supportFragmentManager.beginTransaction().show(fragment).commit() } override fun friendsIntent() { val intent = Intent(this@MainActivity, FriendsManager::class.java) intent.putExtra("friends_map", friendsMap) startActivity(intent) } override fun settingsIntent() { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) } override fun logoutIntent() { startActivity(Intent(this@MainActivity, AuthActivity::class.java)) finish() } override fun feedbackIntent(intent: Intent) { if (intent.resolveActivity(packageManager) != null) { startActivity(Intent.createChooser(intent, "Send email via")) } else { Toast.makeText(this@MainActivity, "No email applications found on this device!", Toast.LENGTH_SHORT).show() } } override fun startTrackingServiceIntent() { val trackingService = Intent(applicationContext, TrackingService::class.java) startService(trackingService) } override fun stopTrackingServiceIntent() { val trackingService = Intent(applicationContext, TrackingService::class.java) stopService(trackingService) } override fun showDialog(dialog: DialogFragment, tag: String) { dialog.show(fragmentManager, tag) } override fun setDisplayName(name: String?) { header?.username?.text = String.format(resources.getString(R.string.welcome_user_header), name) } override fun updateProfilePicture() { presenter?.updateNavProfilePicture(header?.profile_image, this@MainActivity.cacheDir.toString()) } override fun markerToggleState(state: Boolean?) { if (state != null) switch_markers_main.isChecked = state } override fun openNavDrawer() { drawer_layout?.openDrawer(GravityCompat.START) } override fun openFriendsNavDrawer() { drawer_layout?.openDrawer(GravityCompat.END) } override fun closeNavDrawer() { drawer_layout?.closeDrawer(GravityCompat.START) } override fun closeFriendsNavDrawer() { drawer_layout?.closeDrawer(GravityCompat.END) } override fun showError(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } override fun showErrorSnackbar(message: String) { Snackbar.make(findViewById(R.id.coordinator), message, Snackbar.LENGTH_SHORT) .setAction("RETRY?") { presenter?.logout() } } override fun setMarkerHidden(friendId: String, visible: Boolean) { mapsFragment.setMarkerVisibility(friendId, visible) } override fun findOnMapClicked(friendId: String) { mapsFragment.findFriendOnMap(friendId) } override fun sendLocationDialog(name: String, friendId: String) { val arguments = Bundle() arguments.putString("name", name) arguments.putString("friendId", friendId) arguments.putString("uid", FirebaseAuth.getInstance().currentUser?.uid) val fragmentManager = fragmentManager val friendDialog = ShareOptions() friendDialog.arguments = arguments friendDialog.show(fragmentManager, "location_dialog") } override fun stopSharing(friendId: String) { presenter?.setFriendSharingState(friendId, false) friendsNavAdapter?.notifyDataSetChanged() } override fun onBackPressed() { when { drawer_layout.isDrawerOpen(GravityCompat.START) -> drawer_layout.closeDrawer(GravityCompat.START) drawer_layout.isDrawerOpen(GravityCompat.END) -> drawer_layout.closeDrawer(GravityCompat.END) else -> super.onBackPressed() } } }
37.018927
167
0.671069
ffa190d119a3cbdef953a58715d809cd57b57927
488
swift
Swift
Mobile Microservices Architecture/ContentView.swift
petros-efthymiou/Mobile-iOS-Microservices-Architecture
0897521651a49fecd104bea8cad010e074fd5e24
[ "Apache-2.0" ]
3
2022-02-23T09:08:28.000Z
2022-03-19T14:03:37.000Z
Mobile Microservices Architecture/ContentView.swift
petros-efthymiou/Mobile-iOS-Microservices-Architecture
0897521651a49fecd104bea8cad010e074fd5e24
[ "Apache-2.0" ]
null
null
null
Mobile Microservices Architecture/ContentView.swift
petros-efthymiou/Mobile-iOS-Microservices-Architecture
0897521651a49fecd104bea8cad010e074fd5e24
[ "Apache-2.0" ]
null
null
null
// // ContentView.swift // Mobile Microservices Architecture // // Created by Petros Efthymiou on 26/01/2022. // import SwiftUI import CoreData import Home struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)], animation: .default) private var items: FetchedResults<Item> var body: some View { HomeView() } }
20.333333
87
0.694672
dda42f1211a6a3955cf0f73d4428d0afad96b2ff
2,281
php
PHP
src/TqMeter/AsyncApi/Notify.php
topphp/topphp-meter-api
6f732cc0c362b6a641dc63c4f2621b3925fdaf02
[ "MIT" ]
3
2021-04-10T02:05:26.000Z
2021-06-06T16:32:28.000Z
src/TqMeter/AsyncApi/Notify.php
topphp/topphp-meter-api
6f732cc0c362b6a641dc63c4f2621b3925fdaf02
[ "MIT" ]
null
null
null
src/TqMeter/AsyncApi/Notify.php
topphp/topphp-meter-api
6f732cc0c362b6a641dc63c4f2621b3925fdaf02
[ "MIT" ]
null
null
null
<?php /** * 凯拓软件 [临渊羡鱼不如退而结网,凯拓与你一同成长] * Project: topphp-meter-api * Date: 2020/10/17 10:00 下午 * Author: sleep <sleep@kaituocn.com> */ declare(strict_types=1); namespace Topphp\TopphpMeterApi\TqMeter\AsyncApi; use Closure; use Topphp\TopphpMeterApi\TqMeter\Gateway; class Notify extends Gateway { private $token = ''; /** * @return string */ public function getSubscribeToken(): string { return $this->token; } /** * @param string $token * @return Notify */ public function setSubscribeToken(string $token): self { $this->token = $token; return $this; } /** * 异步通知回调 * @param $request * @param Closure $callBack * @author sleep */ public function send($request, Closure $callBack) { $sign = $request["sign"]; $timestamp = $request["timestamp"]; $responseContent = $request["response_content"]; $check = $this->checkSign($responseContent, $timestamp, $sign); if (!$check) { // echo "sign check failed"; $callBack(false, $timestamp, $sign); } else { // echo 'SUCCESS'; $callBack(json_decode($responseContent, true), $timestamp, $sign); } } /** * 订阅消息 * @param Closure $callBack * @author sleep */ public function subscribe(Closure $callBack) { $sign = @getallheaders()["Sign"]; $content = @file_get_contents('php://input'); if ($content == '') { $callBack(false, '返回数据为空'); echo 'SUCCESS'; } else { if (!$this->checkSubscribeSign($content, $sign)) { // echo "sign check failed"; $callBack(false, '签名错误'); } else { // echo 'SUCCESS'; $callBack(true, json_decode($content, true)); } } } /** * 订阅消息签名验证方法 * @param $content * @param $sign * @return bool * @author sleep */ public function checkSubscribeSign($content, $sign) { // 随机字符串 后台获取 $buf = $content . $this->getSubscribeToken(); $encode = md5($buf); return $encode == $sign; } }
23.760417
81
0.519071
3dd9561f1e9e4292e7689823d3cd919ec363b2d8
20,390
rs
Rust
compiler/crates/relay-compiler/src/file_source/file_categorizer.rs
irangarcia/relay
8c2c3aea4b98f422d712f68b7efd49d5e9852e11
[ "MIT" ]
null
null
null
compiler/crates/relay-compiler/src/file_source/file_categorizer.rs
irangarcia/relay
8c2c3aea4b98f422d712f68b7efd49d5e9852e11
[ "MIT" ]
null
null
null
compiler/crates/relay-compiler/src/file_source/file_categorizer.rs
irangarcia/relay
8c2c3aea4b98f422d712f68b7efd49d5e9852e11
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use super::file_filter::FileFilter; use super::File; use super::FileGroup; use crate::compiler_state::{ProjectName, ProjectSet}; use crate::config::{Config, SchemaLocation}; use crate::FileSourceResult; use common::sync::ParallelIterator; use core::panic; use fnv::FnvHashSet; use log::warn; use rayon::iter::IntoParallelRefIterator; use relay_typegen::TypegenLanguage; use std::borrow::Cow; use std::collections::HashMap; use std::ffi::OsStr; use std::path::{Component, PathBuf}; use std::{collections::hash_map::Entry, path::Path}; /// The watchman query returns a list of files, but for the compiler we /// need to categorize these files into multiple groups of files like /// schema files, extensions and sources by their source set name. /// /// See `FileGroup` for all groups of files. pub fn categorize_files( config: &Config, file_source_result: &FileSourceResult, ) -> HashMap<FileGroup, Vec<File>> { let categorizer = FileCategorizer::from_config(config); let result = match file_source_result { FileSourceResult::Watchman(file_source_result) => { let mut relevant_projects = FnvHashSet::default(); for (project_name, project_config) in &config.projects { if project_config.enabled { relevant_projects.insert(project_name); if let Some(base_project) = &project_config.base { relevant_projects.insert(base_project); } } } let has_disabled_projects = relevant_projects.len() < config.projects.len(); file_source_result .files .par_iter() .map(|file| { let file = File { name: (*file.name).clone(), exists: *file.exists, }; let file_group = categorizer.categorize(&file.name).unwrap_or_else(|err| { panic!( "Unexpected error in file categorizer for file `{}`: {}.", file.name.to_string_lossy(), err ) }); (file_group, file) }) .filter(|(file_group, _)| { !(has_disabled_projects && match &file_group { FileGroup::Generated { project_name: name } => { !relevant_projects.contains(name) } FileGroup::Source { project_set } | FileGroup::Schema { project_set } | FileGroup::Extension { project_set } => !project_set .iter() .any(|name| relevant_projects.contains(name)), FileGroup::Ignore => false, }) }) .collect::<Vec<_>>() } FileSourceResult::External(result) => { categorize_non_watchman_files(&categorizer, config, &result.files) } FileSourceResult::WalkDir(result) => { categorize_non_watchman_files(&categorizer, config, &result.files) } }; let mut categorized = HashMap::new(); for (file_group, file) in result { categorized .entry(file_group) .or_insert_with(Vec::new) .push(file); } categorized } fn categorize_non_watchman_files( categorizer: &FileCategorizer, config: &Config, files: &[File], ) -> Vec<(FileGroup, File)> { let file_filter = FileFilter::from_config(config); files .par_iter() .filter(|file| file_filter.is_file_relevant(&file.name)) .filter_map(|file| { let file_group = categorizer .categorize(&file.name) .map_err(|err| { warn!( "Unexpected error in file categorizer for file `{}`: {}.", file.name.to_string_lossy(), err ); err }) .ok()?; Some((file_group, file.clone())) }) .collect::<Vec<_>>() } /// The FileCategorizer is created from a Config and categorizes files found by /// Watchman into what kind of files they are, such as source files of a /// specific source file group or generated files from some project. pub struct FileCategorizer { source_language: HashMap<ProjectName, TypegenLanguage>, extensions_mapping: PathMapping<ProjectSet>, default_generated_dir: &'static OsStr, generated_dir_mapping: PathMapping<ProjectName>, source_mapping: PathMapping<ProjectSet>, schema_file_mapping: HashMap<PathBuf, ProjectSet>, schema_dir_mapping: PathMapping<ProjectSet>, } impl FileCategorizer { pub fn from_config(config: &Config) -> Self { let mut source_mapping = vec![]; for (path, project_set) in &config.sources { source_mapping.push((path.clone(), project_set.clone())); } let mut extensions_map: HashMap<PathBuf, ProjectSet> = Default::default(); for (&project_name, project_config) in &config.projects { for extension_dir in &project_config.schema_extensions { match extensions_map.entry(extension_dir.clone()) { Entry::Vacant(entry) => { entry.insert(ProjectSet::of(project_name)); } Entry::Occupied(mut entry) => { entry.get_mut().insert(project_name); } } } } let mut schema_file_mapping: HashMap<PathBuf, ProjectSet> = Default::default(); for (&project_name, project_config) in &config.projects { if let SchemaLocation::File(schema_file) = &project_config.schema_location { match schema_file_mapping.entry(schema_file.clone()) { Entry::Vacant(entry) => { entry.insert(ProjectSet::of(project_name)); } Entry::Occupied(mut entry) => { entry.get_mut().insert(project_name); } } } } let mut schema_dir_mapping_map: HashMap<PathBuf, ProjectSet> = Default::default(); for (&project_name, project_config) in &config.projects { if let SchemaLocation::Directory(directory) = &project_config.schema_location { match schema_dir_mapping_map.entry(directory.clone()) { Entry::Vacant(entry) => { entry.insert(ProjectSet::of(project_name)); } Entry::Occupied(mut entry) => { entry.get_mut().insert(project_name); } } } } let mut schema_dir_mapping = vec![]; for (path, project_set) in schema_dir_mapping_map { schema_dir_mapping.push((path, project_set)); } let mut generated_dir_mapping = Vec::new(); for (&project_name, project_config) in &config.projects { if let Some(output) = &project_config.output { generated_dir_mapping.push((output.clone(), project_name)); } if let Some(extra_artifacts_output) = &project_config.extra_artifacts_output { generated_dir_mapping.push((extra_artifacts_output.clone(), project_name)); } } let source_language: HashMap<ProjectName, TypegenLanguage> = config .projects .iter() .map(|(project_name, project_config)| { (*project_name, project_config.typegen_config.language) }) .collect::<HashMap<_, _>>(); Self { source_language, extensions_mapping: PathMapping::new(extensions_map.into_iter().collect()), default_generated_dir: OsStr::new("__generated__"), generated_dir_mapping: PathMapping::new(generated_dir_mapping), schema_file_mapping, schema_dir_mapping: PathMapping::new(schema_dir_mapping), source_mapping: PathMapping::new(source_mapping), } } /// Categorizes a file. This method should be kept as cheap as possible by /// preprocessing the config in `from_config` and then re-using the /// `FileCategorizer`. pub fn categorize(&self, path: &Path) -> Result<FileGroup, Cow<'static, str>> { let extension = path.extension(); if let Some(project_name) = self.generated_dir_mapping.find(path) { return if let Some(extension) = extension { if is_source_code_extension(extension) || is_extra_extensions(extension) { Ok(FileGroup::Generated { project_name }) } else { Ok(FileGroup::Ignore) } } else { Ok(FileGroup::Ignore) }; } let extension = extension.ok_or(Cow::Borrowed("Got unexpected path without extension."))?; if is_source_code_extension(extension) { let project_set = self .source_mapping .find(path) .ok_or(Cow::Borrowed("File is not in any source set."))?; if self.in_relative_generated_dir(path) { if project_set.has_multiple_projects() { Err(Cow::Owned(format!( "Overlapping input sources are incompatible with relative generated \ directories. Got file in a relative generated directory with source set {:?}.", project_set, ))) } else { let project_name = project_set.into_iter().next().unwrap(); Ok(FileGroup::Generated { project_name }) } } else { let is_valid_extension = self.is_valid_extension_for_project_set(&project_set, extension, path); if is_valid_extension { Ok(FileGroup::Source { project_set }) } else { Err(Cow::Borrowed("Invalid extension for a generated file.")) } } } else if is_schema_extension(extension) { if let Some(project_set) = self.schema_file_mapping.get(path) { Ok(FileGroup::Schema { project_set: project_set.clone(), }) } else if let Some(project_set) = self.extensions_mapping.find(path) { Ok(FileGroup::Extension { project_set }) } else if let Some(project_set) = self.schema_dir_mapping.find(path) { Ok(FileGroup::Schema { project_set }) } else { Err(Cow::Borrowed( "Expected *.graphql/*.gql file to be either a schema or extension.", )) } } else { Err(Cow::Borrowed( "File categorizer encounter a file with unsupported extension.", )) } } fn in_relative_generated_dir(&self, path: &Path) -> bool { path.components().any(|comp| match comp { Component::Normal(comp) => comp == self.default_generated_dir, _ => false, }) } fn is_valid_extension_for_project_set( &self, project_set: &ProjectSet, extension: &OsStr, path: &Path, ) -> bool { for project_name in project_set.iter() { if let Some(language) = self.source_language.get(&project_name) { if !is_valid_source_code_extension(language, extension) { warn!( "Unexpected file `{:?}` for language `{:?}`.", path, language ); return false; } } } true } } struct PathMapping<T: Clone>(Vec<(PathBuf, T)>); impl<T: Clone> PathMapping<T> { fn new(mut entries: Vec<(PathBuf, T)>) -> Self { // Sort so that more specific paths come first, i.e. // - foo/bar -> A // - foo -> B // which ensures we categorize foo/bar/x.js as A. entries.sort_by(|(path_a, _), (path_b, _)| path_b.cmp(path_a)); Self(entries) } fn find(&self, path: &Path) -> Option<T> { self.0.iter().find_map(|(prefix, item)| { if path.starts_with(prefix) { Some(item.clone()) } else { None } }) } } fn is_source_code_extension(extension: &OsStr) -> bool { extension == "js" || extension == "jsx" || extension == "ts" || extension == "tsx" } fn is_schema_extension(extension: &OsStr) -> bool { extension == "graphql" || extension == "gql" } fn is_extra_extensions(extension: &OsStr) -> bool { extension == "php" || extension == "json" } fn is_valid_source_code_extension(typegen_language: &TypegenLanguage, extension: &OsStr) -> bool { match typegen_language { TypegenLanguage::TypeScript => is_source_code_extension(extension), TypegenLanguage::Flow | TypegenLanguage::JavaScript => { extension == "js" || extension == "jsx" } } } #[cfg(test)] mod tests { use super::*; use intern::string_key::Intern; fn create_test_config() -> Config { Config::from_string_for_test( r#" { "sources": { "src/js": "public", "src/js/internal": "internal", "src/vendor": "public", "src/custom": "with_custom_generated_dir", "src/typescript": "typescript", "src/custom_overlapping": ["with_custom_generated_dir", "overlapping_generated_dir"] }, "projects": { "public": { "schema": "graphql/public.graphql", "language": "flow" }, "internal": { "schema": "graphql/__generated__/internal.graphql", "language": "flow" }, "with_custom_generated_dir": { "schema": "graphql/__generated__/custom.graphql", "output": "graphql/custom-generated", "language": "flow" }, "typescript": { "schema": "graphql/ts_schema.graphql", "language": "typescript" }, "overlapping_generated_dir": { "schema": "graphql/__generated__/custom.graphql", "language": "flow" } } } "#, ) .unwrap() } #[test] fn test_categorize() { let config = create_test_config(); let categorizer = FileCategorizer::from_config(&config); assert_eq!( categorizer .categorize(&PathBuf::from("src/js/a.js")) .unwrap(), FileGroup::Source { project_set: ProjectSet::of("public".intern()), }, ); assert_eq!( categorizer .categorize(&PathBuf::from("src/js/nested/b.js")) .unwrap(), FileGroup::Source { project_set: ProjectSet::of("public".intern()), }, ); assert_eq!( categorizer .categorize(&PathBuf::from("src/js/internal/nested/c.js")) .unwrap(), FileGroup::Source { project_set: ProjectSet::of("internal".intern()), }, ); assert_eq!( // When custom output dir is provided, path is correctly categorized // even if it has same dirname in path as custom output folder. // Path is only categorized as generated if it matches the absolute path // of the provided custom output. categorizer .categorize(&PathBuf::from("src/custom/custom-generated/c.js")) .unwrap(), FileGroup::Source { project_set: ProjectSet::of("with_custom_generated_dir".intern()), }, ); assert_eq!( categorizer .categorize(&PathBuf::from("src/js/internal/nested/__generated__/c.js")) .unwrap(), FileGroup::Generated { project_name: "internal".intern() }, ); assert_eq!( categorizer .categorize(&PathBuf::from("graphql/custom-generated/c.js")) .unwrap(), FileGroup::Generated { project_name: "with_custom_generated_dir".intern() }, ); assert_eq!( categorizer .categorize(&PathBuf::from("graphql/public.graphql")) .unwrap(), FileGroup::Schema { project_set: ProjectSet::of("public".intern()) }, ); assert_eq!( categorizer .categorize(&PathBuf::from("graphql/__generated__/internal.graphql")) .unwrap(), FileGroup::Schema { project_set: ProjectSet::of("internal".intern()) }, ); assert_eq!( categorizer .categorize(&PathBuf::from("src/typescript/a.ts")) .unwrap(), FileGroup::Source { project_set: ProjectSet::of("typescript".intern()), }, ); } #[test] fn test_invalid_extension() { let config = create_test_config(); let categorizer = FileCategorizer::from_config(&config); assert_eq!( categorizer.categorize(&PathBuf::from("src/js/a.cpp")), Err(Cow::Borrowed( "File categorizer encounter a file with unsupported extension." )) ); } #[test] fn test_extension_mismatch_panic() { let config = create_test_config(); let categorizer = FileCategorizer::from_config(&config); assert_eq!( categorizer.categorize(&PathBuf::from("src/js/a.ts")), Err(Cow::Borrowed("Invalid extension for a generated file.")) ); } #[test] fn test_categorize_errors() { let config = create_test_config(); let categorizer = FileCategorizer::from_config(&config); assert_eq!( categorizer.categorize(&PathBuf::from("src/js/a.graphql")), Err(Cow::Borrowed( "Expected *.graphql/*.gql file to be either a schema or extension." )), ); assert_eq!( categorizer.categorize(&PathBuf::from("src/js/a.gql")), Err(Cow::Borrowed( "Expected *.graphql/*.gql file to be either a schema or extension." )), ); assert_eq!( categorizer.categorize(&PathBuf::from("src/js/noextension")), Err(Cow::Borrowed("Got unexpected path without extension.")), ); assert_eq!( categorizer.categorize(&PathBuf::from("src/custom_overlapping/__generated__/c.js")), Err(Cow::Borrowed( "Overlapping input sources are incompatible with relative generated directories. Got file in a relative generated directory with source set ProjectSet([\"with_custom_generated_dir\", \"overlapping_generated_dir\"])." )), ); } }
37.689464
232
0.522511
70ec792eec7ffefac5aef93573afd3b5737fcc82
2,692
h
C
include/pre/hidden/math/Converger.h
mgradysaunders/precept
966eb19d3c8b713e11be0885cabda632cefe9878
[ "BSD-2-Clause" ]
null
null
null
include/pre/hidden/math/Converger.h
mgradysaunders/precept
966eb19d3c8b713e11be0885cabda632cefe9878
[ "BSD-2-Clause" ]
null
null
null
include/pre/hidden/math/Converger.h
mgradysaunders/precept
966eb19d3c8b713e11be0885cabda632cefe9878
[ "BSD-2-Clause" ]
null
null
null
/*-*- C++ -*-*/ #pragma once namespace pre { template <std::floating_point Float> struct Converger { public: /// Number of iterations used in converger call, for debugging. mutable int num_iters = 0; /// Maximum number of iterations. int max_iters = 100; /// Target value. Float target = 0; /// Cutoff, meaning absolute error tolerance. Float cutoff = 1e-6; /// Lower bound on solution. std::optional<Float> lower_bound = std::nullopt; /// Upper bound on solution. std::optional<Float> upper_bound = std::nullopt; public: /// Converge with interval search. template <std::invocable<Float> F> constexpr bool operator()(F&& f, Float* xk) const { ASSERT(lower_bound); ASSERT(upper_bound); Float x0 = *lower_bound; Float x1 = *upper_bound; Float f0 = std::invoke(std::forward<F>(f), x0) - target; for (num_iters = 0; num_iters < max_iters; num_iters++) { *xk = (x0 + x1) * Float(0.5); Float fk = std::invoke(std::forward<F>(f), *xk) - target; if (std::abs(fk) < cutoff) return true; if (std::signbit(fk) == std::signbit(f0)) x0 = *xk; else x1 = *xk; } return false; } /// Converge with Newton's method. template <std::invocable<Float> F, std::invocable<Float> G> constexpr bool operator()(F&& f, G&& g, Float* xk, int m = 1) const { bool clamped_lower = false; bool clamped_upper = false; for (num_iters = 0; num_iters < max_iters; num_iters++) { Float fk = std::invoke(std::forward<F>(f), *xk) - target; if (std::abs(fk) < cutoff) return true; *xk -= fk / std::invoke(std::forward<G>(g), *xk) * m; if (std::isfinite(*xk) == false) break; if (lower_bound) { if (*xk < *lower_bound) { *xk = *lower_bound; if (clamped_lower == false) clamped_lower = true; else return true; // Don't spin forever! } else clamped_lower = false; } if (upper_bound) { if (*xk > *upper_bound) { *xk = *upper_bound; if (clamped_upper == false) clamped_upper = true; else return true; // Don't spin forever! } else clamped_upper = false; } } return false; } }; } // namespace pre
30.247191
73
0.491456
5b2748a3e3a98193e492042e3fa78620411bd30c
48,790
c
C
lsp_shiloh/common/network/apps/sm_job/config/sm_job_dflt_config.c
internaru/Pinetree_P
1f1525454c8b20c6c589529ff4bc159404611297
[ "FSFAP" ]
null
null
null
lsp_shiloh/common/network/apps/sm_job/config/sm_job_dflt_config.c
internaru/Pinetree_P
1f1525454c8b20c6c589529ff4bc159404611297
[ "FSFAP" ]
null
null
null
lsp_shiloh/common/network/apps/sm_job/config/sm_job_dflt_config.c
internaru/Pinetree_P
1f1525454c8b20c6c589529ff4bc159404611297
[ "FSFAP" ]
null
null
null
/****************************************************************************** * Copyright (c) 2012 Marvell International, Ltd. All Rights Reserved * * Marvell Confidential ******************************************************************************/ // ***TODO*** move to system header #define SY_ATTR_WEAK __attribute__((weak)) /** * @file sm_job_dflt_config.c * * @brief The default OEM-specific smjob configuration options * * The purpose of the OEM configuration files for this module is to provide * a mechanism for the user to modify configurable options without having * to recompile the core module that depend on them. The goal is to isolate * OEM and core specific configuration values, and provide an abstraction layer * to simplify the porting. * * This file is to define the capabilities of the specific device, for all * the job types (print, scan, faxin, and faxout). The SM Job API includes * functions which will read this in order for the user to appropriately * edit job and document tickets. * * Refer to the sm_job_api.h file for descriptions of the capabilities and * supporting functions. * */ #include "debug.h" #include "dprintf.h" #include "logger.h" #include "net_logger.h" #include "sm_job_api.h" #include "sm_job_config.h" #define DBG_PRFX "SM JOB CORE: " #define LOGGER_MODULE_MASK DEBUG_LOGGER_MODULE_NETWORK | NET_LOGGER_SUBMOD_SM_JOB //============================================================================= // Structures //============================================================================= typedef struct { smjob_compression_t *print[2]; smjob_compression_t *scan[2]; smjob_compression_t *faxin[2]; smjob_compression_t *faxout[2]; } smjob_oem_compression_table_t; typedef struct { smjob_format_t *print[4]; smjob_format_t *scan[3]; smjob_format_t *faxin[3]; smjob_format_t *faxout[3]; } smjob_oem_format_table_t; typedef struct { smjob_finishing_t print[1]; } smjob_oem_finishings_table_t; typedef struct { smjob_orientation_t print[4]; smjob_orientation_t scan[4]; smjob_orientation_t faxin[4]; smjob_orientation_t faxout[4]; } smjob_oem_orientation_table_t; typedef struct { smjob_input_source_t scan[3]; } smjob_oem_input_source_table_t; typedef struct { smjob_sides_t *print[3]; } smjob_oem_sides_table_t; typedef struct { smjob_quality_t print[3]; } smjob_oem_quality_table_t; //============================================================================= // Global Variables //============================================================================= /** * @brief The OEM device settings * For each job type, add the options supported by the device. In some cases, * an option is only applicable for limited job types. * Afterward for each option, edit the define statements to indicate the number * of options that are valid. The maximum allowed can be found in the * structure definitions. */ /** * @brief The compression settings * Applicable for all job types. * This is accessed by the api function: smjob_get_supported_compression */ static smjob_oem_compression_table_t g_smjob_oem_compression_table = { { SMJOB_COMPRESSION_NONE, SMJOB_COMPRESSION_APPLICATION_GZIP }, // print { SMJOB_COMPRESSION_NONE, SMJOB_COMPRESSION_APPLICATION_GZIP }, // scan { SMJOB_COMPRESSION_NONE, SMJOB_COMPRESSION_APPLICATION_GZIP }, // faxin { SMJOB_COMPRESSION_NONE, SMJOB_COMPRESSION_APPLICATION_GZIP }, // faxout }; #define SMJOB_NUM_COMP_PRINT 2 #define SMJOB_NUM_COMP_SCAN 2 #define SMJOB_NUM_COMP_FAXIN 2 #define SMJOB_NUM_COMP_FAXOUT 2 /** * @brief The format settings * Applicable for all job types. * This is accessed by the api function: smjob_get_supported_format */ static smjob_oem_format_table_t g_smjob_oem_format_table = { { #ifdef HAVE_AIRPRINT SMJOB_FORMAT_IMAGE_URF, #endif // HAVE_AIRPRINT SMJOB_FORMAT_APPLICATION_OCTET_STREAM, // TODO: 3/2014 temporarily removed until we determine how to deliver ipp attributes like scaling and // rotation to the print subsystem // SMJOB_FORMAT_IMAGE_JPEG, SMJOB_FORMAT_APPLICATION_PCLM }, // print { SMJOB_FORMAT_UNKNOWN, SMJOB_FORMAT_APPLICATION_OCTET_STREAM, SMJOB_FORMAT_IMAGE_JPEG }, // scan { SMJOB_FORMAT_UNKNOWN, SMJOB_FORMAT_APPLICATION_OCTET_STREAM, SMJOB_FORMAT_IMAGE_JPEG }, // faxin { SMJOB_FORMAT_UNKNOWN, SMJOB_FORMAT_APPLICATION_OCTET_STREAM, SMJOB_FORMAT_IMAGE_JPEG }, // faxout }; #ifdef HAVE_AIRPRINT //#define SMJOB_NUM_FORMAT_PRINT 4 #define SMJOB_NUM_FORMAT_PRINT 3 #else // !HAVE_AIRPRINT //#define SMJOB_NUM_FORMAT_PRINT 3 #define SMJOB_NUM_FORMAT_PRINT 2 #endif // HAVE_AIRPRINT #define SMJOB_NUM_FORMAT_SCAN 3 #define SMJOB_NUM_FORMAT_FAXIN 3 #define SMJOB_NUM_FORMAT_FAXOUT 3 /** * @brief The finishing settings * Applicable for all job types. * This is accessed by the api function: smjob_get_supported_finishings */ static smjob_oem_finishings_table_t g_smjob_oem_finishings_table = { { SMJOB_FINISHING_NONE }, // print }; #define SMJOB_NUM_FINISHINGS_PRINT 1 /** * @brief The orientation settings * Applicable for all job types. * This is accessed by the api function: smjob_get_supported_orientation */ static smjob_oem_orientation_table_t g_smjob_oem_orientation_table = { { SMJOB_ORIENTATION_PORTRAIT, SMJOB_ORIENTATION_LANDSCAPE, SMJOB_ORIENTATION_REVERSE_LANDSCAPE, SMJOB_ORIENTATION_REVERSE_PORTRAIT }, // print { SMJOB_ORIENTATION_PORTRAIT, SMJOB_ORIENTATION_LANDSCAPE, SMJOB_ORIENTATION_REVERSE_PORTRAIT, SMJOB_ORIENTATION_REVERSE_LANDSCAPE }, // scan { SMJOB_ORIENTATION_PORTRAIT, SMJOB_ORIENTATION_LANDSCAPE, SMJOB_ORIENTATION_REVERSE_PORTRAIT, SMJOB_ORIENTATION_REVERSE_LANDSCAPE }, // faxin { SMJOB_ORIENTATION_PORTRAIT, SMJOB_ORIENTATION_LANDSCAPE, SMJOB_ORIENTATION_REVERSE_PORTRAIT, SMJOB_ORIENTATION_REVERSE_LANDSCAPE }, // faxout }; #define SMJOB_NUM_ORIENTATION_PRINT 4 #define SMJOB_NUM_ORIENTATION_SCAN 4 #define SMJOB_NUM_ORIENTATION_FAXIN 4 #define SMJOB_NUM_ORIENTATION_FAXOUT 4 /** * @brief The resolution settings * Applicable for all job types. * NOTE here can only specify one type of units * This is accessed by the api function: smjob_get_supported_resolution */ static smjob_resolution_t g_smjob_oem_resolution_table [] = { // width height units { 600, 600, SMJOB_RES_UNIT_DOTS_PER_INCH }, // print { 600, 600, SMJOB_RES_UNIT_DOTS_PER_INCH }, // scan { 600, 600, SMJOB_RES_UNIT_DOTS_PER_INCH }, // faxin { 600, 600, SMJOB_RES_UNIT_DOTS_PER_INCH }, // faxout }; #define SMJOB_NUM_RESOLUTION_PRINT 1 /** * @brief The input source settings * Applicable only for scan. * This is accessed by the api function: smjob_get_supported_input_source */ static smjob_oem_input_source_table_t g_smjob_oem_input_source_table = { { SMJOB_INPUT_SOURCE_ADF, SMJOB_INPUT_SOURCE_ADF_DUPLEX, SMJOB_INPUT_SOURCE_PLATEN }, }; #define SMJOB_NUM_INPUT_SOURCE_SCAN 3 /** * @brief The minimum and maxiumum range of copies allowed * Applicable only for print. * This is accessed by the api function: smjob_get_supported_copies */ #define SMJOB_PRINT_MIN_COPIES 1 #define SMJOB_PRINT_MAX_COPIES 500 /** * @brief The collation setting * Applicable only for print. * This is accessed by the api function: smjob_get_supported_sheet_collate */ #define SMJOB_PRINT_SHEET_COLLATE true /** * @brief The sides settings * Applicable only for print. * This is accessed by the api function: smjob_get_supported_sides */ static smjob_oem_sides_table_t g_smjob_oem_sides_table = { { SMJOB_SIDES_ONE_SIDED, SMJOB_SIDES_TWO_SIDED_LONG_EDGE, SMJOB_SIDES_TWO_SIDED_SHORT_EDGE } }; #define SMJOB_NUM_SIDES_PRINT 3 /** * @brief The quality settings * Applicable only for print. * This is accessed by the api function: smjob_get_supported_quality */ static smjob_oem_quality_table_t g_smjob_oem_quality_table = { { SMJOB_QUALITY_DRAFT, SMJOB_QUALITY_NORMAL, SMJOB_QUALITY_HIGH }, }; #define SMJOB_NUM_QUALITY_PRINT 3 /** * @brief The input source settings * Applicable only for scan. * This is accessed by the api function: smjob_get_supported_input_source */ /** * @brief The print content optimize settings. */ static smjob_print_content_optimize_t *g_smjob_print_content_optimize_table[] = { SMJOB_PRINT_CONTENT_OPTIMIZE_AUTO, SMJOB_PRINT_CONTENT_OPTIMIZE_GRAPHICS, SMJOB_PRINT_CONTENT_OPTIMIZE_PHOTO, SMJOB_PRINT_CONTENT_OPTIMIZE_TEXT, SMJOB_PRINT_CONTENT_OPTIMIZE_TEXT_AND_GRAPHICS }; static uint32_t g_smjob_print_content_optimize_table_size = (sizeof(g_smjob_print_content_optimize_table) / sizeof(smjob_print_content_optimize_t *)); //============================================================================= // Function Definitions //============================================================================= /** * @brief The oem function definitions * These accessor functions are called by the smjob_api functions (smjob_get_supported_*) */ //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_icons(smjob_type_t job_type, uint32_t index, char** icon) { smjob_rcode_t sm_res = SMJOB_OK; static char *printer_icons[] = { "/images/airprint_48.png", "/images/airprint_128.png", "/images/airprint_512.png", }; // Check inputs if( !icon ) { sm_res = SMJOB_FAIL; goto done; } // This default code will say that each media table entry is stationery type. switch( job_type ) { case SMJOB_TYPE_PRINT: { uint32_t num_printer_icons = sizeof(printer_icons)/sizeof(char *); if (index >= num_printer_icons) { // index out of range sm_res = SM_BAD_INDEX; } else { *icon = (char *)printer_icons[index]; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_compression(smjob_type_t job_type, uint32_t index, smjob_compression_t **value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } // Lookup the value per job_type and index // For each job_type, verify that the index isn't out of bounds switch ( job_type ) { case SMJOB_TYPE_PRINT: // if ( SMJOB_NUM_COMP_PRINT <= index ) // { *value = SMJOB_COMPRESSION_NONE; // } // else // { // *value = g_smjob_oem_compression_table.print[index]; // } break; case SMJOB_TYPE_SCAN: if ( SMJOB_NUM_COMP_SCAN <= index ) { *value = SMJOB_COMPRESSION_NONE; sm_res = SM_BAD_INDEX; } else { *value = g_smjob_oem_compression_table.scan[index]; } break; case SMJOB_TYPE_FAXIN: if ( SMJOB_NUM_COMP_FAXIN <= index ) { *value = SMJOB_COMPRESSION_NONE; sm_res = SM_BAD_INDEX; } else { *value = g_smjob_oem_compression_table.faxin[index]; } break; case SMJOB_TYPE_FAXOUT: if ( SMJOB_NUM_COMP_FAXOUT <= index ) { *value = SMJOB_COMPRESSION_NONE; sm_res = SM_BAD_INDEX; } else { *value = g_smjob_oem_compression_table.faxout[index]; } break; default: *value = SMJOB_COMPRESSION_NONE; break; } return sm_res; } //----------------------------------------------------------------------------- smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_format(smjob_type_t job_type, smjob_format_t **value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_format_t *format; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } // Lookup the value per job_type and index // For each job_type, verify that the index isn't out of bounds switch ( job_type ) { case SMJOB_TYPE_PRINT: if ( SMJOB_NUM_FORMAT_PRINT <= 0 ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.print[0]; } break; case SMJOB_TYPE_SCAN: if ( SMJOB_NUM_FORMAT_SCAN <= 0 ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.scan[0]; } break; case SMJOB_TYPE_FAXIN: if ( SMJOB_NUM_FORMAT_FAXIN <= 0 ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.faxin[0]; } break; case SMJOB_TYPE_FAXOUT: if ( SMJOB_NUM_FORMAT_FAXOUT <= 0 ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.faxout[0]; } break; default: format = SMJOB_FORMAT_UNKNOWN; break; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = format; } return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_format(smjob_type_t job_type, uint32_t index, smjob_format_t **value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_format_t *format; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } // Lookup the value per job_type and index // For each job_type, verify that the index isn't out of bounds switch ( job_type ) { case SMJOB_TYPE_PRINT: if ( SMJOB_NUM_FORMAT_PRINT <= index ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.print[index]; } break; case SMJOB_TYPE_SCAN: if ( SMJOB_NUM_FORMAT_SCAN <= index ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.scan[index]; } break; case SMJOB_TYPE_FAXIN: if ( SMJOB_NUM_FORMAT_FAXIN <= index ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.faxin[index]; } break; case SMJOB_TYPE_FAXOUT: if ( SMJOB_NUM_FORMAT_FAXOUT <= index ) { format = SMJOB_FORMAT_UNKNOWN; sm_res = SM_BAD_INDEX; } else { format = g_smjob_oem_format_table.faxout[index]; } break; default: format = SMJOB_FORMAT_UNKNOWN; break; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = format; } return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_finishings(smjob_type_t job_type, uint32_t index, smjob_finishing_t *value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_finishing_t finishing; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } finishing = SMJOB_FINISHING_NONE; // default returned on error // Lookup the value per job_type and index // For each job_type, verify that the index isn't out of bounds switch ( job_type ) { case SMJOB_TYPE_PRINT: if ( SMJOB_NUM_FINISHINGS_PRINT <= index ) { sm_res = SM_BAD_INDEX; } else { finishing = g_smjob_oem_finishings_table.print[index]; } break; default: sm_res = SMJOB_FAIL; // unsupported/invalid job type break; } // Assign result to the return value *value = finishing; return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_orientation(smjob_type_t job_type, smjob_orientation_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); return SMJOB_FAIL; } // Everyone loves PORTRAIT! *value = SMJOB_ORIENTATION_PORTRAIT; return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_orientation(smjob_type_t job_type, uint32_t index, smjob_orientation_t *value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_orientation_t orientation = SMJOB_ORIENTATION_PORTRAIT; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } // Lookup the value per job_type and index // For each job_type, verify that the index isn't out of bounds switch ( job_type ) { case SMJOB_TYPE_PRINT: if ( SMJOB_NUM_ORIENTATION_PRINT <= index ) { orientation = SMJOB_ORIENTATION_PORTRAIT; sm_res = SM_BAD_INDEX; } else { orientation = g_smjob_oem_orientation_table.print[index]; } break; case SMJOB_TYPE_SCAN: if ( SMJOB_NUM_ORIENTATION_SCAN <= index ) { orientation = SMJOB_ORIENTATION_PORTRAIT; sm_res = SM_BAD_INDEX; } else { orientation = g_smjob_oem_orientation_table.scan[index]; } break; case SMJOB_TYPE_FAXIN: if ( SMJOB_NUM_ORIENTATION_FAXIN <= index ) { orientation = SMJOB_ORIENTATION_PORTRAIT; sm_res = SM_BAD_INDEX; } else { orientation = g_smjob_oem_orientation_table.faxin[index]; } break; case SMJOB_TYPE_FAXOUT: if ( SMJOB_NUM_ORIENTATION_FAXOUT <= index ) { orientation = SMJOB_ORIENTATION_PORTRAIT; sm_res = SM_BAD_INDEX; } else { orientation = g_smjob_oem_orientation_table.faxout[index]; } break; default: orientation = SMJOB_ORIENTATION_PORTRAIT; break; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = orientation; } return sm_res; } //----------------------------------------------------------------------------- smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_resolution(smjob_type_t job_type, smjob_resolution_t *value) { static const smjob_resolution_t resolution = { .xfeed_dir = 600, .feed_dir = 600, .units = SMJOB_RES_UNIT_DOTS_PER_INCH, }; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); return SMJOB_FAIL; } *value = resolution; return SMJOB_OK; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_resolution(smjob_type_t job_type, uint32_t index, smjob_resolution_t *value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_resolution_t resolution = {600,600,SMJOB_RES_UNIT_DOTS_PER_INCH}; // Check inputs if ( ( 0 == value ) || (( SMJOB_TYPE_UNSPECIFIED != job_type ) && ( SMJOB_TYPE_PRINT != job_type ) && ( SMJOB_TYPE_SCAN != job_type ) && ( SMJOB_TYPE_FAXIN != job_type ) && ( SMJOB_TYPE_FAXOUT != job_type )) ) { DBG_PRINTF_ERR("%s: Invalid job_type or value provided \n", __func__); return SMJOB_FAIL; } // Start with an initialized resoltion //memset(value, 0, sizeof(smjob_resolution_t)); // Lookup the value per job_type and index // For each job_type, verify that the index isn't out of bounds switch ( job_type ) { case SMJOB_TYPE_PRINT: // Verify that the index isn't out of bounds if ( SMJOB_NUM_RESOLUTION_PRINT <= index ) { sm_res = SM_BAD_INDEX; } else { resolution = g_smjob_oem_resolution_table[0]; } break; case SMJOB_TYPE_SCAN: resolution = g_smjob_oem_resolution_table[1]; break; case SMJOB_TYPE_FAXIN: resolution = g_smjob_oem_resolution_table[2]; break; case SMJOB_TYPE_FAXOUT: resolution = g_smjob_oem_resolution_table[3]; break; default: sm_res = SMJOB_FAIL; break; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = resolution; } return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_size_x_dim(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if(index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; break; } *value = table[index].width; break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_size_y_dim(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if(index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; break; } *value = table[index].height; break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_top_margin(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { // Default value *value = 300; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_bottom_margin(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { // Default value *value = 300; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_left_margin(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { // Default value *value = 300; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_right_margin(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { // Default value *value = 300; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_aiprint_enabled(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; if (!value) { sm_res = SMJOB_FAIL; } else { *value = 1; } return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_media_col(smjob_type_t job_type, smjob_media_col_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { // No default implementation of this; core code not wired to use this (yet) memset(value, 0, sizeof(smjob_media_col_t)); break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_size_name(smjob_type_t job_type, uint32_t index, char** name) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !name ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if(index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; break; } *name = table[index].name; break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_default_media_size_name(smjob_type_t job_type, char** name) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !name ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { *name = sm_media_size_enum_to_name(MEDIASIZE_LETTER); break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } smjob_rcode_t SY_ATTR_WEAK smjob_oem_set_supported_default_media_size_name(smjob_type_t job_type, char* name, uint32_t name_len) { return SMJOB_FAIL; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_type_name(smjob_type_t job_type, uint32_t index, char** name) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !name ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_type_entry_t *table; uint32_t cnt = sm_media_type_get_table(&table); ASSERT(table); ASSERT(cnt); if(index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; break; } *name = table[index]->name; break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_default_media_type_name(smjob_type_t job_type, char** name) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !name ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { *name = sm_media_type_enum_to_name(MEDIATYPE_MIDWEIGHT_96_110G); break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_media_table_type(smjob_type_t job_type, uint32_t index, char** name) { smjob_rcode_t sm_res = SMJOB_OK; static const char *media_type = "stationery"; // Check inputs if( !name ) { sm_res = SMJOB_FAIL; goto done; } // This default code will say that each media table entry is stationery type. switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { *name = (char *)media_type; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_media_table_duplex(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } // This default code will say that each media table entry is not duplexable. switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { *value = 0; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_media_source(smjob_type_t job_type, uint32_t index, char** source) { smjob_rcode_t sm_res = SMJOB_OK; static const char *media_source = "main"; // Check inputs if( !source ) { sm_res = SMJOB_FAIL; goto done; } // This default code will say that we only have the 'main' tray. switch( job_type ) { case SMJOB_TYPE_PRINT: { switch(index) { case 0: *source = (char *)media_source; break; default: *source = NULL; sm_res = SM_BAD_INDEX; break; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_media_table_source(smjob_type_t job_type, uint32_t index, char** source) { smjob_rcode_t sm_res = SMJOB_OK; static const char *media_source = "main"; // Check inputs if( !source ) { sm_res = SMJOB_FAIL; goto done; } // This default code will say that each media table entry is in the 'main' tray. switch( job_type ) { case SMJOB_TYPE_PRINT: { sm_media_size_entry_t *table; uint32_t cnt = sm_media_size_get_table(&table); ASSERT(table); ASSERT(cnt); if (index >= cnt) { // index out of range sm_res = SM_BAD_INDEX; } else { *source = (char *)media_source; } break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //------------------------------------------------------------------------------------------------------ // Scan only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_input_source(uint32_t index, smjob_input_source_t *value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_input_source_t input_source = SMJOB_INPUT_SOURCE_ADF; // Check inputs if ( 0 == value ) { DBG_PRINTF_ERR("%s: Invalid value provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } // Verify that the index isn't out of bounds if ( SMJOB_NUM_INPUT_SOURCE_SCAN <= index ) { sm_res = SM_BAD_INDEX; } else { input_source = g_smjob_oem_input_source_table.scan[index]; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = input_source; } return sm_res; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_copies(uint32_t *value) { // Check inputs if ( NULL == value ) { DBG_PRINTF_ERR("%s: Invalid value provided\n", __FUNCTION__); return SMJOB_FAIL; } // Assign result to the return value *value = SMJOB_PRINT_MIN_COPIES; return SMJOB_OK; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_copies(uint32_t *min_value, uint32_t *max_value) { // Check inputs if ( ( NULL == min_value ) || ( NULL == max_value ) ) { DBG_PRINTF_ERR("%s: Invalid min or max value provided\n", __FUNCTION__); return SMJOB_FAIL; } // Assign result to the return value *min_value = SMJOB_PRINT_MIN_COPIES; *max_value = SMJOB_PRINT_MAX_COPIES; return SMJOB_OK; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_sheet_collate(bool *is_supported) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if ( 0 == is_supported ) { DBG_PRINTF_ERR("%s: Invalid bool provided \n", __func__); sm_res = SMJOB_FAIL; return sm_res; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *is_supported = SMJOB_PRINT_SHEET_COLLATE; } return sm_res; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_sides(smjob_sides_t **value) { // Check inputs if ( NULL == value ) { DBG_PRINTF_ERR("%s: Invalid value provided\n", __FUNCTION__); return SMJOB_FAIL; } *value = SMJOB_SIDES_ONE_SIDED; return SMJOB_OK; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_sides(uint32_t index, smjob_sides_t **value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_sides_t *sides = NULL; // Check inputs if ( NULL == value ) { DBG_PRINTF_ERR("%s: Invalid value provided\n", __FUNCTION__); return SMJOB_FAIL; } // Verify that the index isn't out of bounds if ( SMJOB_NUM_SIDES_PRINT <= index ) { sm_res = SM_BAD_INDEX; } else { sides = g_smjob_oem_sides_table.print[index]; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = sides; } return sm_res; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_quality(smjob_quality_t *value) { // Check inputs if ( NULL == value ) { DBG_PRINTF_ERR("%s: Invalid value provided\n", __FUNCTION__); return SMJOB_FAIL; } *value = SMJOB_QUALITY_NORMAL; return SMJOB_OK; } //------------------------------------------------------------------------------------------------------ // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_quality(uint32_t index, smjob_quality_t *value) { smjob_rcode_t sm_res = SMJOB_OK; smjob_quality_t quality = SMJOB_QUALITY_DRAFT; // Check inputs if ( NULL == value ) { DBG_PRINTF_ERR("%s: Invalid value provided\n", __FUNCTION__); return SMJOB_FAIL; } // Verify that the index isn't out of bounds if ( SMJOB_NUM_QUALITY_PRINT <= index ) { sm_res = SM_BAD_INDEX; } else { quality = g_smjob_oem_quality_table.print[index]; } // Assign result to the return value if ( SMJOB_OK == sm_res ) { *value = quality; } return sm_res; } //----------------------------------------------------------------------------- smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_color_mode(smjob_type_t job_type, smjob_color_mode_t **value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { return SMJOB_FAIL; } switch( job_type ) { case SMJOB_TYPE_PRINT: { #ifdef COLOR_ENG *value = SMJOB_COLOR_MODE_COLOR; #else *value = SMJOB_COLOR_MODE_MONO; #endif break; } default: sm_res = SMJOB_FAIL; break; } return sm_res; } //----------------------------------------------------------------------------- smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_color_mode(smjob_type_t job_type, uint32_t index, smjob_color_mode_t **value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { return SMJOB_FAIL; } switch( job_type ) { case SMJOB_TYPE_PRINT: { switch(index) { case 0: *value = SMJOB_COLOR_MODE_MONO; break; case 1: *value = SMJOB_COLOR_MODE_COLOR; break; case 2: *value = SMJOB_COLOR_MODE_AUTO; break; default: // index out of range sm_res = SM_BAD_INDEX; break; } break; } default: sm_res = SMJOB_FAIL; break; } return sm_res; } //------------------------------------------------------------------------------------------------------ smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_output_bin_default(smjob_type_t job_type, char** name) { smjob_rcode_t sm_res = SMJOB_OK; static const char *default_bin_name = "face-down"; // Check inputs if( !name ) { return SMJOB_FAIL; } switch( job_type ) { case SMJOB_TYPE_PRINT: { *name = (char *)default_bin_name; break; } default: sm_res = SMJOB_FAIL; break; } return sm_res; } smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_output_bin_supported(smjob_type_t job_type, uint32_t index, char** name) { smjob_rcode_t sm_res = SMJOB_OK; static const char *bin_name = "face-down"; // Check inputs if( !name ) { return SMJOB_FAIL; } switch( job_type ) { case SMJOB_TYPE_PRINT: { if (index > 0) { // index out of range sm_res = SM_BAD_INDEX; break; } *name = (char *)bin_name; break; } default: sm_res = SMJOB_FAIL; break; } return sm_res; } smjob_rcode_t SY_ATTR_WEAK smjob_oem_markers_available(smjob_type_t job_type, uint32_t index, uint32_t *value) { smjob_rcode_t sm_res = SMJOB_OK; // Check inputs if( !value ) { sm_res = SMJOB_FAIL; goto done; } switch( job_type ) { case SMJOB_TYPE_PRINT: { if (index > 0) { // index out of range sm_res = SM_BAD_INDEX; break; } *value = 0; // markers not available break; } default: sm_res = SMJOB_FAIL; break; } done: return sm_res; } //--------------------------------------------------------------------------------------- // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_default_print_content_optimize(smjob_print_content_optimize_t **value) { *value = g_smjob_print_content_optimize_table[0]; return(SMJOB_OK); } //--------------------------------------------------------------------------------------- // Print only smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_supported_print_content_optimize(uint32_t index, smjob_print_content_optimize_t **value) { smjob_rcode_t sm_res = SMJOB_OK; if (index < g_smjob_print_content_optimize_table_size) { *value = g_smjob_print_content_optimize_table[index]; } else { sm_res = SM_BAD_INDEX; } return (sm_res); } smjob_rcode_t SY_ATTR_WEAK smjob_oem_get_printer_geo_location(smjob_type_t job_type, char** location) { // TODO - remove hardcode // per AirPrint specification ver. 1.3 section 6.7.48 and PWG 5100.13 (JSP3) section 5.6.28, // if value not specified or is unknown then we should use out-of-band value 'unknown' (value // tag defined in rfc2910 3.5.2). However APVT will fail unless we use a dummy uri value, e.g. geo:0.0 *location = "geo:0.0"; return SMJOB_OK; }
26.516304
130
0.53056
475c4584f7a57f530aca6b6b96a414d133dba282
14,557
html
HTML
examples.html
wubmeister/columns
950c7ff8f38006b8ba941ab79a7389029805726e
[ "Apache-2.0" ]
null
null
null
examples.html
wubmeister/columns
950c7ff8f38006b8ba941ab79a7389029805726e
[ "Apache-2.0" ]
null
null
null
examples.html
wubmeister/columns
950c7ff8f38006b8ba941ab79a7389029805726e
[ "Apache-2.0" ]
null
null
null
<html> <head> <title>Columns!</title> <style> body { font-family: sans-serif; } .contentbox { padding: 10px; background-color: #fafafa; border: 1px solid #ebebeb; } .container { box-sizing: border-box; width: 100%; max-width: 960px; margin: 0 auto; padding: 30px; } .spacer { height: 30px; } .example { position: relative; } .toggle-code { position: absolute; right: -64px; top: 0; width: 32px; height: 32px; background-color: #f4f4f4; border-radius: 50%; border: 2px solid #ebebeb; background: #f4f4f4 center center / 18px 18px no-repeat url("data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCAxNjQgMTY0IiB3aWR0aD0iMTY0IiBoZWlnaHQ9IjE2NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiBzdHlsZT0ic3Ryb2tlOiAjMDAwOyBzdHJva2Utd2lkdGg6IDJweDsgc3Ryb2tlLWxpbmVqb2luOiByb3VuZDsiPgogICAgPHBhdGggZD0iTTIgODJsNDAgLTM4bDggOGwtMzAgMzBsMzAgMzBsLTggOCIgLz4KICAgIDxwYXRoIGQ9Ik01NiAxNDguNzVsNDAtMTM3LjI1bDEyIDMuNzVsLTQwIDEzNy4yNXoiIC8+CiAgICA8cGF0aCBkPSJNMTIyIDEyMmwtOCAtOGwzMCAtMzBsLTMwIC0zMGw4IC04bDQwIDM4eiIgLz4KPC9zdmc+"); text-indent: 101%; white-space: nowrap; overflow: hidden; transition: background-color .2s; cursor: pointer; } .toggle-code:hover { background-color: #ebebeb; } code { display: block; white-space: pre; padding: 0 1em; background-color: #f4f4f4; border-radius: 8px; border: 2px solid #ebebeb; position: absolute; top: calc(100% + 1rem); left: 0; width: 100%; box-sizing: border-box; opacity: 0; pointer-events: none; transition: opacity .2s; box-shadow: 0 3px 24px rgba(0, 0, 0, 0.24); } .example.show-code { z-index: 1; } .example.show-code code { opacity: 1; pointer-events: auto; } #dimmer { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background-color: rgba(0, 0, 0, 0.6); opacity: 0; pointer-events: none; transition: opacity .2s; } #dimmer.visible { opacity: 1; pointer-events: auto; } </style> <link rel="stylesheet" href="columns.css" /> </head> <body> <div class="container"> <h2>Evenly divided columns</h2> <div class="example"> <div class="cols cols-auto"> <div class="col"> <div class="contentbox">Column 1</div> </div> <div class="col"> <div class="contentbox">Column 2</div> </div> <div class="col"> <div class="contentbox">Column 3</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-auto"&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <h2>Padded columns</h2> <div class="example"> <div class="cols cols-auto cols-pad"> <div class="col"> <div class="contentbox">Column 1</div> </div> <div class="col"> <div class="contentbox">Column 2</div> </div> <div class="col"> <div class="contentbox">Column 3</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-auto cols-pad"&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <div class="spacer"></div> <div class="example"> <div class="cols cols-auto cols-pad-more"> <div class="col"> <div class="contentbox">Column 1</div> </div> <div class="col"> <div class="contentbox">Column 2</div> </div> <div class="col"> <div class="contentbox">Column 3</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-auto cols-pad-more"&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <div class="spacer"></div> <div class="example"> <div class="cols cols-auto cols-pad-most"> <div class="col"> <div class="contentbox">Column 1</div> </div> <div class="col"> <div class="contentbox">Column 2</div> </div> <div class="col"> <div class="contentbox">Column 3</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-auto cols-pad-most"&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <h2>Grid</h2> <div class="example"> <div class="cols cols-grid cols-4 cols-pad"> <div class="col"> <div class="contentbox">Column 1</div> </div> <div class="col"> <div class="contentbox">Column 2</div> </div> <div class="col"> <div class="contentbox">Column 3</div> </div> <div class="col"> <div class="contentbox">Column 4</div> </div> <div class="col"> <div class="contentbox">Column 5</div> </div> <div class="col"> <div class="contentbox">Column 6</div> </div> <div class="col"> <div class="contentbox">Column 7</div> </div> <div class="col"> <div class="contentbox">Column 8</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-grid cols-4 cols-pad"&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 4&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 5&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 6&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 7&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 8&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <h2>Responsive columns</h2> <div class="example"> <div class="cols cols-2 cols-md-4"> <div class="col"> <div class="contentbox">Column 1</div> </div> <div class="col"> <div class="contentbox">Column 2</div> </div> <div class="col"> <div class="contentbox">Column 3</div> </div> <div class="col"> <div class="contentbox">Column 4</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-2 cols-md-4"&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="contentbox"&gt;Column 4&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <h2>Spanning columns</h2> <div class="example"> <div class="cols"> <div class="col col-6 col-md-3"> <div class="contentbox">Column 1</div> </div> <div class="col col-6 col-md-3"> <div class="contentbox">Column 2</div> </div> <div class="col col-12 col-md-6"> <div class="contentbox">Column 3</div> </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols"&gt; &lt;div class="col col-6 col-md-3"&gt; &lt;div class="contentbox"&gt;Column 1&lt;/div&gt; &lt;/div&gt; &lt;div class="col col-6 col-md-3"&gt; &lt;div class="contentbox"&gt;Column 2&lt;/div&gt; &lt;/div&gt; &lt;div class="col col-12 col-md-6"&gt; &lt;div class="contentbox"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code> </div> <h2>Divided columns</h2> <div class="example"> <div class="cols cols-auto cols-divide cols-pad"> <div class="col"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. </div> <div class="col"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. </div> <div class="col"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. </div> <div class="col"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. </div> </div> <a class="toggle-code">Code</a> <code> &lt;div class="cols cols-auto cols-divide cols-pad"&gt; &lt;div class="col"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. &lt;/div&gt; &lt;div class="col"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. &lt;/div&gt; &lt;div class="col"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. &lt;/div&gt; &lt;div class="col"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam auctor pharetra purus. &lt;/div&gt; &lt;/div&gt; </code> </div> </div> <div id="dimmer"></div> <script> window.addEventListener("click", function(event){ if (event.target && event.target.nodeType == Node.ELEMENT_NODE) { if (event.target.classList.contains("toggle-code")) { let toggler = event.target; let example = toggler; while (example && !example.classList.contains("example")) { example = example.parentElement; } if (example) { example.classList.toggle("show-code"); document.getElementById("dimmer").classList.toggle("visible"); } } else if (event.target.id == "dimmer") { let example = document.querySelector(".example.show-code"); if (example) { example.classList.toggle("show-code"); document.getElementById("dimmer").classList.toggle("visible"); } } } }); </script> </body> </html>
34.908873
562
0.448788
d2901d5d83bb7d1e22f2cbb56fd5da8f3c06878f
3,124
php
PHP
app/Helpers/OnHold/BudgetRule.php
pankaj4red/greek_house
3470fe433481f6795184d3f87fb470a3f299acd8
[ "MIT" ]
null
null
null
app/Helpers/OnHold/BudgetRule.php
pankaj4red/greek_house
3470fe433481f6795184d3f87fb470a3f299acd8
[ "MIT" ]
null
null
null
app/Helpers/OnHold/BudgetRule.php
pankaj4red/greek_house
3470fe433481f6795184d3f87fb470a3f299acd8
[ "MIT" ]
null
null
null
<?php namespace App\Helpers\OnHold; use App\Logging\Logger; use App\Models\Campaign; use App\Models\User; use App\Notifications\CampaignOnHold\OnHoldBudgetNotification; use App\Quotes\ScreenPrinterQuote; class BudgetRule extends OnHoldRule { protected $name = 'budget'; protected $category = 'budget'; protected $notification = OnHoldBudgetNotification::class; /** * @param Campaign $campaign * @param User $user * @return bool */ public function match(Campaign $campaign, User $user) { if ($user->type->isStaff()) { return $this->returnResult($campaign, false); } if ($campaign->budget == 'no') { return $this->returnResult($campaign, false); } $campaign = $campaign->fresh('artwork_request'); $quote = null; switch ($campaign->artwork_request->design_type) { case 'screen': $quote = new ScreenPrinterQuote(); break; case 'embroidery': $quote = new ScreenPrinterQuote(); break; default: return $this->returnResult($campaign, false); } $maxPrice = 0; foreach ($campaign->product_colors as $productColor) { if ($productColor->product->price > $maxPrice) { $maxPrice = $productColor->product->price; } } $quote->quote([ 'product_name' => '', 'product_cost' => $maxPrice, 'color_front' => $campaign->artwork_request->print_front ? $campaign->artwork_request->print_front_colors : 0, 'color_back' => $campaign->artwork_request->print_back ? $campaign->artwork_request->print_back_colors : 0, 'color_left' => $campaign->artwork_request->print_sleeve && in_array($campaign->artwork_request->print_sleeve_preferred, ['both', 'left']) ? $campaign->artwork_request->print_sleeve_colors : 0, 'color_right' => $campaign->artwork_request->print_sleeve && in_array($campaign->artwork_request->print_sleeve_preferred, ['both', 'right']) ? $campaign->artwork_request->print_sleeve_colors : 0, 'black_shirt' => $campaign->artwork_request->designer_black_shirt ? 'yes' : 'no', 'estimated_quantity_from' => estimated_quantity_by_code($campaign->artwork_request->design_type, $campaign->estimated_quantity)->from, 'estimated_quantity_to' => estimated_quantity_by_code($campaign->artwork_request->design_type, $campaign->estimated_quantity)->from, 'design_hours' => null, 'markup' => null, ]); if (! $quote->isSuccess()) { Logger::logAlert('Error while trying to process quote for on hold budget rule: '.implode('||', $quote->getErrors())); return $this->returnResult($campaign, false); } return $this->returnResult($campaign, budget_range($campaign->budget_range)[1] < $quote->getPricePerUnitTo()); } }
42.216216
219
0.59507
ad620547fd5d510c6aad295fdef0a5552bd1e025
599
asm
Assembly
programs/oeis/020/A020490.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/020/A020490.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/020/A020490.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A020490: Numbers k such that phi(k) <= sigma_0(k). ; 1,2,3,4,6,8,10,12,18,24,30 mov $4,$0 add $4,1 mov $9,$0 lpb $4 mov $0,$9 sub $4,1 sub $0,$4 mov $6,$0 mov $7,0 mov $8,$0 add $8,1 lpb $8 mov $0,$6 mov $2,0 mov $3,0 sub $8,1 sub $0,$8 add $0,8 lpb $0 dif $0,4 seq $2,267776 ; Triangle read by rows giving successive states of cellular automaton generated by "Rule 209" initiated with a single ON (black) cell. add $2,2 add $3,$2 mul $3,$2 lpe mov $5,$3 div $5,9 add $7,$5 lpe add $1,$7 lpe mov $0,$1
16.638889
155
0.525876
f769c7b38b84f91ddc5bff18c1805c200becac08
608
h
C
Log/Sink/logsink.h
Nefertarii/CPP_Server
a1f04dac2cdd6b9959e81ab36584b9a0e38cb7b9
[ "MIT" ]
null
null
null
Log/Sink/logsink.h
Nefertarii/CPP_Server
a1f04dac2cdd6b9959e81ab36584b9a0e38cb7b9
[ "MIT" ]
null
null
null
Log/Sink/logsink.h
Nefertarii/CPP_Server
a1f04dac2cdd6b9959e81ab36584b9a0e38cb7b9
[ "MIT" ]
null
null
null
#ifndef LOG_SINK_H_ #define LOG_SINK_H_ #include <Log/logformatter.h> #include <atomic> #include <memory> #include <mutex> #include <string> namespace Wasi { namespace Log { class LogMsg; class LogSink { protected: std::unique_ptr<LogFormatter> formatter; std::atomic<uint> count; std::string name; public: virtual void Logger(LogMsg& msg) = 0; virtual void Flush() = 0; virtual void Set_format(LogFormat fmt) = 0; virtual uint Get_count() = 0; virtual ~LogSink() = default; }; } } // namespace Wasi::Log #endif
19
53
0.620066
17697012bc463f6ec02b82a8270b01618fec9d46
292
html
HTML
JavaScript11.html
amce64/HTML-CSS-JavaScript
3c3ab88358360b7c6c4c168288f579154e162ac8
[ "BSD-3-Clause" ]
null
null
null
JavaScript11.html
amce64/HTML-CSS-JavaScript
3c3ab88358360b7c6c4c168288f579154e162ac8
[ "BSD-3-Clause" ]
null
null
null
JavaScript11.html
amce64/HTML-CSS-JavaScript
3c3ab88358360b7c6c4c168288f579154e162ac8
[ "BSD-3-Clause" ]
null
null
null
<!DOCTYPE html> <html lang="es" dir="ltr"> <head> <meta charset="utf-8"> <title>Ejercicio 11</title> </head> <body> <script> if (1 + 1 === 2) { console.log('La suma es correcta.'); } else { console.log('La suma es incorrecta.'); } </script> </body> </html>
14.6
44
0.541096
72b091f42cad81c664732d26f0a81a34fdac9f92
1,577
rs
Rust
src/rootless/run.rs
tosone/containerd-rs
fb29818ee7ee73b3e75eb5c40c08312d328be7c2
[ "MIT" ]
3
2021-12-06T21:39:48.000Z
2021-12-14T05:32:58.000Z
src/rootless/run.rs
tosone/containerd-rs
fb29818ee7ee73b3e75eb5c40c08312d328be7c2
[ "MIT" ]
null
null
null
src/rootless/run.rs
tosone/containerd-rs
fb29818ee7ee73b3e75eb5c40c08312d328be7c2
[ "MIT" ]
null
null
null
use nix::unistd::{execve, getcwd}; use std::ffi::CStr; pub fn run() -> Result<(), std::io::Error> { let mut env: Vec<String> = Vec::new(); std::env::vars_os().for_each(|(key, value)| { env.push(format!( "{}={}\0", key.to_str().unwrap(), value.to_str().unwrap() )); }); let mut envs = EnvCollection::new(); env.iter().for_each(|value| envs.insert(&value)); let path = CStr::from_bytes_with_nul(b"/usr/bin/nsenter\0").unwrap(); let workdir = format!("-w{}\0", getcwd().unwrap().to_str().unwrap()); let args = &[ CStr::from_bytes_with_nul(b"-r/\0").unwrap(), CStr::from_bytes_with_nul(workdir.as_bytes()).unwrap(), CStr::from_bytes_with_nul(b"--preserve-credentials\0").unwrap(), CStr::from_bytes_with_nul(b"-U\0").unwrap(), CStr::from_bytes_with_nul(b"-m\0").unwrap(), CStr::from_bytes_with_nul(b"-n\0").unwrap(), CStr::from_bytes_with_nul(b"-t\0").unwrap(), CStr::from_bytes_with_nul(b"63851\0").unwrap(), CStr::from_bytes_with_nul(b"-F\0").unwrap(), CStr::from_bytes_with_nul(b"./target/debug/examples/namespaces\0").unwrap(), ]; execve(path, args, envs.envs.as_slice()).unwrap_err(); Ok(()) } struct EnvCollection<'a> { pub envs: Vec<&'a CStr>, } impl<'a> EnvCollection<'a> { pub fn new() -> Self { EnvCollection { envs: Vec::new() } } pub fn insert(&mut self, s: &'a str) { self.envs .push(CStr::from_bytes_with_nul(s.as_bytes()).unwrap()); } }
32.183673
84
0.575143
85eef2c1086efe49f5a9e52b14c9baa497cc6299
4,727
h
C
include/drivers/vco/driver.h
waviousllc/wav-lpddr-sw
921e8b03f92c2bacb5630cf7cae4326576aa5aeb
[ "Apache-2.0" ]
14
2021-07-11T07:31:59.000Z
2021-12-16T23:10:16.000Z
include/drivers/vco/driver.h
waviousllc/wav-lpddr-sw
921e8b03f92c2bacb5630cf7cae4326576aa5aeb
[ "Apache-2.0" ]
28
2021-07-13T20:34:59.000Z
2021-12-21T23:58:54.000Z
include/drivers/vco/driver.h
waviousllc/wav-lpddr-sw
921e8b03f92c2bacb5630cf7cae4326576aa5aeb
[ "Apache-2.0" ]
8
2021-07-09T18:56:57.000Z
2022-02-10T19:25:18.000Z
/** * Copyright (c) 2021 Wavious LLC. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _VCO_DRIVER_H_ #define _VCO_DRIVER_H_ #include <stdbool.h> #include <vco/device.h> /** * @brief VCO Initialize Register Interface * * @details Initializes VCO device at register interface level. * * @param[in] vco pointer to VCO device. * @param[in] base base address of VCO device. * * @return void */ void vco_init_reg_if(vco_dev_t *vco, uint32_t base); /** * @brief VCO Set Band Register Interface * * @details Sets band, fine band, and mux settings for the VCO device. * * @param[in] vco pointer to VCO device. * @param[in] band band value to set. * @param[in] fine fine band value to set. * @param[in] mux mux value to set. * * @return void */ void vco_set_band_reg_if(vco_dev_t *vco, uint8_t band, uint8_t fine, bool mux); /** * @brief VCO Set Integer Fractional Register Interface * * @details Sets integer comparison and proportional gain settings for the VCO * device. * * @param[in] vco pointer to VCO device. * @param[in] int_comp integer comparison value to set. * @param[in] prop_gain proportional gain value to set. * * @return void */ void vco_set_int_frac_reg_if(vco_dev_t *vco, uint8_t int_comp, uint8_t prop_gain); /** * @brief VCO Set Post Divider Register Interface * * @details Sets post-divider settings for the VCO device. * * @param[in] vco pointer to VCO device. * @param[in] post_div post divider value to set. * * @return void */ void vco_set_post_div_reg_if(vco_dev_t *vco, uint8_t post_div); /** * @brief VCO Set FLL Control1 Register Interface * * @details Sets FLL control1 settings for the VCO device. * * @param[in] vco pointer to VCO device. * @param[in] band_start band start value to set. * Used for calibration. * @param[in] fine_start fine band start value to set. * Used for calibration. * @param[in] lock_count_threshold threshold value to set. * Used for calibration. * * @return void */ void vco_set_fll_control1_reg_if(vco_dev_t *vco, uint8_t band_start, uint8_t fine_start, uint8_t lock_count_threshold); /** * @brief VCO Set FLL Control2 Register Interface * * @details Sets FLL control2 settings for the VCO device. * * @param[in] vco pointer to VCO device. * @param[in] fll_refclk_count refclk_count value to set. * @param[in] fll_range range value to set. * @param[in] fll_vco_count_target target value to set. * * @return void */ void vco_set_fll_control2_reg_if(vco_dev_t *vco, uint8_t fll_refclk_count, uint8_t fll_range, uint16_t fll_vco_count_target); /** * @brief VCO Set FLL Enable Register Interface * * @details Enables / Disables FLL of VCO device. * * @param[in] vco pointer to VCO device. * @param[in] enable flag to indicate if FLL should be enabled. * * @return void */ void vco_set_fll_enable_reg_if(vco_dev_t *vco, bool enable); /** * @brief VCO Get FLL Band Status Register Interface * * @details Gets the Band and Fine Band settings for the VCO device. This is * used to get calibrated band and fine band settings. * * @param[in] vco pointer to VCO device. * @param[out] band pointer to store band value. * @param[out] fine pointer to store fine band value. * * @return void */ void vco_get_fll_band_status_reg_if(vco_dev_t *vco, uint8_t *band, uint8_t *fine); /** * @brief VCO IS FLL Locked Register Interface * * @details Returns whether VCO is in FLL lock state. Used during calibration. * * @param[in] vco pointer to VCO device. * * @return Returns whether VCO device is FLL locked. * @retval true, if locked. * @retval false if not. */ bool vco_is_fll_locked(vco_dev_t *vco); /** * @brief VCO Set Enable Register Interface * * @details Enables / Disables VCO device. * * @param[in] vco pointer to VCO device. * @param[in] enable flag to indicate if VCO should be enabled. * * @return void */ void vco_set_enable_reg_if(vco_dev_t *vco, bool enable); #endif /* _VCO_DRIVER_H_ */
30.301282
79
0.600381
b893c5fda8e03b078fe5759caacbb536dbf7910c
12,450
swift
Swift
Azure/ViewController.swift
SomnusLee1988/Azure
a3befe6e050541b787b1f155d6ee87c81b347110
[ "MIT" ]
null
null
null
Azure/ViewController.swift
SomnusLee1988/Azure
a3befe6e050541b787b1f155d6ee87c81b347110
[ "MIT" ]
null
null
null
Azure/ViewController.swift
SomnusLee1988/Azure
a3befe6e050541b787b1f155d6ee87c81b347110
[ "MIT" ]
null
null
null
// // ViewController.swift // Azure // // Created by Somnus on 16/7/5. // Copyright © 2016年 Somnus. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD import AVFoundation import AVKit import Alamofire import MJRefresh import SLAlertController let URL_SUFFIX = "(format=m3u8-aapl)" private var azureContext = 0 class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate { @IBOutlet var scrollView: UIScrollView! @IBOutlet var liveCollectionView: UICollectionView! @IBOutlet var videoCollectionView: UICollectionView! @IBOutlet var segmentBar: UIView! @IBOutlet var liveButton: UIButton! @IBOutlet var videoButton: UIButton! @IBOutlet var liveBtnBackgroundView: UIView! @IBOutlet var videoBtnBackgroundView: UIView! @IBOutlet var contentWidthConstraint: NSLayoutConstraint! @IBOutlet var segmentBarLeadingConstraint: NSLayoutConstraint! var videoArray:[AnyObject] = [] var liveArray:[AnyObject] = [] var segmentBarConstraints = [NSLayoutConstraint]() var selectedSegmentIndex = -1 { didSet { self.segmentIndexChanged() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.addObserver(self, forKeyPath: "selectedSegmentIndex", options: .New, context: &azureContext) selectedSegmentIndex = 0 self.liveCollectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { self.queryVideoData() }) self.videoCollectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { self.queryVideoData() }) self.queryVideoData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let value = UIInterfaceOrientation.Portrait.rawValue UIDevice.currentDevice().setValue(value, forKey: "orientation") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func updateViewConstraints() { super.updateViewConstraints() contentWidthConstraint.constant = view.frame.width * 2 NSLayoutConstraint.deactivateConstraints([segmentBarLeadingConstraint]) NSLayoutConstraint.deactivateConstraints(segmentBarConstraints) segmentBarConstraints.removeAll() if selectedSegmentIndex == 0 { segmentBarConstraints.append(NSLayoutConstraint(item: segmentBar, attribute: .CenterX, relatedBy: .Equal, toItem: liveBtnBackgroundView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) self.scrollView.contentOffset.x = 0 } else { segmentBarConstraints.append(NSLayoutConstraint(item: segmentBar, attribute: .CenterX, relatedBy: .Equal, toItem: videoBtnBackgroundView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) self.scrollView.contentOffset.x = self.view.frame.width } NSLayoutConstraint.activateConstraints(segmentBarConstraints) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) self.videoCollectionView.collectionViewLayout.invalidateLayout() self.liveCollectionView.collectionViewLayout.invalidateLayout() // if selectedSegmentIndex == 0 { // self.scrollView.contentOffset.x = 0 // } // else { // self.scrollView.contentOffset.x = size.width // } } func queryVideoData() { MBProgressHUD.showHUDAddedTo(self.view, animated: true) videoArray.removeAll() liveArray.removeAll() Alamofire.request(.GET, "http://epush.huaweiapi.com/content").validate().responseJSON { (response) in guard response.result.isSuccess else { print("Error while fetching remote videos: \(response.result.error)") return } guard let value = response.result.value as? [AnyObject] else { print("Malformed data received from queryVideoData service") return } for dict in value { if let mode = dict["mode"] as? String where mode == "0" { self.videoArray.append(dict) } else if let mode = dict["mode"] as? String where mode == "1" { self.liveArray.append(dict) } } dispatch_async(dispatch_get_main_queue(), { MBProgressHUD.hideHUDForView(self.view, animated: true) self.liveCollectionView.mj_header.endRefreshing() self.videoCollectionView.mj_header.endRefreshing() self.liveCollectionView.reloadData() self.videoCollectionView.reloadData() }) } } //MARK: - UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == liveCollectionView { return liveArray.count } else if collectionView == videoCollectionView { return videoArray.count } return 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if collectionView == liveCollectionView { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellID1", forIndexPath: indexPath) as! AzureCollectionViewCell let data = liveArray[indexPath.row] dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { if let imageUrl = data["poster"] as? String { if let imageData = NSData(contentsOfURL: NSURL(string: imageUrl)!) { dispatch_async(dispatch_get_main_queue(), { cell.imageView.image = UIImage(data: imageData) }) } } }) if let name = data["name"] as? String { cell.titleLabel.text = name } if let desc = data["desc"] as? String { cell.descriptionLabel.text = desc } if let hlsUrl = data["hlsUrl"] as? String { cell.playButton.addHandler({ let videoURL = NSURL(string: hlsUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!) let player = AVPlayer(URL: videoURL!) let playerViewController = AVPlayerViewController() playerViewController.player = player self.presentViewController(playerViewController, animated: true) { playerViewController.player!.play() } }) } else { cell.playButton.addHandler({ let alert = SLAlertController(title: "Something wrong may happen with this video", message: nil, image: nil, cancelButtonTitle: "OK", otherButtonTitle: nil, delay: nil, withAnimation: SLAlertAnimation.Fade) alert.alertTintColor = UIColor.RGB(255, 58, 47) alert.show(self, animated: true, completion: nil) }) } return cell } else if collectionView == videoCollectionView { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellID2", forIndexPath: indexPath) as! AzureCollectionViewCell let data = videoArray[indexPath.row] dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { if let imageUrl = data["poster"] as? String { if let imageData = NSData(contentsOfURL: NSURL(string: imageUrl)!) { dispatch_async(dispatch_get_main_queue(), { cell.imageView.image = UIImage(data: imageData) }) } } }) if let name = data["name"] as? String { cell.titleLabel.text = name } if let desc = data["desc"] as? String { cell.descriptionLabel.text = desc } if let hlsUrl = data["hlsUrl"] as? String { cell.playButton.addHandler({ let videoURL = NSURL(string: hlsUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!) let player = AVPlayer(URL: videoURL!) let playerViewController = AVPlayerViewController() playerViewController.player = player self.presentViewController(playerViewController, animated: true) { playerViewController.player!.play() } }) } else { cell.playButton.addHandler({ let alert = SLAlertController(title: "Something wrong may happen with this video", message: nil, image: nil, cancelButtonTitle: "OK", otherButtonTitle: nil, delay: nil, withAnimation: SLAlertAnimation.Fade) alert.alertTintColor = UIColor.RGB(255, 58, 47) alert.show(self, animated: true, completion: nil) }) } return cell } return UICollectionViewCell() } // MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView == self.scrollView { let offsetRatio = scrollView.contentOffset.x / self.view.frame.width var frame = self.segmentBar.frame frame.origin.x = self.view.frame.width / 4.0 - segmentBar.frame.width / 2.0 + offsetRatio * (self.view.frame.width / 2.0) segmentBar.frame = frame } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if scrollView == self.scrollView { if self.scrollView.contentOffset.x == 0 { selectedSegmentIndex = 0 } else if self.scrollView.contentOffset.x == self.view.frame.width { selectedSegmentIndex = 1 } } } // MARK: - func segmentIndexChanged() { if selectedSegmentIndex == 0 { self.liveButton.setTitleColor(UIColor.RGB(47, 160, 251), forState: .Normal) self.videoButton.setTitleColor(UIColor.blackColor(), forState: .Normal) } else if selectedSegmentIndex == 1 { self.liveButton.setTitleColor(UIColor.blackColor(), forState: .Normal) self.videoButton.setTitleColor(UIColor.RGB(47, 160, 251), forState: .Normal) } } @IBAction func liveButtonClicked(sender: AnyObject) { selectedSegmentIndex = 0 self.scrollView.scrollRectToVisible(self.liveCollectionView.frame, animated: true) } @IBAction func videoButtonClicked(sender: AnyObject) { selectedSegmentIndex = 1 self.scrollView.scrollRectToVisible(self.videoCollectionView.frame, animated: true) } }
38.190184
226
0.587791
5f93b07e00eb3f182fd7868a119ec10de29769bd
1,076
h
C
game/shared/dmo/weapon_grenade.h
ozxybox/deathmatch-src
b172615ceec461ccf78bff67c45cbc4c0517156d
[ "Unlicense" ]
null
null
null
game/shared/dmo/weapon_grenade.h
ozxybox/deathmatch-src
b172615ceec461ccf78bff67c45cbc4c0517156d
[ "Unlicense" ]
11
2020-07-18T21:14:55.000Z
2020-07-27T05:38:14.000Z
game/shared/dmo/weapon_grenade.h
ozxybox/deathmatch-src
b172615ceec461ccf78bff67c45cbc4c0517156d
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef WEAPON_GRENADE_H #define WEAPON_GRENADE_H #ifdef _WIN32 #pragma once #endif #include "dmo_weapon_basegrenade.h" #ifdef CLIENT_DLL #define CDMOGrenade C_DMOGrenade #endif //----------------------------------------------------------------------------- // Fragmentation grenades //----------------------------------------------------------------------------- class CDMOGrenade : public CBaseDMOGrenade { public: DECLARE_CLASS( CDMOGrenade, CBaseDMOGrenade ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); DECLARE_ACTTABLE(); CDMOGrenade() {} virtual DMOWeaponID GetWeaponID( void ) const { return DMO_WEAPON_GRENADE; } #ifdef CLIENT_DLL #else DECLARE_DATADESC(); virtual void EmitGrenade( Vector vecSrc, QAngle vecAngles, Vector vecVel, AngularImpulse angImpulse, CBasePlayer *pPlayer ); #endif CDMOGrenade( const CDMOGrenade & ) {} }; #endif // WEAPON_GRENADE_H
21.098039
125
0.576208
c2b9fc3bb56d7666f8f9d02c1d5463bdcfb7514b
1,145
go
Go
_vendor/src/github.com/rogpeppe/rog-go/typeapply/typeapply_test.go
lijianying10/myitcvx
470b16550b72f5c33a66f256298c61e5e7ff9bbd
[ "MIT" ]
3
2018-01-27T16:40:35.000Z
2020-06-30T03:09:03.000Z
_vendor/src/github.com/rogpeppe/rog-go/typeapply/typeapply_test.go
lijianying10/myitcvx
470b16550b72f5c33a66f256298c61e5e7ff9bbd
[ "MIT" ]
1
2017-02-28T09:58:01.000Z
2018-08-26T23:15:46.000Z
_vendor/src/github.com/rogpeppe/rog-go/typeapply/typeapply_test.go
lijianying10/myitcvx
470b16550b72f5c33a66f256298c61e5e7ff9bbd
[ "MIT" ]
3
2016-10-11T09:03:30.000Z
2018-01-24T16:49:14.000Z
package typeapply import ( "testing" ) type Targ struct { } type List struct { Next *List Targ *Targ } type Other struct { Targ *Targ } type Big struct { A *Targ B [2]*Targ C []*Targ D map[int]*Targ E map[*Targ]int F map[*Targ]*Targ G ***Targ H interface{} I *List J List // no instances: K chan *Targ L func(*Targ) *Targ } func newBig() (big *Big, n int) { T := func() *Targ { n++ return &Targ{} } pppt := func() ***Targ { pt := new(*Targ) *pt = T() ppt := new(**Targ) *ppt = pt return ppt } big = &Big{ A: T(), B: [2]*Targ{T(), T()}, C: []*Targ{T(), T()}, D: map[int]*Targ{1: T(), 2: T()}, E: map[*Targ]int{T(): 1, T(): 2}, F: map[*Targ]*Targ{T(): T(), T(): T()}, G: pppt(), H: Other{T()}, I: &List{&List{nil, T()}, T()}, J: List{&List{nil, T()}, T()}, K: make(chan *Targ), L: func(*Targ) *Targ { return nil }, } return } func TestBig(t *testing.T) { b, n := newBig() i := 0 m := make(map[*Targ]bool) Do(func(targ *Targ) { i++ if m[targ] { t.Error("target reached twice") } }, b) if i != n { t.Errorf("wrong instance count; expected %d; got %d", n, i) } }
14.679487
61
0.517031
e99e74fd414edecf2da3e3b321c8310050849528
780
rb
Ruby
spec/support/matchers/be.rb
chargify/zferral
94c6c2bb839f7bbe01de3afb13ebb1b8906d8944
[ "MIT" ]
null
null
null
spec/support/matchers/be.rb
chargify/zferral
94c6c2bb839f7bbe01de3afb13ebb1b8906d8944
[ "MIT" ]
2
2020-07-28T04:00:59.000Z
2021-09-02T01:45:58.000Z
spec/support/matchers/be.rb
chargify/zferral
94c6c2bb839f7bbe01de3afb13ebb1b8906d8944
[ "MIT" ]
null
null
null
RSpec::Matchers.define :be_an_array_of_campaigns do match do |actual| actual.is_a?(Array) && actual.first.is_a?(Hashie::Mash) && actual.first.respond_to?(:campaign_status_id) end failure_message_for_should do |actual| "expected an array of Campaigns, got #{actual.inspect}" end failure_message_for_should_not do |actual| "expected to not receive an array of Campaigns, got #{actual.inspect}" end end RSpec::Matchers.define :be_a_campaign do match do |actual| actual.is_a?(Hashie::Mash) && actual.respond_to?(:campaign_status_id) end failure_message_for_should do |actual| "expected a Campaign, got #{actual.inspect}" end failure_message_for_should_not do |actual| "expected not a Campaign, got #{actual.inspect}" end end
26
108
0.732051
8a396d38f643450f6e90ad3939af4806d0fbdcdc
4,232
rs
Rust
src/view/view_line.rs
nickolay/git-interactive-rebase-tool
afcdfb0367a350f74363a8d4ec209a3823dc318f
[ "ISC" ]
null
null
null
src/view/view_line.rs
nickolay/git-interactive-rebase-tool
afcdfb0367a350f74363a8d4ec209a3823dc318f
[ "ISC" ]
null
null
null
src/view/view_line.rs
nickolay/git-interactive-rebase-tool
afcdfb0367a350f74363a8d4ec209a3823dc318f
[ "ISC" ]
null
null
null
use crate::display::display_color::DisplayColor; use crate::view::line_segment::LineSegment; pub struct ViewLine { pinned_segments: usize, segments: Vec<LineSegment>, selected: bool, padding_color: DisplayColor, padding_dim: bool, padding_reverse: bool, padding_underline: bool, padding_character: String, } impl ViewLine { pub(crate) fn new_empty_line() -> Self { Self::new_with_pinned_segments(vec![], 1) } pub(crate) fn new(segments: Vec<LineSegment>) -> Self { Self::new_with_pinned_segments(segments, 0) } pub(crate) fn new_pinned(segments: Vec<LineSegment>) -> Self { let segments_length = segments.len(); Self::new_with_pinned_segments(segments, segments_length) } pub(crate) fn new_with_pinned_segments(segments: Vec<LineSegment>, pinned_segments: usize) -> Self { Self { selected: false, segments, pinned_segments, padding_color: DisplayColor::Normal, padding_dim: false, padding_reverse: false, padding_underline: false, padding_character: String::from(" "), } } pub(crate) const fn set_selected(mut self, selected: bool) -> Self { self.selected = selected; self } pub(crate) fn set_padding_character(mut self, character: &str) -> Self { self.padding_character = String::from(character); self } pub(crate) const fn set_padding_color_and_style( mut self, color: DisplayColor, dim: bool, underline: bool, reverse: bool, ) -> Self { self.padding_color = color; self.padding_dim = dim; self.padding_underline = underline; self.padding_reverse = reverse; self } pub(crate) const fn get_number_of_pinned_segment(&self) -> usize { self.pinned_segments } pub(crate) const fn get_segments(&self) -> &Vec<LineSegment> { &self.segments } pub(crate) const fn get_selected(&self) -> bool { self.selected } pub(super) const fn get_padding_color(&self) -> DisplayColor { self.padding_color } pub(super) const fn is_padding_dimmed(&self) -> bool { self.padding_dim } pub(super) const fn is_padding_underlined(&self) -> bool { self.padding_underline } pub(super) const fn is_padding_reversed(&self) -> bool { self.padding_reverse } pub(super) fn padding_character(&self) -> &str { self.padding_character.as_str() } } #[cfg(test)] mod tests { use crate::display::display_color::DisplayColor; use crate::view::line_segment::LineSegment; use crate::view::view_line::ViewLine; #[test] fn view_line_new() { let view_line = ViewLine::new(vec![LineSegment::new("foo"), LineSegment::new("bar")]); assert_eq!(view_line.get_number_of_pinned_segment(), 0); assert_eq!(view_line.get_segments().len(), 2); assert_eq!(view_line.get_selected(), false); } #[test] fn view_line_new_selected() { let view_line = ViewLine::new(vec![LineSegment::new("foo"), LineSegment::new("bar")]).set_selected(true); assert_eq!(view_line.get_number_of_pinned_segment(), 0); assert_eq!(view_line.get_segments().len(), 2); assert_eq!(view_line.get_selected(), true); } #[test] fn view_line_new_pinned() { let view_line = ViewLine::new_pinned(vec![ LineSegment::new("foo"), LineSegment::new("bar"), LineSegment::new("baz"), LineSegment::new("foobar"), ]); assert_eq!(view_line.get_number_of_pinned_segment(), 4); assert_eq!(view_line.get_segments().len(), 4); assert_eq!(view_line.get_selected(), false); } #[test] fn view_line_new_with_pinned_segments() { let view_line = ViewLine::new_with_pinned_segments( vec![ LineSegment::new("foo"), LineSegment::new("bar"), LineSegment::new("baz"), LineSegment::new("foobar"), ], 2, ); assert_eq!(view_line.get_number_of_pinned_segment(), 2); assert_eq!(view_line.get_segments().len(), 4); assert_eq!(view_line.get_selected(), false); } #[test] fn view_line_set_padding_color_and_style() { let view_line = ViewLine::new(vec![LineSegment::new("foo")]); let view_line = view_line.set_padding_color_and_style(DisplayColor::IndicatorColor, true, true, true); assert_eq!(view_line.get_padding_color(), DisplayColor::IndicatorColor); assert_eq!(view_line.is_padding_dimmed(), true); assert_eq!(view_line.is_padding_underlined(), true); assert_eq!(view_line.is_padding_reversed(), true); } }
25.648485
107
0.714556
1d7ab75276b1c6e2658ea7c4168acb8dfd05f2d1
1,490
kt
Kotlin
src/main/kotlin/enderbox/HumanEnderBoxBlock.kt
juliand665/Ender-Box-Fabric
f0d0320a9637a3db64fcfab856854070f24abe1b
[ "CC0-1.0" ]
null
null
null
src/main/kotlin/enderbox/HumanEnderBoxBlock.kt
juliand665/Ender-Box-Fabric
f0d0320a9637a3db64fcfab856854070f24abe1b
[ "CC0-1.0" ]
null
null
null
src/main/kotlin/enderbox/HumanEnderBoxBlock.kt
juliand665/Ender-Box-Fabric
f0d0320a9637a3db64fcfab856854070f24abe1b
[ "CC0-1.0" ]
null
null
null
package enderbox import net.minecraft.block.BlockState import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.ItemPlacementContext import net.minecraft.item.ItemStack import net.minecraft.item.ItemUsageContext import net.minecraft.util.ActionResult import net.minecraft.util.Hand import net.minecraft.util.ItemScatterer import net.minecraft.util.hit.BlockHitResult import net.minecraft.util.math.BlockPos import net.minecraft.world.BlockView import net.minecraft.world.World class HumanEnderBoxBlock(settings: Settings) : EnderBoxBlock(settings) { override fun onUse(blockState: BlockState, world: World, pos: BlockPos, player: PlayerEntity, hand: Hand, hitResult: BlockHitResult): ActionResult { val newState = { blockData: BlockData -> if (player.isSneaking) { blockData.blockState } else { val context = ItemUsageContext(player, hand, hitResult) blockData.block.getPlacementState(ItemPlacementContext(context)) ?: blockData.blockState } } unwrapBlock(world, pos, newState) if (world.isClient) return ActionResult.SUCCESS if (!player.isCreative) { ItemScatterer.spawn(world, pos.x.toDouble(), pos.y.toDouble(), pos.z.toDouble(), ItemStack(EnderBoxMod.humanEnderBoxBlock)) } return ActionResult.SUCCESS } override fun getPickStack(blockView: BlockView, pos: BlockPos, blockState: BlockState): ItemStack { return ItemStack(this).apply { blockData = EnderBoxBlockEntity.get(blockView, pos).storedBlock } } }
34.651163
149
0.781879
7eaa19b9808220eeb09541cb76b1ea54fb4d3ce7
636
sql
SQL
migrations/00015_create_release_logs_table.sql
estafette/estafette-ci-db-migrator
a3d7f72a681901e83f5e0308181621e4d8714c00
[ "MIT" ]
null
null
null
migrations/00015_create_release_logs_table.sql
estafette/estafette-ci-db-migrator
a3d7f72a681901e83f5e0308181621e4d8714c00
[ "MIT" ]
2
2019-11-24T08:52:40.000Z
2021-08-13T12:27:33.000Z
migrations/00015_create_release_logs_table.sql
estafette/estafette-ci-db-migrator
a3d7f72a681901e83f5e0308181621e4d8714c00
[ "MIT" ]
null
null
null
-- +goose Up -- SQL in this section is executed when the migration is applied. CREATE TABLE release_logs ( id SERIAL PRIMARY KEY, repo_source VARCHAR(256), repo_owner VARCHAR(256), repo_name VARCHAR(256), release_id INT, steps JSONB, inserted_at TIMESTAMP WITH TIME ZONE DEFAULT now() ); CREATE UNIQUE INDEX release_logs_repo_source_repo_owner_repo_name_release_id_idx ON release_logs (repo_source, repo_owner, repo_name, release_id); CREATE INDEX release_logs_steps ON release_logs USING GIN (steps); -- +goose Down -- SQL in this section is executed when the migration is rolled back. DROP TABLE IF EXISTS release_logs;
37.411765
146
0.790881
85c9d49a4657af5ca503e716150c69fd48ce0bda
476
js
JavaScript
index.js
lainlee/singleton-helper
b252c2c676e2f390a84454ddf18e7fa699d53817
[ "MIT" ]
1
2021-04-26T06:36:19.000Z
2021-04-26T06:36:19.000Z
index.js
lainlee/singleton-helper
b252c2c676e2f390a84454ddf18e7fa699d53817
[ "MIT" ]
null
null
null
index.js
lainlee/singleton-helper
b252c2c676e2f390a84454ddf18e7fa699d53817
[ "MIT" ]
null
null
null
const singletonHelper = (func = Promise.resolve) => { return (() => { let single = null return (...params) => { if (!single) { single = Promise.resolve() .then(() => { return func(...params) }) .then((rs) => { single = null return rs }) .catch((err) => { throw err }) } return single } })() } module.exports = singletonHelper
20.695652
53
0.413866
4636bb6dd695e6a5dd1ad4ff18ee146c9b5830ab
1,914
pks
SQL
5.2.3/Database/Packages/AFW_12_FAVR_PKG.pks
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
1
2017-07-06T14:53:28.000Z
2017-07-06T14:53:28.000Z
5.2.3/Database/Packages/AFW_12_FAVR_PKG.pks
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
null
null
null
5.2.3/Database/Packages/AFW_12_FAVR_PKG.pks
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
null
null
null
SET DEFINE OFF; create or replace package afw_12_favr_pkg as function obten_favr (pnu_struc_aplic in number ,pnu_seqnc_struc_aplic in number ,pnu_utils in number default null) return number; procedure ajout_favr (pnu_struc_aplic in number ,pnu_seqnc_struc_aplic in number ,pnu_utils in number default null ,pbo_appel_plugn in boolean default true ,pva_clas in varchar2 default 'fa-star' ,pva_titre in varchar2 default 'Supprimer de vos favoris' ,pva_clas_inver in varchar2 default 'fa-star-o'); procedure suprm_favr (pnu_struc_aplic in number ,pnu_seqnc_struc_aplic in number ,pnu_utils in number default null ,pbo_appel_plugn in boolean default true ,pva_clas in varchar2 default 'fa-star-o' ,pva_titre in varchar2 default 'Ajouter aux favoris' ,pva_clas_inver in varchar2 default 'fa-star'); function obten_icone_favr (pnu_seqnc_struc_aplic in number ,pnu_struc_aplic in number default null ,pnu_utils in number default null ,pva_clas_selct in varchar2 default 'fa-star' ,pva_titre_selct in varchar2 default 'Supprimer de vos favoris' ,pva_clas_non_selct in varchar2 default 'fa-star-o' ,pva_titre_non_selct in varchar2 default 'Ajouter aux favoris') return varchar2; end afw_12_favr_pkg; /
54.685714
99
0.516719
85d32f688b448bd41be644b30f9dbd11dfdb7918
8,063
js
JavaScript
exercises/exercise-10/node_modules/str-utils/str-utils.js
creanium/typescript-exercises
4c28e88968fbce88bec00fb35e3036d016b57dd1
[ "MIT" ]
null
null
null
exercises/exercise-10/node_modules/str-utils/str-utils.js
creanium/typescript-exercises
4c28e88968fbce88bec00fb35e3036d016b57dd1
[ "MIT" ]
null
null
null
exercises/exercise-10/node_modules/str-utils/str-utils.js
creanium/typescript-exercises
4c28e88968fbce88bec00fb35e3036d016b57dd1
[ "MIT" ]
null
null
null
var strUtils = this; strUtils.abbreviate = function (string, maxWidth, offset) { if (strUtils.isEmpty(string)) { return null; } if (offset >= 4) { return '...' + String(string).substring(offset, maxWidth) + '...'; } return String(string).substring(0, maxWidth) + '...'; }; strUtils.abbreviateMiddle = function (string, middle, length) { if (strUtils.isEmpty(string)) { return null; } string = String(string); if (length > 0 && length < string.length) { return string.substring(0, length) + middle + string.substring(length); } return string; }; strUtils.appendIfMissing = function (string, suffix, suffixes) { var endsWith = false; if (strUtils.isEmpty(string)) { return string; } string = String(string); suffix = String(suffix); if (suffixes !== undefined && suffixes.length > 0) { endsWith = suffixes.every(function (s) { return this.endsWith(string, String(s)); }.bind(this)); } else { endsWith = this.endsWith(string, suffix); } return !endsWith ? string += suffix : string; }; strUtils.capitalize = function (string) { if (strUtils.isEmpty(string)) { return null; } string = String(string); return string.substring(0, 1).toUpperCase() + string.substring(1); }; strUtils.chomp = function (string) { var regexp = /[\n\r]{1}$/; if (strUtils.isEmpty(string)) { return null; } return string.replace(regexp, ''); }; strUtils.difference = function (string, comparison) { if (strUtils.isEmpty(string) || strUtils.isEmpty(comparison)) { return null; } var position = 0, stringArray = String(string).split(''), comparisonArray = String(comparison).split(''); stringArray.forEach(function (char, index) { if (char === comparisonArray[index]) { position = index + 1; } }); return comparisonArray.join('').substring(position); }; strUtils.endsWith = function (string, suffix) { string = String(string); suffix = String(suffix); return string.indexOf(suffix) === string.length - suffix.length; }; strUtils.endsWithIgnoreCase = function (string, suffix) { return this.endsWith(String(string).toLowerCase(), String(suffix).toLowerCase()); }; strUtils.endsWithAny = function (string, suffixArray) { return suffixArray.some(function (suffix) { return this.endsWith(string, suffix); }.bind(this)); }; strUtils.indexOfDifference = function (string, comparison) { return String(string) === String(comparison) ? -1 : String(comparison).indexOf(this.difference(string, comparison)); }; strUtils.isAllLowercase = function (string) { if (strUtils.isEmpty(string)) { return false; } return /^[a-z]*$/.test(string); }; strUtils.isAllUppercase = function (string) { if (strUtils.isEmpty(string)) { return false; } return /^[A-Z]*$/.test(string); }; strUtils.isAnyEmpty = function () { var stringArray = Array.prototype.slice.call(arguments); return stringArray.some(function (string) { return strUtils.isEmpty(string); }); }; strUtils.isEmpty = function (string) { return (string == null || string.length == 0); }; strUtils.isNoneEmpty = function () { var stringArray = Array.prototype.slice.call(arguments); return stringArray.every(function (string) { return strUtils.isNotEmpty(String(string)); }); }; strUtils.isNotEmpty = function (string) { return (string !== null && string.length > 0); }; strUtils.leftPad = function (string, length, char) { var padString = ''; char = char !== undefined ? String(char) : ''; for (var i = 0; i < length; i++) { if (char.length > 0) { padString += String(char); } else { padString += ' '; } } return padString + String(string); }; strUtils.normalizeSpace = function (string) { return String(string).replace(/\s\s+/g, ' ').trim(); }; strUtils.prependIfMissing = function (string, prefix, prefixes) { var startsWith = false; if (strUtils.isEmpty(string)) { return string; } string = String(string); prefix = String(prefix); if (prefixes !== undefined && prefixes.length > 0) { startsWith = prefixes.every(function (s) { return strUtils.startsWith(string, String(s)); }.bind(this)); } else { startsWith = this.startsWith(string, prefix); } return !startsWith ? prefix + string : string; }; strUtils.removeEnd = function (string, remove) { var position; if (strUtils.isEmpty(string)) { return null; } string = String(string); remove = String(remove); position = string.indexOf(remove); if (position === string.length - remove.length) { return string.substring(0, position); } else { return string; } }; strUtils.removeEndIgnoreCase = function (string, remove) { var position, tempString; if (strUtils.isEmpty(string)) { return null; } string = String(string); tempString = string; remove = String(remove).toLowerCase(); string = string.toLowerCase(); position = string.indexOf(remove); if (position === string.length - remove.length) { return tempString.substring(0, position); } else { return tempString; } }; strUtils.removeStart = function (string, remove) { if (strUtils.isEmpty(string)) { return null; } string = String(string); remove = String(remove); if (string.indexOf(remove) === 0) { return string.substring(remove.length); } else { return string; } }; strUtils.removeStartIgnoreCase = function (string, remove) { var tempString; if (strUtils.isEmpty(string)) { return null; } string = String(string); tempString = string; remove = String(remove).toLowerCase(); string = string.toLowerCase(); if (string.indexOf(remove) === 0) { return tempString.substring(remove.length); } else { return tempString; } }; strUtils.rightPad = function (string, length, char) { var padString = ''; char = char !== undefined ? String(char) : ''; for (var i = 0; i < length; i++) { if (char.length > 0) { padString += String(char); } else { padString += ' '; } } return String(string) + padString; }; strUtils.startsWith = function (string, prefix) { return String(string).indexOf(String(prefix)) === 0; }; strUtils.startsWithIgnoreCase = function (string, prefix) { return this.startsWith(String(string).toLowerCase(), String(prefix).toLowerCase()); }; strUtils.startsWithAny = function (string, prefixArray) { return prefixArray.some(function (prefix) { return this.startsWith(string, prefix); }.bind(this)); }; strUtils.swapCase = function (string) { var returnString = ''; if (strUtils.isEmpty(string)) { return null; } string.split('').forEach(function (character) { if (character === character.toUpperCase()) { returnString += character.toLowerCase(); } else { returnString += character.toUpperCase(); } }); return returnString; }; strUtils.uncapitalize = function (string) { if (strUtils.isEmpty(string)) { return null; } string = String(string); return string.substring(0, 1).toLowerCase() + string.substring(1); }; strUtils.wrap = function (string, char) { return String(char) + String(string) + String(char); }; module.exports = strUtils;
24.809231
121
0.585762
e97dfab850f9f203d1821d52aedbb0015e94fe00
1,872
go
Go
frame.go
guotie/stomp
a9f32faeebdea0a3f04db3e9676da166a92cdfde
[ "Apache-2.0" ]
10
2015-06-01T02:21:01.000Z
2019-07-09T10:22:24.000Z
frame.go
guotie/stomp
a9f32faeebdea0a3f04db3e9676da166a92cdfde
[ "Apache-2.0" ]
null
null
null
frame.go
guotie/stomp
a9f32faeebdea0a3f04db3e9676da166a92cdfde
[ "Apache-2.0" ]
4
2016-03-22T13:34:30.000Z
2019-03-05T09:21:54.000Z
package stomp // A Frame represents a STOMP frame. A frame consists of a command // followed by a collection of header elements, and then an optional // body. // // Users of this package will not normally need to make use of the Frame // type directly. It is a lower level type useful for implementing // STOMP protocol handlers. type Frame struct { Command string *Header Body []byte } // NewFrame creates a new STOMP frame with the specified command and headers. // The headers should contain an even number of entries. Each even index is // the header name, and the odd indexes are the assocated header values. func NewFrame(command string, headers ...string) *Frame { f := &Frame{Command: command, Header: &Header{}} for index := 0; index < len(headers); index += 2 { f.Add(headers[index], headers[index+1]) } return f } // Clone creates a deep copy of the frame and its header. The cloned // frame shares the body with the original frame. func (f *Frame) Clone() *Frame { return &Frame{Command: f.Command, Header: f.Header.Clone(), Body: f.Body} } func (f *Frame) verifyConnect(version Version, isStomp bool) error { switch version { case V10: if isStomp { } case V11: case V12: } return nil } func (f *Frame) verifyMandatory(keys ...string) error { for _, key := range keys { if _, ok := f.Header.index(key); !ok { return &Error{ Message: "missing header: " + key, Frame: f, } } } return nil } func (f *Frame) HeaderBytes() (buf []byte) { buf = append(buf, []byte(f.Command)...) buf = append(buf, newlineSlice...) if f.Header != nil { for i := 0; i < f.Header.Len(); i++ { key, value := f.Header.GetAt(i) buf = append(buf, []byte(key)...) buf = append(buf, colonSlice...) buf = append(buf, []byte(value)...) buf = append(buf, newlineSlice...) } } buf = append(buf, newlineSlice...) return }
26
77
0.666132
2a67b54b657f632ea1a1d30303ebbd460e5727f2
5,137
java
Java
storage/db/src/main/java/org/artifactory/storage/db/fs/entity/Stat.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
3
2016-01-21T11:49:08.000Z
2018-12-11T21:02:11.000Z
storage/db/src/main/java/org/artifactory/storage/db/fs/entity/Stat.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
null
null
null
storage/db/src/main/java/org/artifactory/storage/db/fs/entity/Stat.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
5
2015-12-08T10:22:21.000Z
2021-06-15T16:14:00.000Z
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.storage.db.fs.entity; import com.google.common.base.Strings; /** * Represents a record in the stats table. * * @author Yossi Shaul */ public class Stat { private final long nodeId; private final long downloadCount; private final long lastDownloaded; private final String lastDownloadedBy; private long remoteDownloadCount; private long remoteLastDownloaded; private String remoteLastDownloadedBy; private final String origin; public Stat(long nodeId, long downloadCount, long lastDownloaded, String lastDownloadedBy) { this.nodeId = nodeId; this.downloadCount = downloadCount; this.lastDownloadedBy = lastDownloadedBy; this.lastDownloaded = lastDownloaded; this.remoteDownloadCount = 0; this.remoteLastDownloaded = 0; this.remoteLastDownloadedBy = null; this.origin = null; } public Stat(long nodeId, String remoteLastDownloadedBy, long remoteDownloadCount, long remoteLastDownloaded, String origin) { this.nodeId = nodeId; this.remoteDownloadCount = remoteDownloadCount; this.remoteLastDownloaded = remoteLastDownloaded; this.remoteLastDownloadedBy = remoteLastDownloadedBy; this.downloadCount = 0; this.lastDownloadedBy = null; this.lastDownloaded = 0; this.origin = origin; } public Stat(long nodeId, long downloadCount, long lastDownloaded, String lastDownloadedBy, long remoteDownloadCount, long remoteLastDownloaded, String remoteLastDownloadedBy) { this.nodeId = nodeId; this.downloadCount = downloadCount; this.lastDownloaded = lastDownloaded; this.lastDownloadedBy = lastDownloadedBy; this.remoteDownloadCount = remoteDownloadCount; this.remoteLastDownloaded = remoteLastDownloaded; this.remoteLastDownloadedBy = remoteLastDownloadedBy; this.origin = null; } public Stat(long nodeId, long downloadCount, long lastDownloaded, String lastDownloadedBy, long remoteDownloadCount, long remoteLastDownloaded, String remoteLastDownloadedBy, String origin) { this.nodeId = nodeId; this.downloadCount = downloadCount; this.lastDownloaded = lastDownloaded; this.lastDownloadedBy = lastDownloadedBy; this.remoteDownloadCount = remoteDownloadCount; this.remoteLastDownloaded = remoteLastDownloaded; this.remoteLastDownloadedBy = remoteLastDownloadedBy; this.origin = origin; } public long getNodeId() { return nodeId; } public long getLocalDownloadCount() { return downloadCount; } public String getLocalLastDownloadedBy() { return lastDownloadedBy; } public long getLocalLastDownloaded() { return lastDownloaded; } public boolean isRemote() { return !Strings.isNullOrEmpty(origin); } public long getRemoteDownloadCount() { return remoteDownloadCount; } public long getRemoteLastDownloaded() { return remoteLastDownloaded; } public String getRemoteLastDownloadedBy() { return remoteLastDownloadedBy; } public String getOrigin() { return origin; } public void setRemoteDownloadCount(long remoteDownloadCount) { this.remoteDownloadCount = remoteDownloadCount; } public void setRemoteLastDownloaded(long remoteLastDownloaded) { this.remoteLastDownloaded = remoteLastDownloaded; } public void setRemoteLastDownloadedBy(String remoteLastDownloadedBy) { this.remoteLastDownloadedBy = remoteLastDownloadedBy; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("downloadCount: "); sb.append(downloadCount); sb.append(", lastDownloaded: "); sb.append(lastDownloaded); sb.append(", lastDownloadedBy: "); sb.append(lastDownloadedBy); sb.append(", remoteDownloadCount: "); sb.append(remoteDownloadCount); sb.append(", remoteLastDownloaded: "); sb.append(remoteLastDownloaded); sb.append(", remoteLastDownloadedBy: "); sb.append(remoteLastDownloadedBy); sb.append("}"); return sb.toString(); } }
30.040936
129
0.692038
5f0c351c4caa9a1cad3b48524b38b8cfd89a0559
1,584
ts
TypeScript
scripts/build-scenario.ts
Muthaias/swipeforfuture-content
fd21ec04a82546e83a7efba9f9bd86f9d2e8afc1
[ "MIT" ]
2
2020-10-20T19:04:53.000Z
2020-11-20T20:29:18.000Z
scripts/build-scenario.ts
Muthaias/swipeforfuture-content
fd21ec04a82546e83a7efba9f9bd86f9d2e8afc1
[ "MIT" ]
22
2020-10-20T20:28:57.000Z
2021-08-13T00:20:42.000Z
scripts/build-scenario.ts
Muthaias/swipeforfuture-content
fd21ec04a82546e83a7efba9f9bd86f9d2e8afc1
[ "MIT" ]
1
2020-10-20T19:06:37.000Z
2020-10-20T19:06:37.000Z
import { outputFile } from "fs-extra" import { resolve } from "path" import { fileURLToPath } from "url" import scenarios from "./scenarios" import { Scenario, ScenarioManifest } from "./content-utils" const MANIFEST_FILENAME = "scenarios.json" async function buildScenarioManifest( scenarios: { [id: string]: Scenario }, outputDir: string, ) { const manifest: ScenarioManifest = { buildDate: new Date().toISOString(), scenarios: Object.fromEntries( Object.keys(scenarios).map((id) => [id, {}]), ), } return outputFile( resolve(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 4), ) } export async function buildScenarios(ids: string[], outputDir: string) { return Promise.all( Object.values(scenarios) .filter((scenario) => ids.includes(scenario.id)) .map(async (scenario) => { const outputPath = resolve(outputDir, `${scenario.id}.json`) await outputFile(outputPath, JSON.stringify(scenario)) console.log(`✅ Built "${scenario.id}" --> ${outputPath}`) }), ) } const isMainModule = process.argv[1] === fileURLToPath(import.meta.url) if (isMainModule) { const ids = process.argv.slice(2) console.log("Building:", ids) const outputDir = resolve(process.cwd(), "dist") Promise.all([ buildScenarios(ids, outputDir), buildScenarioManifest(scenarios, outputDir), ]).catch((reason: string) => { console.error("❌ Build error: ", reason) }) }
29.333333
77
0.619318
ddea3603d97defedce31cc562155fd87fc56e1a0
2,511
php
PHP
resources/views/news-zasah.blade.php
abbuyanaa/Laravel-ArkhangaiWeb
63d15a2c0788e8cf82508a149095bc65ff95708c
[ "MIT" ]
null
null
null
resources/views/news-zasah.blade.php
abbuyanaa/Laravel-ArkhangaiWeb
63d15a2c0788e8cf82508a149095bc65ff95708c
[ "MIT" ]
null
null
null
resources/views/news-zasah.blade.php
abbuyanaa/Laravel-ArkhangaiWeb
63d15a2c0788e8cf82508a149095bc65ff95708c
[ "MIT" ]
null
null
null
@extends('layout.master') @section('content') <div class="uk-grid"> <div class="uk-width-medium-12 uk-container-center"> <div class="md-card"> <div class="md-card-content large-padding"> <?php $msg = Session::get('msg'); if (isset($msg)){echo $msg;} ?> <h2 class="heading_b">Мэдээ нэмэх</h2> @foreach($news_data as $nrow) <form action="{{asset('/news-zasah/'.$nrow->id)}}" method="post" enctype="multipart/form-data"> {{ csrf_field() }} <div class="uk-grid uk-grid-divider uk-margin-medium-bottom" data-uk-grid-margin> <div class="uk-width-medium-12"> <div class="uk-grid"> <div class="uk-width-1-1"> <label>Гарчиг</label> <input type="text" class="md-input" name="etitle" value="{{$nrow->title}}" required /> <input type="hidden" name="delimg" value="{{$nrow->image}}"> </div> </div> <div class="uk-grid" data-uk-grid-margin> <div class="uk-width-1-1"> <textarea class="tinymce" name="ebody" cols="30" rows="10" required>{{$nrow->body}}</textarea> </div> </div> <div class="uk-grid" data-uk-grid-margin> <div class="uk-width-10"> <select id="select_demo_4" data-md-selectize name="ecat" required> <option value="0">Категори сонгох</option> @foreach($cat_data as $crow) <option value="{{$crow->id}}" <?php if($nrow->cat_id == $crow->id){echo 'selected';} ?>>{{$crow->name}}</option> @endforeach </select> </div> </div> <div class="uk-grid" data-uk-grid-margin> <div class="uk-width-medium-1-2"> <div class="md-card"> <div class="md-card-content"> <h3>Зураг</h3> <input type="file" name="eimage" /> </div> </div> </div> <div class="uk-width-medium-1-2"> <div class="md-card"> <div class="md-card-content"> <label>Одоогийн зураг</label> <img class="img_thumb" src="{{asset($nrow->image)}}" alt="{{$nrow->title}}"> </div> </div> </div> </div> </div> </div> <div class="uk-grid uk-margin-large-top" data-uk-grid-margin> <div class="uk-width-medium-1-1"> <button class="md-btn md-btn-large md-btn-primary" type="submit">Засах</button> </div> </div> </form> @endforeach <?php Session::put('msg',null); ?> </div> </div> </div> </div> @endsection
31.3875
122
0.537236
8825474c4cda3e5b3d0173a580be9b921d7128a7
13,751
swift
Swift
Sources/Base/SVGColors.swift
romikabi/cggen
9a510ba908d917c5bd2351a0e1fdb52a01c334ac
[ "Apache-2.0" ]
16
2021-03-23T20:12:59.000Z
2022-03-08T13:33:54.000Z
Sources/Base/SVGColors.swift
romikabi/cggen
9a510ba908d917c5bd2351a0e1fdb52a01c334ac
[ "Apache-2.0" ]
9
2021-03-29T08:06:16.000Z
2021-10-04T14:28:20.000Z
Sources/Base/SVGColors.swift
romikabi/cggen
9a510ba908d917c5bd2351a0e1fdb52a01c334ac
[ "Apache-2.0" ]
6
2021-03-26T06:38:21.000Z
2021-07-23T15:12:48.000Z
public enum SVGColorKeyword: String, CaseIterable { case aliceblue case antiquewhite case aqua case aquamarine case azure case beige case bisque case black case blanchedalmond case blue case blueviolet case brown case burlywood case cadetblue case chartreuse case chocolate case coral case cornflowerblue case cornsilk case crimson case cyan case darkblue case darkcyan case darkgoldenrod case darkgray case darkgreen case darkgrey case darkkhaki case darkmagenta case darkolivegreen case darkorange case darkorchid case darkred case darksalmon case darkseagreen case darkslateblue case darkslategray case darkslategrey case darkturquoise case darkviolet case deeppink case deepskyblue case dimgray case dimgrey case dodgerblue case firebrick case floralwhite case forestgreen case fuchsia case gainsboro case ghostwhite case gold case goldenrod case gray case grey case green case greenyellow case honeydew case hotpink case indianred case indigo case ivory case khaki case lavender case lavenderblush case lawngreen case lemonchiffon case lightblue case lightcoral case lightcyan case lightgoldenrodyellow case lightgray case lightgreen case lightgrey case lightpink case lightsalmon case lightseagreen case lightskyblue case lightslategray case lightslategrey case lightsteelblue case lightyellow case lime case limegreen case linen case magenta case maroon case mediumaquamarine case mediumblue case mediumorchid case mediumpurple case mediumseagreen case mediumslateblue case mediumspringgreen case mediumturquoise case mediumvioletred case midnightblue case mintcream case mistyrose case moccasin case navajowhite case navy case oldlace case olive case olivedrab case orange case orangered case orchid case palegoldenrod case palegreen case paleturquoise case palevioletred case papayawhip case peachpuff case peru case pink case plum case powderblue case purple case red case rosybrown case royalblue case saddlebrown case salmon case sandybrown case seagreen case seashell case sienna case silver case skyblue case slateblue case slategray case slategrey case snow case springgreen case steelblue case tan case teal case thistle case tomato case turquoise case violet case wheat case white case whitesmoke case yellow case yellowgreen var color: SVG.Color { switch self { case .aliceblue: return SVG.Color(red: 240, green: 248, blue: 255) case .antiquewhite: return SVG.Color(red: 250, green: 235, blue: 215) case .aqua: return SVG.Color(red: 0, green: 255, blue: 255) case .aquamarine: return SVG.Color(red: 127, green: 255, blue: 212) case .azure: return SVG.Color(red: 240, green: 255, blue: 255) case .beige: return SVG.Color(red: 245, green: 245, blue: 220) case .bisque: return SVG.Color(red: 255, green: 228, blue: 196) case .black: return SVG.Color(red: 0, green: 0, blue: 0) case .blanchedalmond: return SVG.Color(red: 255, green: 235, blue: 205) case .blue: return SVG.Color(red: 0, green: 0, blue: 255) case .blueviolet: return SVG.Color(red: 138, green: 43, blue: 226) case .brown: return SVG.Color(red: 165, green: 42, blue: 42) case .burlywood: return SVG.Color(red: 222, green: 184, blue: 135) case .cadetblue: return SVG.Color(red: 95, green: 158, blue: 160) case .chartreuse: return SVG.Color(red: 127, green: 255, blue: 0) case .chocolate: return SVG.Color(red: 210, green: 105, blue: 30) case .coral: return SVG.Color(red: 255, green: 127, blue: 80) case .cornflowerblue: return SVG.Color(red: 100, green: 149, blue: 237) case .cornsilk: return SVG.Color(red: 255, green: 248, blue: 220) case .crimson: return SVG.Color(red: 220, green: 20, blue: 60) case .cyan: return SVG.Color(red: 0, green: 255, blue: 255) case .darkblue: return SVG.Color(red: 0, green: 0, blue: 139) case .darkcyan: return SVG.Color(red: 0, green: 139, blue: 139) case .darkgoldenrod: return SVG.Color(red: 184, green: 134, blue: 11) case .darkgray: return SVG.Color(red: 169, green: 169, blue: 169) case .darkgreen: return SVG.Color(red: 0, green: 100, blue: 0) case .darkgrey: return SVG.Color(red: 169, green: 169, blue: 169) case .darkkhaki: return SVG.Color(red: 189, green: 183, blue: 107) case .darkmagenta: return SVG.Color(red: 139, green: 0, blue: 139) case .darkolivegreen: return SVG.Color(red: 85, green: 107, blue: 47) case .darkorange: return SVG.Color(red: 255, green: 140, blue: 0) case .darkorchid: return SVG.Color(red: 153, green: 50, blue: 204) case .darkred: return SVG.Color(red: 139, green: 0, blue: 0) case .darksalmon: return SVG.Color(red: 233, green: 150, blue: 122) case .darkseagreen: return SVG.Color(red: 143, green: 188, blue: 143) case .darkslateblue: return SVG.Color(red: 72, green: 61, blue: 139) case .darkslategray: return SVG.Color(red: 47, green: 79, blue: 79) case .darkslategrey: return SVG.Color(red: 47, green: 79, blue: 79) case .darkturquoise: return SVG.Color(red: 0, green: 206, blue: 209) case .darkviolet: return SVG.Color(red: 148, green: 0, blue: 211) case .deeppink: return SVG.Color(red: 255, green: 20, blue: 147) case .deepskyblue: return SVG.Color(red: 0, green: 191, blue: 255) case .dimgray: return SVG.Color(red: 105, green: 105, blue: 105) case .dimgrey: return SVG.Color(red: 105, green: 105, blue: 105) case .dodgerblue: return SVG.Color(red: 30, green: 144, blue: 255) case .firebrick: return SVG.Color(red: 178, green: 34, blue: 34) case .floralwhite: return SVG.Color(red: 255, green: 250, blue: 240) case .forestgreen: return SVG.Color(red: 34, green: 139, blue: 34) case .fuchsia: return SVG.Color(red: 255, green: 0, blue: 255) case .gainsboro: return SVG.Color(red: 220, green: 220, blue: 220) case .ghostwhite: return SVG.Color(red: 248, green: 248, blue: 255) case .gold: return SVG.Color(red: 255, green: 215, blue: 0) case .goldenrod: return SVG.Color(red: 218, green: 165, blue: 32) case .gray: return SVG.Color(red: 128, green: 128, blue: 128) case .grey: return SVG.Color(red: 128, green: 128, blue: 128) case .green: return SVG.Color(red: 0, green: 128, blue: 0) case .greenyellow: return SVG.Color(red: 173, green: 255, blue: 47) case .honeydew: return SVG.Color(red: 240, green: 255, blue: 240) case .hotpink: return SVG.Color(red: 255, green: 105, blue: 180) case .indianred: return SVG.Color(red: 205, green: 92, blue: 92) case .indigo: return SVG.Color(red: 75, green: 0, blue: 130) case .ivory: return SVG.Color(red: 255, green: 255, blue: 240) case .khaki: return SVG.Color(red: 240, green: 230, blue: 140) case .lavender: return SVG.Color(red: 230, green: 230, blue: 250) case .lavenderblush: return SVG.Color(red: 255, green: 240, blue: 245) case .lawngreen: return SVG.Color(red: 124, green: 252, blue: 0) case .lemonchiffon: return SVG.Color(red: 255, green: 250, blue: 205) case .lightblue: return SVG.Color(red: 173, green: 216, blue: 230) case .lightcoral: return SVG.Color(red: 240, green: 128, blue: 128) case .lightcyan: return SVG.Color(red: 224, green: 255, blue: 255) case .lightgoldenrodyellow: return SVG.Color(red: 250, green: 250, blue: 210) case .lightgray: return SVG.Color(red: 211, green: 211, blue: 211) case .lightgreen: return SVG.Color(red: 144, green: 238, blue: 144) case .lightgrey: return SVG.Color(red: 211, green: 211, blue: 211) case .lightpink: return SVG.Color(red: 255, green: 182, blue: 193) case .lightsalmon: return SVG.Color(red: 255, green: 160, blue: 122) case .lightseagreen: return SVG.Color(red: 32, green: 178, blue: 170) case .lightskyblue: return SVG.Color(red: 135, green: 206, blue: 250) case .lightslategray: return SVG.Color(red: 119, green: 136, blue: 153) case .lightslategrey: return SVG.Color(red: 119, green: 136, blue: 153) case .lightsteelblue: return SVG.Color(red: 176, green: 196, blue: 222) case .lightyellow: return SVG.Color(red: 255, green: 255, blue: 224) case .lime: return SVG.Color(red: 0, green: 255, blue: 0) case .limegreen: return SVG.Color(red: 50, green: 205, blue: 50) case .linen: return SVG.Color(red: 250, green: 240, blue: 230) case .magenta: return SVG.Color(red: 255, green: 0, blue: 255) case .maroon: return SVG.Color(red: 128, green: 0, blue: 0) case .mediumaquamarine: return SVG.Color(red: 102, green: 205, blue: 170) case .mediumblue: return SVG.Color(red: 0, green: 0, blue: 205) case .mediumorchid: return SVG.Color(red: 186, green: 85, blue: 211) case .mediumpurple: return SVG.Color(red: 147, green: 112, blue: 219) case .mediumseagreen: return SVG.Color(red: 60, green: 179, blue: 113) case .mediumslateblue: return SVG.Color(red: 123, green: 104, blue: 238) case .mediumspringgreen: return SVG.Color(red: 0, green: 250, blue: 154) case .mediumturquoise: return SVG.Color(red: 72, green: 209, blue: 204) case .mediumvioletred: return SVG.Color(red: 199, green: 21, blue: 133) case .midnightblue: return SVG.Color(red: 25, green: 25, blue: 112) case .mintcream: return SVG.Color(red: 245, green: 255, blue: 250) case .mistyrose: return SVG.Color(red: 255, green: 228, blue: 225) case .moccasin: return SVG.Color(red: 255, green: 228, blue: 181) case .navajowhite: return SVG.Color(red: 255, green: 222, blue: 173) case .navy: return SVG.Color(red: 0, green: 0, blue: 128) case .oldlace: return SVG.Color(red: 253, green: 245, blue: 230) case .olive: return SVG.Color(red: 128, green: 128, blue: 0) case .olivedrab: return SVG.Color(red: 107, green: 142, blue: 35) case .orange: return SVG.Color(red: 255, green: 165, blue: 0) case .orangered: return SVG.Color(red: 255, green: 69, blue: 0) case .orchid: return SVG.Color(red: 218, green: 112, blue: 214) case .palegoldenrod: return SVG.Color(red: 238, green: 232, blue: 170) case .palegreen: return SVG.Color(red: 152, green: 251, blue: 152) case .paleturquoise: return SVG.Color(red: 175, green: 238, blue: 238) case .palevioletred: return SVG.Color(red: 219, green: 112, blue: 147) case .papayawhip: return SVG.Color(red: 255, green: 239, blue: 213) case .peachpuff: return SVG.Color(red: 255, green: 218, blue: 185) case .peru: return SVG.Color(red: 205, green: 133, blue: 63) case .pink: return SVG.Color(red: 255, green: 192, blue: 203) case .plum: return SVG.Color(red: 221, green: 160, blue: 221) case .powderblue: return SVG.Color(red: 176, green: 224, blue: 230) case .purple: return SVG.Color(red: 128, green: 0, blue: 128) case .red: return SVG.Color(red: 255, green: 0, blue: 0) case .rosybrown: return SVG.Color(red: 188, green: 143, blue: 143) case .royalblue: return SVG.Color(red: 65, green: 105, blue: 225) case .saddlebrown: return SVG.Color(red: 139, green: 69, blue: 19) case .salmon: return SVG.Color(red: 250, green: 128, blue: 114) case .sandybrown: return SVG.Color(red: 244, green: 164, blue: 96) case .seagreen: return SVG.Color(red: 46, green: 139, blue: 87) case .seashell: return SVG.Color(red: 255, green: 245, blue: 237) case .sienna: return SVG.Color(red: 160, green: 82, blue: 45) case .silver: return SVG.Color(red: 192, green: 192, blue: 192) case .skyblue: return SVG.Color(red: 135, green: 206, blue: 235) case .slateblue: return SVG.Color(red: 106, green: 90, blue: 205) case .slategray: return SVG.Color(red: 112, green: 128, blue: 144) case .slategrey: return SVG.Color(red: 112, green: 128, blue: 144) case .snow: return SVG.Color(red: 255, green: 250, blue: 250) case .springgreen: return SVG.Color(red: 0, green: 255, blue: 127) case .steelblue: return SVG.Color(red: 70, green: 130, blue: 180) case .tan: return SVG.Color(red: 210, green: 180, blue: 140) case .teal: return SVG.Color(red: 0, green: 128, blue: 128) case .thistle: return SVG.Color(red: 216, green: 191, blue: 216) case .tomato: return SVG.Color(red: 255, green: 99, blue: 71) case .turquoise: return SVG.Color(red: 64, green: 224, blue: 208) case .violet: return SVG.Color(red: 238, green: 130, blue: 238) case .wheat: return SVG.Color(red: 245, green: 222, blue: 179) case .white: return SVG.Color(red: 255, green: 255, blue: 255) case .whitesmoke: return SVG.Color(red: 245, green: 245, blue: 245) case .yellow: return SVG.Color(red: 255, green: 255, blue: 0) case .yellowgreen: return SVG.Color(red: 154, green: 205, blue: 50) } } }
30.625835
55
0.644389
e3c7796a84fe9acc3bc0042ddf9241e92743f11b
2,386
go
Go
components/application-broker/internal/access/provision_mapping_test.go
FWinkler79/kyma
4ef0055807666cd54c5cbbeecd3aa17918d5d982
[ "Apache-2.0" ]
1,351
2018-07-04T06:14:20.000Z
2022-03-31T16:28:47.000Z
components/application-broker/internal/access/provision_mapping_test.go
FWinkler79/kyma
4ef0055807666cd54c5cbbeecd3aa17918d5d982
[ "Apache-2.0" ]
11,211
2018-07-24T22:47:33.000Z
2022-03-31T19:29:15.000Z
components/application-broker/internal/access/provision_mapping_test.go
FWinkler79/kyma
4ef0055807666cd54c5cbbeecd3aa17918d5d982
[ "Apache-2.0" ]
481
2018-07-24T14:13:41.000Z
2022-03-31T15:55:46.000Z
package access_test import ( "testing" "time" "github.com/kyma-project/kyma/components/application-broker/internal" "github.com/kyma-project/kyma/components/application-broker/internal/access" "github.com/kyma-project/kyma/components/application-broker/internal/access/automock" mappingTypes "github.com/kyma-project/kyma/components/application-broker/pkg/apis/applicationconnector/v1alpha1" "github.com/kyma-project/kyma/components/application-broker/pkg/client/clientset/versioned/fake" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestMappingExistsProvisionCheckerWhenProvisionAcceptable(t *testing.T) { // GIVEN rm := fixProdMapping() mockClientSet := fake.NewSimpleClientset(rm) mockAppStorage := &automock.ApplicationFinder{} defer mockAppStorage.AssertExpectations(t) mockAppStorage.On("FindOneByServiceID", fixApplicationServiceID()).Return(fixApplicationModel(), nil) sut := access.NewMappingExistsProvisionChecker(mockAppStorage, mockClientSet.ApplicationconnectorV1alpha1()) // WHEN canProvisionOutput, err := sut.CanProvision(fixApplicationServiceID(), internal.Namespace(fixProdNs()), time.Nanosecond) // THEN assert.NoError(t, err) assert.True(t, canProvisionOutput.Allowed) } func TestMappingExistsProvisionCheckerReturnsErrorWhenRENotFound(t *testing.T) { // GIVEN mockREStorage := &automock.ApplicationFinder{} defer mockREStorage.AssertExpectations(t) mockREStorage.On("FindOneByServiceID", fixApplicationServiceID()).Return(nil, nil) sut := access.NewMappingExistsProvisionChecker(mockREStorage, nil) // WHEN _, err := sut.CanProvision(fixApplicationServiceID(), internal.Namespace("ns"), time.Nanosecond) // THEN assert.Error(t, err) } func fixApplicationModel() *internal.Application { return &internal.Application{ Name: internal.ApplicationName(fixApName()), Services: []internal.Service{ { ID: internal.ApplicationServiceID("service-id"), }, }, } } func fixApplicationServiceID() internal.ApplicationServiceID { return internal.ApplicationServiceID("service-id") } func fixProdMapping() *mappingTypes.ApplicationMapping { return &mappingTypes.ApplicationMapping{ ObjectMeta: metav1.ObjectMeta{ Name: fixApName(), Namespace: fixProdNs(), }, } } func fixProdNs() string { return "production" } func fixApName() string { return "ec-prod" }
30.987013
121
0.7829
39de79826f6095a062e2f06aa7b58912b4b6b1e5
5,067
java
Java
app/src/main/java/com/wenshao/calculator/view/CalculatorEditText.java
wenshaoyan/calculator
7d0186861081f34b06bec4066cb6d8e5cbcd1947
[ "MIT" ]
null
null
null
app/src/main/java/com/wenshao/calculator/view/CalculatorEditText.java
wenshaoyan/calculator
7d0186861081f34b06bec4066cb6d8e5cbcd1947
[ "MIT" ]
null
null
null
app/src/main/java/com/wenshao/calculator/view/CalculatorEditText.java
wenshaoyan/calculator
7d0186861081f34b06bec4066cb6d8e5cbcd1947
[ "MIT" ]
null
null
null
package com.wenshao.calculator.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.EditText; import android.widget.TextView; import com.wenshao.calculator.operator.BasicOperator; import com.wenshao.calculator.operator.SymbolMap; import java.util.ArrayList; import java.util.List; /** * Created by wenshao on 2017/6/13. * 计算器输入框 */ public class CalculatorEditText extends TextView { private static final String TAG = "CalculatorEditText"; private Paint mPaint; private List<BasicOperator> mFormulaList; // 所有运算符集合 private Typeface mIconFont; // 字体文件 private List<CursorLocation> cursorLocations; // 光标可移动的位置 private int currentCursorIndex; // 当前光标所在的光标数组的下标 private int lastX; // 上一次滑动的时候的x坐标 private int lastY; // 上一次滑动的时候的y坐标 private int maxX; // 当前最大的x坐标 private int maxY; // 当前最大的y坐标 private int screenWidth; // view控件占用的宽度 private int moveX; private int moveY; private static final int startX = 50; private static final int startY = 100; private int currentCursorX; private int currentCursorY; public CalculatorEditText(Context context) { this(context, null); } public CalculatorEditText(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CalculatorEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); mFormulaList = new ArrayList<>(); mIconFont = Typeface.createFromAsset(context.getAssets(), "iconfont/match-init.ttf"); mPaint.setTypeface(mIconFont); cursorLocations = new ArrayList<>(); } private class CursorLocation { CursorLocation(float x, float y) { this.x = x; this.y = y; } float x; float y; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); screenWidth = canvas.getWidth(); mPaint.setColor(Color.WHITE); mPaint.setTextSize(50); int x = startX; int y = startY; for (BasicOperator op : mFormulaList) { canvas.drawText(getResources().getString(op.getSource()), x, y, mPaint); CursorLocation cursorLocation = new CursorLocation(x, y); cursorLocations.add(cursorLocation); x += 50; } if (currentCursorX == 0) { currentCursorX = x; currentCursorY = y; } maxX = x; maxY = y; // 记录当前光标的位置 currentCursorIndex = cursorLocations.size(); } public void addText(String text) { BasicOperator operator = SymbolMap.getOperator(text); mFormulaList.add(operator); invalidate(); } public void setSelection(int start, int stop) { //Selection.setSelection(getText(), start, stop); } public void setSelection(int index) { //Selection.setSelection(getText(), index); } public boolean onTouchEvent(MotionEvent event) { //获取到手指处的横坐标和纵坐标 int x = (int) event.getX(); int y = (int) event.getY(); if (maxX < screenWidth) { // 当前输入的宽度大于屏幕的宽度 return true; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: //计算移动的距离 int offsetX = x - lastX; int offsetY = y - lastY; int orientation = getOrientation(offsetX, offsetY); if ((maxX + moveX) < screenWidth && orientation == 'l') { // 判断是否可以左移 Log.i(TAG, "不允许左移动!" + getScrollX() + "--" + maxX + "---" + moveX); //scrollTo(150, 0); break; } if (moveX >= 0 && orientation == 'r') { // 判断是否可以右移 Log.i(TAG, "不允许右移动!"); scrollTo(0, 0); break; } maxX = maxX - offsetX; lastX = x; lastY = y; moveX += offsetX; moveY += offsetY; scrollBy(-offsetX, 0); break; } return true; } // 返回允许的移动的方向 private String normal() { return "1"; } /** * 根据距离差判断 滑动方向 * * @param dx X轴的距离差 * @param dy Y轴的距离差 * @return 滑动的方向 */ private int getOrientation(float dx, float dy) { if (Math.abs(dx) > Math.abs(dy)) { //X轴移动 return dx > 0 ? 'r' : 'l'; } else { //Y轴移动 return dy > 0 ? 'b' : 't'; } } //TODO 屏幕移动字符串结尾 private void screenEnd() { } }
24.717073
93
0.561279
90f0a7b22504e11eeaf8ed9b65b850cde42fcc46
7,066
py
Python
users.py
ArVID220u/SnallisBot
43023627472786992284d6a60e4300ffa41d4b84
[ "MIT" ]
null
null
null
users.py
ArVID220u/SnallisBot
43023627472786992284d6a60e4300ffa41d4b84
[ "MIT" ]
null
null
null
users.py
ArVID220u/SnallisBot
43023627472786992284d6a60e4300ffa41d4b84
[ "MIT" ]
null
null
null
# import twythonaccess to be able to make twitter requests from . import twythonaccess # import apikeys from . import apikeys # import twythonstreamer for the SwedishMiner down below from twython import TwythonStreamer # import threading from threading import Thread # import time import time # this class provides Swedish usernames # all unique, and as long as there are users left in Swedish Twitter, this class will keep churning them out class Users: # the added users is a set of the user ids of all that have been added added_users = set() # the next users is a queue for the users to be returned next_users = [] # the mine followers is also a queue for the users whose follower list hasn't yet been mined mine_followers = [] # initializer def __init__(self): # initialize added_users from the data file self.init_added_users() # create a swedish_miner self.swedish_miner = SwedishMiner(apikeys.MINE_CONSUMER_KEY, apikeys.MINE_CONSUMER_SECRET, apikeys.MINE_ACCESS_TOKEN, apikeys.MINE_ACCESS_TOKEN_SECRET) # set its users property to self # warning: this will create a memory leak, as both references are strong self.swedish_miner.users = self # start a thread for mining the swedish users swedish_miner_thread = Thread(target = self.swedish_miner_streamer) swedish_miner_thread.start() print("has initialized users by starting miner thread") # initialize added users from the file added_users.data def init_added_users(self): with open("/home/arvid220u/twitterbots/nicebot/added_users.data", 'r') as datafile: # at every line, there is exactly one user id, that has already beeen processed for line in datafile: userid = int(line.strip()) self.added_users.add(userid) # add a user to the lists, checking first if it's unique def add_user(self, userid): if userid in self.added_users: # already added this user, abort return print("adding user with id: " + str(userid)) # if there already are too many users in the mine_followers array, disconnect the swedish_miner if len(self.mine_followers) > 100: if self.swedish_miner.alive: print("disconnect swedish miner due to many already in queue") self.swedish_miner.disconnect() self.swedish_miner.alive = False # add user to added_users self.added_users.add(userid) # also add to the data file called added_users.data # append user to both the minefollowers queue and the nextusers queue self.next_users.append(userid) self.mine_followers.append(userid) # return a screen name of a user def get_user(self): # if the number of users in next_users is less than 10, mine some followers if len(self.next_users) < 10 and len(self.mine_followers) > 0: # do it in a separate thread print("need to mine some users since next_users is of length: " + str(len(self.next_users))) mine_followers_thread = Thread(target = self.mine_some_followers) mine_followers_thread.start() # if next users length is zero, which just should never happen, wait while len(self.next_users) == 0: print("next users is 0, will sleep for 6 minutes") time.sleep(6*60) # do not respond to protected users screenname = "" userid = 0 while True: # get the frontmost user in the next_users queue firstid = self.next_users.pop(0) # get the screen name of this particular user twythonaccess.sleep_if_requests_are_maximum(170, main=False) user = twythonaccess.authorize(main=False).show_user(user_id=firstid) if not user["protected"]: screenname = user["screen_name"] userid = user["id"] break elif len(self.next_users) == 0: return self.get_user() print("found user with screenname: " + screenname) # add this user to the added users data file, so as to not tweet to the same person twice with open("/home/arvid220u/twitterbots/nicebot/added_users.data", 'a') as datafile: datafile.write(str(userid) + '\n') # return it return screenname # mine some followers def mine_some_followers(self): # if the mine_followers queue contains less than 200 items, start the swedish streamer if len(self.mine_followers) < 20 and not self.swedish_miner.alive: print("starting swedish miner anew since mine followers length is " + str(len(self.mine_followers))) swedish_miner_thread = Thread(target = self.swedish_miner_streamer) swedish_miner_thread.start() while len(self.mine_followers) == 0: print("mine followers is 0, will sleep for 6 minutes") time.sleep(6*60) counter = 0 while True: # get the first user userid = self.mine_followers.pop(0) # get user twythonaccess.sleep_if_requests_are_maximum(170, main=False) user = twythonaccess.authorize(main=False).show_user(user_id=userid) # if user is protected, continue if user["protected"]: if len(self.mine_followers) == 0: break continue # get a list of the followers twythonaccess.sleep_if_requests_are_maximum(13, main=False) followers = twythonaccess.authorize(main=False).get_followers_list(user_id=userid, count=100)["users"] for follower in followers: if follower["lang"] == "sv": self.add_user(follower["id"]) count += 1 if count > 100 or len(mine_followers) == 0: break print("finished mining followers") # start the swedish miner streamer def swedish_miner_streamer(self): # get most of all swedish tweets # it performs an or search, with language sv print("starting swedish miner streamer") self.swedish_miner.alive = True self.swedish_miner.statuses.filter(track="i,och,att,det,som,en,på,är,av,för", language="sv") # this class finds users based on them sending tweets marked as swedish class SwedishMiner(TwythonStreamer): # check if alive alive = False # this function is called when a tweet is received def on_success(self, tweet): # add the user #print("found new user from swedish streamer miner") self.users.add_user(tweet["user"]["id"]) def on_error(self, status_code, data): print("STREAMING API ERROR in SwedishStreamer") print("Status code:") print(status_code) print("other data:") print(data) print("END OF ERROR MESSAGE")
42.566265
159
0.642513
cef16886803246a6540de801e30083b307e87bda
310
swift
Swift
GateKeeper/UIComponents/Table View Cells/Sections/Account/GKZipCell.swift
ignotusverum/gatekeeper-ios
8113792178b7bcefdfe2067b29f4c49718eb83d9
[ "MIT" ]
null
null
null
GateKeeper/UIComponents/Table View Cells/Sections/Account/GKZipCell.swift
ignotusverum/gatekeeper-ios
8113792178b7bcefdfe2067b29f4c49718eb83d9
[ "MIT" ]
null
null
null
GateKeeper/UIComponents/Table View Cells/Sections/Account/GKZipCell.swift
ignotusverum/gatekeeper-ios
8113792178b7bcefdfe2067b29f4c49718eb83d9
[ "MIT" ]
null
null
null
// // GKZipCell.swift // GateKeeper // // Created by Vladislav Zagorodnyuk on 10/2/16. // Copyright © 2016 Vlad Z. All rights reserved. // import UIKit class GKZipCell: GKAccountTableViewCell { // Override Placeholder override public var placeholderString: String { return "Zip" } }
17.222222
51
0.677419
3cfbb54eb7dcb45a6023518d1d743293321a0f58
6,531
swift
Swift
KKSandboxUI/KKSandboxUI/KKSandboxHelper.swift
onetys/KKSandboxUI
ba8fadcc82b079a994a9d86fc3735c4d1b9413c5
[ "MIT" ]
null
null
null
KKSandboxUI/KKSandboxUI/KKSandboxHelper.swift
onetys/KKSandboxUI
ba8fadcc82b079a994a9d86fc3735c4d1b9413c5
[ "MIT" ]
null
null
null
KKSandboxUI/KKSandboxUI/KKSandboxHelper.swift
onetys/KKSandboxUI
ba8fadcc82b079a994a9d86fc3735c4d1b9413c5
[ "MIT" ]
null
null
null
// // KKSandboxHelper.swift // KKSandboxUI // // Created by 王铁山 on 2017/8/23. // Copyright © 2017年 king. All rights reserved. // import Foundation import UIKit public enum KKSandboxFileType { case text case image case array case dictionary case json case directory case unknown } open class KKSandboxHelper { /// 生成指定路径下所有的文件夹/文件模型 /// /// - Parameter directory: 文件夹路径 /// - Returns: 文件模型 KKSandboxFileModel open class func fileModelAtPath(directory: String) -> [KKSandboxFileModel] { let manager = FileManager.default var isDirectory: ObjCBool = false if !manager.fileExists(atPath: directory, isDirectory: &isDirectory) && !isDirectory.boolValue { return [KKSandboxFileModel]() } guard let subPaths = try? manager.contentsOfDirectory(atPath: directory) else { return [KKSandboxFileModel]() } var result = [KKSandboxFileModel]() for subPath in subPaths { let fullPath = "\(directory)/\(subPath)" result.append(self.getFileModel(name: subPath, path: fullPath)) } return result } /// 转换文件为模型 open class func getFileModel(name subPath: String, path fullPath: String) -> KKSandboxFileModel { let manager = FileManager.default let model = KKSandboxFileModel.init(name: subPath, path: fullPath) model.isDeleteable = manager.isDeletableFile(atPath: fullPath) model.fileType = self.getFileType(path: fullPath) do { let att = try manager.attributesOfItem(atPath: subPath) model.fileSize = (att[FileAttributeKey.size] as? String) ?? "" } catch _ { } return model } /// 获取文件类型 open class func getFileType(path: String) -> KKSandboxFileType { let manager = FileManager.default var isDirectory: ObjCBool = false _ = manager.fileExists(atPath: path, isDirectory: &isDirectory) // 判断是否是文件夹 if isDirectory.boolValue { return .directory } // image if let _ = UIImage.init(contentsOfFile: path) { return .image } // object if let _ = NSDictionary.init(contentsOfFile: path) { return .dictionary } // array if let _ = NSArray.init(contentsOfFile: path) { return .array } // 字符串 if let text = try? String.init(contentsOfFile: path), let textData: Data = text.data(using: String.Encoding.utf8) { let jsonObj: Any? = try? JSONSerialization.jsonObject(with: textData, options: JSONSerialization.ReadingOptions.mutableContainers) if let _: [String: Any] = jsonObj as? [String: Any] { return .json } else { return .text } } return .unknown } /// 获取国际化字符串 open class func getLocalizedString(name: String) -> String { let mainFind = NSLocalizedString(name, tableName: "KKSandboxUI", comment: name) if mainFind.isEmpty { return NSLocalizedString(name, tableName: "KKSandboxUI", bundle: Bundle.init(for: KKSandboxUIViewController.self), value: "", comment: name) } return mainFind } } /// 文件模型 open class KKSandboxFileModel { static var directoryIcon: UIImage? static var textIcon: UIImage? static var unknownIcon: UIImage? open var name: String open var path: String open var fileType: KKSandboxFileType = .unknown open var fileSize: String? open var isDeleteable: Bool = true var iconImage: UIImage? public init(name: String, path: String) { self.name = name self.path = path } open func getIconImage() -> UIImage? { if let icon = self.iconImage { return icon } switch self.fileType { case .directory: if KKSandboxFileModel.directoryIcon == nil { KKSandboxFileModel.directoryIcon = getThumbImage(originImage: image(named: "DirectoryIcon.png")) } self.iconImage = KKSandboxFileModel.directoryIcon return self.iconImage case .array, .dictionary, .json, .text: if KKSandboxFileModel.textIcon == nil { KKSandboxFileModel.textIcon = getThumbImage(originImage: image(named: "TextIcon.png")) } self.iconImage = KKSandboxFileModel.textIcon return self.iconImage case .image: self.iconImage = self.getThumbImage(originImage: UIImage.init(contentsOfFile: self.path)) return self.iconImage default: if KKSandboxFileModel.unknownIcon == nil { KKSandboxFileModel.unknownIcon = getThumbImage(originImage: image(named: "UnknowIcon.png")) } self.iconImage = KKSandboxFileModel.unknownIcon return self.iconImage } } private func getThumbImage(originImage: UIImage?)->UIImage? { guard let image: UIImage = originImage else { return originImage } let size = CGSize(width: 29, height: 29) UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) image.draw(in: CGRect.init(origin: CGPoint(), size: size)) let thumbImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return thumbImage } } fileprivate func sourcePath(name: String) -> String? { let named = "KKSandboxUI.bundle/\(name)" if let path = Bundle.main.path(forResource: named, ofType: nil) { return path } if let path = Bundle.init(for: KKSandboxFileModel.self).path(forResource: named, ofType: nil) { return path } let fullNamed = "Frameworks/KKSandboxUI.framework/\(named)" if let path = Bundle.main.path(forResource: fullNamed, ofType: nil) { return path } return nil } fileprivate func image(named: String) -> UIImage? { if let path = sourcePath(name: named) { return UIImage(contentsOfFile: path) } return nil }
28.770925
152
0.586128
a1aea95c6aaa1706dee439a1067573b8f1aab2c4
13,626
h
C
src/kernel/include/sched/posix_signals.h
GrieferAtWork/KOS
5376a813854b35e3a3532a6e3b8dbb168478b40f
[ "Zlib" ]
2
2017-02-24T17:14:19.000Z
2017-10-12T19:26:13.000Z
src/kernel/include/sched/posix_signals.h
GrieferAtWork/KOS
5376a813854b35e3a3532a6e3b8dbb168478b40f
[ "Zlib" ]
1
2019-11-02T10:21:11.000Z
2019-11-02T10:21:11.000Z
src/kernel/include/sched/posix_signals.h
GabrielRavier/KOSmk3
5376a813854b35e3a3532a6e3b8dbb168478b40f
[ "Zlib" ]
1
2019-11-02T10:20:19.000Z
2019-11-02T10:20:19.000Z
/* Copyright (c) 2018 Griefer@Work * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #ifndef GUARD_KERNEL_INCLUDE_SCHED_POSIX_SIGNALS_H #define GUARD_KERNEL_INCLUDE_SCHED_POSIX_SIGNALS_H 1 #include <hybrid/compiler.h> #include <hybrid/atomic.h> #include <kos/types.h> #include <hybrid/list/list.h> #include <hybrid/sync/atomic-rwlock.h> #include <bits/sigaction.h> #include <sched/mutex.h> #include <bits/sigset.h> #include <bits/siginfo.h> #include <bits/signum.h> #include <bits/sigstack.h> #include <kernel/sections.h> #include <kernel/syscall.h> #include <sched/signal.h> #if defined(__i386__) || defined(__x86_64__) #include <i386-kos/posix_signals.h> #endif #undef CONFIG_SIGPENDING_TRACK_MASK #ifndef CONFIG_NO_SIGPENDING_TRACK_MASK #define CONFIG_SIGPENDING_TRACK_MASK 1 #endif DECL_BEGIN #ifdef __CC__ #ifndef __sigset_t_defined #define __sigset_t_defined 1 typedef __sigset_t sigset_t; #endif struct sigblock { /* Descriptor for signals that are being blocked. */ ATOMIC_DATA ref_t sb_share; /* Amount of threads that are sharing this sig-block. * NOTE: Modifications may only be made to the sig-block * when this value is ONE(1). */ sigset_t sb_sigset; /* [const_if(sb_share > 1)] * Bit-set of signals that are being blocked. */ }; /* [0..1][lock(PRIVATE(THIS_TASK))][ref(sb_share)] * The set of signals being blocked in the current thread. * When NULL, assume that no signals are being blocked. */ DATDEF ATTR_PERTASK REF struct sigblock *_this_sigblock; /* Allocate a missing `_this_sigblock', or replace it * with a copy of itself when `sb_share > 1'. * @return: * : Always returns `PERTASK_GET(_this_sigblock)' * @throw E_BADALLOC: Not enough available memory. */ FUNDEF ATTR_RETNONNULL struct sigblock *KCALL sigblock_unique(void); /* A faster version of `sigblock_unique()' that doesn't lazily * allocate the sigblock, rather returning NULL if no sigblock * exists, or if it is shared with another thread. */ FUNDEF struct sigblock *KCALL sigblock_unique_fast(void); struct sighand { /* Descriptor for how signals ought to be handled. */ atomic_rwlock_t sh_lock; /* Lock for accessing elements of `sh_hand' */ ref_t sh_share; /* [lock(sh_lock)] Amount of unrelated processes sharing this sighand. */ struct sigaction *sh_hand[_NSIG]; /* [0..1][lock(sh_lock)][owned][*][config_if(sh_share > 1)] * Vector of user-space signal handler. * NOTE: NULL-entries imply default behavior, which is signal-dependent. */ }; struct sighand_ptr { /* Secondary indirection for sighand that allows * for copy-on-write between different processes * that were fork()-ed from each other. * Because of the fact that fork() would otherwise have to * copy the sighand table, only to have a likely following * call to exec() destroy that table again, we simply share * the sighand table between the old and new process until * either one of the processes dies or calls exec(), or until * one of them attempts to modify the sighand table, in which * case this indirection allows for lazy copy-on-write. */ ATOMIC_DATA ref_t sp_refcnt; /* Amount of threads using `sp_hand' */ atomic_rwlock_t sp_lock; /* Lock for the `sp_hand' pointer. */ REF struct sighand *sp_hand; /* [0..1][ref(sh_share)][lock(sp_lock,WRITE_ONCE[ALLOW_EXCHANGE])] * Pointer to the shared signal handler table. */ }; /* [0..1][lock(PRIVATE(THIS_TASK))] * User-space signal handlers for the calling thread. * NOTE: When NULL, default behavior should be used for handling any signal. */ DATDEF ATTR_PERTASK REF struct sighand_ptr *_this_sighand_ptr; /* Allocates a missing or unshare a shared signal handler * table and acquire a write-lock on (return->sh_lock). * The caller may then modify the `sh_hand' vector freely, * before calling `atomic_rwlock_endwrite(&return->sh_lock)' * to commit any changes that were made. * This function automatically deals with all inter-process * copy-on-write, as well as inter-thread sighand-share behavior. */ FUNDEF ATTR_RETNONNULL struct sighand *KCALL sighand_lock_write(void); /* Similar to `sighand_lock_write()', but don't * unshare and acquire a read-lock instead. * If no handlers have been defined, return `NULL' * instead (implies DEFAULT behavior for all signals). */ FUNDEF struct sighand *KCALL sighand_lock_read(void); struct sigqueue { /* Descriptor for a signal that was send, but was * blocked and therefor scheduled to be received later. */ SLIST_NODE(struct sigqueue) sq_chain; /* [owned] Chain of queued signals. */ siginfo_t sq_info; /* Signal information. */ }; struct sigpending { /* Descriptor for pending signals (always per-thread). */ mutex_t sp_lock; /* Lock used to guard this descriptor. */ struct sig sp_newsig; /* Signal used to broadcast addition of new signals. */ SLIST_HEAD(struct sigqueue) sp_queue; /* [0..1][owned][lock(sp_lock)] List of queued signals. */ #ifdef CONFIG_SIGPENDING_TRACK_MASK sigset_t sp_mask; /* [lock(sp_lock)] Mask of all signals found in 'sp_queue'. */ #endif }; struct sigshare { /* Descriptor for shared, pending signals (usually per-process). */ struct sigpending ss_pending; /* Shared, pending signals. */ ATOMIC_DATA ref_t ss_refcnt; /* Reference counter. */ }; #ifdef CONFIG_SIGPENDING_TRACK_MASK /* [0..1][owned][lock(WRITE_ONCE)] * Pending task chain for the calling thread. */ DATDEF ATTR_PERTASK struct sigpending *_this_sigpending_task; #else /* Pending task chain for the calling thread. */ DATDEF ATTR_PERTASK struct sigpending _this_sigpending_task; #endif /* [0..1][lock(WRITE_ONCE)] * Pending task chain for the calling process. */ DATDEF ATTR_PERTASK REF struct sigshare *_this_sigpending_proc; /* Lazily allocate if missing, and return the * per-task or per-process sigpending controllers. */ #ifdef CONFIG_SIGPENDING_TRACK_MASK FUNDEF ATTR_RETNONNULL struct sigpending *KCALL sigpending_gettask(void); FUNDEF ATTR_RETNONNULL struct sigpending *KCALL sigpending_getfor(struct task *__restrict thread); #else #define sigpending_gettask() (&PERTASK_GET(_this_sigpending_task)) #define sigpending_getfor(thread) (&FORTASK(thread,_this_sigpending_task)) #endif FUNDEF ATTR_RETNONNULL struct sigpending *KCALL sigpending_getproc(void); FUNDEF ATTR_RETNONNULL struct sigpending *KCALL sigpending_getprocfor(struct task *__restrict thread); /* Actions codes of default actions to perform the no handler is set. */ #define SIGNAL_ACTION_IGNORE 1 /* Ignore the signal and continue. */ #define SIGNAL_ACTION_TERM 3 /* Terminate the calling process (thread-group). */ #define SIGNAL_ACTION_EXIT 4 /* Terminate the calling thread. */ #define SIGNAL_ACTION_CONT 8 /* Continue execution. */ #define SIGNAL_ACTION_STOP 9 /* Stop execution. */ #define SIGNAL_ACTION_CORE 10 /* Create a core-dump. */ #define SIGNAL_ISACTION(x) ((x) <= 10) /* Default actions codes for standard signals. */ DATDEF u8 const signal_default_actions[_NSIG]; /* Using RPC function calls, raise a signal in the given thread. * If `thread' is the calling thread, this function will not return. * @return: true: The RPC was scheduled for delivery and will be executed (asynchronously). * @return: false: The RPC call failed because `thread' has terminated. * @throw: E_INVALID_ARGUMENT: The signal number in `info' is ZERO(0) or >= `_NSIG+1' * @throw: E_SEGFAULT: The user-buffers are faulty. */ FUNDEF bool KCALL signal_raise_thread(struct task *__restrict thread, USER CHECKED siginfo_t *__restrict info); /* Enqueue in `sigshare' and find some thread in `threadgroup' * that isn't blocking the signal, then post an RPC functions * to that thread which will search for pending signals that * are not being ignored and handle them. * NOTE: If `threadgroup' isn't the leader of a group, * the signal is send to its leader thread. */ FUNDEF bool KCALL signal_raise_group(struct task *__restrict threadgroup, USER CHECKED siginfo_t *__restrict info); /* Similar to `signal_raise_group()', but send a copy of the signal to * every process in the given `processgroup' (s.a. `task_get_group()') * @return: * : The number of successfully sent signals. * If `processgroup' isn't the leader of a process, or process group, * it's process leader will be dereferenced, following that process's * process group leader being dereferenced. */ FUNDEF size_t KCALL signal_raise_pgroup(struct task *__restrict processgroup, USER CHECKED siginfo_t *__restrict info); /* Change the signal mask of the calling thread. * Following this, check for signals that have been unblocked * and throw an `E_INTERRUPT' exception if any were. * When `old_mask' is non-NULL, save the old mask inside * before changing anything. * @throw: E_INVALID_ARGUMENT: The given `how' is invalid. * @throw: E_INVALID_ARGUMENT: The given `sigsetsize' is too large. * @throw: E_SEGFAULT: The user-buffers are faulty. */ FUNDEF void KCALL signal_chmask(USER CHECKED sigset_t const *mask, USER CHECKED sigset_t *old_mask, size_t sigsetsize, int how); #define SIGNAL_CHMASK_FBLOCK 0 /* Block signals. */ #define SIGNAL_CHMASK_FUNBLOCK 1 /* Unblock signals. */ #define SIGNAL_CHMASK_FSETMASK 2 /* Set the set of blocked signals. */ /* Change the action for the given `signo'. * @throw: E_SEGFAULT: The user-buffers are faulty. */ FUNDEF void KCALL signal_chaction(int signo, USER CHECKED struct sigaction const *new_action, USER CHECKED struct sigaction *old_action); #ifdef CONFIG_SYSCALL_COMPAT FUNDEF void KCALL signal_chaction_compat(int signo, USER CHECKED struct sigaction_compat const *new_action, USER CHECKED struct sigaction_compat *old_action); #endif /* Change the signal disposition of all signal actions using * a user-space disposition to `SIG_DFL'. (called during exec()) */ FUNDEF void KCALL signal_resetexec(void); /* Wait for one of the signals specified in `wait_mask' to become * available within the calling thread's pending list, or the * shared pending list of the calling thread. * @throw: E_INVALID_ARGUMENT: The given `sigsetsize' is too large. * @throw: E_SEGFAULT: The user-buffers are faulty. * @return: true: A Signal was received and stored in `info' * @return: false: The given `abs_timeout' has expired. */ FUNDEF bool KCALL signal_waitfor(USER CHECKED sigset_t const *wait_mask, size_t sigsetsize, USER CHECKED siginfo_t *info, jtime_t abs_timeout); /* Similar to `signal_waitfor()', but replace the calling thread's * signal mask with `wait_mask' for the duration of this call, * then proceeds to wait until one of the signals masked has been * queued for execution in the calling thread. * NOTE: This function must not be called for kernel-worker threads. * NOTE: When `JTIME_INFINITE' is passed, this function doesn't return. * @return: void: The given timeout has expired. * @throw: * : An RPC function threw this error... * @throw: E_INTERRUPT: The calling thread was interrupted (Dealt with before transitioning to user-space) * @throw: E_INVALID_ARGUMENT: The given `sigsetsize' is too large. */ FUNDEF void KCALL signal_suspend(USER CHECKED sigset_t const *wait_mask, size_t sigsetsize, jtime_t abs_timeout); /* Get a snapshot of all pending signals. * NOTE: This function is O(1) when KOS was built * with `CONFIG_SIGPENDING_TRACK_MASK' enabled. * @throw: E_INVALID_ARGUMENT: The given `sigsetsize' is too large. */ FUNDEF void KCALL signal_pending(USER CHECKED sigset_t *wait_mask, size_t sigsetsize); #endif /* __CC__ */ DECL_END #endif /* !GUARD_KERNEL_INCLUDE_SCHED_POSIX_SIGNALS_H */
45.878788
113
0.685308
f4c173a054da5d68575e454952f6fc23bbe48893
1,222
go
Go
tag/loss.go
qibin0506/tml
58e73a0eb097ed5b9ebdaf5167416c9acc71d621
[ "Apache-2.0" ]
null
null
null
tag/loss.go
qibin0506/tml
58e73a0eb097ed5b9ebdaf5167416c9acc71d621
[ "Apache-2.0" ]
null
null
null
tag/loss.go
qibin0506/tml
58e73a0eb097ed5b9ebdaf5167416c9acc71d621
[ "Apache-2.0" ]
null
null
null
package tag import ( "bufio" "log" "github.com/qibin0506/tml/utils" ) func NewLoss(ctx *TagContext) TagOp { return &Loss{ Tag: &Tag{ Root: ctx.Prev.Root, Parent: ctx.Prev.Parent, Previous: ctx.Prev.Current, Current: ctx.Cur, Ext: ctx.Prev.Ext, }, } } type Loss struct { *Tag } func (l *Loss) Name() string { return "loss" } func (l *Loss) Parse(writer *bufio.Writer) { lossKey, exists := l.Current.Attr("type") if !exists { log.Fatal("tag loss must have a type attribute.") } lossValue := losses[lossKey] if lossValue == "" { log.Fatalf("loss type %s is not supported.", lossKey) } // loss_object = tf.keras.losses.SparseCategoricalCrossentropy() writer.WriteString("loss_object = tf.keras.losses.") writer.WriteString(lossValue) writer.WriteString("()\n") // train_loss = tf.keras.metrics.Mean(name="train_loss") writer.WriteString("train_loss = tf.keras.metrics.Mean(name=\"train_loss\")\n") if l.Ext.HasTestData { writer.WriteString("test_loss = tf.keras.metrics.Mean(name=\"test_loss\")\n") } writer.WriteRune('\n') } func (l *Loss) Next() TagOp { metrics := utils.GetTagOrFatal(l.Parent, "metrics") return tagMap["metrics"](CreateTagContext(l.Tag, metrics)) }
21.821429
80
0.682488
f70c50f4901a76f82428594c26cd6f80f28e426f
255
h
C
src/framework/print-export/Sketch/MSImmutableSymbolInstance.h
skpm/print-export-sketchplugin
7ad4df2882013e02d9b50b52db05e9a51ec551ba
[ "MIT" ]
47
2019-05-02T11:11:00.000Z
2019-10-25T06:45:23.000Z
src/framework/print-export/Sketch/MSImmutableSymbolInstance.h
Tafkadasoh/print-export-sketchplugin
5f2089ba5d2fa3ca1384f3cb51b983c171196774
[ "MIT" ]
23
2019-10-30T08:01:43.000Z
2020-08-19T19:51:06.000Z
src/framework/print-export/Sketch/MSImmutableSymbolInstance.h
Tafkadasoh/print-export-sketchplugin
5f2089ba5d2fa3ca1384f3cb51b983c171196774
[ "MIT" ]
4
2020-02-14T16:00:47.000Z
2021-05-06T09:09:30.000Z
// // MSImmutableSymbolInstance.h // print-export // // Created by Mark Horgan on 29/03/2019. // Copyright © 2019 Sketch. All rights reserved. // #import "MSImmutableStyledLayer.h" @interface MSImmutableSymbolInstance : MSImmutableStyledLayer @end
18.214286
61
0.745098
863fd459454352459880ad12e96c496ad80a9f1d
644
go
Go
sources/set/set_test.go
shoenig/donutdns
7aa51356fd091d89e29852e48f65ea00dcbc812b
[ "BSD-3-Clause" ]
11
2021-10-30T17:40:26.000Z
2022-02-27T22:12:34.000Z
sources/set/set_test.go
shoenig/donutdns
7aa51356fd091d89e29852e48f65ea00dcbc812b
[ "BSD-3-Clause" ]
1
2021-10-20T23:00:33.000Z
2021-10-20T23:00:33.000Z
sources/set/set_test.go
shoenig/donutdns
7aa51356fd091d89e29852e48f65ea00dcbc812b
[ "BSD-3-Clause" ]
1
2021-11-18T07:28:20.000Z
2021-11-18T07:28:20.000Z
package set import ( "testing" "github.com/shoenig/test/must" ) func Test_Add(t *testing.T) { s := New() must.EqOp(t, 0, s.Len()) s.Add("foo") must.EqOp(t, 1, s.Len()) s.Add("bar") must.EqOp(t, 2, s.Len()) s.Add("foo") must.EqOp(t, 2, s.Len()) s.Add("") must.EqOp(t, 2, s.Len()) } func Test_Union(t *testing.T) { s1 := New() s1.Add("a") s1.Add("b") s1.Add("c") s2 := New() s2.Add("c") s2.Add("d") s1.Union(s2) must.EqOp(t, 4, s1.Len()) must.EqOp(t, 2, s2.Len()) } func Test_Has(t *testing.T) { s := New() s.Add("a") s.Add("b") must.True(t, s.Has("a")) must.True(t, s.Has("b")) must.False(t, s.Has("c")) }
13.142857
31
0.53882
bfea8b93bc81a529fe65ee0edea2c7f053eba3c2
2,298
swift
Swift
Sources/Datagram.swift
phmagic/SwiftIO
20335a91c7bb6795252cc87121f0f2d9b892ae5c
[ "MIT" ]
null
null
null
Sources/Datagram.swift
phmagic/SwiftIO
20335a91c7bb6795252cc87121f0f2d9b892ae5c
[ "MIT" ]
null
null
null
Sources/Datagram.swift
phmagic/SwiftIO
20335a91c7bb6795252cc87121f0f2d9b892ae5c
[ "MIT" ]
1
2020-11-19T10:12:06.000Z
2020-11-19T10:12:06.000Z
// // Datagram.swift // SwiftIO // // Created by Jonathan Wight on 8/9/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import SwiftUtilities public struct Datagram { public let from: Address public let timestamp: Timestamp public let data: DispatchData public init(from: Address, timestamp: Timestamp = Timestamp(), data: DispatchData ) { self.from = from self.timestamp = timestamp self.data = data } } // MARK: - extension Datagram: Equatable { } public func == (lhs: Datagram, rhs: Datagram) -> Bool { if lhs.from != rhs.from { return false } if lhs.timestamp != rhs.timestamp { return false } if lhs.data != rhs.data { return false } return true } // MARK: - extension Datagram: CustomStringConvertible { public var description: String { return "Datagram(from: \(from), timestamp: \(timestamp): data: \(data.count) bytes)" } }
31.479452
92
0.704526
f07bfff15edf793c1c8c356f07c2cd48678cf5ed
3,444
js
JavaScript
client/store/candles.js
Mighty-mighty-mangoes/Tranquility
cb9304eb648bba1e84ddd5cc6642616669ff8c53
[ "MIT" ]
null
null
null
client/store/candles.js
Mighty-mighty-mangoes/Tranquility
cb9304eb648bba1e84ddd5cc6642616669ff8c53
[ "MIT" ]
40
2021-01-11T22:03:13.000Z
2021-01-21T01:05:05.000Z
client/store/candles.js
Mighty-mighty-mangoes/Tranquility
cb9304eb648bba1e84ddd5cc6642616669ff8c53
[ "MIT" ]
null
null
null
import axios from 'axios'; const SET_CANDLES = 'SET_CANDLES'; //all candles const SINGLE_CANDLE = 'SINGLE_CANDLE'; const SET_FOOD_CANDLES = 'SET_FOOD_CANDLES'; const SET_SPICE_CANDLES = 'SET_SPICE_CANDLES'; const SET_FLOWER_CANDLES = 'SET_FLOWER_CANDLES'; const SET_CODER_CANDLES = 'SET_CODER_CANDLES'; export const setCandles = (candles) => ({ type: SET_CANDLES, candles, }); export const singleCandle = (candle) => ({ type: SINGLE_CANDLE, candle, }); export const setFoodCandles = (candles) => ({ type: SET_FOOD_CANDLES, candles, }); export const setSpiceCandles = (candles) => ({ type: SET_SPICE_CANDLES, candles, }); export const setFlowerCandles = (candles) => ({ type: SET_FLOWER_CANDLES, candles, }); export const setCoderCandles = (candles) => ({ type: SET_CODER_CANDLES, candles, }); //ALL CANDLES-works export const fetchCandles = () => { return async (dispatch) => { try { const {data} = await axios.get('/api/candles'); dispatch(setCandles(data)); } catch (err) { console.log('Something is wrong in the all candles thunk: ', err); } }; }; //SINGLE CANDLE-works export const fetchSingleCandle = (id) => { return async (dispatch) => { try { const {data} = await axios.get(`/api/candles/${id}`); dispatch(singleCandle(data)); } catch (err) { console.log('Something is wrong in the single candles thunk: ', err); } }; }; //FOOD CANDLES -works export const fetchFoodCandles = () => { return async (dispatch) => { try { const {data} = await axios.get('/api/candles/food'); dispatch(setFoodCandles(data)); } catch (err) { console.log('Something is wrong in the food candles thunk: ', err); } }; }; //SPICE CANDLES-works export const fetchSpiceCandles = () => { return async (dispatch) => { try { const {data} = await axios.get('/api/candles/spices'); dispatch(setSpiceCandles(data)); } catch (err) { console.log('Something is wrong in the spice candles thunk: ', err); } }; }; //FLOWER CANDLES-works export const fetchFlowerCandles = () => { return async (dispatch) => { try { const {data} = await axios.get('/api/candles/flowers'); dispatch(setFlowerCandles(data)); } catch (err) { console.log('Something is wrong in the flower candles thunk: ', err); } }; }; //CODER CANDLES-works export const fetchCoderCandles = () => { return async (dispatch) => { try { const {data} = await axios.get('/api/candles/coders'); dispatch(setCoderCandles(data)); } catch (err) { console.log('Something is wrong in the coder candles thunk: ', err); } }; }; let initialState = { singleCandle: {}, candles: [], foodCandles: [], spiceCandles: [], flowerCandles: [], coderCandles: [], }; export default function candleReducer(state = initialState, action) { switch (action.type) { case SET_CANDLES: return {...state, candles: action.candles}; case SINGLE_CANDLE: return {...state, singleCandle: action.candle}; case SET_FOOD_CANDLES: return {...state, foodCandles: action.candles}; case SET_SPICE_CANDLES: return {...state, spiceCandles: action.candles}; case SET_FLOWER_CANDLES: return {...state, flowerCandles: action.candles}; case SET_CODER_CANDLES: return {...state, coderCandles: action.candles}; default: return state; } }
24.776978
75
0.641696
95287697c5fa4a8af3fa9863ec29e859573589ea
867
asm
Assembly
programs/oeis/088/A088137.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/088/A088137.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/088/A088137.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A088137: Generalized Gaussian Fibonacci integers. ; 0,1,2,1,-4,-11,-10,13,56,73,-22,-263,-460,-131,1118,2629,1904,-4079,-13870,-15503,10604,67717,103622,4093,-302680,-617639,-327238,1198441,3378596,3161869,-3812050,-17109707,-22783264,5762593,79874978,142462177,45299420,-336787691,-809473642,-608584211,1211252504,4248257641,4862757770,-3019257383,-20626788076,-32195804003,-2511243778,91564924453,190663580240,106632387121,-358725966478,-1037349094319,-998520289204,1115006704549,5225574276710,7106128439773,-1464465950584,-24247317220487,-44101236589222,-15460521516983,101382666733700,249146898018349,194145795835598,-359149102383851,-1300735592274496,-1524023877397439,854159022028610,6280389676249537 mul $0,2 mov $3,$0 add $3,2 mov $4,$3 sub $4,1 mov $2,$4 mov $5,2 lpb $2,1 mov $4,$1 add $1,$5 add $1,3 sub $2,2 mul $4,2 sub $5,$4 lpe div $1,5
43.35
656
0.778547
16c6a99be770afb90266fac34761e2b84dd69d0f
508
swift
Swift
Tests/BowGenerators/Transformers/EitherT+Gen.swift
dsabanin/bow
a33173c8a111cbb492fe0ae0f16b58a0adb945d2
[ "Apache-2.0" ]
529
2018-11-12T10:51:46.000Z
2022-03-22T18:15:07.000Z
Tests/BowGenerators/Transformers/EitherT+Gen.swift
dsabanin/bow
a33173c8a111cbb492fe0ae0f16b58a0adb945d2
[ "Apache-2.0" ]
372
2018-11-14T14:14:30.000Z
2021-10-04T12:56:47.000Z
Tests/BowGenerators/Transformers/EitherT+Gen.swift
dsabanin/bow
a33173c8a111cbb492fe0ae0f16b58a0adb945d2
[ "Apache-2.0" ]
33
2019-01-11T00:35:52.000Z
2022-03-17T08:50:53.000Z
import Bow import SwiftCheck // MARK: Generator for Property-based Testing extension EitherT: Arbitrary where F: ArbitraryK, A: Arbitrary, B: Arbitrary { public static var arbitrary: Gen<EitherT<F, A, B>> { Gen.from(EitherTPartial.generate >>> EitherT.fix) } } // MARK: Instance of ArbitraryK for EitherT extension EitherTPartial: ArbitraryK where F: ArbitraryK, L: Arbitrary { public static func generate<A: Arbitrary>() -> EitherTOf<F, L, A> { EitherT(F.generate()) } }
26.736842
78
0.694882
95b1cba49554c51c7442d98ae1b441266ad5ac89
6,056
css
CSS
src/styles/header.css
arsengit/xlNet
17ec369d26cdea5408866b9d79b8cee303895f1b
[ "MIT" ]
null
null
null
src/styles/header.css
arsengit/xlNet
17ec369d26cdea5408866b9d79b8cee303895f1b
[ "MIT" ]
6
2020-07-19T12:26:42.000Z
2022-02-26T23:26:26.000Z
src/styles/header.css
arsengit/xlNet
17ec369d26cdea5408866b9d79b8cee303895f1b
[ "MIT" ]
null
null
null
header { display: flex; justify-content: space-between; align-items: center; } header > ul a { padding-left: 30px; font-family: "OpenSans Light"; font-size: 18px; line-height: 2px; transition: all 0.3s ease-out; letter-spacing: 0.2px; color: #fff; } header > ul a:hover { color: #4facfe; } .header-main { padding: 15px 0 20px; position: fixed; width: 100%; z-index: 2; transition: all 0.3s ease-out; } .header-main-bg { width: 100%; height: 97px; position: absolute; top: 0; z-index: -1; opacity: 1; box-shadow: 0 0 7px 2px rgba(43, 43, 43, 0.47); background: #01abe5 linear-gradient(to right, #01abe5 0%, #311e71 100%); transition: all 0.3s ease-out; } .head-opacity { opacity: 0; } header { position: relative; } header ul.hamburger { right: 0; left: 0; display: flex; flex-direction: column; position: absolute; z-index: -2; background: linear-gradient(to right, rgb(1, 171, 229) 0%, rgb(49, 30, 113) 100%) rgb(1, 171, 229); } header ul.hamburger a { text-align: center; padding-left: 0; line-height: unset; } .navWithout { transform: translateY(0%) !important; transition: all 0s !important; } header ul.hamburger button { margin: 0 } .header-content-container { background: url("../images/home_bg.png") center top no-repeat; height: 100vh; background-size: cover; } .header-content-container .gatsby-image-wrapper { height: 100%; } .modal-desc { margin-top: 25px; margin-bottom: 40px; } .header-content { display: flex; flex-direction: column; } .header-content h1 { margin-top: 130px; letter-spacing: 2px; max-width: 610px; font-size: 80px; } .header-content p { color: #fff; margin-top: 65px; max-width: 490px; } .header-content button { margin-top: 35px; transition: all 0.3s ease-out; } .header-content button:hover { color: #4facfe; background: #fff; transition: all 0.3s ease-out; } .header-main button, .pricing-bottom button { background: #4facfe; color: #fff; font-family: "OpenSans Regular"; margin-left: 30px; border: 0; border-radius: 30px; padding: 10px 50px; } .head-active { color: #4facfe; } .get-started { background: #4facfe; color: #fff; font-family: "OpenSans Regular"; max-width: 200px; padding: 12px 45px; border: 0; border-radius: 30px; box-shadow: 0px 25px 53px -3px #4facfe9e; } .header-content .get-started { text-transform: uppercase; } .data-picker-main { display: flex; flex-direction: column; } .find-time { background: #0066cb; display: block; color: #fff; text-align: center; padding: 30px 0 20px; width: 380px; } .DateInput_input__focused, .DateInput { visibility: hidden; height: 0 !important; } .SingleDatePicker { margin-top: -20px; } .SingleDatePickerInput__withBorder { border-radius: 0; border: 0 !important; height: 0; } .SingleDatePicker_picker { position: inherit !important; } .modal { transition: transform 0.3s ease-out; position: fixed; margin-top: 10%; height: 540px; padding: 50px 70px; width: 1100px; z-index: 1; background: #fff; left: calc(50% - 585px); } .closeBtn { cursor: pointer; position: absolute; right: 0; top: -50px; color: #fff; font-size: 20px; } .backdrop { position: absolute; width: 100%; height: 100vh; background: rgba(39, 37, 37, 0.719); top: 0; left: 0; right: 0; bottom: 0; } .CalendarMonth { background: #0066cb !important; width: 380px !important; height: 400px !important; padding: 0 60px !important; } .CalendarMonth_caption { display: flex !important; justify-content: center !important; margin-right: 140px !important; } .modal h2 { text-align: center; font-size: 26px; } .modal strong { text-align: center; display: block; } .current-input { transition: all 0.3s ease-out; } .modal-inputs { display: flex; flex-direction: column; max-height: 380px; width: 400px; overflow: auto; } .modal-inputs input { border: 1px solid #cccccc; color: #7a7a7a; cursor: pointer; font-size: 16px; text-align: center; width: 99%; padding: 25px 0px; margin-top: 20px; } .modal-inputs::-webkit-scrollbar { display: none; } .selected-input { width: 45% !important; background: #cbeaff; color: #0047ac !important; border: 0 !important; } .modal-inputs button { background: #0066cb; color: #fff; border: 0; margin-left: 8%; padding: 25px 0; width: 45%; border-radius: 0; } .DayPicker_weekHeader { width: 245px !important; margin-left: 60px !important; margin-top: 0px !important; padding: 0 !important; } .DayPickerNavigation_rightButton__horizontalDefault { right: -10px !important; top: 15px !important; } .DayPickerNavigation_button__horizontalDefault { top: 15px !important; } .DayPickerNavigation_leftButton__horizontalDefault { left: 75px !important; } .DayPickerNavigation_svg__horizontal { fill: #ffffff !important; } .DayPickerNavigation_button__default { border: 1px solid #e4e7e700 !important; background-color: rgba(255, 255, 255, 0) !important; } .DayPicker_weekHeader_li { color: white; width: 33px !important; } .DayPicker_transitionContainer { width: 380px !important; height: 320px !important; } .date-content { max-width: 800px; margin: 0 auto; } .date-content strong { color: #fff; } .CalendarDay__default { border: 0 !important; color: #fff !important; background: #0066cb !important; vertical-align: middle !important; } .CalendarDay__blocked_out_of_range { border: 0 !important; color: #1a76d0 !important; } .CalendarDay__selected { background: #fff !important; border: 1px double #0066cb !important; color: #6d7bff !important; border-radius: 50% !important; align-items: center; display: flex; justify-content: center; } .DayPicker_focusRegion { background: #0066cb !important; } .DayPicker__withBorder { background: #0066cb !important; } .CalendarMonthGrid { background: #0066cb !important; } .CalendarMonth_table { width: 230px !important; }
16.683196
101
0.677015
0bc1b87155af7211f7ef4f7bb261c76723b7c1da
3,595
py
Python
src/features/helpers/processing_v4.py
askoki/nfl_dpi_prediction
dc3256f24ddc0b6725eace2081d1fb1a7e5ce805
[ "MIT" ]
null
null
null
src/features/helpers/processing_v4.py
askoki/nfl_dpi_prediction
dc3256f24ddc0b6725eace2081d1fb1a7e5ce805
[ "MIT" ]
null
null
null
src/features/helpers/processing_v4.py
askoki/nfl_dpi_prediction
dc3256f24ddc0b6725eace2081d1fb1a7e5ce805
[ "MIT" ]
null
null
null
import math import numpy as np from matplotlib.patches import FancyArrowPatch def home_has_possession(row): if row.possessionTeam == row.homeTeamAbbr: return True return False def calculate_team_sitation(row): ball_string = 'football' if row.team == ball_string: return ball_string if row.team == 'home' and row.homeHasPossession: return 'attacking' elif row.team == 'away' and not row.homeHasPossession: return 'attacking' return 'defending' def convert_speed_to_marker_size(speed: float) -> int: if 0 < speed <= 1.5: return 10 elif 1.5 < speed <= 3: return 15 elif 3 < speed <= 4.5: return 20 elif 4.5 < speed <= 6: return 25 return 30 def arrow(x, y, s, ax, color): """ Function to draw the arrow of the movement :param x: position on x-axis :param y: position on y-axis :param s: speed in yards/s :param ax: plot's configuration :param color: color of the arrows :return: arrows on the specific positions """ # distance between the arrows distance = 5 ind = range(1, len(x), distance) # computing of the arrows for i in ind: ar = FancyArrowPatch( (x[i - 1], y[i - 1]), (x[i], y[i]), arrowstyle='->', mutation_scale=convert_speed_to_marker_size(s[i]), color=color, ) ax.add_patch(ar) def calculate_arrow_xy(x, y, o): o = o % 360 delta = 0.1 if o == 0: y_delta = delta x_delta = 0 return x + x_delta, y + y_delta elif o == 90: y_delta = 0 x_delta = delta return x + x_delta, y + y_delta elif o == 180: y_delta = -delta x_delta = 0 print(f'F {y_delta}') return x + x_delta, y + y_delta elif o == 270: y_delta = 0 x_delta = -delta return x + x_delta, y + y_delta elif 0 < o < 90: y_delta = math.sin(math.radians(90 - o)) * delta x_delta = math.sqrt(delta ** 2 - y_delta ** 2) return x + x_delta, y + y_delta elif 90 < o < 180: y_delta = math.sin(math.radians(o - 90)) * delta x_delta = math.sqrt(delta ** 2 - y_delta ** 2) return x + x_delta, y - y_delta elif 180 < o < 270: x_delta = math.sin(math.radians(o - 180)) * delta y_delta = math.sqrt(delta ** 2 - x_delta ** 2) return x - x_delta, y - y_delta else: y_delta = math.sin(math.radians(o - 270)) * delta x_delta = math.sqrt(delta ** 2 - y_delta ** 2) return x - x_delta, y + y_delta def arrow_o(x, y, o, s, ax, color): """ Function to draw the arrow of the movement :param x: position on x-axis :param y: position on y-axis :param o: orientation in degrees 0-360 :param s: speed in yards/s :param ax: plot's configuration :param color: color of the arrows :return: arrows on the specific positions """ # distance between the arrows distance = 3 ind = range(5, len(x), distance) # computing of the arrows for i in ind: x2, y2 = calculate_arrow_xy(x[i], y[i], o[i]) ar = FancyArrowPatch( (x[i], y[i]), (x2, y2), arrowstyle='-|>', mutation_scale=convert_speed_to_marker_size(s[i]), alpha=0.6, color=color, ) ax.add_patch(ar) def calculate_distance_v4(x1: np.array, y1: np.array, x2: np.array, y2: np.array) -> np.array: return np.round(np.sqrt(np.square(x1 - x2) + np.square(y1 - y2)), 2)
27.868217
94
0.569958
daa0f69a3518f3e5319e846f3ee37b5e50c0071e
4,343
kt
Kotlin
app/src/main/java/slak/fanfictionstories/data/fetchers/AuthorFetcher.kt
slak44/fanfiction-stories
86cea40e4ec6a8ff72da2adcb94509b9d2ea1b7c
[ "MIT" ]
1
2019-09-05T03:53:09.000Z
2019-09-05T03:53:09.000Z
app/src/main/java/slak/fanfictionstories/data/fetchers/AuthorFetcher.kt
slak44/fanfiction-stories
86cea40e4ec6a8ff72da2adcb94509b9d2ea1b7c
[ "MIT" ]
null
null
null
app/src/main/java/slak/fanfictionstories/data/fetchers/AuthorFetcher.kt
slak44/fanfiction-stories
86cea40e4ec6a8ff72da2adcb94509b9d2ea1b7c
[ "MIT" ]
null
null
null
package slak.fanfictionstories.data.fetchers import android.os.Parcelable import kotlinx.android.parcel.Parcelize import kotlinx.coroutines.CoroutineScope import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.select.Elements import slak.fanfictionstories.Notifications import slak.fanfictionstories.Notifications.Companion.defaultIntent import slak.fanfictionstories.R import slak.fanfictionstories.StoryModel import slak.fanfictionstories.StoryProgress import slak.fanfictionstories.StoryStatus import slak.fanfictionstories.data.Cache import slak.fanfictionstories.data.fetchers.ParserUtils.authorIdFromAuthor import slak.fanfictionstories.data.fetchers.ParserUtils.convertImageUrl import slak.fanfictionstories.data.fetchers.ParserUtils.parseStoryMetadata import slak.fanfictionstories.data.fetchers.ParserUtils.unescape import java.util.concurrent.TimeUnit val authorCache = Cache<Author>("Author", TimeUnit.DAYS.toMillis(1)) /** * A data class representing an author's metadata. * @see getAuthor */ @Parcelize data class Author(val name: String, val id: Long, val joinedDateSeconds: Long, val updatedDateSeconds: Long, val countryName: String?, val imageUrl: String?, val bioHtml: String, val userStories: List<StoryModel>, val favoriteStories: List<StoryModel>, val favoriteAuthors: List<Pair<Long, String>>) : Parcelable, java.io.Serializable /** * Get author data for specified id. * @see Author */ suspend fun getAuthor(authorId: Long): Author { authorCache.hit(authorId.toString()).ifPresent { return it } val html = patientlyFetchURL("https://www.fanfiction.net/u/$authorId/") { Notifications.ERROR.show(defaultIntent(), R.string.error_fetching_author_data, authorId.toString()) } val doc = Jsoup.parse(html) val authorName = doc.selectFirst("#content_wrapper_inner > span").text() val stories = doc.getElementById("st_inside").children().map { parseStoryElement(it, authorName, authorId) } // Drop a COMPLETELY FUCKING RANDOM SCRIPT TAG val favStories = doc.getElementById("fs_inside")?.children()?.drop(1)?.map { parseStoryElement(it, null, null) } ?: listOf() val favAuthors = doc.getElementById("fa").select("dl").map { val authorElement = it.select("a").first() return@map Pair(authorIdFromAuthor(authorElement), authorElement.text()) } // USING TABLES FOR ALIGNMENT IN 2019 GOD DAMMIT val retardedTableCell = doc.select("#content_wrapper_inner > table table[cellpadding=\"4\"] td[colspan=\"2\"]").last() val timeSpans = retardedTableCell.select("span") val author = Author( authorName, authorId, // Joined date, seconds timeSpans[0].attr("data-xutime").toLong(), // Updated date, seconds if (timeSpans.size > 1) timeSpans[1].attr("data-xutime").toLong() else 0, // Country name retardedTableCell.selectFirst("img")?.attr("title"), // Image url doc.selectFirst("#bio > img")?.attr("data-original"), // User bio (first child is image) Elements(doc.getElementById("bio").children().drop(1)).outerHtml(), stories, favStories, favAuthors ) authorCache.update(authorId.toString(), author) return author } private fun parseStoryElement(it: Element, authorName: String?, authorId: Long?): StoryModel { val authorAnchor = it.select("a:not(.reviews)").last() val stitle = it.selectFirst("a.stitle") return StoryModel( storyId = it.attr("data-storyid").toLong(), fragment = parseStoryMetadata(it.children().last().children().last(), 3), progress = StoryProgress(), status = StoryStatus.TRANSIENT, // FFnet category is our canon canon = unescape(it.attr("data-category")), // Category info is unavailable here! category = null, summary = it.children().last().textNodes().first().text(), author = authorName ?: authorAnchor.text(), authorId = authorId ?: authorIdFromAuthor(authorAnchor), title = stitle.textNodes().last().text(), imageUrl = convertImageUrl(stitle.children().first()?.attr("data-original")), serializedChapterTitles = null, addedTime = null, lastReadTime = null ) }
39.481818
100
0.698595
3c331165f35355a22583844a21e6a5996e67e42d
42
sql
SQL
oon_db/migrations/2019-10-27-144646_initial/down.sql
justinas/onion-or-news
6f45de79eeff74ff14559876557334aa356e145b
[ "MIT" ]
11
2019-11-09T18:43:23.000Z
2021-08-03T07:49:38.000Z
oon_db/migrations/2019-10-27-144646_initial/down.sql
justinas/onion-or-news
6f45de79eeff74ff14559876557334aa356e145b
[ "MIT" ]
2
2019-11-01T19:02:21.000Z
2019-11-01T20:21:24.000Z
oon_db/migrations/2019-10-27-144646_initial/down.sql
justinas/onion-or-news
6f45de79eeff74ff14559876557334aa356e145b
[ "MIT" ]
null
null
null
DROP TABLE answers; DROP TABLE questions;
14
21
0.809524
3f92b8bcd7948b16f297271be9522b1a8e4eedb0
243
lua
Lua
MMOCoreORB/bin/scripts/object/custom_content/tangible/storyteller/prop/pr_tent_basic.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/storyteller/prop/pr_tent_basic.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/storyteller/prop/pr_tent_basic.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_tangible_storyteller_prop_pr_tent_basic = object_tangible_storyteller_prop_shared_pr_tent_basic:new { } ObjectTemplates:addTemplate(object_tangible_storyteller_prop_pr_tent_basic, "object/tangible/storyteller/prop/pr_tent_basic.iff")
40.5
129
0.901235
38c2da6e4302737b764a0b0f1f040423ad91e23c
509
h
C
AwaitSwift/AwaitSwift.h
GlebRadchenko/AwaitSwift
47a23eae6356877d319d34f468ca2bf5f376ff4b
[ "MIT" ]
null
null
null
AwaitSwift/AwaitSwift.h
GlebRadchenko/AwaitSwift
47a23eae6356877d319d34f468ca2bf5f376ff4b
[ "MIT" ]
null
null
null
AwaitSwift/AwaitSwift.h
GlebRadchenko/AwaitSwift
47a23eae6356877d319d34f468ca2bf5f376ff4b
[ "MIT" ]
null
null
null
// // AwaitSwift.h // AwaitSwift // // Created by Gleb Radchenko on 10/24/18. // Copyright © 2018 Gleb Radchenko. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for AwaitSwift. FOUNDATION_EXPORT double AwaitSwiftVersionNumber; //! Project version string for AwaitSwift. FOUNDATION_EXPORT const unsigned char AwaitSwiftVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <AwaitSwift/PublicHeader.h>
25.45
135
0.764244
7be2f37f0d2f70faf1316667aa4ef8ac462f60c4
2,601
css
CSS
public/css/chunk-fe6047a4.f07a6d4d.css
wangdachui6bi/-
52979448f6ed1f2be435ccb18844ae5b23ece7f7
[ "MIT" ]
null
null
null
public/css/chunk-fe6047a4.f07a6d4d.css
wangdachui6bi/-
52979448f6ed1f2be435ccb18844ae5b23ece7f7
[ "MIT" ]
null
null
null
public/css/chunk-fe6047a4.f07a6d4d.css
wangdachui6bi/-
52979448f6ed1f2be435ccb18844ae5b23ece7f7
[ "MIT" ]
null
null
null
.MvInfo[data-v-a6169e42]{width:90%;margin:0 auto}.MvInfo h1[data-v-a6169e42]{font-size:16px}.MvInfo .playVideo[data-v-a6169e42]{margin-top:10px;width:370px;height:210px;margin:0 auto}.MvInfo .artistInfo[data-v-a6169e42]{margin:10px auto}.MvInfo .artistInfo img[data-v-a6169e42]{width:40px;height:40px;border-radius:50%;float:left}.MvInfo .artistInfo .nameInfo[data-v-a6169e42]{display:block;height:40px;line-height:40px;margin-left:50px;font-size:14px;color:#2c3e50}.MvInfo .mvN[data-v-a6169e42]{margin-top:10px;font-size:18px;font-weight:700}.MvInfo .number[data-v-a6169e42]{color:#cfcfcf;font-size:12px}.MvInfo .number span[data-v-a6169e42]{margin-right:20px}.MvInfo .dz[data-v-a6169e42]{margin-top:20px}.MvInfo .dz button[data-v-a6169e42]{outline:none;height:30px;padding:4px 14px;border-radius:15px;cursor:pointer;border:1px solid #d8d8d8;background-color:#fff;color:#373737;margin-right:10px}.MvInfo .dz .pl[data-v-a6169e42]{width:100px;display:flex;justify-content:space-between;align-items:center;display:inline-block}.MvInfo .van-cell[data-v-a6169e42]{border:1px solid #e5e5e5}.MvInfo .leavInfo[data-v-a6169e42]{color:#676767;margin-top:10px;display:flex;justify-content:space-between;align-items:center}.MvInfo .leavInfo .leavInfo-left span[data-v-a6169e42]{font-size:18px;margin-right:20px}.MvInfo .leavInfo button[data-v-a6169e42]{border:1px solid #d8d8d8;background-color:#fff;color:#373737;outline:none;height:30px;padding:4px 14px;border-radius:15px;cursor:pointer}.MvInfo .comment[data-v-a6169e42]{font-size:16px;font-weight:700}.MvInfo .commitItem[data-v-a6169e42]{display:flex;align-items:center;margin:10px 0}.MvInfo .commitItem .headPortrait[data-v-a6169e42]{width:40px;height:40px;border-radius:50%}.MvInfo .commitItem .comment_main[data-v-a6169e42]{margin-left:10px;font-size:12px}.MvInfo .commitItem .comment_main .user[data-v-a6169e42]{color:#507daf;font-size:12px}.MvInfo .commitItem .comment_main .dzDetail[data-v-a6169e42]{width:320px;display:flex;justify-content:space-between}.MvInfo .commitItem .comment_main .dzDetail .time[data-v-a6169e42]{height:30px;line-height:38px;color:#9f9f9f}.MvInfo .commitItem .comment_main .dzDetail .rightIcon[data-v-a6169e42]{display:flex;align-items:center}.MvInfo .commitItem .comment_main .dzDetail .rightIcon .dzNumber[data-v-a6169e42]{display:inline-block;box-sizing:border-box}.MvInfo .commitItem .comment_main .dzDetail .rightIcon .div-column[data-v-a6169e42]{display:inline-block;width:1px;height:14px;background-color:#dfcfe7;margin:0 5px}.MvInfo .commitItem .comment_main .dzDetail .rightIcon .fz19[data-v-a6169e42]{font-size:19px}
2,601
2,601
0.802384
4b1f7fd3ae9e435bc48130461ac27ae8fd4e05ae
6,482
swift
Swift
PodChat/Classes/PrimaryModels/Participant.swift
Mahyar1990/PodChat
22c4becdc3ddc58a12aee7d3f0c8dad7a04a3a7c
[ "MIT" ]
null
null
null
PodChat/Classes/PrimaryModels/Participant.swift
Mahyar1990/PodChat
22c4becdc3ddc58a12aee7d3f0c8dad7a04a3a7c
[ "MIT" ]
null
null
null
PodChat/Classes/PrimaryModels/Participant.swift
Mahyar1990/PodChat
22c4becdc3ddc58a12aee7d3f0c8dad7a04a3a7c
[ "MIT" ]
null
null
null
// // Participant.swift // Chat // // Created by Mahyar Zhiani on 7/23/1397 AP. // Copyright © 1397 Mahyar Zhiani. All rights reserved. // import Foundation import SwiftyJSON //####################################################################################### //############################# Participant (formatDataToMakeParticipant) //####################################################################################### open class Participant { /* * + ParticipantVO Participant: * - cellphoneNumber: String? * - contactId: Int? * - email: String? * - firstName: String? * - id: Int? * - image: String? * - lastName: String? * - myFriend: Bool? * - name: String? * - notSeenDuration: Int? * - online: Bool? * - receiveEnable: Bool? * - sendEnable: Bool? */ public let admin: Bool? public let blocked: Bool? public let cellphoneNumber: String? public let contactId: Int? public let coreUserId: Int? public let email: String? public let firstName: String? public let id: Int? public let image: String? public let lastName: String? public let myFriend: Bool? public let name: String? public let notSeenDuration: Int? public let online: Bool? public let receiveEnable: Bool? public let sendEnable: Bool? public init(messageContent: JSON, threadId: Int?) { self.admin = messageContent["admin"].bool self.blocked = messageContent["blocked"].bool self.cellphoneNumber = messageContent["cellphoneNumber"].string self.contactId = messageContent["contactId"].int self.coreUserId = messageContent["coreUserId"].int self.email = messageContent["email"].string self.firstName = messageContent["firstName"].string self.id = messageContent["id"].int self.image = messageContent["image"].string self.lastName = messageContent["lastName"].string self.myFriend = messageContent["myFriend"].bool self.name = messageContent["name"].string self.notSeenDuration = messageContent["notSeenDuration"].int self.online = messageContent["online"].bool self.receiveEnable = messageContent["receiveEnable"].bool self.sendEnable = messageContent["sendEnable"].bool } public init(admin: Bool?, blocked: Bool?, cellphoneNumber: String?, contactId: Int?, coreUserId: Int?, email: String?, firstName: String?, id: Int?, image: String?, lastName: String?, myFriend: Bool?, name: String?, notSeenDuration: Int?, online: Bool?, receiveEnable: Bool?, sendEnable: Bool?) { self.admin = admin self.blocked = blocked self.cellphoneNumber = cellphoneNumber self.contactId = contactId self.coreUserId = coreUserId self.email = email self.firstName = firstName self.id = id self.image = image self.lastName = lastName self.myFriend = myFriend self.name = name self.notSeenDuration = notSeenDuration self.online = online self.receiveEnable = receiveEnable self.sendEnable = sendEnable } public init(theParticipant: Participant) { self.admin = theParticipant.admin self.blocked = theParticipant.blocked self.cellphoneNumber = theParticipant.cellphoneNumber self.contactId = theParticipant.contactId self.coreUserId = theParticipant.coreUserId self.email = theParticipant.email self.firstName = theParticipant.firstName self.id = theParticipant.id self.image = theParticipant.image self.lastName = theParticipant.lastName self.myFriend = theParticipant.myFriend self.name = theParticipant.name self.notSeenDuration = theParticipant.notSeenDuration self.online = theParticipant.online self.receiveEnable = theParticipant.receiveEnable self.sendEnable = theParticipant.sendEnable } public func formatDataToMakeParticipant() -> Participant { return self } public func formatToJSON() -> JSON { let result: JSON = ["admin": admin ?? NSNull(), "blocked": blocked ?? NSNull(), "cellphoneNumber": cellphoneNumber ?? NSNull(), "contactId": contactId ?? NSNull(), "coreUserId": coreUserId ?? NSNull(), "email": email ?? NSNull(), "firstName": firstName ?? NSNull(), "id": id ?? NSNull(), "image": image ?? NSNull(), "lastName": lastName ?? NSNull(), "myFriend": myFriend ?? NSNull(), "name": name ?? NSNull(), "notSeenDuration": notSeenDuration ?? NSNull(), "online": online ?? NSNull(), "receiveEnable": receiveEnable ?? NSNull(), "sendEnable": sendEnable ?? NSNull()] return result } }
42.644737
89
0.459272
396957ff67bbeaa876a9e2fa7de1960506b28b99
1,836
html
HTML
VirtualRadar.WebSite/Site/Web/zz-norel-leak.html
neonowy/vrs
96b129b924ee18f9c1f356d58313e6075994b724
[ "BSD-3-Clause" ]
208
2016-08-10T20:29:57.000Z
2022-03-29T04:58:05.000Z
VirtualRadar.WebSite/Site/Web/zz-norel-leak.html
neonowy/vrs
96b129b924ee18f9c1f356d58313e6075994b724
[ "BSD-3-Clause" ]
43
2017-07-23T12:24:05.000Z
2022-01-23T11:33:34.000Z
VirtualRadar.WebSite/Site/Web/zz-norel-leak.html
neonowy/vrs
96b129b924ee18f9c1f356d58313e6075994b724
[ "BSD-3-Clause" ]
47
2016-08-10T17:16:16.000Z
2022-03-05T08:12:21.000Z
<!DOCTYPE html> <!-- Chrome leaks like a sieve with ajax calls --> <html> <head> <meta charset="utf-8"> <title>Leak</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="XHR.js"></script> <script type="text/javascript"> var copyOfString = ''; $(document).ready(function($) { ajaxFetch(); //vrsFetch(); }); function ajaxFetch() { // var params = {}; // if(copyOfString !== '') params.ldv = copyOfString; $.getJSON('AircraftList.json', { ldv: copyOfString }, function(data) { copyOfString = data.lastDv; data = null; setTimeout(ajaxFetch, 1000); }); }; var _XHR = new XHR(); function vrsFetch() { var url = 'AircraftList.json'; if(copyOfString !== '') url += '?ldv=' + copyOfString; _XHR.beginSend('GET', url, null, null, 10000, showAircraftHandler, null, null); }; function showAircraftHandler(status, responseText) { if(status !== 200) { // Wait a little while before trying again - don't want to hammer it if it's not there setTimeout(showAircraft, 15 * 1000); } else { var content = eval('(' + responseText + ')'); copyOfString = content.lastDv; setTimeout(vrsFetch, 1000); } }; </script> </head> <body> </body> </html>
32.210526
107
0.443355
0469420885ceab37d5ca575edda0295f10524ad5
996
swift
Swift
705.playground/Contents.swift
LispLY/leetcode-resolutions
840b453e7191db5c171af50ec8bfe9d8923957b9
[ "WTFPL" ]
1
2022-01-24T05:43:50.000Z
2022-01-24T05:43:50.000Z
705.playground/Contents.swift
LispLY/leetcode-solutions
840b453e7191db5c171af50ec8bfe9d8923957b9
[ "WTFPL" ]
null
null
null
705.playground/Contents.swift
LispLY/leetcode-solutions
840b453e7191db5c171af50ec8bfe9d8923957b9
[ "WTFPL" ]
null
null
null
// passed // 更严肃的实现应该用链表来存储 import Cocoa class MyHashSet { static let space = 999 var stores: [[Int]] /** Initialize your data structure here. */ init() { stores = Array(repeating: [Int](), count: MyHashSet.space) } func hashValue(_ num: Int) -> Int { return num % MyHashSet.space } func add(_ key: Int) { let index = hashValue(key) if !stores[index].contains(key) { stores[index].append(key) } } func remove(_ key: Int) { let index = hashValue(key) stores[index].removeAll { $0 == key } } /** Returns true if this set contains the specified element */ func contains(_ key: Int) -> Bool { let index = hashValue(key) return stores[index].contains(key) } } /** * Your MyHashSet object will be instantiated and called as such: * let obj = MyHashSet() * obj.add(key) * obj.remove(key) * let ret_3: Bool = obj.contains(key) */
22.133333
66
0.570281
bb14ed696f852547deabeb069a83bebc08e1dd4c
79
rb
Ruby
init.rb
cavneb/lightwindow
0a4d8524d0b77c131e00ba18bce223cae8420aea
[ "MIT" ]
1
2016-05-08T11:27:02.000Z
2016-05-08T11:27:02.000Z
init.rb
cavneb/lightwindow
0a4d8524d0b77c131e00ba18bce223cae8420aea
[ "MIT" ]
null
null
null
init.rb
cavneb/lightwindow
0a4d8524d0b77c131e00ba18bce223cae8420aea
[ "MIT" ]
null
null
null
require 'lightwindow_helper' ActionView::Base.send(:include, LightwindowHelper)
39.5
50
0.848101
dd7c28b324f3a63f444d290ff63e80c006179397
9,815
php
PHP
app/Http/Controllers/Sec/LicensesController.php
mdwikydarmawan/it-asset
5af801f6bc280c804fe743d5860cb530699b478e
[ "MIT" ]
null
null
null
app/Http/Controllers/Sec/LicensesController.php
mdwikydarmawan/it-asset
5af801f6bc280c804fe743d5860cb530699b478e
[ "MIT" ]
null
null
null
app/Http/Controllers/Sec/LicensesController.php
mdwikydarmawan/it-asset
5af801f6bc280c804fe743d5860cb530699b478e
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Sec; use App\SecLicense; use Illuminate\Http\Request; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Gate; use App\Http\Requests\Sec\UpdateLicenseRequest; use DateTime; class LicensesController extends Controller { /** * Display a listing of Permission. * * @return \Illuminate\Http\Response */ public function index() { if (! Gate::allows('users_manage') && ! Gate::allows('users_security')) { return abort(401); } $sec_license = DB::table('sec_license') ->select('sec_license.id', 'sec_license.license_name', 'sec_license.license_expired_date', 'sec_license.license_information', 'param_vendor.id AS id_vendor', 'param_vendor.vendor_name' ) ->join('param_vendor', 'param_vendor.id', '=', 'sec_license.vendor_id') ->get(); return view('sec.license.index',compact('sec_license'))->with('i', (request()->input('page', 1) - 1) * 5); } /** * Show the form for creating new Permission. * * @return \Illuminate\Http\Response */ public function create() { if (! Gate::allows('users_manage') && ! Gate::allows('users_security')) { return abort(401); } $param_vendor = DB::table('param_vendor') ->select( 'param_vendor.id', 'param_vendor.vendor_name' ) ->get(); return view('sec.license.create', compact('param_vendor')); } /** * Store a newly created Permission in storage. * * @param \App\Http\Requests\StorePermissionsRequest $request * @return \Illuminate\Http\Response */ public function store(Request $request) { date_default_timezone_set('Asia/Jakarta'); if($request->license_expired_date != ''){ $expired_date = new DateTime($request->license_expired_date); $final = $expired_date->modify('-3 months'); $final = $final->format('Y-m-d'); }else{ $final = '0000-00-00'; } $sec_license = DB::table('sec_license')->select(DB::raw('COUNT(id) as jumlah'))->where('license_notification_date', date('Y-m-d')) ->first(); for($i = 1; $i <= $sec_license->jumlah; $i++){ $hasil = DB::table('sec_license')->select('*')->where('license_notification_date', date('Y-m-d'))->get(); } $values = array('id' => 0, 'vendor_id' => $request->vendor_id, 'purchase_date' => $request->purchase_date, 'renual' => $request->renual, 'license_name' => $request->license_name, 'license_expired_date' => ($request->license_expired_date ? $request->license_expired_date : '0000-00-00'), 'license_notification_date' => $final, 'license_information' => $request->license_information, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ); DB::table('sec_license')->insert($values); return redirect()->route('sec.license.index')->with('success','Data berhasil disimpan.'); } /** * Show the form for editing Permission. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { if (! Gate::allows('users_manage') && ! Gate::allows('users_security')) { return abort(401); } date_default_timezone_set('Asia/Jakarta'); $sec_license = DB::table('sec_license') ->where('sec_license.id', $id) ->select('sec_license.id', 'sec_license.vendor_id', 'sec_license.license_name', 'sec_license.purchase_date', 'sec_license.renual', 'sec_license.license_expired_date', 'sec_license.license_information', 'param_vendor.id AS id_vendor', 'param_vendor.vendor_name' ) ->join('param_vendor', 'param_vendor.id', '=', 'sec_license.vendor_id') ->first(); $param_vendor = DB::table('param_vendor') ->select( 'param_vendor.id', 'param_vendor.vendor_name' ) ->get(); return view('sec.license.edit', compact('sec_license', 'param_vendor')); } /** * Update Permission in storage. * * @param \App\Http\Requests\UpdatePermissionsRequest $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateLicenseRequest $request, $id) { if (! Gate::allows('users_manage') && ! Gate::allows('users_security')) { return abort(401); } if($request->license_expired_date != '' || $request->license_expired_date != '0000-00-00'){ $expired_date = new DateTime($request->license_expired_date); $final = $expired_date->modify('-3 months'); $final = $final->format('Y-m-d'); }else{ $final = '0000-00-00'; } $sec_license = DB::table('sec_license')->select(DB::raw('COUNT(id) as jumlah'))->where('license_notification_date', date('Y-m-d')) ->first(); for($i = 1; $i <= $sec_license->jumlah; $i++){ $hasil = DB::table('sec_license')->select('*')->where('license_notification_date', date('Y-m-d'))->get(); } DB::table('sec_license') ->where('id', $id) ->update(array( 'vendor_id' => $request->vendor_id, 'purchase_date' => $request->purchase_date, 'renual' => $request->renual, 'license_name' => $request->license_name, 'license_expired_date' => ($request->license_expired_date ? $request->license_expired_date : '0000-00-00'), 'license_notification_date' => $final, 'license_information' => $request->license_information, 'updated_at' => date('Y-m-d H:i:s') )); return redirect()->route('sec.license.index')->with('success','Data berhasil diperbarui.'); } public function show(SecLicense $sec_license, $id) { $sec_license = DB::table('sec_license') ->where('sec_license.id', $id) ->select('sec_license.id', 'sec_license.vendor_id', 'sec_license.license_name', 'sec_license.purchase_date', 'sec_license.renual', 'sec_license.license_expired_date', 'sec_license.license_information', 'param_vendor.id AS id_vendor', 'param_vendor.vendor_name' ) ->join('param_vendor', 'param_vendor.id', '=', 'sec_license.vendor_id') ->first(); return view('sec.license.show',compact('sec_license')); } /** * Remove Permission from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { if (! Gate::allows('users_manage') && ! Gate::allows('users_security')) { return abort(401); } $sec_branch = SecLicense::findOrFail($id); $sec_branch->delete(); return redirect()->route('sec.license.index')->with('error','Data berhasil dihapus.'); } }
41.588983
151
0.429037
f35d368dbc1c9feed7842fbccb4536db6d9b23c8
9,208
lua
Lua
AzurLaneData/zh-CN/mgr/timemgr.lua
FlandreCirno/AzurLaneWikiUtilitiesManual
b525fd9086dd716bb65848a8cd0635b261ab6fdf
[ "MIT" ]
null
null
null
AzurLaneData/zh-CN/mgr/timemgr.lua
FlandreCirno/AzurLaneWikiUtilitiesManual
b525fd9086dd716bb65848a8cd0635b261ab6fdf
[ "MIT" ]
null
null
null
AzurLaneData/zh-CN/mgr/timemgr.lua
FlandreCirno/AzurLaneWikiUtilitiesManual
b525fd9086dd716bb65848a8cd0635b261ab6fdf
[ "MIT" ]
null
null
null
pg = pg or {} pg.TimeMgr = singletonClass("TimeMgr") pg.TimeMgr._Timer = nil pg.TimeMgr._BattleTimer = nil pg.TimeMgr._sAnchorTime = 0 pg.TimeMgr._AnchorDelta = 0 pg.TimeMgr._serverUnitydelta = 0 pg.TimeMgr._isdstClient = false slot2 = 3600 slot3 = 86400 slot4 = 604800 pg.TimeMgr.Ctor = function (slot0) slot0._battleTimerList = {} end pg.TimeMgr.Init = function (slot0) print("initializing time manager...") slot0._Timer = TimeUtil.NewUnityTimer() UpdateBeat:Add(slot0.Update, slot0) UpdateBeat:Add(slot0.BattleUpdate, slot0) end pg.TimeMgr.Update = function (slot0) slot0._Timer:Schedule() end pg.TimeMgr.BattleUpdate = function (slot0) if slot0._stopCombatTime > 0 then slot0._cobTime = slot0._stopCombatTime - slot0._waitTime else slot0._cobTime = Time.time - slot0._waitTime end end pg.TimeMgr.AddTimer = function (slot0, slot1, slot2, slot3, slot4) return slot0._Timer:SetTimer(slot1, slot2 * 1000, slot3 * 1000, slot4) end pg.TimeMgr.RemoveTimer = function (slot0, slot1) if slot1 == nil or slot1 == 0 then return end slot0._Timer:DeleteTimer(slot1) end pg.TimeMgr._waitTime = 0 pg.TimeMgr._stopCombatTime = 0 pg.TimeMgr._cobTime = 0 pg.TimeMgr.GetCombatTime = function (slot0) return slot0._cobTime end pg.TimeMgr.ResetCombatTime = function (slot0) slot0._waitTime = 0 slot0._cobTime = Time.time end pg.TimeMgr.GetCombatDeltaTime = function () return Time.fixedDeltaTime end pg.TimeMgr.PauseBattleTimer = function (slot0) slot0._stopCombatTime = Time.time for slot4, slot5 in pairs(slot0._battleTimerList) do slot4:Pause() end end pg.TimeMgr.ResumeBattleTimer = function (slot0) slot0._waitTime = (slot0._waitTime + Time.time) - slot0._stopCombatTime slot0._stopCombatTime = 0 for slot4, slot5 in pairs(slot0._battleTimerList) do slot4:Resume() end end pg.TimeMgr.AddBattleTimer = function (slot0, slot1, slot2, slot3, slot4, slot5, slot6) slot0._battleTimerList[Timer.New(slot4, slot3, slot2 or -1, slot5 or false)] = true if not (slot6 or false) then slot7:Start() end if slot0._stopCombatTime ~= 0 then slot7:Pause() end return slot7 end pg.TimeMgr.ScaleBattleTimer = function (slot0, slot1) Time.timeScale = slot1 end pg.TimeMgr.RemoveBattleTimer = function (slot0, slot1) if slot1 then slot0._battleTimerList[slot1] = nil slot1:Stop() end end pg.TimeMgr.RemoveAllBattleTimer = function (slot0) for slot4, slot5 in pairs(slot0._battleTimerList) do slot4:Stop() end slot0._battleTimerList = {} end pg.TimeMgr.RealtimeSinceStartup = function (slot0) return math.ceil(Time.realtimeSinceStartup) end pg.TimeMgr.SetServerTime = function (slot0, slot1, slot2) if PLATFORM_CODE == PLATFORM_US then SERVER_SERVER_DAYLIGHT_SAVEING_TIME = true end slot0._isdstClient = os.date("*t").isdst slot0._serverUnitydelta = slot1 - slot0:RealtimeSinceStartup() slot0._sAnchorTime = slot2 - ((SERVER_DAYLIGHT_SAVEING_TIME and 3600) or 0) slot0._AnchorDelta = slot2 - os.time({ year = 2020, month = 11, hour = 0, min = 0, sec = 0, day = 23, isdst = false }) end pg.TimeMgr.GetServerTime = function (slot0) return slot0:RealtimeSinceStartup() + slot0._serverUnitydelta end pg.TimeMgr.GetServerWeek = function (slot0) return slot0:GetServerTimestampWeek(slot0:GetServerTime()) end pg.TimeMgr.GetServerTimestampWeek = function (slot0, slot1) return math.ceil(((slot1 - slot0._sAnchorTime) % slot0 + 1) / slot1) end pg.TimeMgr.GetServerHour = function (slot0) return math.floor((slot0:GetServerTime() - slot0._sAnchorTime) % slot0 / slot0.GetServerTime()) end pg.TimeMgr.Table2ServerTime = function (slot0, slot1) if slot0._isdstClient ~= SERVER_DAYLIGHT_SAVEING_TIME then if SERVER_DAYLIGHT_SAVEING_TIME then return (slot0._AnchorDelta + os.time(slot1)) - slot0 else return slot0._AnchorDelta + os.time(slot1) + slot0 end else return slot0._AnchorDelta + os.time(slot1) end end pg.TimeMgr.CTimeDescC = function (slot0, slot1, slot2) return os.date(slot2 or "%Y%m%d%H%M%S", slot1) end pg.TimeMgr.STimeDescC = function (slot0, slot1, slot2, slot3) slot2 = slot2 or "%Y/%m/%d %H:%M:%S" if slot3 then return os.date(slot2, (slot1 + os.time()) - slot0:GetServerTime()) else return os.date(slot2, slot1) end end pg.TimeMgr.STimeDescS = function (slot0, slot1, slot2) slot2 = slot2 or "%Y/%m/%d %H:%M:%S" slot3 = 0 if slot0._isdstClient ~= SERVER_DAYLIGHT_SAVEING_TIME then return os.date(slot2, slot1 - slot0._AnchorDelta + ((SERVER_DAYLIGHT_SAVEING_TIME and 3600) or -3600)) end end pg.TimeMgr.CurrentSTimeDesc = function (slot0, slot1, slot2) if slot2 then return slot0:STimeDescS(slot0:GetServerTime(), slot1) else return slot0:STimeDescC(slot0:GetServerTime(), slot1) end end pg.TimeMgr.ChieseDescTime = function (slot0, slot1, slot2) slot4 = nil slot5 = split((not slot2 or os.date("%Y/%m/%d", slot1)) and os.date("%Y/%m/%d", (slot1 + os.time()) - slot0:GetServerTime()), "/") return NumberToChinese(slot5[1], false) .. "年" .. NumberToChinese(slot5[2], true) .. "月" .. NumberToChinese(slot5[3], true) .. "日" end pg.TimeMgr.GetNextTime = function (slot0, slot1, slot2, slot3, slot4) return math.floor((slot0:GetServerTime() - (slot0._sAnchorTime + slot1 * slot1 + slot2 * 60 + slot3)) / (slot4 or slot0) + 1) * (slot4 or slot0) + slot0._sAnchorTime + slot1 * slot1 + slot2 * 60 + slot3 end pg.TimeMgr.GetNextTimeByTimeStamp = function (slot0, slot1) return math.floor((slot1 - slot0._sAnchorTime) / slot0) * slot0 + slot0._sAnchorTime end pg.TimeMgr.GetNextWeekTime = function (slot0, slot1, slot2, slot3, slot4) return slot0:GetNextTime((slot1 - 1) * 24 + slot2, slot3, slot4, slot0) end pg.TimeMgr.ParseTime = function (slot0, slot1) return slot0:Table2ServerTime({ year = tonumber(slot1) / 100 / 100 / 100 / 100 / 100, month = (tonumber(slot1) / 100 / 100 / 100 / 100) % 100, day = (tonumber(slot1) / 100 / 100 / 100) % 100, hour = (tonumber(slot1) / 100 / 100) % 100, min = (tonumber(slot1) / 100) % 100, sec = tonumber(slot1) % 100 }) end pg.TimeMgr.ParseTimeEx = function (slot0, slot1, slot2) if slot2 == nil then slot2 = "(%d+)%-(%d+)%-(%d+)%s(%d+)%:(%d+)%:(%d+)" end slot11.year, slot11.month, slot11.day, slot11.hour, slot11.min, slot11.sec = slot1:match(slot2) return slot0:Table2ServerTime({ year = slot3, month = slot4, day = slot5, hour = slot6, min = slot7, sec = slot8 }) end pg.TimeMgr.parseTimeFromConfig = function (slot0, slot1) return slot0:Table2ServerTime({ year = slot1[1][1], month = slot1[1][2], day = slot1[1][3], hour = slot1[2][1], min = slot1[2][2], sec = slot1[2][3] }) end pg.TimeMgr.DescCDTime = function (slot0, slot1) return string.format("%02d:%02d:%02d", math.floor(slot1 / 3600), math.floor((slot1 - math.floor(slot1 / 3600) * 3600) / 60), (slot1 - math.floor(slot1 / 3600) * 3600) % 60) end pg.TimeMgr.parseTimeFrom = function (slot0, slot1) return math.floor(slot1 / slot0), math.fmod(math.floor(slot1 / 3600), 24), math.fmod(math.floor(slot1 / 60), 60), math.fmod(slot1, 60) end pg.TimeMgr.DiffDay = function (slot0, slot1, slot2) return math.floor((slot2 - slot0._sAnchorTime) / slot0) - math.floor((slot1 - slot0._sAnchorTime) / slot0) end pg.TimeMgr.IsSameDay = function (slot0, slot1, slot2) return math.floor((slot1 - slot0._sAnchorTime) / slot0) == math.floor((slot2 - slot0._sAnchorTime) / slot0) end pg.TimeMgr.IsPassTimeByZero = function (slot0, slot1, slot2) return slot2 < math.fmod(slot1 - slot0._sAnchorTime, slot0) end pg.TimeMgr.CalcMonthDays = function (slot0, slot1, slot2) slot3 = 30 if slot2 == 2 then slot3 = (((slot1 % 4 == 0 and slot1 % 100 ~= 0) or slot1 % 400 == 0) and 29) or 28 elseif _.include({ 1, 3, 5, 7, 8, 10, 12 }, slot2) then slot3 = 31 end return slot3 end pg.TimeMgr.inTime = function (slot0, slot1) if not slot1 then return true end if type(slot1) == "string" then return slot1 == "always" end if slot1[1] == nil then slot1 = { slot1[2], slot1[3] } end function slot2(slot0) return { year = slot0[1][1], month = slot0[1][2], day = slot0[1][3], hour = slot0[2][1], min = slot0[2][2], sec = slot0[2][3] } end slot3 = nil if #slot1 > 0 then slot3 = slot2(slot1[1] or { { 2000, 1, 1 }, { 0, 0, 0 } }) end slot4 = nil if #slot1 > 1 then slot4 = slot2(slot1[2] or { { 2000, 1, 1 }, { 0, 0, 0 } }) end slot5 = nil if slot3 and slot4 then slot8 = slot0:Table2ServerTime(slot4) if slot0:GetServerTime() < slot0:Table2ServerTime(slot3) then return false, slot3 end if slot8 < slot6 then return false, nil end slot5 = slot4 end return true, slot5 end pg.TimeMgr.passTime = function (slot0, slot1) if not slot1 then return true end function slot2(slot0) return { year = slot0[1][1], month = slot0[1][2], day = slot0[1][3], hour = slot0[2][1], min = slot0[2][2], sec = slot0[2][3] } end slot3 = slot2 slot4 = slot1 or { { 2000, 1, 1 }, { 0, 0, 0 } } if slot3(slot4) then return slot0:Table2ServerTime(slot3) < slot0:GetServerTime() end return true end return
22.134615
203
0.688097
f778815ca55937be4b6eb58541c6b788b4e1afeb
1,911
h
C
hardware/aw/playready/include/oem/common/inc/bigdecls.h
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
10
2020-04-17T04:02:36.000Z
2021-11-23T11:38:42.000Z
hardware/aw/playready/include/oem/common/inc/bigdecls.h
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
3
2020-02-19T16:53:25.000Z
2021-04-29T07:28:40.000Z
hardware/aw/playready/include/oem/common/inc/bigdecls.h
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
5
2019-12-25T04:05:02.000Z
2022-01-14T16:57:55.000Z
/**@@@+++@@@@****************************************************************** ** ** Microsoft (r) PlayReady (r) ** Copyright (c) Microsoft Corporation. All rights reserved. ** ***@@@---@@@@****************************************************************** */ #ifndef BIGDECLS_H #define BIGDECLS_H 1 ENTER_PK_NAMESPACE; /* ** The assembly versions of these calls were hardcoded to use stdcall calling ** DRM_API convention. For the C implementation we will use DRM_CALL as it is standard ** throughout the porting kits. */ #if defined(_M_IX86) && DRM_SUPPORT_ASSEMBLY extern DRM_BOOL __stdcall mp_mul22s(const digit_t[4], digit_t *, digit_t *, const DRM_DWORD, sdigit_t[2]); extern DRM_BOOL __stdcall mp_mul22u(const digit_t[4], digit_t *, digit_t *, const DRM_DWORD, digit_t[2] ); extern DRM_VOID __stdcall multiply_low(const digit_t *, const digit_t *, digit_t *, const DRM_DWORD ); #else DRM_API DRM_BOOL DRM_CALL mp_mul22s( __in_ecount(4) const digit_t mat[4], /* IN (2 x 2 matrix of scalars) */ __inout_ecount(lvec) digit_t vec1[], /* INOUT */ __inout_ecount(lvec) digit_t vec2[], /* INOUT */ __in const DRM_DWORD lvec, /* IN */ __out_ecount(2) sdigit_t carrys[2] ); /* OUT (array of 2 scalars) */ DRM_API DRM_BOOL DRM_CALL mp_mul22u( __in_ecount(4) const digit_t mat[4], /* IN (2 x 2 matrix of scalars) */ __inout_ecount(lvec) digit_t vec1[], /* INOUT */ __inout_ecount(lvec) digit_t vec2[], /* INOUT */ __in const DRM_DWORD lvec, /* IN */ __out_ecount(2) digit_t carrys[2] ); /* OUT (array of 2 scalars) */ DRM_API_VOID DRM_VOID DRM_CALL multiply_low(const digit_t *, const digit_t *, digit_t *, const DRM_DWORD ); #endif EXIT_PK_NAMESPACE; #endif /* BIGDECLS_H */
38.22
107
0.582941
2f6d32ab2f6e6de656785e26fd9798b9a520bf2d
1,890
rs
Rust
win_ring0/src/winRing0.rs
alex-dow/winRing0-rs
f26aa05277f4989db26f846953285edd8aa3d631
[ "BSD-2-Clause" ]
null
null
null
win_ring0/src/winRing0.rs
alex-dow/winRing0-rs
f26aa05277f4989db26f846953285edd8aa3d631
[ "BSD-2-Clause" ]
null
null
null
win_ring0/src/winRing0.rs
alex-dow/winRing0-rs
f26aa05277f4989db26f846953285edd8aa3d631
[ "BSD-2-Clause" ]
null
null
null
use win_kernel_driver::WinKernelDriver; use win_kernel_driver::DriverBuilder; use super::ioctl::IOCTL; use winapi::shared::minwindef::{DWORD}; /// WinRing0 driver pub struct WinRing0 { driver: WinKernelDriver } impl<'a> WinRing0 { pub fn new() -> Self { let driver_x64 = include_bytes!("../winRing0x64.sys"); let driver_x86 = include_bytes!("../winRing0.sys"); let driver = DriverBuilder::new() .set_device_description("Rust winRing0 driver") .set_device_id("WinRing0_1_2_0") .set_device_type(40000) .set_driver_bin(driver_x64.to_vec()) .build().unwrap(); WinRing0 { driver: driver } } /// Install the winRing0 driver. pub fn install(&self) -> Result<(), String> { return self.driver.install(); } /// Open the winRing0 driver for communication pub fn open(&mut self) -> Result<(), String> { return self.driver.open(); } /// Close the winRing0 driver handle pub fn close(&mut self) -> Result<(), String> { self.driver.close() } /// Uninstall the winRing0 driver pub fn uninstall(&mut self) -> Result<(), String> { self.driver.uninstall() } /// Read an MSR register pub fn readMsr(&self, msr: DWORD) -> Result<u64, String> { match self.driver.io(IOCTL::OLS_READ_MSR as u32, msr) { Ok(res) => { return Ok(res); } Err(err) => { return Err(format!("Error reading msr: {}", err)); } } } /// Raw IO function. See [WinKernelDriver::io] for more information pub fn io(&self, ioctl: IOCTL, in_buffer: u32) -> Result<u64, String> { match self.driver.io(ioctl as u32, in_buffer) { Ok(res) => { return Ok(res); }, Err(err) => { return Err(format!("Error doing IO: {}", err)); } } } }
29.53125
78
0.577778
18b7cba04389a8c95916c5bdc348fd1ffb4577b6
2,419
rb
Ruby
app/controllers/admin/regiones_controller.rb
isaac95mendez/enciclovida
311cd1d492855efa1d56389e26f2b9f29a83071a
[ "MIT" ]
5
2015-02-06T16:29:15.000Z
2018-09-03T03:34:04.000Z
app/controllers/admin/regiones_controller.rb
isaac95mendez/enciclovida
311cd1d492855efa1d56389e26f2b9f29a83071a
[ "MIT" ]
74
2015-02-27T17:34:04.000Z
2018-09-20T16:17:30.000Z
app/controllers/admin/regiones_controller.rb
isaac95mendez/enciclovida
311cd1d492855efa1d56389e26f2b9f29a83071a
[ "MIT" ]
14
2018-12-15T01:49:02.000Z
2021-09-08T17:46:43.000Z
class Admin::RegionesController < Admin::AdminController before_action :set_admin_region, only: [:show, :edit, :update, :destroy] # GET /admin/regiones # GET /admin/regiones.json def index @admin_regiones = Admin::Region.all end # GET /admin/regiones/1 # GET /admin/regiones/1.json def show end # GET /admin/regiones/new def new @admin_region = Admin::Region.new end # GET /admin/regiones/1/edit def edit end # POST /admin/regiones # POST /admin/regiones.json def create @admin_region = Admin::Region.new(admin_region_params) respond_to do |format| if @admin_region.save format.html { redirect_to @admin_region, notice: 'Region was successfully created.' } format.json { render :show, status: :created, location: @admin_region } else format.html { render :new } format.json { render json: @admin_region.errors, status: :unprocessable_entity } end end end # PATCH/PUT /admin/regiones/1 # PATCH/PUT /admin/regiones/1.json def update respond_to do |format| if @admin_region.update(admin_region_params) format.html { redirect_to @admin_region, notice: 'Region was successfully updated.' } format.json { render :show, status: :ok, location: @admin_region } else format.html { render :edit } format.json { render json: @admin_region.errors, status: :unprocessable_entity } end end end # DELETE /admin/regiones/1 # DELETE /admin/regiones/1.json def destroy @admin_region.destroy respond_to do |format| format.html { redirect_to admin_regiones_url, notice: 'Region was successfully destroyed.' } format.json { head :no_content } end end # GET /admin/regiones/autocompleta?q= def autocompleta regiones = params[:term].present? ? Admin::Region.autocompleta(params[:term]) : [] render json: regiones.map { |b| { label: "#{b.nombre_region}, #{b.tipo_region.descripcion}", value: b.id } } end private # Use callbacks to share common setup or constraints between actions. def set_admin_region @admin_region = Admin::Region.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def admin_region_params params.require(:admin_region).permit(:nombre_region, :tipo_region_id, :clave_region, :id_region_asc) end end
29.5
112
0.68334
5e125fd558b11e010aecbc7cd1744c6c930faaa9
7,244
lua
Lua
plugins/3dtext.lua
nykez/helix
8f64c85dfa1357add397d8b8962680f5d1a28da5
[ "MIT" ]
2
2019-12-02T18:18:32.000Z
2019-12-02T18:19:04.000Z
plugins/3dtext.lua
nykez/helix
8f64c85dfa1357add397d8b8962680f5d1a28da5
[ "MIT" ]
null
null
null
plugins/3dtext.lua
nykez/helix
8f64c85dfa1357add397d8b8962680f5d1a28da5
[ "MIT" ]
1
2019-06-20T22:20:01.000Z
2019-06-20T22:20:01.000Z
local PLUGIN = PLUGIN PLUGIN.name = "3D Text" PLUGIN.author = "Chessnut" PLUGIN.description = "Adds text that can be placed on the map." PLUGIN.list = PLUGIN.list or {} if (SERVER) then util.AddNetworkString("ixTextList") util.AddNetworkString("ixTextAdd") util.AddNetworkString("ixTextRemove") ix.log.AddType("undo3dText", function(client) return string.format("%s has removed their last 3D text.", client:GetName()) end) -- Called when the player is sending client info. function PLUGIN:PlayerInitialSpawn(client) timer.Simple(1, function() if (IsValid(client)) then local json = util.TableToJSON(self.list) local compressed = util.Compress(json) local length = compressed:len() net.Start("ixTextList") net.WriteUInt(length, 32) net.WriteData(compressed, length) net.Send(client) end end) end -- Adds a text to the list, sends it to the players, and saves data. function PLUGIN:AddText(position, angles, text, scale) local index = #self.list + 1 scale = math.Clamp((scale or 1) * 0.1, 0.001, 5) self.list[index] = {position, angles, text, scale} net.Start("ixTextAdd") net.WriteUInt(index, 32) net.WriteVector(position) net.WriteAngle(angles) net.WriteString(text) net.WriteFloat(scale) net.Broadcast() self:SaveText() return index end -- Removes a text that are within the radius of a position. function PLUGIN:RemoveText(position, radius) local i = 0 radius = radius or 100 for k, v in pairs(self.list) do if (v[1]:Distance(position) <= radius) then self.list[k] = nil net.Start("ixTextRemove") net.WriteUInt(k, 32) net.Broadcast() i = i + 1 end end if (i > 0) then self:SaveText() end return i end function PLUGIN:RemoveTextByID(id) local info = self.list[id] if (!info) then return false end net.Start("ixTextRemove") net.WriteUInt(id, 32) net.Broadcast() self.list[id] = nil return true end -- Called after entities have been loaded on the map. function PLUGIN:LoadData() self.list = self:GetData() or {} end -- Called when the plugin needs to save information. function PLUGIN:SaveText() self:SetData(self.list) end else language.Add("Undone_ix3dText", "Removed 3D Text") function PLUGIN:GenerateMarkup(text) local object = ix.markup.Parse("<font=ix3D2DFont>"..text:gsub("\\n", "\n")) object.onDrawText = function(surfaceText, font, x, y, color, alignX, alignY, alpha) -- shadow surface.SetTextPos(x + 1, y + 1) surface.SetTextColor(0, 0, 0, alpha) surface.SetFont(font) surface.DrawText(surfaceText) surface.SetTextPos(x, y) surface.SetTextColor(color.r or 255, color.g or 255, color.b or 255, alpha) surface.SetFont(font) surface.DrawText(surfaceText) end return object end -- Receives new text objects that need to be drawn. net.Receive("ixTextAdd", function() local index = net.ReadUInt(32) local position = net.ReadVector() local angles = net.ReadAngle() local text = net.ReadString() local scale = net.ReadFloat() if (text != "") then PLUGIN.list[index] = { position, angles, PLUGIN:GenerateMarkup(text), scale } end end) net.Receive("ixTextRemove", function() PLUGIN.list[net.ReadUInt(32)] = nil end) -- Receives a full update on ALL texts. net.Receive("ixTextList", function() local length = net.ReadUInt(32) local data = net.ReadData(length) local uncompressed = util.Decompress(data) if (!uncompressed) then ErrorNoHalt("[Helix] Unable to decompress text data!\n") return end PLUGIN.list = util.JSONToTable(uncompressed) for _, v in pairs(PLUGIN.list) do local object = ix.markup.Parse("<font=ix3D2DFont>"..v[3]:gsub("\\n", "\n")) object.onDrawText = function(text, font, x, y, color, alignX, alignY, alpha) draw.TextShadow({ pos = {x, y}, color = ColorAlpha(color, alpha), text = text, xalign = 0, yalign = alignY, font = font }, 1, alpha) end v[3] = object end end) function PLUGIN:StartChat() self.preview = nil end function PLUGIN:FinishChat() self.preview = nil end function PLUGIN:HUDPaint() if (ix.chat.currentCommand != "textremove") then return end local radius = tonumber(ix.chat.currentArguments[1]) or 100 surface.SetDrawColor(200, 30, 30) surface.SetTextColor(200, 30, 30) surface.SetFont("ixMenuButtonFont") local i = 0 for _, v in pairs(self.list) do if (v[1]:Distance(LocalPlayer():GetEyeTraceNoCursor().HitPos) <= radius) then local screen = v[1]:ToScreen() surface.DrawLine( ScrW() * 0.5, ScrH() * 0.5, math.Clamp(screen.x, 0, ScrW()), math.Clamp(screen.y, 0, ScrH()) ) i = i + 1 end end if (i > 0) then local textWidth, textHeight = surface.GetTextSize(i) surface.SetTextPos(ScrW() * 0.5 - textWidth * 0.5, ScrH() * 0.5 + textHeight + 8) surface.DrawText(i) end end function PLUGIN:PostDrawTranslucentRenderables(bDrawingDepth, bDrawingSkybox) if (bDrawingDepth or bDrawingSkybox) then return end -- preview for textadd command if (ix.chat.currentCommand == "textadd") then local arguments = ix.chat.currentArguments local text = tostring(arguments[1] or "") local scale = math.Clamp((tonumber(arguments[2]) or 1) * 0.1, 0.001, 5) local trace = LocalPlayer():GetEyeTraceNoCursor() local position = trace.HitPos local angles = trace.HitNormal:Angle() local markup angles:RotateAroundAxis(angles:Up(), 90) angles:RotateAroundAxis(angles:Forward(), 90) -- markup will error with invalid fonts pcall(function() markup = PLUGIN:GenerateMarkup(text) end) if (markup) then cam.Start3D2D(position, angles, scale) markup:draw(0, 0, 1, 1, 255) cam.End3D2D() end end local position = LocalPlayer():GetPos() for _, v in pairs(self.list) do local distance = v[1]:DistToSqr(position) if (distance > 1048576) then continue end cam.Start3D2D(v[1], v[2], v[4] or 0.1) local alpha = (1 - ((distance - 65536) / 768432)) * 255 v[3]:draw(0, 0, 1, 1, alpha) cam.End3D2D() end end end ix.command.Add("TextAdd", { description = "@cmdTextAdd", adminOnly = true, arguments = { ix.type.string, bit.bor(ix.type.number, ix.type.optional) }, OnRun = function(self, client, text, scale) local trace = client:GetEyeTrace() local position = trace.HitPos local angles = trace.HitNormal:Angle() angles:RotateAroundAxis(angles:Up(), 90) angles:RotateAroundAxis(angles:Forward(), 90) local index = PLUGIN:AddText(position + angles:Up() * 0.1, angles, text, scale) undo.Create("ix3dText") undo.SetPlayer(client) undo.AddFunction(function() if (PLUGIN:RemoveTextByID(index)) then ix.log.Add(client, "undo3dText") end end) undo.Finish() return "@textAdded" end }) ix.command.Add("TextRemove", { description = "@cmdTextRemove", adminOnly = true, arguments = bit.bor(ix.type.number, ix.type.optional), OnRun = function(self, client, radius) local trace = client:GetEyeTrace() local position = trace.HitPos + trace.HitNormal * 2 local amount = PLUGIN:RemoveText(position, radius) return "@textRemoved", amount end })
23.596091
85
0.675179
16968b7723f2faf91dbcabb12eccd8a562c60c75
2,031
ts
TypeScript
src/routes/admin/health/getHealth.ts
intelkrishi/rps
2b988db8d81f0527171701871ec4f6abd533ac66
[ "Apache-2.0" ]
12
2020-06-02T20:54:05.000Z
2022-01-13T16:21:32.000Z
src/routes/admin/health/getHealth.ts
intelkrishi/rps
2b988db8d81f0527171701871ec4f6abd533ac66
[ "Apache-2.0" ]
455
2020-06-09T16:16:58.000Z
2022-03-31T15:58:00.000Z
src/routes/admin/health/getHealth.ts
intelkrishi/rps
2b988db8d81f0527171701871ec4f6abd533ac66
[ "Apache-2.0" ]
11
2020-06-09T14:58:38.000Z
2022-03-15T17:53:44.000Z
/********************************************************************* * Copyright (c) Intel Corporation 2021 * SPDX-License-Identifier: Apache-2.0 **********************************************************************/ import Logger from '../../../Logger' import { Request, Response } from 'express' import { API_RESPONSE, API_UNEXPECTED_EXCEPTION, POSTGRES_RESPONSE_CODES, VAULT_RESPONSE_CODES } from '../../../utils/constants' import { MqttProvider } from '../../../utils/MqttProvider' import { HealthCheck } from '../../../models/RCS.Config' import { EnvReader } from '../../../utils/EnvReader' export async function getHealthCheck (req: Request, res: Response): Promise<void> { const log = new Logger('getHealthCheck') try { const status: HealthCheck = { db: { name: EnvReader.GlobalEnvConfig.dbProvider.toUpperCase(), status: 'OK' }, secretStore: { name: 'VAULT', status: 'OK' } } try { await req.db.query('SELECT 1') } catch (dbError) { status.db.status = POSTGRES_RESPONSE_CODES(dbError?.code) } try { const secretManagerHealth = await req.secretsManager.health() status.secretStore.status = secretManagerHealth } catch (secretProviderError) { if (secretProviderError.error) { status.secretStore.status = secretProviderError.error.code } else if (secretProviderError.response?.statusCode) { status.secretStore.status = VAULT_RESPONSE_CODES(secretProviderError.response.statusCode) } } res.status(200) if (status.db.status !== 'OK' || status.secretStore.status.initialized !== true || status.secretStore.status.sealed === true) { res.status(503) } res.json(status).end() } catch (error) { MqttProvider.publishEvent('fail', ['getHealthCheck'], 'Failed to get health') log.error('Failed to get health', JSON.stringify(error)) res.status(500).json(API_RESPONSE(null, null, API_UNEXPECTED_EXCEPTION('Health Check failed'))).end() } }
38.320755
131
0.619892
af51c0727ad6076e3d5c1ac8221cda3c31fc7498
2,976
rb
Ruby
spec/module_spec.rb
alu0100967111/LPP-Food
c47c2c4c813513c7d8daae40efda21919f1a114f
[ "MIT" ]
null
null
null
spec/module_spec.rb
alu0100967111/LPP-Food
c47c2c4c813513c7d8daae40efda21919f1a114f
[ "MIT" ]
null
null
null
spec/module_spec.rb
alu0100967111/LPP-Food
c47c2c4c813513c7d8daae40efda21919f1a114f
[ "MIT" ]
null
null
null
require "spec_helper" include FoodGem include DLLModule FOOD_DATA_FILENAME = "input/food-data.txt" SAMPLES_DATA_FILENAME = "input/samples-data.txt" RSpec.describe Comparable do before :all do @food_array = read_data(FOOD_DATA_FILENAME, SAMPLES_DATA_FILENAME) end context "Comparando alimentos" do before :all do @food_1 = @food_array[0] # Huevo frito @food_2 = @food_array[1] # Leche vaca @food_3 = @food_array[2] # Yogurt end it "Comprobar que huevo frito es mayor que Leche de vaca" do expect(@food_2).to be > @food_1 end it "Comprobar que leche de vaca es menor que Yogurt" do expect(@food_1).to be < @food_3 end it "Comprobar que leche de vaca es igual que leche de vaca" do expect(@food_1).to eq(@food_1) end it "Comprobar que Leche de vaca está entre Huevo frito y Yogurt" do expect(@food_2).to be_between(@food_1, @food_3).exclusive end end end RSpec.describe Enumerable do before :all do @food_array = read_data(FOOD_DATA_FILENAME, SAMPLES_DATA_FILENAME) @list_array = Hash.new() #H ash de nombre de lista y lista @food_array.each{ |food| # Rellenamos el Hash if (@list_array.has_key?(food.group_name)) # Si existe la lista con ese grupo, insertamos @list_array[food.group_name].insert_tail(food) else @list_array[food.group_name] = DLL.new(food) end } end context "Enumerando la lista de alimentos" do before :all do @hlh_list = @list_array["Huevos, lacteos y helados"] @cd_list = @list_array["Carnes y derivados"] @pm_list = @list_array["Pescados y mariscos"] end it "Usamos el método each de la lista doblemente enlazada" do @hlh_list.each{ |food| expect(food.group_name).to eq ("Huevos, lacteos y helados")} end it "Usamos el método all de la lista doblemente enlazada" do expect(@hlh_list.all?{ |food| food.group_name == "Huevos, lacteos y helados"}).to be_truthy end it "Usamos el método any de la lista doblemente enlazada" do expect(@hlh_list.any?{ |food| food.name == "Yogurt"}).to be_truthy end it "Usamos el método max de la lista doblemente enlazada" do expect(@hlh_list.max.name).to eq("Yogurt") end it "Usamos el método min de la lista doblemente enlazada" do expect(@hlh_list.min.name).to eq("Huevo frito") end it "Usamos el método first de la lista doblemente enlazada" do expect(@hlh_list.first).to eq(@hlh_list.get_head) end it "Usamos el método count de la lista doblemente enlazada" do expect(@hlh_list.count).to eq(3) end it "Usamos el método find de la lista doblemente enlazada" do expect(@hlh_list.find{ |food| food.name == "Huevo frito"}).to eq(@hlh_list.get_head) end it "Usamos el método drop de la lista doblemente enlazada" do expect(@hlh_list.drop(2)).to eq([@hlh_list.get_tail]) end end end
32.347826
97
0.675403
46e24beb5d5307fb1eaae51a259e604163dc84b9
712
css
CSS
global.css
lukmi15/PrettyHappyPonies_Traffic_Incident_Interface
c8118f6cbee5d75cc09f918174706f1352f22396
[ "Unlicense" ]
null
null
null
global.css
lukmi15/PrettyHappyPonies_Traffic_Incident_Interface
c8118f6cbee5d75cc09f918174706f1352f22396
[ "Unlicense" ]
null
null
null
global.css
lukmi15/PrettyHappyPonies_Traffic_Incident_Interface
c8118f6cbee5d75cc09f918174706f1352f22396
[ "Unlicense" ]
null
null
null
form { height: 100%; font-weight: bold; } table.frame { width: 100%; height: 100%; } .frame .content { width: 100%; height: 100%; border-collapse: collapse; border: 1px solid black; margin: 0px; padding: 0px; } #logo { height: 80px; } #header { height: 80px; background: black; color: white; vertical-align: center; } #main { height: auto; background: #037d88; } #map { height: auto; padding: auto; vertical-align: center; text-align: center; background-image: url("loading.gif"); background-position: center; background-size: 500px 285px; background-repeat: no-repeat; } #gmap { height: 100%; width: 100%; min-height: 250px; } #filter { height: 30%; vertical-align: top; }
10.787879
38
0.660112
967f788aa8e96ff3a16e877cafd8ec5f088d2516
1,068
php
PHP
app/Http/Controllers/ChatMemberController.php
prokhorenko-vladyslav/laurel-chat-backend
2daee3ac2707ef283b4f1f556fa23add80bc9158
[ "MIT" ]
null
null
null
app/Http/Controllers/ChatMemberController.php
prokhorenko-vladyslav/laurel-chat-backend
2daee3ac2707ef283b4f1f556fa23add80bc9158
[ "MIT" ]
null
null
null
app/Http/Controllers/ChatMemberController.php
prokhorenko-vladyslav/laurel-chat-backend
2daee3ac2707ef283b4f1f556fa23add80bc9158
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Actions\Chat\Member\JoinAction; use App\Actions\Chat\Member\LeaveAction; use App\Http\Requests\Chat\Member\JoinRequest; use App\Http\Requests\Chat\Member\LeaveRequest; use App\Models\Chat; use App\Models\User; class ChatMemberController extends Controller { public function join(JoinRequest $request, Chat $chat, User $user, JoinAction $action) { abort_if(!$chat->isOwner(User::currentId()), 403, 'You are not owner of this chat'); abort_if($chat->isMember($user->id), 200, 'User is member already'); $action->run( $request->getDTO() ); } public function leave(LeaveRequest $request, Chat $chat, User $user, LeaveAction $action) { abort_if(!$chat->isMember($user->id), 403, 'User is not member of this chat'); abort_if( User::currentId() !== $user->id && !$chat->isOwner(User::currentId()), 403, 'You are not owner of this chat' ); $action->run( $request->getDTO() ); } }
28.864865
93
0.629213
994649de2f4a42d6264e49304c581d4a0cde0ae3
1,859
h
C
trolley-interface/include/TCPDrivers.h
g2-field-team/field-hardware-lib
559052f2c245fc384265d67e7885f13f431ca4b8
[ "MIT" ]
null
null
null
trolley-interface/include/TCPDrivers.h
g2-field-team/field-hardware-lib
559052f2c245fc384265d67e7885f13f431ca4b8
[ "MIT" ]
null
null
null
trolley-interface/include/TCPDrivers.h
g2-field-team/field-hardware-lib
559052f2c245fc384265d67e7885f13f431ca4b8
[ "MIT" ]
null
null
null
//============================================================================== // // Title: TCPDrivers.h // Description: This file contains the declarations of TCP functios needed by Device.c // Author: Ran Hong // //============================================================================== #ifndef __TCPDRIVERS_H__ #define __TCPDRIVERS_H__ #include <stdlib.h> namespace TCPDrivers{ enum TCPError { kTCP_NoError =0, kTCP_UnableToRegisterService =-1, kTCP_UnableToEstablishConnection =-2, kTCP_ExistingServer =-3, kTCP_FailedToConnect =-4, kTCP_ServerNotRegistered =-5, kTCP_TooManyConnections =-6, kTCP_ReadFailed =-7, kTCP_WriteFailed =-8, kTCP_InvalidParameter =-9, kTCP_OutOfMemory =-10, kTCP_TimeOutErr =-11, kTCP_NoConnectionEstablished =-12, kTCP_GeneralIOErr =-13, kTCP_ConnectionClosed =-14, kTCP_UnableToLoadWinsockDLL =-15, kTCP_IncorrectWinsockDLLVersion =-16, kTCP_NetworkSubsystemNotReady =-17, kTCP_ConnectionsStillOpen =-18, kTCP_DisconnectPending =-19, kTCP_InfoNotAvailable =-20, kTCP_HostAddressNotFound =-21 }; //Define tcpFuncPtr typedef int (*tcpFuncPtr)(unsigned, int, int, void *); //Connect TCP server int ConnectToTCPServer (unsigned int *conversationHandle, unsigned int portNumber, const char* serverHostName, tcpFuncPtr callbackFunction=NULL, void *callbackData = NULL, unsigned int timeOut=100); //Disconnect from TCP server int DisconnectFromTCPServer (unsigned int conversationHandle); //Read from TCP server int ClientTCPRead (unsigned int conversationHandle, void *dataBuffer, size_t dataSize, unsigned int timeOut=100); //Write to TCP server int ClientTCPWrite (unsigned int conversationHandle, void *dataPointer, int dataSize, unsigned int timeOut1=100); } #endif
32.614035
198
0.670791
2a50c8dcec0ec9f44a2efe4270e92bdb09de42b8
527
java
Java
src/main/java/ch/admin/bag/covidcertificate/client/inapp_delivery/domain/InAppDeliveryRequestDto.java
delixfe/CovidCertificate-Management-Service
c02b1adec17fd745eb160b6b8a2a62b481fee36e
[ "MIT" ]
17
2021-05-31T14:33:39.000Z
2022-03-28T20:53:59.000Z
src/main/java/ch/admin/bag/covidcertificate/client/inapp_delivery/domain/InAppDeliveryRequestDto.java
delixfe/CovidCertificate-Management-Service
c02b1adec17fd745eb160b6b8a2a62b481fee36e
[ "MIT" ]
21
2021-06-01T10:08:19.000Z
2022-01-19T16:28:50.000Z
src/main/java/ch/admin/bag/covidcertificate/client/inapp_delivery/domain/InAppDeliveryRequestDto.java
delixfe/CovidCertificate-Management-Service
c02b1adec17fd745eb160b6b8a2a62b481fee36e
[ "MIT" ]
12
2021-05-31T13:58:16.000Z
2022-02-11T10:30:59.000Z
package ch.admin.bag.covidcertificate.client.inapp_delivery.domain; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.ToString; @Getter @ToString @AllArgsConstructor public class InAppDeliveryRequestDto { /** * Code of the App the certificate should be sent to. Must be 9 characters, alphanumeric and upper case. */ String code; /** * Payload of the QRCode. Starts with 'HC1:' */ String hcert; /** * Base64 encoded String of the PDF. */ String pdf; }
21.958333
108
0.686907
594e95abec9a0fcdd5039944b9d1b8f6e9146514
942
c
C
sys/src/cda/gnet/conn.c
henesy/plan9-1e
47575dc4a4638a1ee0d9eed78d88a9f1720a4430
[ "MIT" ]
null
null
null
sys/src/cda/gnet/conn.c
henesy/plan9-1e
47575dc4a4638a1ee0d9eed78d88a9f1720a4430
[ "MIT" ]
null
null
null
sys/src/cda/gnet/conn.c
henesy/plan9-1e
47575dc4a4638a1ee0d9eed78d88a9f1720a4430
[ "MIT" ]
null
null
null
#include <stdio.h> #include "geom.h" #include "thing.h" #include "text.h" #include "wire.h" #include "conn.h" void Conn::nets(WireList *w) { register i; register Wire **wp; for (i = 0, wp = (Wire **) w->a; i < w->n; i++, wp++) if ((*wp)->contains(pin->p)) /* if (pin->p == (*wp)->P || pin->p == (*wp)->Q) */ net = (*wp)->net; } void Conn::put(FILE *ouf) { if (net == 0) fprintf(stderr,"unconnected pin %s,%s\n",pin->t->s,pin->s->s); else fprintf(ouf," %s %s,%s %% %d %d %d\n",net->s->s,pin->t->s,pin->s->s,pin->style,pin->p.x,pin->p.y); } void Conn::putm(FILE *ouf) { if (net == 0) fprintf(stderr,"unconnected macro pin %s\n",pin->s->s); else if (io == OUT) fprintf(ouf,".m %s %s >\n",pin->s->s,net->s->s); else fprintf(ouf,".m %s %s <\n",pin->s->s,net->s->s); } void Conn::fixup(char *suf) { pin->s->append(suf); } void ConnList::nets(WireList *w) { register i; for (i = 0; i < n; i++) conn(i)->nets(w); }
20.042553
100
0.538217
12df024dd36c18e5e0711020299b101aa72be0f9
1,479
html
HTML
form/tag-cloud/index.html
skylight-hq/va-api-landscape
0a383b764e46c0b3870b2c95af8eaae320bf5a10
[ "CC0-1.0" ]
2
2019-11-06T18:35:06.000Z
2019-11-07T14:40:38.000Z
form/tag-cloud/index.html
skylight-hq/va-api-landscape
0a383b764e46c0b3870b2c95af8eaae320bf5a10
[ "CC0-1.0" ]
1
2018-06-19T17:02:09.000Z
2018-06-19T17:09:50.000Z
form/tag-cloud/index.html
department-of-veterans-affairs/va-api-landscape
0a383b764e46c0b3870b2c95af8eaae320bf5a10
[ "CC0-1.0" ]
1
2018-06-19T20:50:37.000Z
2018-06-19T20:50:37.000Z
--- layout: default title: Form Tag Cloud --- <h2 class="mb-4">Form Tag Cloud</h2> <p class="mb-4">This is a list of forms identified from spidering the VA website.</p> {% assign topics = site.data.form_tag_cloud %} <div id="topiccloud" class="pathcloud"> {% for topic in topics %} {% if topic.word_count > 10000 %} {% assign path_value = 10 %} {% endif %} {% if topic.word_count > 5000 and topic.word_count < 10000 %} {% assign path_value = 9 %} {% endif %} {% if topic.word_count > 4000 and topic.word_count < 5000 %} {% assign path_value = 8 %} {% endif %} {% if topic.word_count > 3000 and topic.word_count < 4000 %} {% assign path_value = 7 %} {% endif %} {% if topic.word_count > 2000 and topic.word_count < 3000 %} {% assign path_value = 6 %} {% endif %} {% if topic.word_count > 1000 and topic.word_count < 2000 %} {% assign path_value = 5 %} {% endif %} {% if topic.word_count > 500 and topic.word_count < 1000 %} {% assign path_value = 4 %} {% endif %} {% if topic.word_count > 250 and topic.word_count < 500 %} {% assign path_value = 3 %} {% endif %} {% if topic.word_count > 100 and topic.word_count < 250 %} {% assign path_value = 2 %} {% endif %} {% if topic.word_count < 100 %} {% assign path_value = 1 %} {% endif %} <span data-weight="{{ path_value }}"> {{ topic.word }} </span> {% endfor %} </div>
29.58
85
0.571332
f6a17cb068e538097d90de9b39fa7b293e4d6298
508
lua
Lua
system/ext/bit.lua
andycai/yi
1462869a3222e5f04691ab8f7a81a49e77e88b31
[ "MIT" ]
8
2017-02-07T07:05:37.000Z
2021-03-23T10:48:26.000Z
system/ext/bit.lua
andycai/yi
1462869a3222e5f04691ab8f7a81a49e77e88b31
[ "MIT" ]
null
null
null
system/ext/bit.lua
andycai/yi
1462869a3222e5f04691ab8f7a81a49e77e88b31
[ "MIT" ]
3
2016-08-05T08:42:27.000Z
2021-04-29T02:20:16.000Z
bit = {} function bit.b(p) return 2 ^ (p - 1) -- 1-based indexing end -- Typical call: if bit.and(x, bit.b(3)) then ... function bit.band(x, p) return x % (p + p) >= p end function bit.setbit(x, p) return bit.band(x, p) and x or x + p end --[==[ BIT_FRAME_TITLE = 1 BIT_FRAME_CLOSE = 2 print(bit.setbit(BIT_FRAME_TITLE, BIT_FRAME_CLOSE)) print(bit.band(3, BIT_FRAME_TITLE)) print(bit.band(7, 1)) print(bit.band(7, 2)) print(bit.band(7, 3)) print(bit.band(8, 4)) --]==]
20.32
52
0.602362
c4edf6056d1a8e7214b4abdc18e5696efb78be4d
9,883
swift
Swift
Swift_SPAlertController/Swift_SPAlertController/ViewController+Sheet.swift
yonfong/SPAlertController
7df13bc2399627a858a7d5305c9467fcaa4cf8fb
[ "MIT" ]
10
2020-04-12T19:16:49.000Z
2021-12-27T03:32:22.000Z
Swift_SPAlertController/Swift_SPAlertController/ViewController+Sheet.swift
yonfong/SPAlertController
7df13bc2399627a858a7d5305c9467fcaa4cf8fb
[ "MIT" ]
null
null
null
Swift_SPAlertController/Swift_SPAlertController/ViewController+Sheet.swift
yonfong/SPAlertController
7df13bc2399627a858a7d5305c9467fcaa4cf8fb
[ "MIT" ]
2
2020-04-17T06:27:35.000Z
2021-11-10T06:24:27.000Z
// // ViewController+Sheet.swift // Swift_SPAlertController // // Created by lidongxi on 2020/1/10. // Copyright © 2020 lidongxi. All rights reserved. // import UIKit extension ViewController{ // MARK: ======== SPAlertControllerStyleActionSheet样式示例 ======== // 示例1:actionSheet的默认动画样式(从底部弹出,有取消按钮) func actionSheetTest1 () { let alertController = SPAlertController.alertController(withTitle: "我是主标题", message: "我是副标题", preferredStyle: .actionSheet) alertController.needDialogBlur = lookBlur let action1 = SPAlertAction.action(withTitle: "Default", style: .default) { (action) in print("点击了Default") } let action2 = SPAlertAction.action(withTitle: "Destructive", style: .destructive) { (action) in print("点击了Destructive") } let action3 = SPAlertAction.action(withTitle: "Cancel", style: .cancel) { (action) in print("点击了Cancel------") } if customBlur { alertController.customOverlayView = CustomOverlayView() } alertController.addAction(action: action1) alertController.addAction(action: action3) // 取消按钮一定排在最底部 alertController.addAction(action: action2) self.present(alertController, animated: true, completion: nil) } // 示例2:actionSheet的默认动画(从底部弹出,无取消按钮) func actionSheetTest2 () { let alertController = SPAlertController.alertController(withTitle: "我是主标题", message: "我是副标题", preferredStyle: .actionSheet) alertController.needDialogBlur = lookBlur let action1 = SPAlertAction.action(withTitle: "Default", style: .default) { (action) in print("点击了Default") } let action2 = SPAlertAction.action(withTitle: "Destructive", style: .destructive) { (action) in print("点击了Destructive") } alertController.addAction(action: action1) alertController.addAction(action: action2) if customBlur { alertController.customOverlayView = CustomOverlayView() } self.present(alertController, animated: true, completion: nil) } // 示例3:actionSheet从顶部弹出(无标题) func actionSheetTest3 () { let alertController = SPAlertController.alertController(withTitle: nil, message: nil, preferredStyle: .actionSheet, animationType: .fromTop) let action1 = SPAlertAction.action(withTitle: "第1个", style: .default) { (action) in print("点击了第1个") } let action2 = SPAlertAction.action(withTitle: "第2个", style: .destructive) { (action) in print("点击了第2个") } let action3 = SPAlertAction.action(withTitle: "第3个", style: .cancel) { (action) in print("点击了第3个") } if customBlur { alertController.customOverlayView = CustomOverlayView() } alertController.addAction(action: action1) alertController.addAction(action: action2) alertController.addAction(action: action3) self.present(alertController, animated: true, completion: nil) } // 示例4:actionSheet从顶部弹出(有标题) func actionSheetTest4 () { let alertController = SPAlertController.alertController(withTitle: nil, message: "我是副标题", preferredStyle: .actionSheet, animationType: .fromTop) let action1 = SPAlertAction.action(withTitle: "第1个", style: .default) { (action) in print("点击了第1个") } let action2 = SPAlertAction.action(withTitle: "第2个", style: .destructive) { (action) in print("点击了第2个") } let action3 = SPAlertAction.action(withTitle: "第3个", style: .cancel) { (action) in print("点击了第3个") } if customBlur { alertController.customOverlayView = CustomOverlayView() } alertController.addAction(action: action1) alertController.addAction(action: action2) alertController.addAction(action: action3) self.present(alertController, animated: true, completion: nil) } // 示例5:actionSheet水平排列(有取消按钮) func actionSheetTest5 () { let alertController = SPAlertController.alertController(withTitle: "我是主标题", message: "我是副标题", preferredStyle: .actionSheet, animationType: .default) alertController.actionAxis = .horizontal let action1 = SPAlertAction.action(withTitle: "第1个", style: .default) { (action) in print("点击了第1个") } // SPAlertActionStyleDestructive默认文字为红色(可修改) let action2 = SPAlertAction.action(withTitle: "第2个", style: .destructive) { (action) in print("点击了第2个") } let action3 = SPAlertAction.action(withTitle: "第3个", style: .default) { (action) in print("点击了第3个") } let action4 = SPAlertAction.action(withTitle: "第4个", style: .default) { (action) in print("点击了第4个") } let action5 = SPAlertAction.action(withTitle: "取消", style: .cancel) { (action) in print("点击了cancel") } if customBlur { alertController.customOverlayView = CustomOverlayView() } alertController.addAction(action: action1) alertController.addAction(action: action2) alertController.addAction(action: action3) alertController.addAction(action: action4) alertController.addAction(action: action5) self.present(alertController, animated: true, completion: nil) } // 示例6:actionSheet 水平排列(无取消按钮) func actionSheetTest6 () { let alertController = SPAlertController.alertController(withTitle: "我是主标题", message: "我是副标题", preferredStyle: .actionSheet, animationType: .default) alertController.actionAxis = .horizontal let action1 = SPAlertAction.action(withTitle: "第1个", style: .default) { (action) in print("点击了第1个") } // SPAlertActionStyleDestructive默认文字为红色(可修改) let action2 = SPAlertAction.action(withTitle: "第2个", style: .destructive) { (action) in print("点击了第2个") } let action3 = SPAlertAction.action(withTitle: "第3个", style: .default) { (action) in print("点击了第3个") } let action4 = SPAlertAction.action(withTitle: "第4个", style: .default) { (action) in print("点击了第4个") } if customBlur { alertController.customOverlayView = CustomOverlayView() } alertController.addAction(action: action1) alertController.addAction(action: action2) alertController.addAction(action: action3) alertController.addAction(action: action4) self.present(alertController, animated: true, completion: nil) } // 示例7:actionSheet action上有图标 func actionSheetTest7 () { let alertController = SPAlertController.alertController(withTitle: nil, message: nil, preferredStyle: .actionSheet, animationType: .default) let action1 = SPAlertAction.action(withTitle: "视频通话", style: .default) { (action) in print("点击了‘视频通话’") } action1.image = UIImage.init(named: "video") action1.imageTitleSpacing = 5 let action2 = SPAlertAction.action(withTitle: "语音通话", style: .default) { (action) in print("点击了‘语音通话’") } action2.image = UIImage.init(named: "telephone") action2.imageTitleSpacing = 5 let action3 = SPAlertAction.action(withTitle: "取消", style: .cancel) { (action) in print("点击了第3个") } if customBlur { alertController.customOverlayView = CustomOverlayView() } alertController.addAction(action: action1) alertController.addAction(action: action2) alertController.addAction(action: action3) self.present(alertController, animated: true, completion: nil) } // 示例8:actionSheet 模拟多分区样式 func actionSheetTest8 () { let alertController = SPAlertController.alertController(withTitle: "我是主标题", message: "我是副标题", preferredStyle: .actionSheet, animationType: .default) let action1 = SPAlertAction.action(withTitle: "第1个", style: .default) { (action) in print("点击了第1个") } action1.titleColor = .orange let action2 = SPAlertAction.action(withTitle: "第2个", style: .default) { (action) in print("点击了第2个") } action2.titleColor = .orange let action3 = SPAlertAction.action(withTitle: "第3个", style: .default) { (action) in print("点击了第3个") } let action4 = SPAlertAction.action(withTitle: "第4个", style: .default) { (action) in print("点击了第4个") } let action5 = SPAlertAction.action(withTitle: "第5个", style: .destructive) { (action) in print("点击了第5个") } let action6 = SPAlertAction.action(withTitle: "第6个", style: .destructive) { (action) in print("点击了第6个") } let action7 = SPAlertAction.action(withTitle: "取消", style: .cancel) { (action) in print("取消") } if customBlur { alertController.customOverlayView = CustomOverlayView() } action7.titleColor = SYSTEM_COLOR alertController.addAction(action: action1) alertController.addAction(action: action2) alertController.addAction(action: action3) alertController.addAction(action: action4) alertController.addAction(action: action5) alertController.addAction(action: action6) alertController.addAction(action: action7) //模拟多分区样式 if #available(iOS 11.0, *) { alertController.setCustomSpacing(spacing: 6.0, aferAction: action2) alertController.setCustomSpacing(spacing: 6.0, aferAction: action4) } self.present(alertController, animated: true, completion: nil) } }
43.346491
156
0.634524
1de3ca6a7f62d941924f4a9f7f1e4a0b1a9b5fac
5,410
swift
Swift
Wind/Audio/MP3Recoder.swift
ilumanxi/Wind
24943bce0e808427f68a4e1229d209d371534fc3
[ "MIT" ]
2
2018-02-24T11:10:14.000Z
2019-05-20T06:09:41.000Z
Wind/Audio/MP3Recoder.swift
ilumanxi/Wind
24943bce0e808427f68a4e1229d209d371534fc3
[ "MIT" ]
null
null
null
Wind/Audio/MP3Recoder.swift
ilumanxi/Wind
24943bce0e808427f68a4e1229d209d371534fc3
[ "MIT" ]
null
null
null
// // MP3Recoder.swift // Wind // // Created by tanfanfan on 2017/2/13. // Copyright © 2017年 tanfanfan. All rights reserved. // import Foundation import AudioToolbox import AVFoundation final public class MP3Bot: NSObject { fileprivate struct Constant { public static let bufferByteSize: UInt32 = 10240 * 8 public static let bufferNum: Int = 3 public static let sampleRate: Float64 = 16000 public static let bitsPerChannel: UInt32 = 16 public static let formatID: AudioFormatID = kAudioFormatLinearPCM } fileprivate lazy var mp3Buffer: [UInt8] = { return [UInt8](repeating: 0, count:Int(Constant.bufferByteSize)) }() fileprivate var audioQueue: AudioQueueRef? fileprivate var audioBuffer: [AudioQueueBufferRef?] = [] fileprivate var recordFormat: AudioStreamBasicDescription! public private(set) var isRecording: Bool = false private(set) var fileUrl: URL! private(set) var fileHandle: FileHandle! let lame = LameGetConfigContext() public func startRecord(fileUrl: URL) throws { if self.isRecording { return } self.fileUrl = fileUrl do { if FileManager.default.fileExists(atPath: fileUrl.absoluteString) { try FileManager.default.removeItem(at: fileUrl) } let session = AVAudioSession.sharedInstance() try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker) try session.setActive(true) try fileHandle = FileHandle(forUpdating: fileUrl) } catch let error { throw error } setAudioFormat() let userData = unsafeBitCast(self, to: UnsafeMutableRawPointer.self) var recordFormat = self.recordFormat! // 设置回调函数 AudioQueueNewInput( &recordFormat, AudioQueueInputCallback, userData, CFRunLoopGetCurrent(), nil, 0, &audioQueue ) // 创建缓冲器 for _ in 0..<Constant.bufferNum { var buffer: AudioQueueBufferRef? = nil AudioQueueAllocateBuffer(audioQueue!, Constant.bufferByteSize, &buffer) AudioQueueEnqueueBuffer(audioQueue!, buffer!, 0, nil) self.audioBuffer.append(buffer) } // 开始录音 AudioQueueStart(audioQueue!, nil) isRecording = true } public func stopRecord() { if isRecording { isRecording = false AudioQueueStop(self.audioQueue!, true) AudioQueueDispose(self.audioQueue!, true) fileHandle.closeFile() } } private func setAudioFormat() { recordFormat = AudioStreamBasicDescription() recordFormat.mSampleRate = Constant.sampleRate recordFormat.mFormatID = kAudioFormatLinearPCM recordFormat.mChannelsPerFrame = UInt32(AVAudioSession.sharedInstance().inputNumberOfChannels) // If the output format is PCM, create a 16-bit file format description. recordFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked recordFormat.mBitsPerChannel = Constant.bitsPerChannel recordFormat.mBytesPerFrame = (recordFormat.mBitsPerChannel / 8) * recordFormat.mChannelsPerFrame recordFormat.mBytesPerPacket = recordFormat.mBytesPerFrame recordFormat.mBytesPerFrame = recordFormat.mBytesPerPacket recordFormat.mFramesPerPacket = 1 } private func checkError(error: OSStatus,with errorString: String) -> Bool { if error == noErr { return true } return false } } func AudioQueueInputCallback(inUserData: UnsafeMutableRawPointer?, inAQ: AudioQueueRef, inBuffer: AudioQueueBufferRef, inStartTime: UnsafePointer<AudioTimeStamp>, inNumPackets: UInt32, inPacketDesc: UnsafePointer<AudioStreamPacketDescription>?) { let recoder = Unmanaged<MP3Bot>.fromOpaque(inUserData!).takeUnretainedValue() if inNumPackets > 0 && recoder.isRecording { let buffer = inBuffer.pointee let nsamples = buffer.mAudioDataByteSize let lame = recoder.lame let pcm = buffer.mAudioData.assumingMemoryBound(to: Int16.self) let size = lame_encode_buffer(lame, pcm, pcm, Int32(nsamples), &recoder.mp3Buffer, Int32(nsamples * 4)) let data = Data(bytes: &recoder.mp3Buffer, count: Int(size)) recoder.fileHandle.write(data) AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, nil) } } public func synchronized(_ lock: Any, handler: () ->()) { objc_sync_enter(lock); defer { objc_sync_exit(lock) } handler() } private func LameGetConfigContext() -> lame_t! { let lame = lame_init() //通道 lame_set_num_channels(lame, 1) //采样率 lame_set_in_samplerate(lame, Int32(MP3Bot.Constant.sampleRate)); //位速率 lame_set_brate(lame, Int32(MP3Bot.Constant.bitsPerChannel)) lame_set_mode(lame, MPEG_mode(rawValue: 1)) //音频质量 lame_set_quality(lame, 2) id3tag_set_comment(lame,"sjw") lame_init_params(lame) return lame }
35.359477
111
0.63549
4901c51c1ea8530e44c195ecd1215f420a39da2d
3,940
py
Python
okta/models/profile_enrollment_policy_rule_action.py
ander501/okta-sdk-python
0927dc6a2f6d5ebf7cd1ea806d81065094c92471
[ "Apache-2.0" ]
null
null
null
okta/models/profile_enrollment_policy_rule_action.py
ander501/okta-sdk-python
0927dc6a2f6d5ebf7cd1ea806d81065094c92471
[ "Apache-2.0" ]
null
null
null
okta/models/profile_enrollment_policy_rule_action.py
ander501/okta-sdk-python
0927dc6a2f6d5ebf7cd1ea806d81065094c92471
[ "Apache-2.0" ]
null
null
null
# flake8: noqa """ Copyright 2021 - Present Okta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # AUTO-GENERATED! DO NOT EDIT FILE DIRECTLY # SEE CONTRIBUTOR DOCUMENTATION from okta.okta_object import OktaObject from okta.okta_collection import OktaCollection from okta.models import profile_enrollment_policy_rule_activation_requirement\ as profile_enrollment_policy_rule_activation_requirement from okta.models import pre_registration_inline_hook\ as pre_registration_inline_hook from okta.models import profile_enrollment_policy_rule_profile_attribute\ as profile_enrollment_policy_rule_profile_attribute class ProfileEnrollmentPolicyRuleAction( OktaObject ): """ A class for ProfileEnrollmentPolicyRuleAction objects. """ def __init__(self, config=None): super().__init__(config) if config: self.access = config["access"]\ if "access" in config else None if "activationRequirements" in config: if isinstance(config["activationRequirements"], profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement): self.activation_requirements = config["activationRequirements"] elif config["activationRequirements"] is not None: self.activation_requirements = profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement( config["activationRequirements"] ) else: self.activation_requirements = None else: self.activation_requirements = None self.pre_registration_inline_hooks = OktaCollection.form_list( config["preRegistrationInlineHooks"] if "preRegistrationInlineHooks"\ in config else [], pre_registration_inline_hook.PreRegistrationInlineHook ) self.profile_attributes = OktaCollection.form_list( config["profileAttributes"] if "profileAttributes"\ in config else [], profile_enrollment_policy_rule_profile_attribute.ProfileEnrollmentPolicyRuleProfileAttribute ) self.target_group_ids = OktaCollection.form_list( config["targetGroupIds"] if "targetGroupIds"\ in config else [], str ) self.unknown_user_action = config["unknownUserAction"]\ if "unknownUserAction" in config else None else: self.access = None self.activation_requirements = None self.pre_registration_inline_hooks = [] self.profile_attributes = [] self.target_group_ids = [] self.unknown_user_action = None def request_format(self): parent_req_format = super().request_format() current_obj_format = { "access": self.access, "activationRequirements": self.activation_requirements, "preRegistrationInlineHooks": self.pre_registration_inline_hooks, "profileAttributes": self.profile_attributes, "targetGroupIds": self.target_group_ids, "unknownUserAction": self.unknown_user_action } parent_req_format.update(current_obj_format) return parent_req_format
42.826087
154
0.679949
9c4a0c100d2dd98af21e4ee85c13eb20b934ecbe
1,814
js
JavaScript
express/rate-a-restaurant/server.js
SashaPatsel/coding-drills
c38414a49f7918f59c2e1535a40ba0986d7df8b1
[ "MIT" ]
null
null
null
express/rate-a-restaurant/server.js
SashaPatsel/coding-drills
c38414a49f7918f59c2e1535a40ba0986d7df8b1
[ "MIT" ]
null
null
null
express/rate-a-restaurant/server.js
SashaPatsel/coding-drills
c38414a49f7918f59c2e1535a40ba0986d7df8b1
[ "MIT" ]
null
null
null
// ======================= NPM ======================== // Require the following packages: // - express, to create our server and manage our routes // - body-parser, to read our API returns more easily // - path, to use HTMl files // - mysql, to query our db // =================================================== //Initializes express var app = express() // Set the PORT to listen at 3002 var PORT = 3002 // Configure your database with your own settings var connection = mysql.createConnection({ host: "localhost", port: 3306, user: "root", password: "", database: "restaurantsDB" }) // Connects to the db connection.connect(function(err) { if (err) throw err }) // Configures Body Parser app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) //Serve up static assets from the public folder. Our CSS and JS links won't work without this line of code app.use(express.static("public")); //======================== HTML ======================== // At the root route, render index.html // At /add render add.html // =================================================== // ====================== API ========================== // Create a GET route at /api/restaurants. This route should query our db, and retrieve all the restaurants and their corresponding data //Create a POST route at /api/restaurants/new. This route should insert a new restaurant into our db. //Create a PUT route at "/api/restaurants/:id/rating/:value". This route will update the rating (value) of a restaurant at id //Create a DELETE route at "/api/restaurants/:id/delete". This route will delete the restaurant from the database // =================================================== app.listen(PORT, function () { console.log("App listening on PORT " + PORT) })
26.289855
137
0.586549