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
9fd27515d730b139f93e6b86b06ae1b83650900b
587
py
Python
main.py
lcbm/themis
ec7b2e973003164fdc6ec17e166ee0eb50ce61a8
[ "0BSD" ]
1
2021-11-27T23:00:31.000Z
2021-11-27T23:00:31.000Z
main.py
lcbm/themis
ec7b2e973003164fdc6ec17e166ee0eb50ce61a8
[ "0BSD" ]
null
null
null
main.py
lcbm/themis
ec7b2e973003164fdc6ec17e166ee0eb50ce61a8
[ "0BSD" ]
null
null
null
"""Adapt SIDARTHE model to the Pernambuco (Brazil) scenario.""" import datetime as dt import themis.data.transform INITIAL_DATE = dt.datetime.fromisoformat("2020-04-03") FINAL_DATE = dt.datetime.fromisoformat("2020-05-19") def main(): """Main program, achieves the following: - Data transformation. - Writes transformed data in CSV format to the data/out. - Writes transformed data in TXT format, as expected by the Matlab simulation, to the data/out. """ _ = themis.data.transform.execute(INITIAL_DATE, FINAL_DATE) if __name__ == "__main__": main()
24.458333
99
0.715503
72b2a2d05882c7b2d05e4894d00006a7428c8d0a
11,623
cs
C#
FundWeaverApp/UserControls/Bfund.Designer.cs
Anjitha95/FundWeaver
26f8131db4b1d219c25c6e71df7c22c56164bf4f
[ "MIT" ]
null
null
null
FundWeaverApp/UserControls/Bfund.Designer.cs
Anjitha95/FundWeaver
26f8131db4b1d219c25c6e71df7c22c56164bf4f
[ "MIT" ]
null
null
null
FundWeaverApp/UserControls/Bfund.Designer.cs
Anjitha95/FundWeaver
26f8131db4b1d219c25c6e71df7c22c56164bf4f
[ "MIT" ]
null
null
null
namespace FundWeaverApp.UserControls { partial class Bfund { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Century Gothic", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.MediumBlue; this.label1.Location = new System.Drawing.Point(362, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(172, 32); this.label1.TabIndex = 1; this.label1.Text = "Fund History"; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.label2.AutoSize = true; this.label2.ForeColor = System.Drawing.Color.MediumBlue; this.label2.Location = new System.Drawing.Point(29, 97); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(67, 21); this.label2.TabIndex = 2; this.label2.Text = "Filter By"; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this.label3.AutoSize = true; this.label3.ForeColor = System.Drawing.Color.MediumBlue; this.label3.Location = new System.Drawing.Point(400, 96); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(67, 21); this.label3.TabIndex = 3; this.label3.Text = "Filter By"; // // comboBox1 // this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.comboBox1.DropDownWidth = 154; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(120, 93); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(149, 29); this.comboBox1.TabIndex = 4; // // comboBox2 // this.comboBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this.comboBox2.FormattingEnabled = true; this.comboBox2.Items.AddRange(new object[] { "Church", "Convent", "Beneficiary"}); this.comboBox2.Location = new System.Drawing.Point(491, 94); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(154, 29); this.comboBox2.TabIndex = 5; // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.button1.BackColor = System.Drawing.Color.MediumBlue; this.button1.FlatAppearance.BorderSize = 0; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.button1.Location = new System.Drawing.Point(293, 91); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(83, 33); this.button1.TabIndex = 10; this.button1.Text = "Search"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this.button2.BackColor = System.Drawing.Color.MediumBlue; this.button2.FlatAppearance.BorderSize = 0; this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button2.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.button2.Location = new System.Drawing.Point(669, 91); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(83, 33); this.button2.TabIndex = 11; this.button2.Text = "Search"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this.button3.BackColor = System.Drawing.Color.MediumBlue; this.button3.FlatAppearance.BorderSize = 0; this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button3.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.button3.Location = new System.Drawing.Point(776, 91); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(83, 33); this.button3.TabIndex = 12; this.button3.Text = "Clear"; this.button3.UseVisualStyleBackColor = false; this.button3.Click += new System.EventHandler(this.button3_Click); // // dataGridView1 // this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.ButtonHighlight; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(3, 165); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(857, 416); this.dataGridView1.TabIndex = 13; // // panel1 // this.panel1.BackColor = System.Drawing.Color.MediumBlue; this.panel1.Dock = System.Windows.Forms.DockStyle.Right; this.panel1.Location = new System.Drawing.Point(866, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(10, 597); this.panel1.TabIndex = 14; // // panel2 // this.panel2.BackColor = System.Drawing.Color.MediumBlue; this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(0, 587); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(866, 10); this.panel2.TabIndex = 15; // // Bfund // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ButtonHighlight; this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.comboBox2); this.Controls.Add(this.comboBox1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Century Gothic", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(5); this.Name = "Bfund"; this.Size = new System.Drawing.Size(876, 597); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; } }
51.202643
162
0.609051
0d6684bd42b2087db88e065a04e113e6abb19586
541
lua
Lua
mods/mobiles/zombie/spawn.lua
AntumMT/mtgame-antum
af837362b1f62ded10ec98d219bf39848e2ba823
[ "CC-BY-3.0" ]
3
2017-08-16T22:50:15.000Z
2022-02-03T20:58:45.000Z
mods/mobiles/zombie/spawn.lua
AntumMT/mtgame-antum
af837362b1f62ded10ec98d219bf39848e2ba823
[ "CC-BY-3.0" ]
null
null
null
mods/mobiles/zombie/spawn.lua
AntumMT/mtgame-antum
af837362b1f62ded10ec98d219bf39848e2ba823
[ "CC-BY-3.0" ]
null
null
null
-- Place spawners in dungeons local function place_spawner(tab) local pos = tab[math.random(1, (#tab or 4))] pos.y = pos.y - 1 local n = core.get_node_or_nil(pos) if n and n.name ~= "air" then pos.y = pos.y + 1 core.set_node(pos, {name="creatures:zombie_spawner"}) end end core.set_gen_notify("dungeon") core.register_on_generated(function(minp, maxp, blockseed) local ntf = core.get_mapgen_object("gennotify") if ntf and ntf.dungeon and #ntf.dungeon > 3 then core.after(3, place_spawner, table.copy(ntf.dungeon)) end end)
24.590909
58
0.719039
82cc8bdb946dcebad17f605d46a7f6b02adbf168
14,278
rs
Rust
src/board.rs
evanj97/Rusty-Chess
0e2cbe115dd61b0d6f5f37f38ef0cbbf72142e76
[ "MIT" ]
null
null
null
src/board.rs
evanj97/Rusty-Chess
0e2cbe115dd61b0d6f5f37f38ef0cbbf72142e76
[ "MIT" ]
null
null
null
src/board.rs
evanj97/Rusty-Chess
0e2cbe115dd61b0d6f5f37f38ef0cbbf72142e76
[ "MIT" ]
null
null
null
use crate::piece; use piece::Piece; use piece::PieceType; use crate::piece::PieceType::Empty; use std::collections::HashMap; use std::num; use std::ops::Range; pub struct BoardState { board: HashMap<u8, piece::Piece> } impl BoardState { pub fn new() -> Self { BoardState { board: HashMap::new() } } pub fn reset(&mut self) { self.board.clear(); self.board.insert(0, Piece::new(PieceType::Rook, false)); self.board.insert(1, Piece::new(PieceType::Knight, false)); self.board.insert(2, Piece::new(PieceType::Bishop, false)); self.board.insert(3, Piece::new(PieceType::King, false)); self.board.insert(4, Piece::new(PieceType::Queen, false)); self.board.insert(5, Piece::new(PieceType::Bishop, false)); self.board.insert(6, Piece::new(PieceType::Knight, false)); self.board.insert(7, Piece::new(PieceType::Rook, false)); for i in 8..16 { self.board.insert(i, Piece::new(PieceType::Pawn, false)); } for i in 48..56 { self.board.insert(i, Piece::new(PieceType::Pawn, true)); } self.board.insert(56, Piece::new(PieceType::Rook, true)); self.board.insert(57, Piece::new(PieceType::Knight, true)); self.board.insert(58, Piece::new(PieceType::Bishop, true)); self.board.insert(59, Piece::new(PieceType::King, true)); self.board.insert(60, Piece::new(PieceType::Queen, true)); self.board.insert(61, Piece::new(PieceType::Bishop, true)); self.board.insert(62, Piece::new(PieceType::Knight, true)); self.board.insert(63, Piece::new(PieceType::Rook, true)); } pub fn draw_board(&self) { println!(" 0 1 2 3 4 5 6 7 "); println!(" -----------------------------------------"); for y in 0u8..8 { print!("{} ", y); for x in 0u8..8 { if let Some(icon) = self.board.get(&(x + (8 * y))) { print!("| {} ", icon.to_string()); } else { print!("| "); } } println!("|"); println!(" -----------------------------------------"); } } } impl BoardState { // returns type of piece at (x,y) as a enumerated type of PieceType pub fn piece_type_at(&self, x: u8, y: u8) -> PieceType { return if let Some(piece) = self.board.get(&(x + (8 * y))) { piece.piece_type() } else { PieceType::Empty } } // returns the player (0 or 1) who owns the piece at (x, y) or -1 if no piece at (x, y) pub fn piece_player_at(&self, x: u8, y: u8) -> i8 { if let Some(piece) = self.board.get(&(x + (8 * y))) { if piece.player() { 1 } else { 0 } } else { return -1; } } // returns true if piece successfully moved from (x, y) to (x2, y2) pub fn move_piece(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if let Some(p) = self.board.get(&(x + (8 * y))) { match p.piece_type() { PieceType::Empty => false, PieceType::Pawn => self.move_pawn(x, y, x2, y2), PieceType::Rook => self.move_rook(x, y, x2, y2), PieceType::Knight => self.move_knight(x, y, x2, y2), PieceType::Bishop => self.move_bishop(x, y, x2, y2), PieceType::King => self.move_king(x, y, x2, y2), PieceType::Queen => self.move_queen(x, y, x2, y2), } } else { false }; } fn move_pawn(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if self.is_valid_move_pawn(x, y, x2, y2) { if let Some(temp) = self.board.remove(&(x + (8 * y))) { self.board.remove(&(x2 + (8 * y2))); self.board.insert((x2 + (8 * y2)), temp); true } else { false } } else { false }; } fn move_rook(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if self.is_valid_move_rook(x, y, x2, y2) { if let Some(temp) = self.board.remove(&(x + (8 * y))) { self.board.remove(&(x2 + (8 * y2))); self.board.insert((x2 + (8 * y2)), temp); true } else { false } } else { false }; } fn move_knight(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if self.is_valid_move_knight(x, y, x2, y2) { if let Some(temp) = self.board.remove(&(x + (8 * y))) { self.board.remove(&(x2 + (8 * y2))); self.board.insert((x2 + (8 * y2)), temp); true } else { false } } else { false }; } fn move_bishop(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if self.is_valid_move_bishop(x, y, x2, y2) { if let Some(temp) = self.board.remove(&(x + (8 * y))) { self.board.remove(&(x2 + (8 * y2))); self.board.insert((x2 + (8 * y2)), temp); true } else { false } } else { false }; } fn move_king(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if self.is_valid_move_king(x, y, x2, y2) { if let Some(temp) = self.board.remove(&(x + (8 * y))) { self.board.remove(&(x2 + (8 * y2))); self.board.insert((x2 + (8 * y2)), temp); true } else { false } } else { false }; } fn move_queen(&mut self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if self.is_valid_move_queen(x, y, x2, y2) { if let Some(temp) = self.board.remove(&(x + (8 * y))) { self.board.remove(&(x2 + (8 * y2))); self.board.insert((x2 + (8 * y2)), temp); true } else { false } } else { false }; } pub fn is_valid_move(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { return if let Some(p) = self.board.get(&(x + (8 * y))) { match p.piece_type() { PieceType::Empty => false, PieceType::Pawn => self.is_valid_move_pawn(x, y, x2, y2), PieceType::Rook => self.is_valid_move_rook(x, y, x2, y2), PieceType::Knight => self.is_valid_move_knight(x, y, x2, y2), PieceType::Bishop => self.is_valid_move_bishop(x, y, x2, y2), PieceType::King => self.is_valid_move_king(x, y, x2, y2), PieceType::Queen => self.is_valid_move_queen(x, y, x2, y2), } } else { false }; } fn is_valid_move_pawn(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { // can move forward 1 or 2 if at starting location and NOT blocked by piece // can move diagonally forward 1 ONLY IF blocked by piece of enemy player if let Some(p) = self.board.get(&(x + (8 * y))) { if x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 { return false; } // if movement outside of board bounds if p.player() == false // player 0 { // if move forward if x == x2 { // if moving forward 1 piece if y2 == y + 1 { return self.piece_type_at(x, y + 1) == PieceType::Empty; } // if moving forward 2 piece else if y2 == y + 2 && y == 1 { self.piece_type_at(x, y + 1) == Empty && self.piece_type_at(x, y + 2) == Empty } // if not moving forward 1 or 2 spaces else { false } } // if attacking diagonally else if abs_dif(x, x2) == 1 && y + 1 == y2 { return self.piece_player_at(x2, y2) == 1; } else { false } } else // player 1 { // if move forward if x == x2 { // if moving forward 1 piece if y2 == y - 1 { self.piece_type_at(x, y - 1) == Empty } // if moving forward 2 piece else if y2 == y - 2 && y == 6 { self.piece_type_at(x, y - 1) == Empty && self.piece_type_at(x, y - 2) == Empty } // if not moving forward 1 or 2 spaces else { false } } // if attacking diagonally else if abs_dif(x, x2) == 1 && y - 1 == y2 { return self.piece_player_at(x2, y2) == 1; } else { false } } } else { false } } fn is_valid_move_rook(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { // can move 4 ways, optionally move into piece owned by enemy player if x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 { return false; } // if movement outside of board bounds return if x == x2 // if vertically aligned { for i in y + 1..y2 { // if non-empty space encountered before destination, then invalid move if self.piece_type_at(x, i) != Empty { return false; } } // if path to destination is empty AND destination is empty OR enemy, then move is valid if self.piece_player_at(x2, y2) != self.piece_player_at(x, y) { true } else { false } } else if y == y2 // if horizontally aligned { for i in x + 1..x2 { // if non-empty space encountered before destination, then invalid move if self.piece_type_at(y, i) != Empty { return false; } } // if path to destination is empty AND destination is empty OR enemy, then move is valid return if self.piece_player_at(x2, y2) != self.piece_player_at(x, y) { true } else { false } } else { false } // if not aligned, false // if x = x2 then moving along y axis // all spaces from between y and y2 are empty, and (x2, y2) is empty or enemy // true // else // false // if y = y2 then moving along x axis // all spaces from between x and x2 are empty, and (x2, y2) is empty or enemy // true // else // false // if does not align with x or y axis, invalid } fn is_valid_move_knight(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { if x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 { return false; } // if movement outside of board bounds // can move in L pattern in any direction, jumping over pieces, can only take enemy player piece // if L pattern away return if (abs_dif(x, x2) == 1 && abs_dif(y, y2) == 2) || (abs_dif(x, x2) == 2 && abs_dif(y, y2) == 1) { if self.piece_player_at(x2, y2) != self.piece_player_at(x, y) { true } else { false } } else { false } // if (x2, y2) is L jump away, and destination is empty or enemy // true // else // false } fn is_valid_move_bishop(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { if x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 { return false; } // if movement outside of board bounds else if x == x2 && y == y2 { return false; } // if destination == origin if abs_dif(x, x2) == abs_dif(y, y2) { // if every space between origin and destination is empty let mut temp_x: Range<u8>; let mut temp_y: Range<u8>; if x2 < x { temp_x = (x - 1)..x2; } else { temp_x = (x + 1)..x2; } if y2 < y { temp_y = (y - 1)..y2; } else { temp_y = (y + 1)..y2; } for (X, Y) in temp_x.zip(temp_y) // check every square between origin and destination { if self.piece_type_at(X, Y) != Empty { return false; } } return if self.piece_player_at(x2, y2) != self.piece_player_at(x, y) { true } else { false } // AND if destination is empty or enemy } // can move 4 ways diagonally, until contact with piece is made, can only take enemy player piece false } fn is_valid_move_king(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { // can move 8 ways, one space, can only take enemy player piece if x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 { return false; } // if movement outside of board bounds return if abs_dif(x, x2) <= 1 && abs_dif(y, y2) <= 1 // if within 1 square { if self.piece_player_at(x2, y2) != self.piece_player_at(x, y) // if destination is empty or enemy piece { true } else { false } } else { false } // if (x2, y2) is within 1 square, and is empty or enemy // true // else // false } fn is_valid_move_queen(&self, x: u8, y: u8, x2: u8, y2: u8) -> bool { // can move 8 ways, until contact is made, can only take enemy player piece return if self.is_valid_move_bishop(x, y, x2, y2) || self.is_valid_move_rook(x, y, x2, y2) { true } else { false } // if (x2, y2) is along horizontal/vertical // reuse Rook logic // if (x2, y2) is along diagonal // reuse bishop logic // else // false } } fn abs_dif(x: u8, y: u8) -> u8 { return (x as i16 - y as i16).abs() as u8; }
32.085393
115
0.46281
f4065d8f2b6cbc71d02afd44d5bb0a06dbc653ff
356
cs
C#
CSharp OOP Advanced/Generics - Exercises/GenericBoxOfString/GenericBoxOfString/StartUp.cs
valkin88/CSharp-Fundamentals
4847558dcf589b572b758be101ea3f1f67d8585e
[ "MIT" ]
1
2018-04-15T19:27:41.000Z
2018-04-15T19:27:41.000Z
CSharp OOP Advanced/Generics - Exercises/GenericBoxOfString/GenericBoxOfString/StartUp.cs
valkin88/CSharp-Fundamentals
4847558dcf589b572b758be101ea3f1f67d8585e
[ "MIT" ]
null
null
null
CSharp OOP Advanced/Generics - Exercises/GenericBoxOfString/GenericBoxOfString/StartUp.cs
valkin88/CSharp-Fundamentals
4847558dcf589b572b758be101ea3f1f67d8585e
[ "MIT" ]
null
null
null
using System; class StartUp { static void Main(string[] args) { var countOfInput = int.Parse(Console.ReadLine()); for (int count = 0; count < countOfInput; count++) { var value = Console.ReadLine(); Box<string> box = new Box<string>(value); Console.WriteLine(box); } } }
18.736842
58
0.533708
17da9b312f80809a21e8b805b8d53447c6d8e631
132
kt
Kotlin
cache/src/main/kotlin/gg/rsmod/cache/struct/ArchiveChunk.kt
andtheysay/rsmod
ff6ba961acf3905a89746682b3e7c2eaad558bf5
[ "Apache-2.0" ]
null
null
null
cache/src/main/kotlin/gg/rsmod/cache/struct/ArchiveChunk.kt
andtheysay/rsmod
ff6ba961acf3905a89746682b3e7c2eaad558bf5
[ "Apache-2.0" ]
2
2020-07-29T20:28:19.000Z
2020-07-29T21:21:47.000Z
cache/src/main/kotlin/gg/rsmod/cache/struct/ArchiveChunk.kt
andtheysay/rsmod
ff6ba961acf3905a89746682b3e7c2eaad558bf5
[ "Apache-2.0" ]
null
null
null
package gg.rsmod.cache.struct /** * @author Tom <rspsmods@gmail.com> */ data class ArchiveChunk(val offset: Int, val length: Int)
22
57
0.719697
cc8f2cc40022de77e2cd9a9d936300b0f1e5c087
1,162
rb
Ruby
config/software/chef-server-bootstrap.rb
mhorbul/opscode-omnibus
b42aa63007e771d0487b41bbfc7529b730b6753c
[ "Apache-2.0" ]
5
2015-01-27T22:45:21.000Z
2016-10-22T19:48:48.000Z
config/software/chef-server-bootstrap.rb
mhorbul/opscode-omnibus
b42aa63007e771d0487b41bbfc7529b730b6753c
[ "Apache-2.0" ]
96
2015-01-22T21:12:10.000Z
2016-08-02T20:43:26.000Z
config/software/chef-server-bootstrap.rb
mhorbul/opscode-omnibus
b42aa63007e771d0487b41bbfc7529b730b6753c
[ "Apache-2.0" ]
15
2015-01-26T23:32:54.000Z
2016-08-02T18:40:35.000Z
# # Author:: Tyler Cloke (<tyler@getchef.com>) # Copyright:: Copyright (c) 2012-2014 Chef Software, Inc. # License:: Apache License, Version 2.0 # # 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. # name "chef-server-bootstrap" default_version "1.0.1" source git: "https://github.com/opscode/chef-server-bootstrap" dependency "ruby" dependency "libxml2" dependency "bundler" dependency "postgresql92" build do env = with_standard_compiler_flags(with_embedded_path) bundle "install" \ " --path=#{install_dir}/embedded/service/gem" \ " --without dev", env: env sync project_dir, "#{install_dir}/embedded/service/chef-server-bootstrap/" end
30.578947
76
0.739243
ef8297ca9759def8076b9193a900d4d9a0fb59b4
3,527
h
C
opencamlib-read-only/src/common/kdnode.h
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
null
null
null
opencamlib-read-only/src/common/kdnode.h
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
null
null
null
opencamlib-read-only/src/common/kdnode.h
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
1
2020-07-04T13:58:00.000Z
2020-07-04T13:58:00.000Z
/* $Id: kdnode.h 766 2011-06-14 13:23:59Z anders.e.e.wallin $ * * Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #ifndef KDNODE_H #define KDNODE_H #include <iostream> #include <list> namespace ocl { /// \brief K-D tree node. http://en.wikipedia.org/wiki/Kd-tree /// /// A k-d tree is used for searching for triangles overlapping with the cutter. /// template < class BBObj > class KDNode { public: /// Create a node which partitions(cuts) along dimension d, at /// cut value cv, with child-nodes hi_c and lo_c. /// If this is a bucket-node containing triangles, /// they are in the list tris /// depth indicates the depth of the node in the tree KDNode(int d, double cv, KDNode<BBObj> *parentNode, // parent node KDNode<BBObj> *hi_child, // hi-child KDNode<BBObj> *lo_child, // lo-child const std::list< BBObj >* tlist, // list of tris, if bucket int nodeDepth) // depth of node { dim = d; cutval = cv; parent = parentNode; hi = hi_child; lo = lo_child; tris = new std::list<BBObj>(); depth = nodeDepth; isLeaf = false; if (tlist) { isLeaf = true; BOOST_FOREACH(BBObj bo, *tlist) { tris->push_back(bo); } } } virtual ~KDNode() { // std::cout << " ~KDNode3()\n"; if (hi) delete hi; if (lo) delete lo; if (tris) delete tris; } /// string repr std::string str() const { std::ostringstream o; o << "KDNode d:" << dim << " cv:" << cutval; return o.str(); } // DATA /// level of node in tree int depth; /// dimension of cut int dim; /// Cut value. /// Child node hi contains only triangles with a higher value than this. /// Child node lo contains triangles with lower values. double cutval; /// parent-node KDNode* parent; /// Child-node hi. KDNode* hi; /// Child-node lo. KDNode* lo; /// A list of triangles, if this is a bucket-node (NULL for internal nodes) std::list< BBObj >* tris; /// flag to indicate leaf in the tree. Leafs or bucket-nodes contain triangles in the list tris. bool isLeaf; }; } // end namespace #endif // end file kdnode.h
33.913462
104
0.525092
4e65532fc0541e479e796bc3a6189cc41620cfdb
833
dart
Dart
lib/app/styling/app_theme.dart
Naprimer-app-git/naprimer.app
b707bd7448f3d040635ca2c7b3d8793a9abf1d22
[ "MIT" ]
1
2022-01-07T08:36:08.000Z
2022-01-07T08:36:08.000Z
lib/app/styling/app_theme.dart
megogo/naprimer.app
7b7866ab5d10e98bd7f901dc1d664b5f409aeb96
[ "MIT" ]
null
null
null
lib/app/styling/app_theme.dart
megogo/naprimer.app
7b7866ab5d10e98bd7f901dc1d664b5f409aeb96
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:naprimer_app_v2/app/styling/app_colors.dart'; import 'package:naprimer_app_v2/app/styling/app_text_theme.dart'; class AppTheme { AppTheme._internal(); static final _instance = AppTheme._internal(); factory AppTheme() => _instance; static final ThemeData defaultAppTheme = ThemeData( primaryColor: Colors.black, backgroundColor: Colors.black, bottomAppBarColor: Colors.black, accentColor: Colors.white, brightness: Brightness.dark, canvasColor: Colors.black, textSelectionTheme: TextSelectionThemeData( cursorColor: AppColors.accentBlue, selectionColor: AppColors.accentBlue.withOpacity(0.5)), visualDensity: VisualDensity.adaptivePlatformDensity, textTheme: AppTextTheme.defaultAppTheme); }
33.32
65
0.745498
e0b9617497dd70d9f966426b0cb24a5bf9bd755c
1,780
lua
Lua
lua/vusted/assert.lua
klen/vusted
df9b2560a31f37fad7669d760e0fd0a2ed99cdd6
[ "MIT" ]
39
2020-05-20T13:25:56.000Z
2022-03-03T21:05:49.000Z
lua/vusted/assert.lua
klen/vusted
df9b2560a31f37fad7669d760e0fd0a2ed99cdd6
[ "MIT" ]
3
2021-02-16T11:08:31.000Z
2022-03-27T07:09:02.000Z
lua/vusted/assert.lua
klen/vusted
df9b2560a31f37fad7669d760e0fd0a2ed99cdd6
[ "MIT" ]
2
2021-02-17T03:05:56.000Z
2021-12-29T15:22:33.000Z
local assert = require("luassert") local say = require("say") local M = {} local Assert = {} Assert.__index = Assert M.asserts = Assert function Assert.create(name) vim.validate({name = {name, "string"}}) local tbl = { name = name, positive = ("assertion.%s.positive"):format(name), negative = ("assertion.%s.negative"):format(name), } return setmetatable(tbl, Assert) end function Assert.set_positive(self, msg) say:set(self.positive, msg) end function Assert.set_negative(self, msg) say:set(self.negative, msg) end function Assert.register(self, fn) assert:register("assertion", self.name, fn(self), self.positive, self.negative) end function Assert.register_eq(self, get_actual) local fn = function(_, args) local expected = args[#args] local actual = get_actual(unpack(args, 1, #args - 1)) local positive_msg = ("%s should be %s, but actual: %s"):format(self.name, expected, actual) self:set_positive(positive_msg) local negative_msg = ("%s should not be %s, but actual: %s"):format(self.name, expected, actual) self:set_negative(negative_msg) return actual == expected end self:register(function(_) return fn end) end function Assert.register_same(self, get_actual) local fn = function(_, args) local expected = vim.inspect(args[#args]) local actual = vim.inspect(get_actual(unpack(args, 1, #args - 1))) local positive_msg = ("%s should be %s, but actual: %s"):format(self.name, expected, actual) self:set_positive(positive_msg) local negative_msg = ("%s should not be %s, but actual: %s"):format(self.name, expected, actual) self:set_negative(negative_msg) return vim.deep_equal(actual, expected) end self:register(function(_) return fn end) end return M
26.567164
100
0.694944
9fe0060fcc93266141442ef1fb0f458c880f4905
1,107
py
Python
setup.py
wilsonify/sampyl
fb05a0d04393e4f1691bcc9bc664dbc1b688fc97
[ "MIT" ]
308
2015-06-30T18:16:04.000Z
2022-03-14T17:21:59.000Z
setup.py
wilsonify/sampyl
fb05a0d04393e4f1691bcc9bc664dbc1b688fc97
[ "MIT" ]
20
2015-07-02T06:12:20.000Z
2020-11-26T16:06:57.000Z
setup.py
wilsonify/sampyl
fb05a0d04393e4f1691bcc9bc664dbc1b688fc97
[ "MIT" ]
66
2015-07-27T11:19:03.000Z
2022-03-24T03:35:53.000Z
#!/usr/bin/env python import setuptools with open("README.md", "r") as fh: long_description = fh.read() classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Operating System :: OS Independent'] setuptools.setup(name='sampyl-mcmc', version='0.3', description='MCMC Samplers in Python & Numpy', author='Mat Leonard', author_email='leonard.mat@gmail.com', url='http://matatat.org/sampyl/', packages=['sampyl', 'sampyl.samplers'], classifiers=classifiers, install_requires=['numpy', 'scipy', 'autograd'])
36.9
65
0.535682
25deff88fdbea1bfa9f498378ff98fd60e68bd4f
1,585
cs
C#
Kaskela.WorkflowElements.Shared/Activities/EmailSendSavedEmail.cs
ryanperrymba/WorkflowElements
c92d9cc668618654bcd77404a780ec2870a963f8
[ "MIT" ]
17
2019-08-08T23:37:05.000Z
2022-03-03T11:55:15.000Z
Kaskela.WorkflowElements.Shared/Activities/EmailSendSavedEmail.cs
ryanperrymba/WorkflowElements
c92d9cc668618654bcd77404a780ec2870a963f8
[ "MIT" ]
9
2019-08-22T22:07:54.000Z
2022-02-17T01:43:26.000Z
Kaskela.WorkflowElements.Shared/Activities/EmailSendSavedEmail.cs
ryanperrymba/WorkflowElements
c92d9cc668618654bcd77404a780ec2870a963f8
[ "MIT" ]
5
2019-08-17T18:33:10.000Z
2020-09-08T08:43:11.000Z
using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Workflow; using System; using System.Activities; namespace Kaskela.WorkflowElements.Shared.Activities { public class EmailSendSavedEmail : Kaskela.WorkflowElements.Shared.ContributingClasses.WorkflowBase { [RequiredArgument] [Input("Email to Send")] [ReferenceTarget("email")] public InArgument<EntityReference> Email { get; set; } protected override void Execute(System.Activities.CodeActivityContext context) { var workflowContext = context.GetExtension<IWorkflowContext>(); var service = this.RetrieveOrganizationService(context); Entity email = service.Retrieve("email", this.Email.Get(context).Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("statuscode")); if (email["statuscode"] == null || email.GetAttributeValue<OptionSetValue>("statuscode").Value != 1) { throw new ArgumentException("Email must be in Draft status."); } SendEmailRequest sendEmailrequest = new SendEmailRequest { EmailId = email.Id, TrackingToken = "", IssueSend = true }; try { SendEmailResponse sendEmailresponse = (SendEmailResponse)service.Execute(sendEmailrequest); } catch(Exception ex) { throw new Exception($"Exception on SendEmailResponse - {ex.Message}"); } } } }
36.022727
134
0.613249
e739d69749626bd8b4ba52e81e8b129663e77a09
518
lua
Lua
src/ClosestPointOn/AABBToPoint.lua
zoebasil/lua-geometry
b7e28d06b26efcca09804b2b5473bcee31ec7369
[ "MIT" ]
10
2020-05-04T10:32:32.000Z
2022-01-31T01:18:20.000Z
src/ClosestPointOn/AABBToPoint.lua
zoebasil/lua-geometry
b7e28d06b26efcca09804b2b5473bcee31ec7369
[ "MIT" ]
2
2019-09-24T23:23:40.000Z
2019-09-25T20:57:56.000Z
src/ClosestPointOn/AABBToPoint.lua
zoebasil/lua-collisions
b7e28d06b26efcca09804b2b5473bcee31ec7369
[ "MIT" ]
1
2022-01-20T09:20:00.000Z
2022-01-20T09:20:00.000Z
-- Reference: http://www.r-5.org/files/books/computers/algo-list/realtime-3d/Christer_Ericson-Real-Time_Collision_Detection-EN.pdf -- Page 130-132: Closest Point on AABB to Point local function ClosestPointOnAABBToPoint(pointA, AABBmax, AABBmin) local clampedX = math.clamp(pointA.x, AABBmax.x, AABBmin.x) local clampedY = math.clamp(pointA.y, AABBmax.y, AABBmin.y) local clampedZ = math.clamp(pointA.z, AABBmax.z, AABBmin.z) return Vector3.new(clampedX, clampedY, clampedZ) end return ClosestPointOnAABBToPoint
43.166667
130
0.789575
d47bf411e830eab9a1fa4cf68079c2f7684dd1ea
477
sh
Shell
bin/mac/adhocpackage.sh
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
bin/mac/adhocpackage.sh
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
bin/mac/adhocpackage.sh
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
#!/bin/bash APP_NAME="Redline" CONFIG="AdHoc" BUILD_DIR="${CONFIG}-iphoneos" # del old app rm -rf "${APP_NAME}.ipa" # make tmp directory mkdir -p tmp/Payload cd tmp # copy artwork for iTunes cp ../iTunesArtwork.png iTunesArtwork # copy app cp -rp "../build/${BUILD_DIR}/${APP_NAME}.app" Payload/ # zip zip -r ${APP_NAME}.zip iTunesArtwork Payload # rename so iTunes recognises this bundle mv ${APP_NAME}.zip ../${APP_NAME}.ipa # back and del tmp files cd .. rm -rf tmp
16.448276
55
0.70021
a380202a41ac8fb89795ea1463b7867e67bc9218
547
java
Java
Booking/src/controller/commands/SetBookingBuilderCommand.java
Tonnanto/uni-car-reservation-service
d29ec4db870a95d3e224340b303c8ec08d2394ca
[ "MIT" ]
null
null
null
Booking/src/controller/commands/SetBookingBuilderCommand.java
Tonnanto/uni-car-reservation-service
d29ec4db870a95d3e224340b303c8ec08d2394ca
[ "MIT" ]
null
null
null
Booking/src/controller/commands/SetBookingBuilderCommand.java
Tonnanto/uni-car-reservation-service
d29ec4db870a95d3e224340b303c8ec08d2394ca
[ "MIT" ]
null
null
null
package controller.commands; import controller.BookingService; import model.Language; public class SetBookingBuilderCommand extends BookingServiceCommand { private final Language language; public SetBookingBuilderCommand(BookingService bookingService, Language language) { super(bookingService); this.language = language; } @Override public void execute() { receiver.setBookingBuilder(language); } @Override public String getDescription() { return language.toString(); } }
21.88
87
0.716636
135f0a2b3d29c6d2693394d5e6f71b5c4fbc14db
6,518
dart
Dart
lib/home.dart
goyalmuskan/girlscript_app
d56d85d6cf69e509d132e0221a8e2b1e30ecde21
[ "MIT" ]
1
2020-03-03T08:12:16.000Z
2020-03-03T08:12:16.000Z
lib/home.dart
mySTRiouscoder/girlscript_app
d2100deaf6a10203d401d2b9d2dae1a7aeb16ee1
[ "MIT" ]
null
null
null
lib/home.dart
mySTRiouscoder/girlscript_app
d2100deaf6a10203d401d2b9d2dae1a7aeb16ee1
[ "MIT" ]
null
null
null
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:noob_project/Contactus.dart'; //Adding the new AboutUs renamed file... import 'package:noob_project/AboutUs.dart'; import 'package:noob_project/Project.dart'; import 'package:noob_project/notification.dart'; import 'Project.dart'; import 'Announcements.dart'; import 'Sponsors.dart'; import 'Contactus.dart'; import 'package:url_launcher/url_launcher.dart'; class Hello extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: RichText( text: TextSpan( style: DefaultTextStyle.of(context).style, children: <TextSpan>[ TextSpan(text: 'GIRLSCRIPT', style: TextStyle(color: Color(0xff7d7d7d), fontFamily: 'Moonhouse', decoration: TextDecoration.none, fontSize: 26)), TextSpan(text: ' <Chennai>', style: TextStyle(color: Color(0xff7d7d7d), fontFamily: 'Moonhouse', decoration: TextDecoration.none, fontSize: 20)), ], ), ), backgroundColor: Color(0xffffc929), actions: <Widget>[ IconButton( icon: Icon(Icons.notifications), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (BuildContext context)=>Notifications())); } ) ], ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: FloatingActionButton( child: const Icon(Icons.code), onPressed: () { Navigator.of(context).push( MaterialPageRoute(builder: (context) => Projectpage(),)); },), bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), notchMargin: 4.0, child: new Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton(icon: Icon(Icons.menu), onPressed: () { _menu(context); },), /*IconButton(icon: Icon(Icons.search), onPressed: () {},),*/ ], ), ), body: ListView( scrollDirection: Axis.horizontal, children: <Widget>[ _buildgstile(context), _buildupdate1(context, 'Launch of the app', '/assets/images/GSsoc-Type-Logo-Black.png', 'Girlscript Chennai had their app lanched', null), ], ), ); } _buildgstile(BuildContext context){ return Padding( padding: EdgeInsets.all(15.0), child: InkWell( onTap: (){launch('https://www.girlscript.tech/');}, child: Container( width: MediaQuery.of(context).size.width, height: 100.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/images/GSsoc-Type-Logo-Black.png') ), ), ), ), ); } _buildupdate1(BuildContext context, String titleText, String postImage, String bodyText, String link) { return Padding( padding: EdgeInsets.all(15.0), child: InkWell( onTap: () {launch(link);}, child: Container( width: MediaQuery.of(context).size.width, height: 100.0, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Container( height: 75.0, width: 75.0, decoration: BoxDecoration( shape: BoxShape.rectangle, ), child: Image.asset('assets/images/michael-dam-mEZ3PoFGs_k-unsplash.jpg'), ), RichText( text: TextSpan( text: "Placeholder Text" ), ), ], ), ], ), ), ) ); } void _menu(context){ showModalBottomSheet( context: context, builder: (BuildContext bc){ return Container( child: new Wrap( children: <Widget>[ new ListTile( leading: new Icon(Icons.announcement), title: new Text('Announcements', style: TextStyle( color: Color(0xffff4a4a), fontSize: 14) ), onTap: () => { Navigator.of(context).pop(), Navigator.of(context).push( MaterialPageRoute(builder: (context) => Announcementspage(),) ), } ), new ListTile( leading: new Icon(Icons.monetization_on), title: new Text('Sponsors', style: TextStyle( color: Color(0xffff4a4a), fontSize: 14)) , onTap: () => { Navigator.of(context).pop(), Navigator.of(context).push( MaterialPageRoute(builder: (context) => Sponsorspage(),) ), }, ), new ListTile( leading: new Icon(Icons.account_box), title: new Text('About us', style: TextStyle( color: Color(0xffff4a4a), fontSize: 14)) , onTap: () => { Navigator.of(context).pop(), Navigator.of(context).push( MaterialPageRoute(builder: (context) => ABoutUs(),) ), }, ), new ListTile( leading: new Icon(Icons.perm_phone_msg), title: new Text('Contact us', style: TextStyle( color: Color(0xffff4a4a), fontSize: 14)) , onTap: () => { Navigator.of(context).pop(), Navigator.of(context).push( MaterialPageRoute(builder: (context) => Contactuspage(),) ), }, ), ], ), ); } ); } }
33.255102
159
0.496318
79d3c5ad0f65689a7dbad3834c0d123395077068
502
php
PHP
resources/views/puestos/form.blade.php
linares82/ambiental
075690a678278d4c24b13b89c437af111a0e90eb
[ "MIT" ]
null
null
null
resources/views/puestos/form.blade.php
linares82/ambiental
075690a678278d4c24b13b89c437af111a0e90eb
[ "MIT" ]
2
2020-09-06T01:03:41.000Z
2021-03-09T10:19:35.000Z
resources/views/puestos/form.blade.php
linares82/ambiental
075690a678278d4c24b13b89c437af111a0e90eb
[ "MIT" ]
null
null
null
<div class="form-group col-md-4 {{ $errors->has('puesto') ? 'has-error' : '' }}"> <label for="puesto" class="control-label">{{ trans('puestos.puesto') }}</label> <input class="form-control input-sm " name="puesto" type="text" id="puesto" value="{{ old('puesto', optional($puesto)->puesto) }}" minlength="1" maxlength="255" required="true" placeholder="{{ trans('puestos.puesto__placeholder') }}"> {!! $errors->first('puesto', '<p class="help-block">:message</p>') !!} </div>
55.777778
242
0.611554
25bcb013cb7aaadb98388cb7c3eead2a2666756c
369
cs
C#
src/IxMilia.Step/StepReadException.cs
dwpessoa/step
f2dcd4b9992de65fd3a02bf27b7115280850b4cc
[ "MIT" ]
38
2019-06-12T23:18:08.000Z
2022-02-20T13:00:20.000Z
src/IxMilia.Step/StepReadException.cs
R1C4RDO13/step
f6b79f006ffdd53cb04791198df9d10bfc967cbd
[ "MIT" ]
8
2020-03-03T19:47:10.000Z
2021-07-09T16:58:56.000Z
src/IxMilia.Step/StepReadException.cs
R1C4RDO13/step
f6b79f006ffdd53cb04791198df9d10bfc967cbd
[ "MIT" ]
23
2019-08-06T11:26:21.000Z
2022-02-20T13:03:41.000Z
using System; namespace IxMilia.Step { public class StepReadException : Exception { public int Line { get; } public int Column { get; } public StepReadException(string message, int line, int column) : base($"{message} at [{line}:{column}]") { Line = line; Column = column; } } }
20.5
70
0.533875
1f3751b0719c81149cbdb88323209b8a95d831bd
212
cs
C#
ItkDispatcher/NHS111.Utils/FeatureToggle/EnabledByDefaultSettingStrategy.cs
111Online/nhs111-itk-dispatcher-api
be037746f10202e305b2744ae8248b60e2fc642b
[ "Apache-2.0" ]
null
null
null
ItkDispatcher/NHS111.Utils/FeatureToggle/EnabledByDefaultSettingStrategy.cs
111Online/nhs111-itk-dispatcher-api
be037746f10202e305b2744ae8248b60e2fc642b
[ "Apache-2.0" ]
null
null
null
ItkDispatcher/NHS111.Utils/FeatureToggle/EnabledByDefaultSettingStrategy.cs
111Online/nhs111-itk-dispatcher-api
be037746f10202e305b2744ae8248b60e2fc642b
[ "Apache-2.0" ]
1
2021-04-10T17:21:03.000Z
2021-04-10T17:21:03.000Z
 namespace NHS111.Utils.FeatureToggle { public class EnabledByDefaultSettingStrategy : IDefaultSettingStrategy { public bool GetDefaultSetting() { return true; } } }
19.272727
48
0.636792
dbcf4f48c80697d4da1858452f6703340673f395
2,833
php
PHP
app/Http/Controllers/User/UsersController.php
abdulkadirkaradas/printing-editor
c80e46b7da8085b8c745695af5dff146f32eaa20
[ "MIT" ]
null
null
null
app/Http/Controllers/User/UsersController.php
abdulkadirkaradas/printing-editor
c80e46b7da8085b8c745695af5dff146f32eaa20
[ "MIT" ]
null
null
null
app/Http/Controllers/User/UsersController.php
abdulkadirkaradas/printing-editor
c80e46b7da8085b8c745695af5dff146f32eaa20
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\User; use App\Http\Controllers\Controller; use App\Models\Users; use App\Models\UsersImages; use App\Models\UsersImagesTable; use Illuminate\Http\Request; use Illuminate\Support\Str; class UsersController extends Controller { public function store(Request $request) { $file = $request->file("images"); $fileId = Str::uuid(); if($file) { $fileName = $file->getClientOriginalName(); $fileExtension = $file->getClientOriginalExtension(); } $users = new Users(); $users->name = $request->name; $users->surname = $request->surname; $users->email = $request->email; $users->phone = $request->phone; $users->address = $request->address; $users->save(); if($file) { $images = new UsersImages(); $images->file_id = $fileId; $images->file_name = $fileName; $images->file_extension = $fileExtension; $images->file_url = env("APP_URL") . "/" . "users_images". "/" . $users->id . "/" . $fileId . "." . $fileExtension; $images->user_id = $users->id; $images->save(); } if(!file_exists(public_path("users_images"))) { mkdir(public_path("users_images"), 0777, true); } if(!file_exists(public_path("users_images" . "/" . $users->id . "/"))) { mkdir(public_path("users_images" . "/" . $users->id . "/"), 0777, true); } $file->move(public_path("users_images" . "/" . $users->id . "/"), $fileId . "." . $fileExtension); return [ "status" => "0_SUCCESS", "data" => "Successfully created" ]; } public function findUser(Request $request) { $user = Users::find($request->id); $user = UsersImages::where("deleted_at")->where("user_id", $user->id)->get(); return [ "status" => "0_SUCCESS", "data" => $user, ]; } public function getAllUser(Request $request) { $users = Users::all(); foreach ($users as $key => $user) { $image = UsersImages::whereNull("deleted_at")->where("user_id", $user->id)->get(); $user->image = $image[0]; } return [ "status" => "0_SUCCESS", "data" => $users, ]; } public function update(Request $request) { $user = Users::find($request->id); $user->name = $request->name; $user->surname = $request->surname; $user->email = $request->email; $user->phone = $request->phone; $user->address = $request->address; $user->save(); return [ "status" => "0_SUCCESS", "data" => "Successfully updated" ]; } }
30.138298
127
0.524532
ed31ffa4e0e4242af6bc23b8e39eca85fe1dc0ea
1,872
h
C
pbrt/src/samplers/stratified.h
benjaminum/surface-reconstruction-benchmark
c9e7516297620ba01fc91917f0186fbe677bbf7c
[ "BSD-2-Clause" ]
39
2019-03-28T03:02:41.000Z
2022-01-28T14:45:04.000Z
pbrt/src/samplers/stratified.h
benjaminum/surface-reconstruction-benchmark
c9e7516297620ba01fc91917f0186fbe677bbf7c
[ "BSD-2-Clause" ]
8
2020-09-08T16:02:42.000Z
2021-05-25T06:36:16.000Z
pbrt/src/samplers/stratified.h
benjaminum/surface-reconstruction-benchmark
c9e7516297620ba01fc91917f0186fbe677bbf7c
[ "BSD-2-Clause" ]
12
2018-11-14T02:01:56.000Z
2022-01-21T06:47:16.000Z
/* pbrt source code Copyright(c) 1998-2010 Matt Pharr and Greg Humphreys. This file is part of pbrt. pbrt is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Note that the text contents of the book "Physically Based Rendering" are *not* licensed under the GNU GPL. pbrt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #if defined(_MSC_VER) #pragma once #endif #ifndef PBRT_SAMPLERS_STRATIFIED_H #define PBRT_SAMPLERS_STRATIFIED_H // samplers/stratified.h* #include "sampler.h" #include "film.h" // StratifiedSampler Declarations class StratifiedSampler : public Sampler { public: // StratifiedSampler Public Methods StratifiedSampler(int xstart, int xend, int ystart, int yend, int xs, int ys, bool jitter, float sopen, float sclose); ~StratifiedSampler(); int RoundSize(int size) const { return size; } Sampler *GetSubSampler(int num, int count); int GetMoreSamples(Sample *sample, RNG &rng); int MaximumSampleCount() { return xPixelSamples * yPixelSamples; } private: // StratifiedSampler Private Data int xPixelSamples, yPixelSamples; bool jitterSamples; int xPos, yPos; float *sampleBuf; }; StratifiedSampler *CreateStratifiedSampler(const ParamSet &params, const Film *film, const Camera *camera); #endif // PBRT_SAMPLERS_STRATIFIED_H
31.728814
84
0.728632
ebdca0abf0b68f05cd1baae907274af88e4a2bcd
331
swift
Swift
Tests/raytraceTests/pixelTests.swift
notCalle/swift-raytrace
9fee2c769b7a3e22c7e1bba69364abe8eac00060
[ "MIT" ]
null
null
null
Tests/raytraceTests/pixelTests.swift
notCalle/swift-raytrace
9fee2c769b7a3e22c7e1bba69364abe8eac00060
[ "MIT" ]
null
null
null
Tests/raytraceTests/pixelTests.swift
notCalle/swift-raytrace
9fee2c769b7a3e22c7e1bba69364abe8eac00060
[ "MIT" ]
null
null
null
import XCTest @testable import raytrace final class pixelTests: XCTestCase { func testMakePixel() { let p = Pixel.rgb(0.1, 0.2, 0.3) XCTAssertEqual(p.r, 0.1) XCTAssertEqual(p.g, 0.2) XCTAssertEqual(p.b, 0.3) } static var allTests = [ ("testMakePixel", testMakePixel), ] }
19.470588
41
0.592145
4055cdaaaa12a5e8762648a355b4a496f38bc47b
19,279
swift
Swift
Sources/ObjectiveC/PinLayoutObjCImpl.swift
AdrianBinDC/PinLayout
8377b23dfae8b12939c000af6bb41fee9cad8043
[ "MIT" ]
1
2019-01-08T20:49:53.000Z
2019-01-08T20:49:53.000Z
Sources/ObjectiveC/PinLayoutObjCImpl.swift
AdrianBinDC/PinLayout
8377b23dfae8b12939c000af6bb41fee9cad8043
[ "MIT" ]
null
null
null
Sources/ObjectiveC/PinLayoutObjCImpl.swift
AdrianBinDC/PinLayout
8377b23dfae8b12939c000af6bb41fee9cad8043
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Luc Dion // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif #if os(iOS) || os(tvOS) @objc extension UIView { public var anchor: AnchorList { return AnchorListImpl(view: self) } public var edge: EdgeList { return EdgeListImpl(view: self) } } #else @objc extension NSView { public var anchor: AnchorList { return AnchorListImpl(view: self) } public var edge: EdgeList { return EdgeListImpl(view: self) } } #endif @objc class PinLayoutObjCImpl: NSObject, PinLayoutObjC { #if os(iOS) || os(tvOS) typealias PView = UIView #else typealias PView = NSView #endif private var impl: PinLayout<PView>? #if os(iOS) || os(tvOS) var safeArea: PEdgeInsets { return impl?.safeArea ?? .zero } #endif init(view: PView, keepTransform: Bool) { impl = PinLayout<PView>(view: view, keepTransform: keepTransform) } deinit { if impl != nil { impl?.warn("With the Objective-C interface, you must call the \"layout\" method to ensure the view is layouted correctly (ex: [[[textLabel.pin_objc top] left] layout];") } } func layout() { // With objective-c PinLayoutObjCImpl instance are sometimes deallocated only after the context has been quit. For this reason // developpers must call the layout: method implicetely. impl?.layout() impl = nil } func top() -> PinLayoutObjC { _ = impl?.top() return self } func top(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.top(value) return self } func top(percent: CGFloat) -> PinLayoutObjC { _ = impl?.top(percent%) return self } func top(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.top(insets) return self } func left() -> PinLayoutObjC { _ = impl?.left() return self } func left(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.left(value) return self } func left(percent: CGFloat) -> PinLayoutObjC { _ = impl?.left(percent%) return self } func left(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.left(insets) return self } func bottom() -> PinLayoutObjC { _ = impl?.bottom() return self } func bottom(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.bottom(value) return self } func bottom(percent: CGFloat) -> PinLayoutObjC { _ = impl?.bottom(percent%) return self } func bottom(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.bottom(insets) return self } func right() -> PinLayoutObjC { _ = impl?.right() return self } func right(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.right(value) return self } func right(percent: CGFloat) -> PinLayoutObjC { _ = impl?.right(percent%) return self } func right(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.right(insets) return self } func hCenter() -> PinLayoutObjC { _ = impl?.hCenter() return self } func hCenter(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.hCenter(value) return self } func hCenter(percent: CGFloat) -> PinLayoutObjC { _ = impl?.hCenter(percent%) return self } func vCenter() -> PinLayoutObjC { _ = impl?.vCenter() return self } func vCenter(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.vCenter(value) return self } func vCenter(percent: CGFloat) -> PinLayoutObjC { _ = impl?.vCenter(percent%) return self } func start() -> PinLayoutObjC { _ = impl?.start() return self } func start(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.start(value) return self } func start(percent: CGFloat) -> PinLayoutObjC { _ = impl?.start(percent%) return self } func start(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.start(insets) return self } func end() -> PinLayoutObjC { _ = impl?.end() return self } func end(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.end(value) return self } func end(percent: CGFloat) -> PinLayoutObjC { _ = impl?.end(percent%) return self } func end(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.end(insets) return self } func top(to edge: VerticalEdge) -> PinLayoutObjC { _ = impl?.top(to: edge) return self } func vCenter(to edge: VerticalEdge) -> PinLayoutObjC { _ = impl?.vCenter(to: edge) return self } func bottom(to edge: VerticalEdge) -> PinLayoutObjC { _ = impl?.bottom(to: edge) return self } func left(to edge: HorizontalEdge) -> PinLayoutObjC { _ = impl?.left(to: edge) return self } func hCenter(to edge: HorizontalEdge) -> PinLayoutObjC { _ = impl?.hCenter(to: edge) return self } func right(to edge: HorizontalEdge) -> PinLayoutObjC { _ = impl?.right(to: edge) return self } func start(to edge: HorizontalEdge) -> PinLayoutObjC { _ = impl?.start(to: edge) return self } func end(to edge: HorizontalEdge) -> PinLayoutObjC { _ = impl?.end(to: edge) return self } func all() -> PinLayoutObjC { _ = impl?.all() return self } func horizontally() -> PinLayoutObjC { _ = impl?.horizontally() return self } func horizontally(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.horizontally(value) return self } func vertically() -> PinLayoutObjC { _ = impl?.vertically() return self } func vertically(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.vertically(value) return self } func topLeft(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.topLeft(to: anchor) return self } func topLeft() -> PinLayoutObjC { _ = impl?.topLeft() return self } func topStart(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.topStart(to: anchor) return self } func topStart() -> PinLayoutObjC { _ = impl?.topStart() return self } func topCenter(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.topCenter(to: anchor) return self } func topCenter() -> PinLayoutObjC { _ = impl?.topCenter() return self } func topRight(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.topRight(to: anchor) return self } func topRight() -> PinLayoutObjC { _ = impl?.topRight() return self } func topEnd(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.topEnd(to: anchor) return self } func topEnd() -> PinLayoutObjC { _ = impl?.topEnd() return self } func centerLeft(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.centerLeft(to: anchor) return self } func centerLeft() -> PinLayoutObjC { _ = impl?.centerLeft() return self } func centerStart(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.centerStart(to: anchor) return self } func centerStart() -> PinLayoutObjC { _ = impl?.centerStart() return self } func center(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.center(to: anchor) return self } func center() -> PinLayoutObjC { _ = impl?.center() return self } func centerRight(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.centerRight(to: anchor) return self } func centerRight() -> PinLayoutObjC { _ = impl?.centerRight() return self } func centerEnd(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.centerEnd(to: anchor) return self } func centerEnd() -> PinLayoutObjC { _ = impl?.centerEnd() return self } func bottomLeft(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.bottomLeft(to: anchor) return self } func bottomLeft() -> PinLayoutObjC { _ = impl?.bottomLeft() return self } func bottomStart(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.bottomStart(to: anchor) return self } func bottomStart() -> PinLayoutObjC { _ = impl?.bottomStart() return self } func bottomCenter(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.bottomCenter(to: anchor) return self } func bottomCenter() -> PinLayoutObjC { _ = impl?.bottomCenter() return self } func bottomRight(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.bottomRight(to: anchor) return self } func bottomRight() -> PinLayoutObjC { _ = impl?.bottomRight() return self } func bottomEnd(to anchor: Anchor) -> PinLayoutObjC { _ = impl?.bottomEnd(to: anchor) return self } func bottomEnd() -> PinLayoutObjC { _ = impl?.bottomEnd() return self } func above(of view: PView) -> PinLayoutObjC { _ = impl?.above(of: view) return self } func above(ofViews views: [PView]) -> PinLayoutObjC { _ = impl?.above(of: views) return self } func above(of view: PView, aligned: HorizontalAlign) -> PinLayoutObjC { _ = impl?.above(of: view, aligned: aligned) return self } func above(ofViews views: [PView], aligned: HorizontalAlign) -> PinLayoutObjC { _ = impl?.above(of: views, aligned: aligned) return self } func below(of view: PView) -> PinLayoutObjC { _ = impl?.below(of: view) return self } func below(ofViews views: [PView]) -> PinLayoutObjC { _ = impl?.below(of: views) return self } func below(of view: PView, aligned: HorizontalAlign) -> PinLayoutObjC { _ = impl?.below(of: view, aligned: aligned) return self } func below(ofViews views: [PView], aligned: HorizontalAlign) -> PinLayoutObjC { _ = impl?.below(of: views, aligned: aligned) return self } func left(of view: PView) -> PinLayoutObjC { _ = impl?.left(of: view) return self } func left(ofViews views: [PView]) -> PinLayoutObjC { _ = impl?.left(of: views) return self } func left(of view: PView, aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.left(of: view, aligned: aligned) return self } func left(ofViews views: [PView], aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.left(of: views, aligned: aligned) return self } func right(of view: PView) -> PinLayoutObjC { _ = impl?.right(of: view) return self } func right(ofViews views: [PView]) -> PinLayoutObjC { _ = impl?.right(of: views) return self } func right(of view: PView, aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.right(of: view, aligned: aligned) return self } func right(ofViews views: [PView], aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.right(of: views, aligned: aligned) return self } func before(of view: PView) -> PinLayoutObjC { _ = impl?.before(of: view) return self } func before(ofViews views: [PView]) -> PinLayoutObjC { _ = impl?.before(of: views) return self } func before(of view: PView, aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.before(of: view, aligned: aligned) return self } func before(ofViews views: [PView], aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.before(of: views, aligned: aligned) return self } func after(of view: PView) -> PinLayoutObjC { _ = impl?.after(of: view) return self } func after(ofViews views: [PView]) -> PinLayoutObjC { _ = impl?.after(of: views) return self } func after(of view: PView, aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.after(of: view, aligned: aligned) return self } func after(ofViews views: [PView], aligned: VerticalAlign) -> PinLayoutObjC { _ = impl?.after(of: views, aligned: aligned) return self } func justify(_ align: HorizontalAlign) -> PinLayoutObjC { _ = impl?.justify(align) return self } func align(_ align: VerticalAlign) -> PinLayoutObjC { _ = impl?.align(align) return self } func width(_ width: CGFloat) -> PinLayoutObjC { _ = impl?.width(width) return self } func width(percent: CGFloat) -> PinLayoutObjC { _ = impl?.width(percent%) return self } func width(of view: PView) -> PinLayoutObjC { _ = impl?.width(of: view) return self } func minWidth(_ width: CGFloat) -> PinLayoutObjC { _ = impl?.minWidth(width) return self } func minWidth(percent: CGFloat) -> PinLayoutObjC { _ = impl?.minWidth(percent%) return self } func maxWidth(_ width: CGFloat) -> PinLayoutObjC { _ = impl?.maxWidth(width) return self } func maxWidth(percent: CGFloat) -> PinLayoutObjC { _ = impl?.maxWidth(percent%) return self } func height(_ height: CGFloat) -> PinLayoutObjC { _ = impl?.height(height) return self } func height(percent: CGFloat) -> PinLayoutObjC { _ = impl?.height(percent%) return self } func height(of view: PView) -> PinLayoutObjC { _ = impl?.height(of: view) return self } func minHeight(_ height: CGFloat) -> PinLayoutObjC { _ = impl?.minHeight(height) return self } func minHeight(percent: CGFloat) -> PinLayoutObjC { _ = impl?.minHeight(percent%) return self } func maxHeight(_ height: CGFloat) -> PinLayoutObjC { _ = impl?.maxHeight(height) return self } func maxHeight(percent: CGFloat) -> PinLayoutObjC { _ = impl?.maxHeight(percent%) return self } func size(_ size: CGSize) -> PinLayoutObjC { _ = impl?.size(size) return self } func size(length: CGFloat) -> PinLayoutObjC { _ = impl?.size(length) return self } func size(percent: CGFloat) -> PinLayoutObjC { _ = impl?.size(percent%) return self } func size(of view: PView) -> PinLayoutObjC { _ = impl?.size(of: view) return self } func aspectRatio(_ ratio: CGFloat) -> PinLayoutObjC { _ = impl?.aspectRatio(ratio) return self } func aspectRatio(of view: PView) -> PinLayoutObjC { _ = impl?.aspectRatio(of: view) return self } #if os(iOS) || os(tvOS) func aspectRatio() -> PinLayoutObjC { _ = impl?.aspectRatio() return self } #endif func sizeToFit() -> PinLayoutObjC { return sizeToFit(.content) } func sizeToFit(_ fitType: Fit) -> PinLayoutObjC { let type: FitType switch fitType { case .width: type = .width case .height: type = .height case .widthFlexible: type = .widthFlexible case .heightFlexible: type = .heightFlexible case .content: type = .content } _ = impl?.sizeToFit(type) return self } func marginTop(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginTop(value) return self } func marginLeft(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginLeft(value) return self } func marginBottom(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginBottom(value) return self } func marginRight(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginRight(value) return self } func marginStart(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginStart(value) return self } func marginEnd(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginEnd(value) return self } func marginHorizontal(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginHorizontal(value) return self } func marginVertical(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.marginVertical(value) return self } func margin(insets: PEdgeInsets) -> PinLayoutObjC { _ = impl?.margin(insets) return self } func margin(_ value: CGFloat) -> PinLayoutObjC { _ = impl?.margin(value) return self } func margin(vertical: CGFloat, horizontal: CGFloat) -> PinLayoutObjC { _ = impl?.margin(vertical, horizontal) return self } func margin(top: CGFloat, horizontal: CGFloat, bottom: CGFloat) -> PinLayoutObjC { _ = impl?.margin(top, horizontal, bottom) return self } func margin(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> PinLayoutObjC { _ = impl?.margin(top, left, bottom, right) return self } func pinEdges() -> PinLayoutObjC { _ = impl?.pinEdges() return self } }
25.070221
181
0.564552
b324614aaf859130164590db9a2eb5dfbe394219
1,111
py
Python
models/db.py
mcnamara-charles/evote-3.9
d99f2d08631bfbdd90ea83622cb3c17715291ae5
[ "BSD-3-Clause" ]
null
null
null
models/db.py
mcnamara-charles/evote-3.9
d99f2d08631bfbdd90ea83622cb3c17715291ae5
[ "BSD-3-Clause" ]
null
null
null
models/db.py
mcnamara-charles/evote-3.9
d99f2d08631bfbdd90ea83622cb3c17715291ae5
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from gluon.tools import Auth from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) DEVELOPMENT = myconf.take('app.development').lower()=='true' AS_SERVICE = myconf.take('app.as_service').lower()=='true' DEBUG_MODE = myconf.take('app.debug_mode').lower()=='true' SCHEME = 'http' # if DEVELOPMENT else 'https' db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) response.generic_patterns = [] response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') auth = Auth(db) ## configure email mail = auth.settings.mailer mail.settings.server = myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = not DEVELOPMENT auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True
35.83871
105
0.742574
0318c1160e774d8ab7936f063678b9c7d050475d
1,133
cpp
C++
fbhackcup/2011/quals/studious-student/studious-student.cpp
mathemage/CompetitiveProgramming
fe39017e3b017f9259f9c1e6385549270940be64
[ "MIT" ]
2
2015-08-18T09:51:19.000Z
2019-01-29T03:18:10.000Z
fbhackcup/2011/quals/studious-student/studious-student.cpp
mathemage/CompetitiveProgramming
fe39017e3b017f9259f9c1e6385549270940be64
[ "MIT" ]
null
null
null
fbhackcup/2011/quals/studious-student/studious-student.cpp
mathemage/CompetitiveProgramming
fe39017e3b017f9259f9c1e6385549270940be64
[ "MIT" ]
null
null
null
/* ======================================== ID: mathema6 TASK: studious-student LANG: C++11 (...for USACO solutions) * File Name : studious-student.cpp * Creation Date : 11-01-2015 * Last Modified : * Created By : Karel Ha <mathemage@gmail.com> * URL : * Points Gained (in case of online contest) : ==========================================*/ #include <bits/stdc++.h> using namespace std; #define FOR(I,A,B) for(int I = (A); I < (B); ++I) #define REP(I,N) FOR(I,0,N) #define ALL(A) (A).begin(), (A).end() #define MSG(a) cout << #a << " == " << a << endl; int n, m; bool cmp(string l, string u) { for (int i = 0; i < max(l.size(), u.size()); ++i) { if ( l[i % l.size()] < u[i % u.size()] ) { return true; } if ( l[i % l.size()] > u[i % u.size()] ) { return false; } } return false; } int main() { cin >> n; REP(i,n) { printf("Case #%d: ", i+1); cin >> m; vector<string> words(m); REP(j,m) { cin >> words[j]; } sort(ALL(words), cmp); for (string w : words) cout << w; cout << endl; } return 0; }
18.883333
53
0.459841
40d7a66f0d76dd7a1f8ee290b2ca2731e76f216e
2,145
tsx
TypeScript
src/client/src/App.tsx
openbaseball/openbaseball
b17f77fe8f56036f62b50db53dfbf048874c17a2
[ "Apache-2.0" ]
null
null
null
src/client/src/App.tsx
openbaseball/openbaseball
b17f77fe8f56036f62b50db53dfbf048874c17a2
[ "Apache-2.0" ]
56
2018-11-14T21:15:21.000Z
2022-01-19T19:00:26.000Z
src/client/src/App.tsx
openbaseball/openbaseball
b17f77fe8f56036f62b50db53dfbf048874c17a2
[ "Apache-2.0" ]
null
null
null
import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { Route, withRouter } from 'react-router-dom' import { Flex } from 'rebass' import { bindActionCreators, Dispatch } from 'redux' import styled from 'styled-components' import { Normalize } from 'styled-normalize' import AboutPage from './containers/about' import HomePage from './containers/home' import NavBar from './containers/navbar' import PlayBeginningPage from './containers/play-beginning' import PlayerPage from './containers/player' import ProtectedPage from './containers/protected' import SuccessLoginPage from './containers/success-login' import TeamCreatePage from './containers/team-create' import './main.css' import { IAuth, isAuthenticated, refreshUser } from './modules/auth' import User from './modules/auth/user' const AppContainer = styled(Flex)` font-family: "Play", "Helvetica Neue", "Helvetica", "Arial", sans-serif; ` AppContainer.defaultProps = { flexDirection: 'column', } const Content = styled(Flex)` width: 100%; ` interface IAppProps { user?: User refreshUser: any } class App extends PureComponent<IAppProps> { public render() { return (<AppContainer> <Normalize /> <NavBar /> <Content> <Route exact path='/' component={HomePage} /> <Route exact path='/play' component={PlayBeginningPage} /> <Route exact path='/play/new-team' component={this.protect(TeamCreatePage)} /> <Route exact path='/player/:id' component={PlayerPage} /> <Route exact path='/about' component={AboutPage} /> <Route exact path='/callback' component={SuccessLoginPage} /> </Content> </AppContainer>) } public componentDidMount() { this.props.refreshUser() } protected protect = (component: any) => isAuthenticated() ? component : ProtectedPage } const mapDispatchToProps = (dispatch: Dispatch) => bindActionCreators( { refreshUser, }, dispatch, ) const mapStateToProps = ({ auth }: { auth: IAuth }) => ({ user: auth.user, }) export default withRouter<any>(connect( mapStateToProps, mapDispatchToProps, )(App))
28.6
87
0.696037
5db4dcaa97c8e90d29947b66e5a3ddc51388d606
7,673
hpp
C++
contrib/native/client/src/clientlib/streamSocket.hpp
akumarb2010/incubator-drill
a690b97074376a65ac0c1d86ee2a9fa32e997003
[ "Apache-2.0" ]
1
2020-12-27T04:08:49.000Z
2020-12-27T04:08:49.000Z
contrib/native/client/src/clientlib/streamSocket.hpp
akumarb2010/incubator-drill
a690b97074376a65ac0c1d86ee2a9fa32e997003
[ "Apache-2.0" ]
null
null
null
contrib/native/client/src/clientlib/streamSocket.hpp
akumarb2010/incubator-drill
a690b97074376a65ac0c1d86ee2a9fa32e997003
[ "Apache-2.0" ]
2
2019-11-12T09:21:02.000Z
2019-12-16T09:51:25.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #ifndef STREAMSOCKET_HPP #define STREAMSOCKET_HPP #include "logger.hpp" #include "wincert.ipp" #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> namespace Drill { typedef boost::asio::ip::tcp::socket::lowest_layer_type streamSocket_t; typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> sslTCPSocket_t; typedef boost::asio::ip::tcp::socket basicTCPSocket_t; // Some helper typedefs to define the highly templatized boost::asio methods typedef boost::asio::const_buffers_1 ConstBufferSequence; typedef boost::asio::mutable_buffers_1 MutableBufferSequence; // ReadHandlers have different possible signatures. // // As a standard C-type callback // typedef void (*ReadHandler)(const boost::system::error_code& ec, std::size_t bytes_transferred); // // Or as a C++ functor // struct ReadHandler { // virtual void operator()( // const boost::system::error_code& ec, // std::size_t bytes_transferred) = 0; //}; // // We need a different signature though, since we need to pass in a member function of a drill client // class (which is C++), as a functor generated by boost::bind as a ReadHandler // typedef boost::function<void (const boost::system::error_code& ec, std::size_t bytes_transferred) > ReadHandler; class AsioStreamSocket{ public: virtual ~AsioStreamSocket(){}; virtual streamSocket_t& getInnerSocket() = 0; virtual std::size_t writeSome( const ConstBufferSequence& buffers, boost::system::error_code & ec) = 0; virtual std::size_t readSome( const MutableBufferSequence& buffers, boost::system::error_code & ec) = 0; // // boost::asio::async_read has the signature // template< // typename AsyncReadStream, // typename MutableBufferSequence, // typename ReadHandler> // void-or-deduced async_read( // AsyncReadStream & s, // const MutableBufferSequence & buffers, // ReadHandler handler); // // For our use case, the derived class will have an instance of a concrete type for AsyncReadStream which // will implement the requirements for the AsyncReadStream type. We need not pass that in as a parameter // since the class already has the value // The method is templatized since the ReadHandler type is dependent on the class implementing the read // handler (basically the class using the asio stream) // virtual void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler) = 0; // call the underlying protocol's handshake method. // if the useSystemConfig flag is true, then use properties read // from the underlying operating system virtual void protocolHandshake(bool useSystemConfig) = 0; virtual void protocolClose() = 0; }; class Socket: public AsioStreamSocket, public basicTCPSocket_t{ public: Socket(boost::asio::io_service& ioService) : basicTCPSocket_t(ioService) { } ~Socket(){ boost::system::error_code ignorederr; this->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr); this->close(); }; basicTCPSocket_t& getSocketStream(){ return *this;} streamSocket_t& getInnerSocket(){ return this->lowest_layer();} std::size_t writeSome( const ConstBufferSequence& buffers, boost::system::error_code & ec){ return this->write_some(buffers, ec); } std::size_t readSome( const MutableBufferSequence& buffers, boost::system::error_code & ec){ return this->read_some(buffers, ec); } void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler){ return async_read(*this, buffers, handler); } void protocolHandshake(bool useSystemConfig){}; //nothing to do void protocolClose(){ // shuts down the socket! boost::system::error_code ignorederr; ((basicTCPSocket_t*)this)->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr ); } }; #if defined(IS_SSL_ENABLED) class SslSocket: public AsioStreamSocket, public sslTCPSocket_t{ public: SslSocket(boost::asio::io_service& ioService, boost::asio::ssl::context &sslContext) : sslTCPSocket_t(ioService, sslContext) { } ~SslSocket(){ this->lowest_layer().close(); }; sslTCPSocket_t& getSocketStream(){ return *this;} streamSocket_t& getInnerSocket(){ return this->lowest_layer();} std::size_t writeSome( const ConstBufferSequence& buffers, boost::system::error_code & ec){ return this->write_some(buffers, ec); } std::size_t readSome( const MutableBufferSequence& buffers, boost::system::error_code & ec){ return this->read_some(buffers, ec); } void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler){ return async_read(*this, buffers, handler); } // // public method that can be invoked by callers to invoke the ssl handshake // throws: boost::system::system_error void protocolHandshake(bool useSystemConfig){ if(useSystemConfig){ std::string msg = ""; int ret = loadSystemTrustStore(this->native_handle(), msg); if(!msg.empty()){ DRILL_LOG(LOG_WARNING) << msg.c_str() << std::endl; } if(ret){ boost::system::error_code ec(EPROTO, boost::system::system_category()); boost::asio::detail::throw_error(ec, msg.c_str()); } } this->handshake(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::client); return; }; // // public method that can be invoked by callers to invoke a clean ssl shutdown // throws: boost::system::system_error void protocolClose(){ try{ this->shutdown(); }catch(boost::system::system_error e){ //swallow the exception. The channel is unusable anyway } // shuts down the socket! boost::system::error_code ignorederr; this->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr ); return; }; }; #endif } // namespace Drill #endif //STREAMSOCKET_HPP
35.03653
114
0.619314
5843ce86176f1a2352d63a512d286307622229d9
232
lua
Lua
http/src/json.lua
Ozzypig/roblox-requests
f31aa1d096cbc082393848fee7add375ab7af79a
[ "MIT" ]
32
2019-09-23T09:31:51.000Z
2022-02-13T23:39:43.000Z
http/src/json.lua
Ozzypig/roblox-requests
f31aa1d096cbc082393848fee7add375ab7af79a
[ "MIT" ]
2
2021-02-17T04:47:38.000Z
2021-03-26T18:31:47.000Z
http/src/json.lua
Ozzypig/roblox-requests
f31aa1d096cbc082393848fee7add375ab7af79a
[ "MIT" ]
3
2021-03-23T09:13:26.000Z
2021-12-03T21:52:29.000Z
-- json shortcuts local httpservice = game:GetService("HttpService") local function enc(t) return httpservice:JSONEncode(t) end local function dec(s) return httpservice:JSONDecode(s) end return {["enc"] = enc, ["dec"] = dec}
15.466667
50
0.724138
b01e9e552534dd15db353e35482d2cbd9c856658
4,829
py
Python
tests/test_s12.py
wordlesstruth/stomp.py
d7382554eadc29c34c3aec4d5c300fe267a64e42
[ "Apache-2.0" ]
null
null
null
tests/test_s12.py
wordlesstruth/stomp.py
d7382554eadc29c34c3aec4d5c300fe267a64e42
[ "Apache-2.0" ]
null
null
null
tests/test_s12.py
wordlesstruth/stomp.py
d7382554eadc29c34c3aec4d5c300fe267a64e42
[ "Apache-2.0" ]
null
null
null
import pytest import stomp from stomp import exception from stomp.listener import TestListener from .testutils import * @pytest.fixture() def conn(): conn = stomp.Connection12(get_default_host()) listener = TestListener("123", print_to_log=True) conn.set_listener("testlistener", listener) conn.connect(get_default_user(), get_default_password(), wait=True) yield conn conn.disconnect(receipt=None) class Test12Connect(object): def test_send(self, conn): listener = conn.get_listener("testlistener") queuename = "/queue/testsend12-%s" % listener.timestamp conn.subscribe(destination=queuename, id=1, ack="auto") conn.send(body="this is a test using protocol 1.2", destination=queuename, receipt="123") validate_send(conn, 1, 1, 0) def test_clientack(self, conn): listener = conn.get_listener("testlistener") queuename = "/queue/testclientack12-%s" % listener.timestamp conn.subscribe(destination=queuename, id=1, ack="client-individual") conn.send(body="this is a test", destination=queuename, receipt="123") listener.wait_for_message() (headers, _) = listener.get_latest_message() ack_id = headers["ack"] conn.ack(ack_id) def test_clientnack(self, conn): listener = conn.get_listener("testlistener") queuename = "/queue/testclientnack12-%s" % listener.timestamp conn.subscribe(destination=queuename, id=1, ack="client-individual") conn.send(body="this is a test", destination=queuename, receipt="123") listener.wait_for_message() (headers, _) = listener.get_latest_message() ack_id = headers["ack"] conn.nack(ack_id) def test_should_send_extra_header_clientnack(self, conn, mocker): listener = conn.get_listener("testlistener") queuename = "/queue/testclientnack12-%s" % listener.timestamp conn.subscribe(destination=queuename, id=1, ack="client-individual") conn.send(body="this is a test", destination=queuename, receipt="123") listener.wait_for_message() (headers, _) = listener.get_latest_message() ack_id = headers["ack"] wrapped_send_frame = mocker.patch.object(conn, "send_frame", wraps=conn.send_frame) conn.nack(ack_id, requeue="false") expected_headers = {HDR_ID: ack_id.replace(':', '\\c'), "requeue": "false"} wrapped_send_frame.assert_called_with(CMD_NACK, expected_headers) def test_timeout(self): server = StubStompServer("127.0.0.1", 60000) try: server.start() server.add_frame('''ERROR message: connection failed\x00''') conn = stomp.Connection12([("127.0.0.1", 60000)]) listener = TestListener(print_to_log=True) conn.set_listener('', listener) try: conn.connect(wait=True) self.fail("shouldn't happen") except exception.ConnectFailedException: pass finally: server.stop() def test_specialchars(self, conn): listener = conn.get_listener("testlistener") queuename = "/queue/testspecialchars12-%s" % listener.timestamp conn.subscribe(destination=queuename, id=1, ack="client") hdrs = { "special-1": "test with colon : test", "special-2": "test with backslash \\ test", "special-3": "test with newlines \n \n", "special-4": "test with carriage return \r" } conn.send(body="this is a test", headers=hdrs, destination=queuename, receipt="123") listener.wait_for_message() (headers, _) = listener.get_latest_message() _ = headers["message-id"] _ = headers["subscription"] assert "special-1" in headers assert "test with colon : test" == headers["special-1"] assert "special-2" in headers assert "test with backslash \\ test" == headers["special-2"] assert "special-3" in headers assert "test with newlines \n \n" == headers["special-3"] assert "special-4" in headers cr_header = headers["special-4"].replace('\\r', '\r') assert "test with carriage return \r" == cr_header def test_suppress_content_length(self, conn, mocker): listener = conn.get_listener("testlistener") queuename = "/queue/testspecialchars12-%s" % listener.timestamp conn = stomp.Connection12(get_default_host(), vhost=get_default_vhost(), auto_content_length=False) conn.transport = mocker.Mock() conn.send(body="test", destination=queuename, receipt="123") args, kwargs = conn.transport.transmit.call_args frame = args[0] assert "content-length" not in frame.headers
34.741007
107
0.641541
f8f0e3500e42ada3b9423b0291d2d2a5cb689350
15,161
hpp
C++
src/api/face/cpp/doc/Vortex_FACE.hpp
agenihorganization/opensplice
314d3a4538474f2b8e22acffe3c206f4ac38b66b
[ "Apache-2.0" ]
null
null
null
src/api/face/cpp/doc/Vortex_FACE.hpp
agenihorganization/opensplice
314d3a4538474f2b8e22acffe3c206f4ac38b66b
[ "Apache-2.0" ]
null
null
null
src/api/face/cpp/doc/Vortex_FACE.hpp
agenihorganization/opensplice
314d3a4538474f2b8e22acffe3c206f4ac38b66b
[ "Apache-2.0" ]
null
null
null
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to TO_YEAR PrismTech * Limited, its affiliated companies and licensors. All rights reserved. * * 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. */ #ifndef VORTEX_FACE_ISOCPP2_Data_HPP_ #define VORTEX_FACE_ISOCPP2_Data_HPP_ #include "Vortex_FACE.hpp" #include "Vortex/FACE/Macros.hpp" namespace FACE { namespace TS { /** * The Initialize function call allows for the Portable Components Segment (PCS) and Platform-Specific Services Segment (PSSS) * component to trigger the initialization of the Transport Services Segment (TSS) component. * * Possible return codes: * <ul> * <li>INVALID_PARAM - The provided configuration is not valid * <li>INVALID_CONFIG - The provided configuration contains invalid settings * <li>NO_ACTION - There is already an initialized configuration. * </ul> * @param configuration * The configuration defined as an xml file which hold the connection configuration. * This is an input parameter * @param return_code * The return_code */ void Initialize( /* in */ const FACE::CONFIGURATION_RESOURCE &configuration, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The Transport Services Segment (TSS) provides an interface to create a connection. * The parameters for the individual connections are determined through the TSS configuration * capability which is set by the Initialize function call. * * Possible return codes: * <ul> * <li>NO_ERROR - Successful completion.</li> * <li>NO_ACTION - Returned if the participant has already been created and * registered. - Type has already been registered.</li> * <li>INVALID_CONFIG - Could not allocate enough memory. - Policies are not * consistent with each other (e.g., configuration data is invalid, QoS * attributes not supported). * <ul> * <li>Generic, unspecified error.</li> * <li>Attempted to modify an immutable QoSPolicy.</li> * </ul></li> * <li>INVALID_PARAM - Returned under the following conditions: - Could not * find topic name associated with the connection.</li> * <li>NOT_AVAILABLE - Unsupported operation.</li> * <li>INVALID_MODE - Connection could not be created in the current mode or * operation performed at an inappropriate type.</li> * </ul> * * @param connection_name * The connection_name which needs to match one of the configured connection names in the configuration * This is an input parameter. * @param pattern * The pattern set in the connection configuration which for DDS only can be PUB_SUB. * This is an input parameter. * @param connection_id * The connection_id which is generated by DDS and set on successful creation. * This is an output parameter. * @param connection_direction * The connection_direction of the connection that is created. This can be SOURCE or DESTINATION. * This is an output parameter. * @param max_message_size * The max_message_size for DDS this parameter is not relevant. * This is an output parameter. * @param timeout * The timeout for DDS this parameter is not relevant. * This is an input parameter. * @param return_code * The return_code * This is an output parameter. */ void Create_Connection( /* in */ const FACE::CONNECTION_NAME_TYPE &connection_name, /* in */ const FACE::MESSAGING_PATTERN_TYPE &pattern, /* out */ FACE::CONNECTION_ID_TYPE &connection_id, /* out */ FACE::CONNECTION_DIRECTION_TYPE &connection_direction, /* out */ FACE::MESSAGE_SIZE_TYPE &max_message_size, /* in */ const FACE::TIMEOUT_TYPE &timeout, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The Destroy_Connection function frees up any resources allocated to the connection. * * Possible return codes: * <ul> * <li>NO_ERROR - Successful completion.</li> * <li>NO_ACTION - Object target of this operation has already been deleted.</li> * <li>INVALID_MODE - An operation was invoked on an inappropriate object or * at an inappropriate time.</li> * <li>INVALID_PARAM - Connection identification (ID) invalid.</li> * <li>NOT_AVAILABLE - Unsupported operation.</li> * <li>INVALID_CONFIG - Generic, unspecified error.</li> * <li>INVALID_MODE - A pre-condition for the operation was not met. Note: * In a FACE implementation, this error may imply an implementation problem * since the connection is deleted and should clean up all entities/children * associated with the connection.</li> * </ul> * * @param connection_id * The connection_id of the connection that needs to be destroyed. * This is an input parameter. * @param return_code * The return_code. * This is an output parameter. */ void Destroy_Connection( /* in */ const FACE::CONNECTION_ID_TYPE &connection_id, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The purpose of Get_Connection_Parameters is to get the information regarding the requested connection. * * @param connection_name * The connection_name which belongs to the given connection_id. * This is an output parameter. * @param connection_id * The connection_id for which this status needs to return information * This is an input parameter. * @param connection_status * The connection_status which consists of the following settings: * <ul> * <li>MESSAGE - Always 0 * <li>MAX_MESSAGE - Always 0. * <li>MAX_MESSAGE_SIZE - Always 0. * <li>CONNECTION_DIRECTION - SOURCE or DESTINATION * <li>WAITING_PROCESSES_OR_MESSAGES - Not implemented * <li>REFRESH_PERIOD - The configured refresh period. * <li>LAST_MSG_VALIDITY - Whether or not the refresh period of last taken message has expired or not (DESTINATION) * </ul> * This is an output parameter. * @param return_code * The return_code * This is an output parameter. */ void Get_Connection_Parameters( /* inout */ FACE::CONNECTION_NAME_TYPE &connection_name, /* inout */ FACE::CONNECTION_ID_TYPE &connection_id, /* out */ FACE::TRANSPORT_CONNECTION_STATUS_TYPE &connection_status, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The purpose of Unregister_Callback is to provide a mechanism to unregister the callback * associated with a connection_id. * * @param connection_id * The connection_id of the connection where the callback was registered. * This is an input parameter. * @param return_code * The return_code * This is an output parameter. */ void Unregister_Callback( /* in */ const FACE::CONNECTION_ID_TYPE &connection_id, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The Receive_Message Function is used to receive data from another source. * * Possible return codes: * <ul> * <li>NO_ERROR - Successful completion. * <li>NO_ACTION - Object target of this operation has already been deleted. * <li>INVALID_MODE - An operation was invoked on an inappropriate object or * <li>INVALID_PARAM - Illegal parameter value (e.g., connection ID). * <li>INVALID_CONFIG - Generic, unspecified error. * <li>NOT_AVAILABLE - Unsupported operation. * <li>INVALID_MODE * <ul> * <li>A pre-condition for the operation was not met. * <li>Operation invoked on an entity that is not yet enabled. * </ul> * <li>NO_ACTION - Indicates a transient situation where the operation did * </ul> * @param connection_id * The connection_id which is used to get the connection where to receive messages on. * This is an input parameter. * @param timeout * The timeout in nanoseconds, this is used to determine how long DDS should wait for new messages * to arrive before returning the result. * This is an input parameter. * @param transaction_id * The transaction_id, each time a message is read an unique transaction_id is generated for it. * This is an output parameter. * @param message * The message that is read by DDS * This is an output parameter. * @param message_type_id * The message_type_id for DDS this parameter is not relevant. * This is an output parameter. * @param message_size * The message_type_id for DDS this parameter is not relevant. * This is an output parameter. * @param return_code * The return_code * This is an output parameter. */ void Receive_Message( /* in */ const FACE::CONNECTION_ID_TYPE &connection_id, /* in */ const FACE::TIMEOUT_TYPE &timeout, /* inout */ FACE::TRANSACTION_ID_TYPE &transaction_id, /* inout */ Data::Type &message, /* inout */ FACE::MESSAGE_TYPE_GUID &message_type_id, /* inout */ FACE::MESSAGE_SIZE_TYPE &message_size, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The Send_Message Function is used to send data to another source. * * Possible return codes: * <ul> * <li>NO_ERROR - Successful completion. * <li>NO_ACTION - Object target of this operation has already been deleted. * <li>INVALID_MODE - An operation was invoked on an inappropriate object or * at an inappropriate time. * <li>INVALID_PARAM - Illegal parameter value (e.g., connection ID). * <li>INVALID_CONFIG - Generic, unspecified error. * <li>NOT_AVAILABLE - Unsupported operation. * <li>INVALID_MODE * <ul> * <li>A pre-condition for the operation was not met. * <li>Operation invoked on an entity that is not yet enabled. * </ul> * <li>INVALID_CONFIG - Service ran out of resources needed to complete the * operation. * <li>TIMED_OUT - DDS will not return TIMEOUT, but this could be returned * by the TSS implementation. * </ul> * * @param connection_id * The connection_id which is used to get the connection where to send messages to. * This is an input parameter. * @param timeout * The timeout in nanoseconds, this is used to determine how long DDS at maximum can wait to send the message. * This timeout cannot be greater than max_blocking_time of the supplied DataWriter QoS. * This is an input parameter. * @param transaction_id * The transaction_id, each time a message is send an unique transaction_id is generated for it. * This is an output parameter. * @param message * The message that is read by DDS * This is an output parameter. * @param message_type_id * The message_type_id for DDS this parameter is not relevant. * This is an output parameter. * @param message_size * The message_type_id for DDS this parameter is not relevant. * This is an output parameter. * @param return_code * The return_code * This is an output parameter. */ void Send_Message( /* in */ const FACE::CONNECTION_ID_TYPE &connection_id, /* in */ const FACE::TIMEOUT_TYPE &timeout, /* inout */ FACE::TRANSACTION_ID_TYPE &transaction_id, /* inout */ Data::Type &message, /* in */ const FACE::MESSAGE_TYPE_GUID &message_type_id, /* in */ const FACE::MESSAGE_SIZE_TYPE &message_size, /* out */ FACE::RETURN_CODE_TYPE &return_code); /** * The purpose of Register_Callback is to provide a mechanism to read data without polling. * This needs to be called on the generated type interface without using the TS Interface. * There can only be one callback registration per connection_id. * * Possible return codes: * <ul> * <li>NO_ERROR - Successful completion. * <li>NO_ACTION - Callback already registered for specified type. * <li>INVALID_PARAM - One or more of the parameters are incorrect (e.g., * invalid connection identification (ID), invalid callback, invalid message * size). * <li>NOT_AVAILABLE - Callback/routing function not available (e.g., * callback service is not provided in this implementation). * <li>INVALID_CONFIG - One or more fields in the configuration data for the * connection is invalid (e.g., invalid TSS thread parameters). * </ul> * * <p> * <b><i>Register_Callback Example</i></b> * <pre> * <code> * * static void data_callback (const FACE::TRANSACTION_ID_TYPE &transaction_id, * Data::Type &message, * const FACE::MESSAGE_TYPE_GUID &message_type_id, * const FACE::MESSAGE_SIZE_TYPE &message_size, * const FACE::WAITSET_TYPE &waitset, * FACE::RETURN_CODE_TYPE &return_code) * { * do your action here * } * * then the callback can be registered by calling: * FACE::TS::Register_Callback(connection_id, waitset, data_callback, maxMessageSize, status); * </code> * </pre> * * @param connection_id * The connection_id of the connection that needs to be used for the callback. * This is an input parameter. * @param waitset * The waitset for DDS this parameter is not relevant. * This is an input parameter. * @param data_callback * The data_callback class in which an action can be set on how to react when receiving data. * This data_callback is the external operation (interface, which must be implemented by the application see example) * that is called by the FACE API when new data is available for this connection. * This is an input parameter. * @param max_message_size * The max_message_size for DDS this parameter is not relevant however the max_message_size supplied * needs to be less then the max_message_size of the configured connection. * This is an input parameter. * @param return_code the return_code * This is an output parameter. */ void Register_Callback( /* in */ const FACE::CONNECTION_ID_TYPE &connection_id, /* in */ const FACE::WAITSET_TYPE &waitset, /* inout */ FACE::Read_Callback<Data::Type>::send_event data_callback, /* in */ const FACE::MESSAGE_SIZE_TYPE &max_message_size, /* out */ FACE::RETURN_CODE_TYPE &return_code); } /* namespace TS */ } /* namespace FACE */ #endif /* VORTEX_FACE_ISOCPP2_Data_HPP_ */
43.317143
127
0.675879
e84db9e22178ebe593239d2b6def61087c2a40ae
1,714
cs
C#
src/Validation.Common.Job/Validation/INuGetValidationRequest.cs
nikhgup/NuGet.Jobs
062f7501e34d34a12abf780f6a01629e66b7f28b
[ "Apache-2.0" ]
44
2015-05-25T10:40:15.000Z
2022-01-20T10:55:18.000Z
src/Validation.Common.Job/Validation/INuGetValidationRequest.cs
nikhgup/NuGet.Jobs
062f7501e34d34a12abf780f6a01629e66b7f28b
[ "Apache-2.0" ]
320
2015-03-31T18:55:14.000Z
2022-03-22T18:52:09.000Z
src/Validation.Common.Job/Validation/INuGetValidationRequest.cs
nikhgup/NuGet.Jobs
062f7501e34d34a12abf780f6a01629e66b7f28b
[ "Apache-2.0" ]
21
2015-04-06T14:55:59.000Z
2021-04-24T09:26:04.000Z
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace NuGet.Services.Validation { /// <summary> /// The request to start or check a validation step for a NuGet package or symbol. /// </summary> public interface INuGetValidationRequest { /// <summary> /// The identifier for a single validation step execution. /// </summary> Guid ValidationId { get; } /// <summary> /// The package key in the NuGet gallery database. If a package is hard deleted and created, the package key /// will be different but the <see cref="PackageId"/> and <see cref="PackageVersion"/> will be the same. /// </summary> int PackageKey { get; } /// <summary> /// The package ID. The casing of this ID need not match the author-intended casing of the ID. /// </summary> string PackageId { get; } /// <summary> /// The package version. The casing of this version need not match the author-intended casing of the version. /// This value is not necessarily a normalized version. /// </summary> string PackageVersion { get; } /// <summary> /// The URL to the NuGet package content. This URL should be accessible without special authentication headers. /// However, authentication information could be included in the URL (e.g. Azure Blob Storage SAS URL). This URL /// need not have a single value for a specific <see cref="ValidationId"/>. /// </summary> string NupkgUrl { get; } } }
39.860465
120
0.631855
4475590c1b70563bd14935c95f52893c912778f8
1,550
py
Python
tests/repo/test_models.py
trewjames/receipt-tracker
1f1768741f8599252f9bb153f111b245bdc995d4
[ "MIT" ]
null
null
null
tests/repo/test_models.py
trewjames/receipt-tracker
1f1768741f8599252f9bb153f111b245bdc995d4
[ "MIT" ]
null
null
null
tests/repo/test_models.py
trewjames/receipt-tracker
1f1768741f8599252f9bb153f111b245bdc995d4
[ "MIT" ]
null
null
null
from receipt_tracker.repo.models import Seller, Buyer, Receipt def test_table_initial_inserts(db_session): query_buyer = db_session.query(Buyer).all() query_seller = db_session.query(Seller).all() query_receipt = db_session.query(Receipt).all() assert str(query_buyer) == '[Buyer(1, James Trew), Buyer(2, Eugene Min), Buyer(3, Anna Trew)]' assert str(query_seller) == '[Seller(1, Steam), Seller(2, No Frills), Seller(3, Amazon), Seller(4, Always Clean Coin Laundry), Seller(5, Eagle Dynamics)]' assert str(query_receipt) == '[Receipt(1, James Trew, Steam, 2020-08-16, 9.67, Steam game), Receipt(2, James Trew, No Frills, 2020-08-17, 17.86, Groceries), Receipt(3, Eugene Min, Amazon, 2020-08-18, 57.36, Random amazon purchases), Receipt(4, Eugene Min, Always Clean Coin Laundry, 2020-08-19, 2.5, None)]' def test_table_relationship(db_session): james = db_session.query(Buyer).filter(Buyer.id == 1).one() steam = db_session.query(Seller).filter(Seller.id == 1).one() assert james.name == 'James Trew' assert str(james.purchases) == '[Receipt(1, James Trew, Steam, 2020-08-16, 9.67, Steam game), Receipt(2, James Trew, No Frills, 2020-08-17, 17.86, Groceries)]' assert steam.name == 'Steam' assert str(steam.sales) == '[Receipt(1, James Trew, Steam, 2020-08-16, 9.67, Steam game)]' def test_table_column_names(): test_data = Buyer.__table__.columns.keys() assert test_data == ['id', 'name'] def test_table_name(): test_name = Buyer.__tablename__ assert test_name == 'buyers'
44.285714
311
0.695484
02dbd1f9ba556de18b310d4cc40ee5e55ee6fc21
4,952
html
HTML
Software/gcc-arm-none-eabi-4_8-2014q1/share/doc/gcc-arm-none-eabi/html/stabs/Source-Files.html
rdfong/smartvision-copy
20846bb57acb3b47f29e28a93fe42b54e73425a3
[ "MIT" ]
null
null
null
Software/gcc-arm-none-eabi-4_8-2014q1/share/doc/gcc-arm-none-eabi/html/stabs/Source-Files.html
rdfong/smartvision-copy
20846bb57acb3b47f29e28a93fe42b54e73425a3
[ "MIT" ]
null
null
null
Software/gcc-arm-none-eabi-4_8-2014q1/share/doc/gcc-arm-none-eabi/html/stabs/Source-Files.html
rdfong/smartvision-copy
20846bb57acb3b47f29e28a93fe42b54e73425a3
[ "MIT" ]
null
null
null
<html lang="en"> <head> <title>Source Files - STABS</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="STABS"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Program-Structure.html#Program-Structure" title="Program Structure"> <link rel="prev" href="Main-Program.html#Main-Program" title="Main Program"> <link rel="next" href="Include-Files.html#Include-Files" title="Include Files"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1992-2013 Free Software Foundation, Inc. Contributed by Cygnus Support. Written by Julia Menapace, Jim Kingdon, and David MacKenzie. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Source-Files"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Include-Files.html#Include-Files">Include Files</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Main-Program.html#Main-Program">Main Program</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Program-Structure.html#Program-Structure">Program Structure</a> <hr> </div> <h3 class="section">2.2 Paths and Names of the Source Files</h3> <p><a name="index-N_005fSO-2"></a>Before any other stabs occur, there must be a stab specifying the source file. This information is contained in a symbol of stab type <code>N_SO</code>; the string field contains the name of the file. The value of the symbol is the start address of the portion of the text section corresponding to that file. <p>Some compilers use the desc field to indicate the language of the source file. Sun's compilers started this usage, and the first constants are derived from their documentation. Languages added by gcc/gdb start at 0x32 to avoid conflict with languages Sun may add in the future. A desc field with a value 0 indicates that no language has been specified via this mechanism. <dl> <dt><code>N_SO_AS</code> (0x1)<dd>Assembly language <br><dt><code>N_SO_C</code> (0x2)<dd>K&amp;R traditional C <br><dt><code>N_SO_ANSI_C</code> (0x3)<dd>ANSI C <br><dt><code>N_SO_CC</code> (0x4)<dd>C++ <br><dt><code>N_SO_FORTRAN</code> (0x5)<dd>Fortran <br><dt><code>N_SO_PASCAL</code> (0x6)<dd>Pascal <br><dt><code>N_SO_FORTRAN90</code> (0x7)<dd>Fortran90 <br><dt><code>N_SO_OBJC</code> (0x32)<dd>Objective-C <br><dt><code>N_SO_OBJCPLUS</code> (0x33)<dd>Objective-C++ </dl> <p>Some compilers (for example, GCC2 and SunOS4 <samp><span class="file">/bin/cc</span></samp>) also include the directory in which the source was compiled, in a second <code>N_SO</code> symbol preceding the one containing the file name. This symbol can be distinguished by the fact that it ends in a slash. Code from the <code>cfront</code> C<tt>++</tt> compiler can have additional <code>N_SO</code> symbols for nonexistent source files after the <code>N_SO</code> for the real source file; these are believed to contain no useful information. <p>For example: <pre class="example"> .stabs "/cygint/s1/users/jcm/play/",100,0,0,Ltext0 # <span class="roman">100 is N_SO</span> .stabs "hello.c",100,0,0,Ltext0 .text Ltext0: </pre> <p><a name="index-C_005fFILE-3"></a>Instead of <code>N_SO</code> symbols, XCOFF uses a <code>.file</code> assembler directive which assembles to a <code>C_FILE</code> symbol; explaining this in detail is outside the scope of this document. <!-- FIXME: Exactly when should the empty N_SO be used? Why? --> <p>If it is useful to indicate the end of a source file, this is done with an <code>N_SO</code> symbol with an empty string for the name. The value is the address of the end of the text section for the file. For some systems, there is no indication of the end of a source file, and you just need to figure it ended when you see an <code>N_SO</code> for a different source file, or a symbol ending in <code>.o</code> (which at least some linkers insert to mark the start of a new <code>.o</code> file). </body></html>
48.07767
121
0.728191
dd86afcf290cf7d7d1d2e65324ab5e0a90351b37
21,853
java
Java
server/src/test/java/org/killbill/billing/server/healthchecks/TestHoltWintersComputer.java
vnandwana/killbill-platform
5da87cca795eb8fc459c59b8e1ef86439df55ac9
[ "Apache-2.0" ]
13
2015-03-13T19:06:42.000Z
2022-03-12T08:32:41.000Z
server/src/test/java/org/killbill/billing/server/healthchecks/TestHoltWintersComputer.java
vnandwana/killbill-platform
5da87cca795eb8fc459c59b8e1ef86439df55ac9
[ "Apache-2.0" ]
35
2015-03-27T21:13:35.000Z
2022-03-25T14:24:59.000Z
server/src/test/java/org/killbill/billing/server/healthchecks/TestHoltWintersComputer.java
vnandwana/killbill-platform
5da87cca795eb8fc459c59b8e1ef86439df55ac9
[ "Apache-2.0" ]
40
2015-03-13T14:26:24.000Z
2022-03-31T02:19:28.000Z
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.server.healthchecks; import java.util.ArrayList; import org.testng.Assert; import org.testng.annotations.Test; public class TestHoltWintersComputer { // Atmospheric concentrations of CO2 are expressed in parts per million (ppm) and // reported in the preliminary 1997 SIO manometric mole fraction scale. // A time series of 468 observations; monthly from 1959 to 1997. private static double[] CO2 = {315.42, 316.31, 316.5, 317.56, 318.13, 318, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43, 316.27, 316.81, 317.42, 318.87, 319.87, 319.43, 318.01, 315.74, 314, 313.68, 314.84, 316.03, 316.73, 317.54, 318.38, 319.31, 320.42, 319.61, 318.42, 316.63, 314.83, 315.16, 315.94, 316.85, 317.78, 318.4, 319.53, 320.42, 320.85, 320.45, 319.45, 317.25, 316.11, 315.27, 316.53, 317.53, 318.58, 318.92, 319.7, 321.22, 322.08, 321.31, 319.58, 317.61, 316.05, 315.83, 316.91, 318.2, 319.41, 320.07, 320.74, 321.4, 322.06, 321.73, 320.27, 318.54, 316.54, 316.71, 317.53, 318.55, 319.27, 320.28, 320.73, 321.97, 322, 321.71, 321.05, 318.71, 317.66, 317.14, 318.7, 319.25, 320.46, 321.43, 322.23, 323.54, 323.91, 323.59, 322.24, 320.2, 318.48, 317.94, 319.63, 320.87, 322.17, 322.34, 322.88, 324.25, 324.83, 323.93, 322.38, 320.76, 319.1, 319.24, 320.56, 321.8, 322.4, 322.99, 323.73, 324.86, 325.4, 325.2, 323.98, 321.95, 320.18, 320.09, 321.16, 322.74, 323.83, 324.26, 325.47, 326.5, 327.21, 326.54, 325.72, 323.5, 322.22, 321.62, 322.69, 323.95, 324.89, 325.82, 326.77, 327.97, 327.91, 327.5, 326.18, 324.53, 322.93, 322.9, 323.85, 324.96, 326.01, 326.51, 327.01, 327.62, 328.76, 328.4, 327.2, 325.27, 323.2, 323.4, 324.63, 325.85, 326.6, 327.47, 327.58, 329.56, 329.9, 328.92, 327.88, 326.16, 324.68, 325.04, 326.34, 327.39, 328.37, 329.4, 330.14, 331.33, 332.31, 331.9, 330.7, 329.15, 327.35, 327.02, 327.99, 328.48, 329.18, 330.55, 331.32, 332.48, 332.92, 332.08, 331.01, 329.23, 327.27, 327.21, 328.29, 329.41, 330.23, 331.25, 331.87, 333.14, 333.8, 333.43, 331.73, 329.9, 328.4, 328.17, 329.32, 330.59, 331.58, 332.39, 333.33, 334.41, 334.71, 334.17, 332.89, 330.77, 329.14, 328.78, 330.14, 331.52, 332.75, 333.24, 334.53, 335.9, 336.57, 336.1, 334.76, 332.59, 331.42, 330.98, 332.24, 333.68, 334.8, 335.22, 336.47, 337.59, 337.84, 337.72, 336.37, 334.51, 332.6, 332.38, 333.75, 334.78, 336.05, 336.59, 337.79, 338.71, 339.3, 339.12, 337.56, 335.92, 333.75, 333.7, 335.12, 336.56, 337.84, 338.19, 339.91, 340.6, 341.29, 341, 339.39, 337.43, 335.72, 335.84, 336.93, 338.04, 339.06, 340.3, 341.21, 342.33, 342.74, 342.08, 340.32, 338.26, 336.52, 336.68, 338.19, 339.44, 340.57, 341.44, 342.53, 343.39, 343.96, 343.18, 341.88, 339.65, 337.81, 337.69, 339.09, 340.32, 341.2, 342.35, 342.93, 344.77, 345.58, 345.14, 343.81, 342.21, 339.69, 339.82, 340.98, 342.82, 343.52, 344.33, 345.11, 346.88, 347.25, 346.62, 345.22, 343.11, 340.9, 341.18, 342.8, 344.04, 344.79, 345.82, 347.25, 348.17, 348.74, 348.07, 346.38, 344.51, 342.92, 342.62, 344.06, 345.38, 346.11, 346.78, 347.68, 349.37, 350.03, 349.37, 347.76, 345.73, 344.68, 343.99, 345.48, 346.72, 347.84, 348.29, 349.23, 350.8, 351.66, 351.07, 349.33, 347.92, 346.27, 346.18, 347.64, 348.78, 350.25, 351.54, 352.05, 353.41, 354.04, 353.62, 352.22, 350.27, 348.55, 348.72, 349.91, 351.18, 352.6, 352.92, 353.53, 355.26, 355.52, 354.97, 353.75, 351.52, 349.64, 349.83, 351.14, 352.37, 353.5, 354.55, 355.23, 356.04, 357, 356.07, 354.67, 352.76, 350.82, 351.04, 352.69, 354.07, 354.59, 355.63, 357.03, 358.48, 359.22, 358.12, 356.06, 353.92, 352.05, 352.11, 353.64, 354.89, 355.88, 356.63, 357.72, 359.07, 359.58, 359.17, 356.94, 354.92, 352.94, 353.23, 354.09, 355.33, 356.63, 357.1, 358.32, 359.41, 360.23, 359.55, 357.53, 355.48, 353.67, 353.95, 355.3, 356.78, 358.34, 358.89, 359.95, 361.25, 361.67, 360.94, 359.55, 357.49, 355.84, 356, 357.59, 359.05, 359.98, 361.03, 361.66, 363.48, 363.82, 363.3, 361.94, 359.5, 358.11, 357.8, 359.61, 360.74, 362.09, 363.29, 364.06, 364.76, 365.45, 365.01, 363.7, 361.54, 359.51, 359.65, 360.8, 362.38, 363.23, 364.06, 364.61, 366.4, 366.84, 365.68, 364.52, 362.57, 360.24, 360.83, 362.49, 364.34}; @Test(groups = "fast") public void testExponentialSmoothing() throws Exception { // seasonal <- c(315.42,316.31,316.5,317.56,318.13,318.0,316.39,314.65,313.68,313.18,314.66,315.430) // smooth<-HoltWinters(co2, alpha=0.513, beta=0.009, gamma=0.47, l.start = 316.31, b.start = 0.8899, s.start=seasonal) final double[] smooth = {632.6199, 470.6517138117, 390.639939945329, 352.519079609679, 334.05271282566, 324.807110616726, 318.573956221258, 314.677346244792, 312.39009345864, 310.861014290286, 311.945207992319, 312.371655579909, 240.017367520252, 315.999938806999, 333.983110569806, 334.573652058746, 330.176145953271, 325.418803950448, 320.265797767209, 316.277923555616, 313.942130284222, 312.506783696153, 313.709914980136, 314.153694426107, 258.206391730428, 308.290378178855, 326.885384043855, 331.962337737318, 330.929290097554, 327.103001449562, 322.613435964528, 318.636022780413, 315.706535518878, 314.599835917296, 314.852731831459, 315.280998039128, 272.282177787016, 304.331883209043, 321.345478091202, 328.538310633349, 330.171617131195, 328.322976268678, 324.619536686661, 320.249920320124, 317.244394499389, 315.529275937077, 315.971697295194, 316.296858684042, 283.346469866347, 302.98422072885, 317.671212389663, 326.113577819763, 329.047705401723, 328.158953398938, 325.356206604106, 321.661069754128, 318.886532205992, 317.064216795264, 317.455197113874, 317.692846472184, 292.154629456775, 302.946635542762, 314.64191077189, 322.955434013277, 327.402348850349, 327.582871640154, 325.503397666745, 322.716275219386, 319.794407417494, 318.667408728304, 318.67979890366, 319.193316689245, 299.375812881207, 304.928083659635, 313.712321323853, 321.753808998084, 326.72502020431, 328.25053069795, 327.248874473571, 324.407553092775, 321.938371074557, 320.392491730605, 320.401652401664, 320.630749432352, 305.834180562268, 307.994072136799, 313.927190729432, 320.735554358964, 325.632592487852, 327.869754407699, 327.263146742103, 324.775341352022, 322.68273488419, 321.409209096453, 322.055645456275, 322.248601338102, 310.884213984301, 310.194413931785, 314.169070141805, 320.118714147262, 324.736760334325, 327.094362791044, 327.41708516041, 325.972395010836, 324.077810417074, 323.067359201408, 323.550821712839, 323.61751224833, 314.862944082395, 313.238133300115, 315.633856128485, 320.69415238368, 325.002445622681, 327.651552860155, 328.111038194394, 327.162123359016, 325.575662456814, 325.151306487157, 325.579580295781, 325.829220002201, 318.901905001978, 316.293265081289, 317.717734357679, 321.516936555609, 325.400156354577, 327.512541380195, 328.315946190695, 327.28112061486, 326.310521800961, 325.911466894706, 326.833960290654, 327.346665843318, 322.037659395571, 319.273468562948, 319.472460111632, 321.950681048952, 324.576662236975, 327.025313452676, 328.115857310526, 327.633280454239, 326.786521061241, 326.43425146936, 327.419237126136, 328.237334186122, 324.452278576477, 321.559555189106, 321.201396026417, 322.706348845415, 325.654117377815, 327.546621857208, 328.16684580671, 327.73318920143, 327.072944962815, 327.526085521386, 328.917589149749, 330.006457871525, 327.211037511667, 324.736912268583, 323.904838549138, 325.50309930338, 327.380672604739, 329.022872060225, 330.098029166384, 329.893526195008, 329.542717573599, 330.149632681378, 331.259457934922, 332.050712533749, 329.691720930135, 327.21668620672, 326.110222730836, 327.132232717243, 328.599570986785, 329.497872317528, 329.937766244086, 329.705541203304, 329.200744621037, 329.769052036626, 331.183665611647, 332.144567593348, 330.96437149966, 329.30385962159, 327.957527918885, 328.381863229994, 329.345109617861, 329.948666675291, 330.54256194394, 330.054006865444, 329.421400778979, 330.356911632473, 331.932085037167, 333.121395360026, 332.551731113159, 331.430379835043, 330.070865880351, 330.393415500582, 330.943224253799, 331.004152748724, 330.942909095066, 330.572275038568, 329.958455970874, 330.769127112302, 332.387182587005, 333.822578233372, 333.768766476992, 333.106613644051, 331.887023365704, 332.101458085541, 332.515826636703, 332.621564870345, 332.478082160766, 331.916712349297, 331.354369359081, 332.394809914161, 334.295263315773, 335.864159651928, 336.21322065248, 335.658880246251, 334.763946321689, 334.801720130697, 334.791154583771, 334.27955610589, 333.872714893958, 333.084625321266, 332.803484944026, 333.400237239287, 335.391560859964, 337.180141353755, 337.630824661524, 337.248707039198, 336.766127820506, 336.732675566155, 336.393008840308, 335.924895274756, 335.201805893582, 334.121861316618, 333.685688502361, 334.260679663157, 336.375469058004, 338.220193243978, 339.273129757172, 339.213651458151, 338.963104696317, 339.142166975354, 338.78016206581, 338.203791045496, 337.112201796518, 335.890145981813, 334.950747875711, 335.773704508002, 338.083381713966, 339.920590626881, 340.944169507801, 340.776684517701, 341.28994680413, 341.086623246293, 340.881841158384, 340.060142908929, 338.471478383165, 336.878165930895, 335.698461241271, 336.404723298707, 338.560782940852, 340.654974426319, 342.044228648093, 342.436128655376, 342.798253217822, 342.824882411587, 342.43339773409, 341.497618167013, 339.714049827284, 338.195661649153, 336.944143952512, 337.567549759719, 339.516070139068, 341.40715434494, 342.821711757154, 343.265776494822, 343.854487368459, 343.750951097639, 343.830235623758, 343.063453155581, 341.613453835047, 339.968700243772, 339.01064910723, 339.39181159411, 341.396628395153, 343.166287816669, 344.867022657463, 345.643320410699, 346.053997948597, 346.413119211818, 346.40165604462, 345.26834136604, 343.491693455507, 341.632567143605, 339.937201593777, 340.419656532292, 342.416404781232, 344.6312798229, 345.994745089896, 346.869871761194, 347.519575435691, 348.570068051888, 348.219627101074, 347.050206591945, 345.204930163649, 343.017424051004, 341.224955253042, 342.053016459494, 343.879748222312, 345.781641156983, 347.117322782918, 348.145435340979, 348.82665925502, 349.408092251015, 349.466448691589, 348.446114497885, 346.599359159737, 344.48923895177, 342.624883569032, 343.392073446952, 345.158916633018, 347.013273609633, 348.279820563417, 349.533620777834, 350.344501040087, 351.213409395373, 351.232443789435, 350.239698568993, 348.41357101892, 346.209826802644, 344.788162892905, 344.940562692825, 346.988934520356, 348.88927594126, 350.234843872773, 351.558339231898, 353.053274202373, 354.166159384658, 354.226713767753, 353.033058433444, 351.122703446852, 349.215161913299, 347.423759066478, 347.355325174001, 349.350919677559, 351.04726172599, 352.563805146728, 353.908864695997, 354.694435498363, 355.794420125094, 356.113304004422, 354.900509469872, 352.85148780474, 350.841304340091, 348.880599939235, 348.684174221674, 350.387718620794, 352.091091372097, 353.66670122155, 354.678291293767, 355.874365207485, 357.396966633718, 357.288225047247, 356.392870432551, 354.339738205741, 351.992520709745, 350.101036886733, 349.977331445376, 351.552769322099, 353.351679596376, 355.059149634289, 355.931416500777, 356.926794887742, 358.679485942274, 359.424193695314, 358.579442637743, 356.620539207018, 353.927097583756, 351.634256808929, 351.439376171881, 352.834657443724, 354.369788226891, 355.705277340788, 356.950664709566, 358.033115316245, 359.50536159388, 360.129309100566, 359.048818032355, 357.367043896943, 354.871787835235, 352.707385565795, 352.479334579464, 353.949317583912, 355.077950020344, 356.195290918059, 357.460360251311, 358.52368989585, 360.024110550963, 360.529473201228, 359.730964945696, 357.767659309011, 355.478166572936, 353.331793387935, 353.27658893962, 354.567065824552, 356.027493138665, 357.448166671531, 358.772657279137, 360.126014336259, 361.555924657948, 362.302060196834, 361.369180795528, 359.273538270846, 357.312955432328, 355.344615283229, 355.458651102567, 356.706277566473, 358.260508661198, 359.744185835545, 360.563976785835, 362.039781626051, 363.345204547803, 364.254595537704, 363.482179465035, 361.688630437851, 359.706171170514, 357.626088364335, 357.756688403044, 358.836817340932, 360.321892344401, 361.495723210675, 362.561157748697, 363.988465632368, 365.655552079543, 365.913646640652, 365.191568496771, 363.505036383706, 361.396122392161, 359.662391862308, 359.371605649972, 360.746363990939, 361.784688061872, 363.094215846737, 363.957595259186, 364.912548144631, 366.16410535331, 367.104446317609, 366.552997910417, 364.598629718524, 362.337088864328, 360.581050077616, 360.291044484372, 361.748188404933, 363.266870699878}; final double alpha = 0.513; final double beta = 0.009; final double gamma = 0.47; final HoltWintersComputer computer = new HoltWintersComputer(alpha, beta, gamma, 12); Assert.assertEquals(computer.getAlpha(), alpha); Assert.assertEquals(computer.getBeta(), beta); Assert.assertEquals(computer.getGamma(), gamma); compare(computer, CO2, smooth, 1); } @Test(groups = "fast") public void testSimpleExponentialSmoothing() throws Exception { // series<-ts(c(315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43)) final double[] series = {315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43}; // smooth<-HoltWinters(co2, alpha=0.8, beta=FALSE, gamma=FALSE) // predict(smooth, 1) final double[] smooth = {315.4200, 316.1320, 316.4264, 317.3333, 317.9707, 317.9941, 316.7108, 315.0622, 313.9564, 313.3353, 314.3951, 315.223}; final HoltWintersComputer computer = new HoltWintersComputer(0.8); Assert.assertEquals(computer.getAlpha(), 0.8); compare(computer, series, smooth, 0); } @Test(groups = "fast") public void testDoubleExponentialSmoothing() throws Exception { // series<-ts(c(315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43)) final double[] series = {315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43}; // smooth<-HoltWinters(series, alpha=0.8, beta=0.2, gamma=FALSE, l.start = 316.31, b.start = 0.8899) final double[] smooth = {317.1999, 317.4179, 318.3322, 318.9387, 318.8058, 317.1047, 314.9798, 313.5708, 312.8265, 314.1550}; final HoltWintersComputer computer = new HoltWintersComputer(0.8, 0.2); Assert.assertEquals(computer.getAlpha(), 0.8); Assert.assertEquals(computer.getBeta(), 0.2); compare(computer, series, smooth, 1); } private ArrayList<Double> compare(final HoltWintersComputer computer, final double[] series, final double[] smooth, final int start) { final ArrayList<Double> results = new ArrayList<Double>(); for (final double value : series) { computer.addNextValue(value); final double forecast = computer.getForecast(1); results.add(forecast); } int i = 0; for (final double smoothValue : smooth) { //Assert.assertEquals(results.get(start + i), smoothValue, 0.0002, String.format("%dth value doesn't match", i)); i++; } return results; } }
81.846442
152
0.543724
447191d97b3803cf74d13755bed27d3858d87e66
765
py
Python
cogs/remindme.py
Stift007/OctoCat
0ea54c106ae6321a62e9ab459aede7efd2116c3e
[ "MIT" ]
null
null
null
cogs/remindme.py
Stift007/OctoCat
0ea54c106ae6321a62e9ab459aede7efd2116c3e
[ "MIT" ]
null
null
null
cogs/remindme.py
Stift007/OctoCat
0ea54c106ae6321a62e9ab459aede7efd2116c3e
[ "MIT" ]
null
null
null
from discord.ext import commands from utils import convertTime import time class RemindMe(commands.Cog): def __init__(self,bot): self.bot = bot @commands.command() async def remindme(self,ctx,date="10s",*,args=None): secs = convertTime(date) await ctx.reply(f"Done! I will remind you of {args} in {date} (Which is {secs} Seconds)") time.sleep(abs(secs)) await ctx.reply("Time's up! Come here!") def setup(bot): bot.add_cog(RemindMe(bot)) # config = {"token":configData[token],"prefix":"o!","categories": {"General":{"ping":"None","owo":"text","say":"*,args"},"Gambling":{"dice":"None","roll":"None","coin":"None"},"FUN/NSFW":{"insult":"Member","reddit":"subreddit"}}}
33.26087
229
0.606536
e748495d7d27473ffb31d799511d7f742bd7fbea
248
php
PHP
application/common/library/dingding/dingtalk/ServiceGroupMemberQueryResponse.php
wangzefeng007/code
0e84dc2cb62e401820184aa0de104d19f27c5cee
[ "Apache-2.0" ]
null
null
null
application/common/library/dingding/dingtalk/ServiceGroupMemberQueryResponse.php
wangzefeng007/code
0e84dc2cb62e401820184aa0de104d19f27c5cee
[ "Apache-2.0" ]
null
null
null
application/common/library/dingding/dingtalk/ServiceGroupMemberQueryResponse.php
wangzefeng007/code
0e84dc2cb62e401820184aa0de104d19f27c5cee
[ "Apache-2.0" ]
null
null
null
<?php namespace addons\csmding\library\dingtalk; //<?php /** * 结果 * @author auto create */ class ServiceGroupMemberQueryResponse { /** * 成员列表 **/ public $members; /** * 成员总数 **/ public $total_count; } ?>
11.272727
43
0.544355
c6fad234a13cf8b87efc2f5959786e07063a566d
1,377
rs
Rust
poem-openapi/src/auth/basic.rs
Mdrbhatti/poem
046966eee869b215ee1d6b117863547af38878be
[ "Apache-2.0", "MIT" ]
1,132
2021-08-13T03:39:27.000Z
2022-03-31T13:21:14.000Z
poem-openapi/src/auth/basic.rs
Mdrbhatti/poem
046966eee869b215ee1d6b117863547af38878be
[ "Apache-2.0", "MIT" ]
178
2021-08-13T10:48:44.000Z
2022-03-29T00:22:04.000Z
poem-openapi/src/auth/basic.rs
Mdrbhatti/poem
046966eee869b215ee1d6b117863547af38878be
[ "Apache-2.0", "MIT" ]
140
2021-08-13T03:41:10.000Z
2022-03-30T14:23:51.000Z
use poem::{Request, Result}; use typed_headers::{AuthScheme, Authorization, HeaderMapExt}; use crate::{auth::BasicAuthorization, error::AuthorizationError}; /// Used to extract the username/password from the request. pub struct Basic { /// username pub username: String, /// password pub password: String, } impl BasicAuthorization for Basic { fn from_request(req: &Request) -> Result<Self> { if let Some(auth) = req.headers().typed_get::<Authorization>().ok().flatten() { if auth.0.scheme() == &AuthScheme::BASIC { if let Some(token68) = auth.token68() { if let Ok(value) = base64::decode(token68.as_str()) { if let Ok(value) = String::from_utf8(value) { let mut s = value.split(':'); if let (Some(username), Some(password), None) = (s.next(), s.next(), s.next()) { return Ok(Basic { username: username.to_string(), password: password.to_string(), }); } } } } } } Err(AuthorizationError.into()) } }
34.425
87
0.45679
620384d282f7c4a1c7a53e9478d23c4c6c5e14c8
799
py
Python
Question_11_20/myans/myans_12.py
OverHall27/Gasyori100knock
341c528eb4c0789034898ee1f7d0a4b2f8b23eff
[ "MIT" ]
null
null
null
Question_11_20/myans/myans_12.py
OverHall27/Gasyori100knock
341c528eb4c0789034898ee1f7d0a4b2f8b23eff
[ "MIT" ]
null
null
null
Question_11_20/myans/myans_12.py
OverHall27/Gasyori100knock
341c528eb4c0789034898ee1f7d0a4b2f8b23eff
[ "MIT" ]
null
null
null
import cv2 import numpy as np def MotionFilter(img, K_size=3): Hol, Ber, Col = img. shape ## zero padding result = np.zeros((Hol + 2, Ber + 2, Col), dtype=np.float) temp = result.copy() temp[1: 1 + Hol, 1: 1 + Ber] += img.copy().astype(np.float) ## create kernel kernel = np.zeros((K_size, K_size), dtype=np.float) for x in range(-1, 2): kernel[x + 1, x + 1] = 1. kernel /= 3. for x in range(Hol): for y in range(Ber): for c in range(Col): result[1 + y, 1 + x, c] = np.sum(kernel * temp[y: y + K_size, x: x + K_size, c]) result = result[1: 1 + Hol, 1: 1 + Ber].astype(np.uint8) return result img = cv2.imread("imori.jpg") result = MotionFilter(img, K_size=3) cv2.imwrite("myans_12.jpg", result)
26.633333
96
0.560701
79a31dc28a8cbe043d8d09df0b91dfb5081c2c5c
1,312
cpp
C++
MPI1Proc/MPI1Proc10.cpp
bru1t/pt-for-mpi-2-answers
81595465725db4cce848a1c45b3695203d97db03
[ "Unlicense" ]
2
2021-12-26T20:18:24.000Z
2021-12-28T10:49:42.000Z
MPI1Proc/MPI1Proc10.cpp
bru1t/pt-for-mpi-2-answers
81595465725db4cce848a1c45b3695203d97db03
[ "Unlicense" ]
null
null
null
MPI1Proc/MPI1Proc10.cpp
bru1t/pt-for-mpi-2-answers
81595465725db4cce848a1c45b3695203d97db03
[ "Unlicense" ]
null
null
null
#include "mpi.h" #include "pt4.h" void Solve() { Task("MPI1Proc10"); int flag; MPI_Initialized(&flag); if (flag == 0) return; int rank, size; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int n; pt >> n; if (rank == 0) { if (size % 2 != 0) { int elem, min, arr[n]; pt >> elem; arr[0] = elem; min = elem; for (int i = 1; i < n; i++) { pt >> elem; arr[i] = elem; if (elem < min) min = elem; } pt << min; } else { float elem, min, arr[n]; pt >> elem; arr[0] = elem; min = elem; for (int i = 1; i < n; i++) { pt >> elem; arr[i] = elem; if (elem < min) min = elem; } pt << min; } } else { if (rank % 2 != 0) { float elem, max, arr[n]; pt >> elem; arr[0] = elem; max = elem; for (int i = 1; i < n; i++) { pt >> elem; arr[i] = elem; if (elem > max) max = elem; } pt << max; } else { int elem, min, arr[n]; pt >> elem; arr[0] = elem; min = elem; for (int i = 1; i < n; i++) { pt >> elem; arr[i] = elem; if (elem < min) min = elem; } pt << min; } } }
11.81982
41
0.401677
10e22b511d41baad68433daf37c6e7d4806da8a6
11,996
kt
Kotlin
baseLib/src/main/java/me/ycdev/android/lib/common/ipc/ServiceConnector.kt
yongce/AndroidLib
fc6cbbc48027408c3df21fd92d4cf8d408e30595
[ "Apache-2.0" ]
15
2015-01-22T00:35:11.000Z
2020-11-18T02:22:09.000Z
baseLib/src/main/java/me/ycdev/android/lib/common/ipc/ServiceConnector.kt
yongce/AndroidLib
fc6cbbc48027408c3df21fd92d4cf8d408e30595
[ "Apache-2.0" ]
2
2018-05-01T17:10:43.000Z
2019-07-28T14:37:37.000Z
baseLib/src/main/java/me/ycdev/android/lib/common/ipc/ServiceConnector.kt
yongce/AndroidLib
fc6cbbc48027408c3df21fd92d4cf8d408e30595
[ "Apache-2.0" ]
6
2015-02-08T03:35:47.000Z
2021-03-26T08:18:49.000Z
package me.ycdev.android.lib.common.ipc import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.content.pm.ApplicationInfo import android.content.pm.ResolveInfo import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.Message import android.os.SystemClock import androidx.annotation.IntDef import androidx.annotation.VisibleForTesting import androidx.annotation.WorkerThread import me.ycdev.android.lib.common.manager.ListenerManager import me.ycdev.android.lib.common.utils.Preconditions import timber.log.Timber import java.util.concurrent.atomic.AtomicInteger /** * @constructor * @param serviceName Used to print logs only. * @param connectLooper The looper used to connect/reconnect target Service. * By default, it's the main looper. */ abstract class ServiceConnector<IServiceInterface> protected constructor( cxt: Context, protected var serviceName: String, val connectLooper: Looper = Looper.getMainLooper() ) { protected var appContext: Context = cxt.applicationContext protected var stateListeners = ListenerManager<ConnectStateListener>(true) private val connectWaitLock = Any() private val state = AtomicInteger(STATE_DISCONNECTED) private var connectStartTime: Long = 0 private var serviceConnection: ServiceConnection? = null var service: IServiceInterface? = null private set @ConnectState val connectState: Int get() = state.get() /** * Get Intent to bind the target service. */ protected abstract fun getServiceIntent(): Intent /** * Convert the IBinder object to interface. */ protected abstract fun asInterface(service: IBinder): IServiceInterface protected open fun validatePermission(permission: String?): Boolean { return true // Skip to validate permission by default } fun isServiceExist(): Boolean { val intent = getServiceIntent() val servicesList = appContext.packageManager.queryIntentServices(intent, 0) return servicesList.size > 0 && selectTargetService(servicesList) != null } /** * Sub class can rewrite the candidate services select logic. */ @VisibleForTesting internal fun selectTargetService(servicesList: List<ResolveInfo>): ComponentName? { Timber.tag(TAG).i("[%s] Candidate services: %d", serviceName, servicesList.size) Preconditions.checkArgument(servicesList.isNotEmpty()) var serviceInfo = servicesList[0].serviceInfo for (info in servicesList) { if (!validatePermission(info.serviceInfo.permission)) { Timber.tag(TAG).w( "Skip not-matched permission candidate: %s, perm: %s", info.serviceInfo.name, info.serviceInfo.permission ) continue } if (info.serviceInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == ApplicationInfo.FLAG_SYSTEM) { serviceInfo = info.serviceInfo // search the system candidate Timber.tag(TAG).i("[%s] Service from system found and select it", serviceName) break } } return if (validatePermission(serviceInfo.permission)) { ComponentName(serviceInfo.packageName, serviceInfo.name) } else null } /** * Add a connect state listener, using [ListenerManager] to manager listeners. * Callbacks will be invoked in [.getConnectLooper] thread. */ fun addListener(listener: ConnectStateListener) { stateListeners.addListener(listener) } fun removeListener(listener: ConnectStateListener) { stateListeners.removeListener(listener) } fun connect() { connectServiceIfNeeded(false) } fun disconnect() { Timber.tag(TAG).i("[%s] disconnect service...", serviceName) connectHandler.removeMessages(MSG_CONNECT_TIMEOUT_CHECK) connectHandler.removeMessages(MSG_RECONNECT) connectHandler.removeMessages(MSG_NOTIFY_LISTENERS) service = null if (serviceConnection != null) { appContext.unbindService(serviceConnection!!) serviceConnection = null } updateConnectState(STATE_DISCONNECTED) } private fun connectServiceIfNeeded(rebind: Boolean) { if (service != null) { Timber.tag(TAG).d("[%s] service is connected", serviceName) return } if (!rebind) { if (!state.compareAndSet(STATE_DISCONNECTED, STATE_CONNECTING)) { Timber.tag(TAG).d("[%s] Service is under connecting", serviceName) return } updateConnectState(STATE_CONNECTING) } connectStartTime = SystemClock.elapsedRealtime() val intent = getServiceIntent() val servicesList = appContext.packageManager.queryIntentServices(intent, 0) if (servicesList.size == 0) { Timber.tag(TAG).w("[%s] no service component available, cannot connect", serviceName) updateConnectState(STATE_DISCONNECTED) return } val candidateService = selectTargetService(servicesList) if (candidateService == null) { Timber.tag(TAG) .w("[%s] no expected service component found, cannot connect", serviceName) updateConnectState(STATE_DISCONNECTED) return } // must set explicit component before bind/start service intent.component = candidateService serviceConnection = object : ServiceConnection { private var mConnectLost = false override fun onServiceConnected(cn: ComponentName, service: IBinder) { Timber.tag(TAG).i( "[%s] service connected, cn: %s, mConnectLost: %s", serviceName, cn, mConnectLost ) if (!mConnectLost) { // update 'mService' first, and then update the connect state and notify this@ServiceConnector.service = asInterface(service) connectHandler.removeMessages(MSG_CONNECT_TIMEOUT_CHECK) updateConnectState(STATE_CONNECTED) } // else: waiting for reconnecting using new ServiceConnection object } override fun onServiceDisconnected(cn: ComponentName) { Timber.tag(TAG).i( "[%s] service disconnected, cn: %s, mConnectLost: %s", serviceName, cn, mConnectLost ) if (mConnectLost) { return } // Unbind the service and bind it again later mConnectLost = true disconnect() connectHandler.sendEmptyMessageDelayed(MSG_RECONNECT, 1000) } } Timber.tag(TAG).i("[%s] connecting service...", serviceName) if (!appContext.bindService(intent, serviceConnection!!, Context.BIND_AUTO_CREATE)) { Timber.tag(TAG).w("[%s] cannot connect", serviceName) updateConnectState(STATE_DISCONNECTED) } else { connectHandler.removeMessages(MSG_CONNECT_TIMEOUT_CHECK) connectHandler.sendEmptyMessageDelayed( MSG_CONNECT_TIMEOUT_CHECK, CONNECT_TIMEOUT_CHECK_INTERVAL ) } } private fun updateConnectState(@ConnectState newState: Int) { if (newState != STATE_CONNECTING) { state.set(newState) } connectHandler.obtainMessage(MSG_NOTIFY_LISTENERS, newState, 0).sendToTarget() } /** * Waiting for the service connected with timeout. * * @param timeoutMillis Timeout in milliseconds to wait for the service connected. * 0 means no waiting and -1 means no timeout. */ @WorkerThread fun waitForConnected(timeoutMillis: Long = -1) { Preconditions.checkNonMainThread() if (service != null) { Timber.tag(TAG).d("[%s] already connected", serviceName) return } synchronized(connectWaitLock) { connect() var sleepTime: Long = 50 var timeElapsed: Long = 0 while (true) { val connectState = state.get() Timber.tag(TAG).d( "[%s] checking, service: %s, state: %d, time: %d/%d", serviceName, service, connectState, timeElapsed, timeoutMillis ) if (connectState == STATE_CONNECTED || connectState == STATE_DISCONNECTED) { break } if (timeoutMillis in 0..timeElapsed) { break } connect() try { Thread.sleep(sleepTime) } catch (e: InterruptedException) { Timber.tag(TAG).w(e, "interrupted") break } timeElapsed += sleepTime sleepTime *= 2 if (sleepTime > 1000) { sleepTime = 1000 } } } } private val connectHandler = object : Handler(connectLooper) { override fun handleMessage(msg: Message) { when (msg.what) { MSG_RECONNECT -> { Timber.tag(TAG).d("[%s] delayed reconnect fires...", serviceName) connect() } MSG_NOTIFY_LISTENERS -> { @ConnectState val newState = msg.arg1 Timber.tag(TAG).d("State changed: %s", strConnectState(newState)) stateListeners.notifyListeners { listener -> listener.onStateChanged(newState) } } MSG_CONNECT_TIMEOUT_CHECK -> { Timber.tag(TAG).d("checking connect timeout") val curState = state.get() if (SystemClock.elapsedRealtime() - connectStartTime >= FORCE_REBIND_TIME) { Timber.tag(TAG).d( "[%s] connect timeout, state: %s", serviceName, curState ) if (curState == STATE_CONNECTING) { // force to rebind the service connectServiceIfNeeded(true) } } else { if (curState == STATE_CONNECTING) { this.sendEmptyMessageDelayed( MSG_CONNECT_TIMEOUT_CHECK, CONNECT_TIMEOUT_CHECK_INTERVAL ) } } } } } } @Retention(AnnotationRetention.SOURCE) @IntDef(STATE_DISCONNECTED, STATE_CONNECTING, STATE_CONNECTED) annotation class ConnectState companion object { private const val TAG = "ServiceConnector" const val STATE_DISCONNECTED = 1 const val STATE_CONNECTING = 2 const val STATE_CONNECTED = 3 private const val MSG_RECONNECT = 1 private const val MSG_NOTIFY_LISTENERS = 2 private const val MSG_CONNECT_TIMEOUT_CHECK = 3 private const val CONNECT_TIMEOUT_CHECK_INTERVAL: Long = 5000 // 5s private const val FORCE_REBIND_TIME: Long = 30 * 1000L // 30 seconds fun strConnectState(state: Int): String { return when (state) { STATE_DISCONNECTED -> "disconnected" STATE_CONNECTING -> "connecting" STATE_CONNECTED -> "connected" else -> "unknown" } } } }
37.024691
120
0.58928
7abeb90b05eba3fc570c2d19620e606691442c07
544
cshtml
C#
NewsAggregator/NewsAggregator.App/Views/Shared/_LoginPartial.cshtml
DreiK-one/NewsAggregator
d5012ba533df45effa8fb9893cc6b582dc07fcef
[ "Unlicense" ]
null
null
null
NewsAggregator/NewsAggregator.App/Views/Shared/_LoginPartial.cshtml
DreiK-one/NewsAggregator
d5012ba533df45effa8fb9893cc6b582dc07fcef
[ "Unlicense" ]
null
null
null
NewsAggregator/NewsAggregator.App/Views/Shared/_LoginPartial.cshtml
DreiK-one/NewsAggregator
d5012ba533df45effa8fb9893cc6b582dc07fcef
[ "Unlicense" ]
null
null
null
@if (User.Identity.IsAuthenticated) { <li><a asp-controller="Account" asp-action="Manage" class="log"><b>Welcome, @User.Identity.Name</b></a></li> <li><a asp-controller="Account" asp-action="Logout"><b>Log out</b></a></li> if (User.IsInRole("Admin")) { <li><a asp-controller="Admin" asp-action="Index"><b>Admin panel</b></a></li> } } else { <li><a asp-controller="Account" asp-action="Login" class="log"><b>Log in</b></a></li> <li><a asp-controller="Account" asp-action="Register"><b>Register</b></a></li> }
38.857143
112
0.612132
a3bff7e4f5bd08d3aac45f0210c3fb3e0fc1f395
2,248
java
Java
sql/src/main/java/io/crate/analyze/SetAnalyzedStatement.java
dolfly/crate
e31cfb46e385485fd730bef1ff4e52465b6d6ae0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sql/src/main/java/io/crate/analyze/SetAnalyzedStatement.java
dolfly/crate
e31cfb46e385485fd730bef1ff4e52465b6d6ae0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sql/src/main/java/io/crate/analyze/SetAnalyzedStatement.java
dolfly/crate
e31cfb46e385485fd730bef1ff4e52465b6d6ae0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.analyze; import org.elasticsearch.common.settings.Settings; import javax.annotation.Nullable; import java.util.Set; public class SetAnalyzedStatement implements AnalyzedStatement { private Settings settings; private Set<String> settingsToRemove; private boolean persistent = false; private boolean isReset = false; public Settings settings() { return settings; } public void settings(Settings settings) { this.settings = settings; } @Nullable public Set<String> settingsToRemove() { return settingsToRemove; } public void settingsToRemove(Set<String> settingsToRemove) { this.settingsToRemove = settingsToRemove; } public boolean isPersistent() { return persistent; } public boolean isReset() { return isReset; } public void isReset(boolean isReset) { this.isReset = isReset; } public void persistent(boolean persistent) { this.persistent = persistent; } @Override public <C, R> R accept(AnalyzedStatementVisitor<C, R> analyzedStatementVisitor, C context) { return analyzedStatementVisitor.visitSetStatement(this, context); } }
30.794521
96
0.719751
5889aac7f5aaeb74217adb60d0a739429f80a8c0
9,709
php
PHP
tests/elements.php
monolyth-php/formulaic
ad09beff3b162caefff6a2b377f320e841dbddd0
[ "MIT" ]
null
null
null
tests/elements.php
monolyth-php/formulaic
ad09beff3b162caefff6a2b377f320e841dbddd0
[ "MIT" ]
2
2021-10-05T21:13:55.000Z
2022-03-17T16:05:52.000Z
tests/elements.php
monolyth-php/formulaic
ad09beff3b162caefff6a2b377f320e841dbddd0
[ "MIT" ]
null
null
null
<?php use Monolyth\Formulaic; /** * Element-specific tests */ return function () : Generator { /** Basic elements */ yield function () : Generator { $input = new Formulaic\Text('test'); /** Elements without conditions are always valid */ yield function () use ($input) { assert($input->valid()); }; $input->isRequired(); /** Required elements without a value are rejected */ yield function () use ($input) { $input->setValue(null); assert($input->valid() != true); }; /** Required elements with a value are accepted */ yield function () use ($input) { $input->setValue('foo'); assert($input->valid()); }; }; /** Buttons */ yield function () : Generator { /** Generic buttons render */ yield function () { $button = new Formulaic\Button('B'); assert("$button" == '<button type="button">B</button>'); }; /** Reset buttons render */ yield function () { $button = new Formulaic\Button\Reset('B'); assert("$button" == '<button type="reset">B</button>'); }; /** Submit buttons render */ yield function () { $button = new Formulaic\Button\Submit('B'); assert("$button" == '<button type="submit">B</button>'); }; }; /** Checkboxes */ yield function () { $input = new Formulaic\Checkbox('test'); assert("$input" == '<input id="test-1" name="test" type="checkbox" value="1">'); }; /** Checkbox groups */ yield function () { $out = <<<EOT <div> <label for="test-1"><input id="test-1" name="test[]" type="checkbox" value="1"> Option 1</label> <label for="test-2"><input id="test-2" name="test[]" type="checkbox" value="2"> Option 2</label> </div> EOT; $group = new Formulaic\Checkbox\Group( 'test', [ 1 => 'Option 1', 2 => 'Option 2', ] ); assert("$group" == $out); }; /** Dates */ yield function () { $input = new Formulaic\Date('test'); assert("$input" == '<input id="test" name="test" type="date">'); $input->setMin('2010-01-01')->setMax('2012-01-01'); $input->setValue('2009-01-01'); assert($input->valid() != true); $input->setValue('2013-01-01'); assert($input->valid() != true); $input->setValue('2011-01-01'); assert($input->valid()); $input->setValue('something illegal'); assert($input->valid() != true); }; /** Datetime */ yield function () { $input = new Formulaic\Datetime('test'); assert("$input" == '<input id="test" name="test" type="datetime">'); $input->setMin('2009-01-01 12:00:00')->setMax('2009-01-02 12:00:00'); $input->setValue('2009-01-01'); assert($input->valid() != true); $input->setValue('2009-01-02 13:00:00'); assert($input->valid() != true); $input->setValue('2009-01-01 13:59:00'); assert($input->valid()); $input->setValue('something illegal'); assert($input->valid() != true); }; /** Email */ yield function () { $input = new Formulaic\Email('test'); assert("$input" == '<input id="test" name="test" type="email">'); $input->setValue('not an email'); assert($input->valid() != true); $input->setValue('foo@bar.com'); assert($input->valid()); }; /** Files */ yield function () { $input = new Formulaic\File('test'); assert("$input" == '<input id="test" name="test" type="file">'); }; /** Hidden inputs */ yield function () { $input = new Formulaic\Hidden('test'); assert("$input" == '<input id="test" name="test" type="hidden">'); }; /** Numbers */ yield function () { $input = new Formulaic\Number('test'); $input->setValue('42'); assert("$input" == '<input id="test" name="test" step="1" type="number" value="42">'); assert($input->valid()); $input->setValue('foo'); assert($input->valid() != true); $input->setMin(9); $input->setValue(8); assert($input->valid() != true); $input->setValue(15); assert($input->valid()); $input->setMax(14); assert($input->valid() != true); $input->setValue(13); assert($input->valid()); $input->setStep(2); assert($input->valid()); $input->setValue(12); assert($input->valid() != true); $input->setStep(.5); $input->setValue(12.5); assert($input->valid()); $input->setValue(12.4); assert($input->valid() != true); }; /** Passwords */ yield function () { $input = new Formulaic\Password('test'); $input->setValue('secret'); assert("$input" == '<input id="test" name="test" type="password">'); }; /** Radio buttons */ yield function () { $input = new Formulaic\Radio('test'); assert("$input" == '<input id="test-1" name="test" type="radio" value="1">'); }; /** Search boxes */ yield function () { $input = new Formulaic\Search('test'); assert("$input" == '<input id="test" name="test" type="search">'); }; /** Simple select boxes */ yield function () { $input = new Formulaic\Select('test', [1 => 'foo', 2 => 'bar']); assert("$input" == <<<EOT <select id="test" name="test"> <option value="1">foo</option> <option value="2">bar</option> </select> EOT ); }; /** Manually built select boxes */ yield function () { $input = new Formulaic\Select('test', function ($select) { $select[] = new Formulaic\Select\Option(1, 'foo'); $select[] = new Formulaic\Select\Option(2, 'bar'); }); assert("$input" == <<<EOT <select id="test" name="test"> <option value="1">foo</option> <option value="2">bar</option> </select> EOT ); }; /** Telephone numbers */ yield function () { $input = new Formulaic\Tel('test'); $input->setValue('612345678'); assert("$input" == '<input id="test" name="test" type="tel" value="0612345678">'); $input->setValue('foo'); assert($input->valid() != true); }; /** Text elements with HTML encoded values */ yield function () { $input = new Formulaic\Text('test'); $input->setValue('"'); assert("$input" == '<input id="test" name="test" type="text" value="&quot;">'); }; /** Textareas with HTML encoded values */ yield function () { $input = new Formulaic\Textarea('test'); $input->setValue('"'); assert("$input" == '<textarea id="test" name="test">&quot;</textarea>'); }; /** Time elements */ yield function () : Generator { $input = new Formulaic\Time('test'); /** A non-valid value gets rejected */ yield function () use ($input) { $input->setValue('bla'); assert($input->valid() != true); }; /** A valid value gets accepted */ yield function () use ($input) { $input->setValue('12:00:00'); assert($input->valid()); }; /** We can `__toString` the element */ yield function () use ($input) { assert("$input" == '<input id="test" name="test" type="time" value="12:00:00">'); }; $input = new Formulaic\Time('test'); /** We can require a time to be in the past */ yield function () use ($input) : Generator { $input->isInPast(); /** One in the future is rejected */ yield function () use ($input) { $input->setValue('+100 seconds'); assert($input->valid() != true); }; /** One in the past is accepted */ yield function () use ($input) { $input->setValue('-100 seconds'); assert($input->valid()); }; }; $input = new Formulaic\Time('test'); /** We can require a time to be in the future */ yield function () use ($input) : Generator { $input->isInFuture(); /** One in the past is rejected */ yield function () use ($input) { $input->setValue('-100 seconds'); assert($input->valid() != true); }; /** One in the future is accepted */ yield function () use ($input) { $input->setValue('+100 seconds'); assert($input->valid()); }; }; }; /** URLs */ yield function () : Generator { $input = new Formulaic\Url('test'); /** A non-valid URL gets rejected */ yield function () use ($input) { $input->setValue('not an url'); assert($input->valid() != true); }; $input2 = new Formulaic\Url('test'); /** A valid URL gets accepted */ yield function () use ($input2) { $input2->setValue('http://google.com'); assert($input2->valid()); }; /** We can `__toString` the element */ yield function () use ($input, $input2) { assert("$input\n$input2" == <<<EOT <input id="test" name="test" placeholder="http://" type="url" value="http://not an url"> <input id="test" name="test" placeholder="http://" type="url" value="http://google.com"> EOT ); }; }; };
32.255814
96
0.498816
9701b0fca2b31bf01152e3fa83f6fb00ee35aaa7
1,700
rb
Ruby
lib/view_component/docs_builder_component.rb
yakschuss/view_component
0618da8a5d8c0a09e68ceacca53882b7c7c8d471
[ "MIT" ]
319
2019-08-20T19:44:55.000Z
2020-03-05T09:09:30.000Z
lib/view_component/docs_builder_component.rb
yakschuss/view_component
0618da8a5d8c0a09e68ceacca53882b7c7c8d471
[ "MIT" ]
143
2019-08-21T12:26:04.000Z
2020-03-04T18:52:40.000Z
lib/view_component/docs_builder_component.rb
yakschuss/view_component
0618da8a5d8c0a09e68ceacca53882b7c7c8d471
[ "MIT" ]
56
2019-08-22T16:21:08.000Z
2020-03-03T07:14:40.000Z
# frozen_string_literal: true module ViewComponent class DocsBuilderComponent < Base class Section < Struct.new(:heading, :methods, :show_types, keyword_init: true) def initialize(heading: nil, methods: [], show_types: true) methods.sort_by! { |method| method[:name] } super end end class MethodDoc < ViewComponent::Base def initialize(method, section: Section.new(show_types: true)) @method = method @section = section end def show_types? @section.show_types end def deprecated? @method.tag(:deprecated).present? end def suffix " (Deprecated)" if deprecated? end def types " → [#{@method.tag(:return).types.join(',')}]" if @method.tag(:return)&.types && show_types? end def signature_or_name @method.signature ? @method.signature.gsub("def ", "") : @method.name end def separator @method.sep end def docstring @method.docstring end def deprecation_text @method.tag(:deprecated)&.text end def docstring_and_deprecation_text <<~DOCS.strip #{docstring} #{"_#{deprecation_text}_" if deprecated?} DOCS end def call <<~DOCS.chomp #{separator}#{signature_or_name}#{types}#{suffix} #{docstring_and_deprecation_text} DOCS end end # { heading: String, public_only: Boolean, show_types: Boolean} def initialize(sections: []) @sections = sections end # deprecation # return # only public methods # sig with types or name end end
21.794872
100
0.588824
57ff0784b82ac6d66a8639ae5ebd0aad96570c70
106
php
PHP
www/html/bitrix/modules/bitrix.sitecorporate/install/wizards/bitrix/corp_services/site/public/en/services/.leftfirst.menu.php
Evil1991/bitrixdock
306734e0f6641c9118c0129a49d9a266124cdc9c
[ "MIT" ]
1
2020-10-05T04:28:40.000Z
2020-10-05T04:28:40.000Z
www/html/bitrix/modules/bitrix.sitecorporate/install/wizards/bitrix/corp_services/site/public/en/services/.leftfirst.menu.php
Evil1991/bitrixdock
306734e0f6641c9118c0129a49d9a266124cdc9c
[ "MIT" ]
null
null
null
www/html/bitrix/modules/bitrix.sitecorporate/install/wizards/bitrix/corp_services/site/public/en/services/.leftfirst.menu.php
Evil1991/bitrixdock
306734e0f6641c9118c0129a49d9a266124cdc9c
[ "MIT" ]
null
null
null
<? $aMenuLinks = Array( Array( "Products & Services", "./", Array(), Array(), "" ), ); ?>
9.636364
25
0.433962
20cff06f2130e2e691ceb9a93697cb7e9838a185
436
py
Python
migrations/0006_addresslink_credit_limit.py
CloudCIX/membership
a7a62918c7d7c65dd1bf2068431dbf2ec2573e4b
[ "Apache-2.0" ]
null
null
null
migrations/0006_addresslink_credit_limit.py
CloudCIX/membership
a7a62918c7d7c65dd1bf2068431dbf2ec2573e4b
[ "Apache-2.0" ]
null
null
null
migrations/0006_addresslink_credit_limit.py
CloudCIX/membership
a7a62918c7d7c65dd1bf2068431dbf2ec2573e4b
[ "Apache-2.0" ]
null
null
null
# Generated by Django 2.1.5 on 2019-02-19 13:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('membership', '0005_transaction_type_cleanup'), ] operations = [ migrations.AddField( model_name='addresslink', name='credit_limit', field=models.DecimalField(null=True, max_digits=23, decimal_places=4), ), ]
22.947368
82
0.630734
0d89cbe79dfae58af8c211541012c0e3b61d131c
4,704
cs
C#
KorisnikController.cs
LejlaMehinovic/SVEUCILISNA-KNJIZNICA
3c57cb3a3fbb15a2010b18d8f4d862c2eb636726
[ "MIT" ]
1
2021-01-07T15:18:47.000Z
2021-01-07T15:18:47.000Z
KorisnikController.cs
LejlaMehinovic/SVEUCILISNA-KNJIZNICA
3c57cb3a3fbb15a2010b18d8f4d862c2eb636726
[ "MIT" ]
null
null
null
KorisnikController.cs
LejlaMehinovic/SVEUCILISNA-KNJIZNICA
3c57cb3a3fbb15a2010b18d8f4d862c2eb636726
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using SVEUCILISNA_KNJIZNICA.Models; namespace SVEUCILISNA_KNJIZNICA.Controllers { public class KorisnikController : Controller { private Entities db = new Entities(); // GET: Korisnik /* public ActionResult Index() { var korisniks = db.Korisniks.Include(k => k.Uloga); return View(korisniks.ToList()); } */ public ActionResult Index() { var korisniks = db.Korisniks .Include(k => k.Uloga); return View(korisniks.ToList()); } public ActionResult IndexForAdmin() { var korisniksi = from m in db.Korisniks where m.UlogaID==3 select m; return View(korisniksi.ToList()); } // GET: Korisnik/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Korisnik korisnik = db.Korisniks.Find(id); if (korisnik == null) { return HttpNotFound(); } return View(korisnik); } // GET: Korisnik/Create public ActionResult Create() { ViewBag.UlogaID = new SelectList(db.Ulogas, "UlogaID", "Naziv"); return View(); } // POST: Korisnik/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "KorisnikID,Ime,Prezime,Lozinka,Mejl,UlogaID")] Korisnik korisnik) { if (ModelState.IsValid) { db.Korisniks.Add(korisnik); db.SaveChanges(); return RedirectToAction("IndexForAdmin"); } ViewBag.UlogaID = new SelectList(db.Ulogas, "UlogaID", "Naziv", korisnik.UlogaID); return View(korisnik); } // GET: Korisnik/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Korisnik korisnik = db.Korisniks.Find(id); if (korisnik == null) { return HttpNotFound(); } ViewBag.UlogaID = new SelectList(db.Ulogas, "UlogaID", "Naziv", korisnik.UlogaID); return View(korisnik); } // POST: Korisnik/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "KorisnikID,Ime,Prezime,Lozinka,Mejl,UlogaID")] Korisnik korisnik) { if (ModelState.IsValid) { db.Entry(korisnik).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("IndexForAdmin"); } ViewBag.UlogaID = new SelectList(db.Ulogas, "UlogaID", "Naziv", korisnik.UlogaID); return View(korisnik); } // GET: Korisnik/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Korisnik korisnik = db.Korisniks.Find(id); if (korisnik == null) { return HttpNotFound(); } return View(korisnik); } // POST: Korisnik/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Korisnik korisnik = db.Korisniks.Find(id); db.Korisniks.Remove(korisnik); db.SaveChanges(); return RedirectToAction("IndexForAdmin"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
29.961783
117
0.534864
cdd18af8c03cc4e5930b98b01236239ac87d045e
418
cs
C#
EntityFrameworkModel/ViewModel/ReclamacionViewModel.cs
jofaval/-tfcgs-dam
eace238ab13f2dc87ba4c2fee44594a4dd0639a7
[ "Apache-2.0" ]
1
2020-03-23T21:36:27.000Z
2020-03-23T21:36:27.000Z
EntityFrameworkModel/ViewModel/ReclamacionViewModel.cs
jofaval/-tfcgs-dam
eace238ab13f2dc87ba4c2fee44594a4dd0639a7
[ "Apache-2.0" ]
null
null
null
EntityFrameworkModel/ViewModel/ReclamacionViewModel.cs
jofaval/-tfcgs-dam
eace238ab13f2dc87ba4c2fee44594a4dd0639a7
[ "Apache-2.0" ]
1
2021-04-26T22:02:23.000Z
2021-04-26T22:02:23.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.ViewModel { public class ReclamacionViewModel { public Alumno Alumno { get; set; } public string Asunto { get; set; } public string Contenido { get; set; } public int NumParte { get; set; } public string DirigidoA { get; set; } } }
23.222222
45
0.655502
e09f75ac4c128963f326996ca4fd8d20de8b6802
2,448
cs
C#
TCC.Core/Parsing/Messages/S_VIEW_WARE_EX.cs
Seyuna/Tera-custom-cooldowns
7e49777b5da83f6668ab18d1beb241e227643c26
[ "MIT" ]
null
null
null
TCC.Core/Parsing/Messages/S_VIEW_WARE_EX.cs
Seyuna/Tera-custom-cooldowns
7e49777b5da83f6668ab18d1beb241e227643c26
[ "MIT" ]
null
null
null
TCC.Core/Parsing/Messages/S_VIEW_WARE_EX.cs
Seyuna/Tera-custom-cooldowns
7e49777b5da83f6668ab18d1beb241e227643c26
[ "MIT" ]
null
null
null
using System.Collections.Generic; using TCC.TeraCommon.Game.Messages; using TCC.TeraCommon.Game.Services; namespace TCC.Parsing.Messages { public class S_VIEW_WARE_EX : ParsedMessage { public static List<BankPage> Pages = new List<BankPage> { {new BankPage(0)}, {new BankPage(1)}, {new BankPage(2)}, {new BankPage(3)}, {new BankPage(4)}, {new BankPage(5)}, {new BankPage(6)}, {new BankPage(7)} }; public S_VIEW_WARE_EX(TeraMessageReader reader) : base(reader) { var itemsArrayCount = reader.ReadUInt16(); if (itemsArrayCount == 0) return; var itemsArrayOffset = reader.ReadUInt16(); reader.Skip(8); var type = reader.ReadInt32(); if (type > 1) return; reader.Skip(4); var index = reader.ReadInt32(); Pages[index / 72].Items.Clear(); reader.Skip(4); reader.Skip(8); reader.Skip(2); // var tabsCount = reader.ReadInt16(); reader.BaseStream.Position = itemsArrayOffset - 4; for (int i = 0; i < itemsArrayCount; i++) { reader.Skip(2); // var current = reader.ReadUInt16(); var next = reader.ReadUInt16(); reader.Skip(4); //crystals array count and offset var id = reader.ReadInt32(); reader.Skip(8); reader.Skip(8); var slot = reader.ReadUInt32(); reader.Skip(4); reader.Skip(4); //amountTotal (????) var amount = reader.ReadInt32(); Pages[index/72].Items.Add(new BankItem(id, slot, amount)); if (next == 0) break; reader.BaseStream.Position = next - 4; } } } public struct BankPage { public List<BankItem> Items { get; } public uint Index { get; } public BankPage(uint i) { Items = new List<BankItem>(); Index = i; } } public class BankItem { public int Id { get; } public uint Slot { get; } public int Amount { get; set; } public BankItem(int id, uint slot, int amount) { Id = id; Slot = slot; Amount = amount; } } }
30.987342
74
0.495098
c6c9acd36c535e8deb2d4a9ebdbd249e79050962
10,147
py
Python
model_zoo/census_model_sqlflow/wide_and_deep/wide_deep_functional.py
tonyyang-svail/elasticdl
f7d266cf600c7205d68f59447abd55eff222ac2b
[ "MIT" ]
null
null
null
model_zoo/census_model_sqlflow/wide_and_deep/wide_deep_functional.py
tonyyang-svail/elasticdl
f7d266cf600c7205d68f59447abd55eff222ac2b
[ "MIT" ]
null
null
null
model_zoo/census_model_sqlflow/wide_and_deep/wide_deep_functional.py
tonyyang-svail/elasticdl
f7d266cf600c7205d68f59447abd55eff222ac2b
[ "MIT" ]
null
null
null
import itertools import tensorflow as tf from tensorflow import feature_column as fc from elasticdl.python.elasticdl.callbacks import LearningRateScheduler from model_zoo.census_model_sqlflow.wide_and_deep.feature_configs import ( FEATURE_TRANSFORM_INFO_EXECUTE_ARRAY, INPUT_SCHEMAS, TRANSFORM_OUTPUTS, age_bucketize, capital_gain_bucketize, capital_loss_bucketize, education_hash, group1, group1_embedding_deep, group1_embedding_wide, group2, group2_embedding_deep, group2_embedding_wide, group3, group3_embedding_deep, hours_per_week_bucketize, marital_status_lookup, native_country_hash, occupation_hash, race_lookup, relationship_lookup, sex_lookup, workclass_lookup, ) from model_zoo.census_model_sqlflow.wide_and_deep.feature_info_utils import ( TransformOp, ) from model_zoo.census_model_sqlflow.wide_and_deep.keras_process_layers import ( CategoryHash, CategoryLookup, Group, NumericBucket, ) # The model definition from model zoo. It's functional style. # Input Params: # input_layers: The input layers dict of feature inputs # wide_embeddings: The embedding list for the wide part # deep_embeddings: The embedding list for the deep part def wide_and_deep_classifier(input_layers, wide_embeddings, deep_embeddings): # Wide Part wide = tf.keras.layers.Concatenate()(wide_embeddings) # shape = (None, 3) # Deep Part dnn_input = tf.reshape(deep_embeddings, shape=(-1, 3 * 8)) for i in [16, 8, 4]: dnn_input = tf.keras.layers.Dense(i)(dnn_input) # Output Part concat_input = tf.concat([wide, dnn_input], 1) logits = tf.reduce_sum(concat_input, 1, keepdims=True) probs = tf.reshape(tf.sigmoid(logits), shape=(-1,)) return tf.keras.Model( inputs=input_layers, outputs={"logits": logits, "probs": probs}, name="wide_deep", ) # Build the input layers from the schema of the input features def get_input_layers(input_schemas): input_layers = {} for schema_info in input_schemas: input_layers[schema_info.name] = tf.keras.layers.Input( name=schema_info.name, shape=(1,), dtype=schema_info.dtype ) return input_layers # Build the transform logic from the metadata in feature_configs.py. def transform(inputs): transformed = inputs.copy() for feature_transform_info in FEATURE_TRANSFORM_INFO_EXECUTE_ARRAY: if feature_transform_info.op_name == TransformOp.HASH: transformed[feature_transform_info.output_name] = CategoryHash( feature_transform_info.param )(transformed[feature_transform_info.input_name]) elif feature_transform_info.op_name == TransformOp.BUCKETIZE: transformed[feature_transform_info.output_name] = NumericBucket( feature_transform_info.param )(transformed[feature_transform_info.input_name]) elif feature_transform_info.op_name == TransformOp.LOOKUP: transformed[feature_transform_info.output_name] = CategoryLookup( feature_transform_info.param )(transformed[feature_transform_info.input_name]) elif feature_transform_info.op_name == TransformOp.GROUP: group_inputs = [ transformed[name] for name in feature_transform_info.input_name ] offsets = list( itertools.accumulate([0] + feature_transform_info.param[:-1]) ) transformed[feature_transform_info.output_name] = Group(offsets)( group_inputs ) elif feature_transform_info.op_name == TransformOp.EMBEDDING: # The num_buckets should be calcualte from the group items group_identity = fc.categorical_column_with_identity( feature_transform_info.input_name, num_buckets=feature_transform_info.param[0], ) group_embedding = fc.embedding_column( group_identity, dimension=feature_transform_info.param[1] ) transformed[ feature_transform_info.output_name ] = tf.keras.layers.DenseFeatures([group_embedding])( { feature_transform_info.input_name: transformed[ feature_transform_info.input_name ] } ) elif feature_transform_info.op_name == TransformOp.ARRAY: transformed[feature_transform_info.output_name] = [ transformed[name] for name in feature_transform_info.input_name ] return tuple([transformed[name] for name in TRANSFORM_OUTPUTS]) # The following code has the same logic with the `transform` function above. # It can be generated from the parsed meta in feature_configs using code_gen. def transform_from_code_gen(source_inputs): inputs = source_inputs.copy() education_hash_out = CategoryHash(education_hash.param)( inputs["education"] ) occupation_hash_out = CategoryHash(occupation_hash.param)( inputs["occupation"] ) native_country_hash_out = CategoryHash(native_country_hash.param)( inputs["native_country"] ) workclass_lookup_out = CategoryLookup(workclass_lookup.param)( inputs["workclass"] ) marital_status_lookup_out = CategoryLookup(marital_status_lookup.param)( inputs["marital_status"] ) relationship_lookup_out = CategoryLookup(relationship_lookup.param)( inputs["relationship"] ) race_lookup_out = CategoryLookup(race_lookup.param)(inputs["race"]) sex_lookup_out = CategoryLookup(sex_lookup.param)(inputs["sex"]) age_bucketize_out = NumericBucket(age_bucketize.param)(inputs["age"]) capital_gain_bucketize_out = NumericBucket(capital_gain_bucketize.param)( inputs["capital_gain"] ) capital_loss_bucketize_out = NumericBucket(capital_loss_bucketize.param)( inputs["capital_loss"] ) hours_per_week_bucketize_out = NumericBucket( hours_per_week_bucketize.param )(inputs["hours_per_week"]) group1_out = Group(group1.param)( [ workclass_lookup_out, hours_per_week_bucketize_out, capital_gain_bucketize_out, capital_loss_bucketize_out, ] ) group2_out = Group(group2.param)( [ education_hash_out, marital_status_lookup_out, relationship_lookup_out, occupation_hash_out, ] ) group3_out = Group(group3.param)( [ age_bucketize_out, sex_lookup_out, race_lookup_out, native_country_hash_out, ] ) group1_wide_embedding_column = fc.embedding_column( fc.categorical_column_with_identity( "group1", num_buckets=group1_embedding_wide.param[0] ), dimension=group1_embedding_wide.param[1], ) group1_embedding_wide_out = tf.keras.layers.DenseFeatures( [group1_wide_embedding_column] )({"group1": group1_out}) group2_wide_embedding_column = fc.embedding_column( fc.categorical_column_with_identity( "group2", num_buckets=group2_embedding_wide.param[0] ), dimension=group2_embedding_wide.param[1], ) group2_embedding_wide_out = tf.keras.layers.DenseFeatures( [group2_wide_embedding_column] )({"group2": group2_out}) group1_deep_embedding_column = fc.embedding_column( fc.categorical_column_with_identity( "group1", num_buckets=group1_embedding_deep.param[0] ), dimension=group1_embedding_deep.param[1], ) group1_embedding_deep_out = tf.keras.layers.DenseFeatures( [group1_deep_embedding_column] )({"group1": group1_out}) group2_deep_embedding_column = fc.embedding_column( fc.categorical_column_with_identity( "group2", num_buckets=group2_embedding_deep.param[0] ), dimension=group2_embedding_deep.param[1], ) group2_embedding_deep_out = tf.keras.layers.DenseFeatures( [group2_deep_embedding_column] )({"group2": group2_out}) group3_deep_embedding_column = fc.embedding_column( fc.categorical_column_with_identity( "group3", num_buckets=group3_embedding_deep.param[0] ), dimension=group3_embedding_deep.param[1], ) group3_embedding_deep_out = tf.keras.layers.DenseFeatures( [group3_deep_embedding_column] )({"group3": group3_out}) wide_embeddings_out = [ group1_embedding_wide_out, group2_embedding_wide_out, ] deep_embeddings_out = [ group1_embedding_deep_out, group2_embedding_deep_out, group3_embedding_deep_out, ] return wide_embeddings_out, deep_embeddings_out # The entry point of the submitter program def custom_model(): input_layers = get_input_layers(input_schemas=INPUT_SCHEMAS) wide_embeddings, deep_embeddings = transform(input_layers) return wide_and_deep_classifier( input_layers, wide_embeddings, deep_embeddings ) def loss(labels, predictions): logits = predictions["logits"] return tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.cast(tf.reshape(labels, (-1, 1)), tf.float32), logits=logits, ) ) def optimizer(lr=0.001): return tf.keras.optimizers.Adam(learning_rate=lr) def eval_metrics_fn(): return { "logits": { "accuracy": lambda labels, predictions: tf.equal( tf.cast(tf.reshape(predictions, [-1]) > 0.5, tf.int32), tf.cast(tf.reshape(labels, [-1]), tf.int32), ) }, "probs": {"auc": tf.keras.metrics.AUC()}, } def callbacks(): def _schedule(model_version): if model_version < 5000: return 0.0003 elif model_version < 12000: return 0.0002 else: return 0.0001 return [LearningRateScheduler(_schedule)]
33.268852
79
0.675865
b7a7a97dc4621a06fda2b867d490ded5d636c919
545
cpp
C++
examples/multithreading/bots/abstractbot.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
examples/multithreading/bots/abstractbot.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
examples/multithreading/bots/abstractbot.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include "abstractbot.h" bots::AbstractBot::AbstractBot() : m_strategy(nullptr) { } bots::AbstractBot::~AbstractBot() { if (m_strategy) { m_strategy->delRef(); } } void bots::AbstractBot::setStrategy(bots::shootingstrategies::ShootingStrategy* strategy) { if (m_strategy) { m_strategy->delRef(); } m_strategy = strategy; if (m_strategy) { m_strategy->addRef(); } } bots::shootingstrategies::ShootingStrategy* bots::AbstractBot::strategy() const { return m_strategy; }
16.515152
89
0.638532
0d6118a61e65e1984e5278dcd96ca25c037b4e18
6,003
h
C
dev/Code/CryEngine/CryCommon/MovementStyle.h
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/CryEngine/CryCommon/MovementStyle.h
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/CryEngine/CryCommon/MovementStyle.h
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRYCOMMON_MOVEMENTSTYLE_H #define CRYINCLUDE_CRYCOMMON_MOVEMENTSTYLE_H #pragma once #include "XMLAttrReader.h" #include <IAIActor.h> // Defines how an agent should move to the destination. // Moving to cover, running, crouching and so on. class MovementStyle { public: // When you change these, change ReadFromXml as well. enum Stance { Relaxed, Alerted, Stand, Crouch }; enum Speed { Walk, Run, Sprint }; public: MovementStyle() : m_stance(Stand) , m_speed(Run) , m_speedLiteral(0.0f) , m_hasSpeedLiteral(false) , m_bodyOrientationMode(HalfwayTowardsAimOrLook) , m_movingToCover(false) , m_movingAlongDesignedPath(false) , m_turnTowardsMovementDirectionBeforeMoving(false) , m_strafe(false) , m_hasExactPositioningRequest(false) , m_glanceInMovementDirection(false) { } void ConstructDictionariesIfNotAlreadyDone(); void ReadFromXml(const XmlNodeRef& node); void SetStance(const Stance stance) { m_stance = stance; } void SetSpeed(const Speed speed) { m_speed = speed; } void SetSpeedLiteral(float speedLiteral) { m_speedLiteral = speedLiteral; m_hasSpeedLiteral = true; } void SetMovingToCover(const bool movingToCover) { m_movingToCover = movingToCover; } void SetTurnTowardsMovementDirectionBeforeMoving(const bool enabled) { m_turnTowardsMovementDirectionBeforeMoving = enabled; } void SetMovingAlongDesignedPath(const bool movingAlongDesignedPath) { m_movingAlongDesignedPath = movingAlongDesignedPath; } void SetExactPositioningRequest(const SAIActorTargetRequest* const pExactPositioningRequest) { if (pExactPositioningRequest != 0) { m_hasExactPositioningRequest = true; m_exactPositioningRequest = *pExactPositioningRequest; } else { m_hasExactPositioningRequest = false; } } Stance GetStance() const { return m_stance; } Speed GetSpeed() const { return m_speed; } bool HasSpeedLiteral() const { return m_hasSpeedLiteral; } float GetSpeedLiteral() const { return m_speedLiteral; } EBodyOrientationMode GetBodyOrientationMode() const { return m_bodyOrientationMode; } bool IsMovingToCover() const { return m_movingToCover; } bool IsMovingAlongDesignedPath() const { return m_movingAlongDesignedPath; } bool ShouldTurnTowardsMovementDirectionBeforeMoving() const { return m_turnTowardsMovementDirectionBeforeMoving; } bool ShouldStrafe() const { return m_strafe; } bool ShouldGlanceInMovementDirection() const { return m_glanceInMovementDirection; } const SAIActorTargetRequest* GetExactPositioningRequest() const { return m_hasExactPositioningRequest ? &m_exactPositioningRequest : NULL; } private: Stance m_stance; Speed m_speed; float m_speedLiteral; bool m_hasSpeedLiteral; EBodyOrientationMode m_bodyOrientationMode; SAIActorTargetRequest m_exactPositioningRequest; bool m_movingToCover; bool m_movingAlongDesignedPath; bool m_turnTowardsMovementDirectionBeforeMoving; bool m_strafe; bool m_hasExactPositioningRequest; bool m_glanceInMovementDirection; }; struct MovementStyleDictionaryCollection { MovementStyleDictionaryCollection(); CXMLAttrReader<MovementStyle::Speed> speeds; CXMLAttrReader<MovementStyle::Stance> stances; CXMLAttrReader<EBodyOrientationMode> bodyOrientations; CXMLAttrReader<bool> booleans; }; inline MovementStyleDictionaryCollection::MovementStyleDictionaryCollection() { speeds.Reserve(3); speeds.Add("Walk", MovementStyle::Walk); speeds.Add("Run", MovementStyle::Run); speeds.Add("Sprint", MovementStyle::Sprint); stances.Reserve(4); stances.Add("Relaxed", MovementStyle::Relaxed); stances.Add("Alerted", MovementStyle::Alerted); stances.Add("Stand", MovementStyle::Stand); stances.Add("Crouch", MovementStyle::Crouch); bodyOrientations.Reserve(3); bodyOrientations.Add("FullyTowardsMovementDirection", FullyTowardsMovementDirection); bodyOrientations.Add("FullyTowardsAimOrLook", FullyTowardsAimOrLook); bodyOrientations.Add("HalfwayTowardsAimOrLook", HalfwayTowardsAimOrLook); booleans.Reserve(4); booleans.Add("true", true); booleans.Add("false", false); booleans.Add("1", true); booleans.Add("0", false); } namespace { MovementStyleDictionaryCollection g_movementStyleDictionaryCollection; } inline void MovementStyle::ReadFromXml(const XmlNodeRef& node) { g_movementStyleDictionaryCollection.speeds.Get(node, "speed", m_speed, true); g_movementStyleDictionaryCollection.stances.Get(node, "stance", m_stance); g_movementStyleDictionaryCollection.bodyOrientations.Get(node, "bodyOrientation", m_bodyOrientationMode); g_movementStyleDictionaryCollection.booleans.Get(node, "moveToCover", m_movingToCover); g_movementStyleDictionaryCollection.booleans.Get(node, "turnTowardsMovementDirectionBeforeMoving", m_turnTowardsMovementDirectionBeforeMoving); g_movementStyleDictionaryCollection.booleans.Get(node, "strafe", m_strafe); g_movementStyleDictionaryCollection.booleans.Get(node, "glanceInMovementDirection", m_glanceInMovementDirection); } #endif // CRYINCLUDE_CRYCOMMON_MOVEMENTSTYLE_H
37.51875
147
0.749459
c428833922bad37bca68690b5d71003424c6b628
1,249
cpp
C++
01-Question_after_WangDao/Chapter_02/2.2/T01.cpp
ysl970629/kaoyan_data_structure
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
[ "MIT" ]
2
2021-03-24T03:29:16.000Z
2022-03-29T16:34:30.000Z
01-Question_after_WangDao/Chapter_02/2.2/T01.cpp
ysl2/kaoyan-data-structure
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
[ "MIT" ]
null
null
null
01-Question_after_WangDao/Chapter_02/2.2/T01.cpp
ysl2/kaoyan-data-structure
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> using namespace std; #define INFINITY 9999 typedef int ElemType; typedef struct { ElemType *data; int length; } SqList; SqList initList(int arr[], int length) { SqList L; L.length = length; L.data = (ElemType *)malloc(sizeof(ElemType) * L.length); for (int i = 0; i < length; i++) L.data[i] = arr[i]; return L; } void outPutList(SqList L) { for (int i = 0; i < L.length; i++) cout << L.data[i] << " "; cout << endl; } bool deleteList(SqList &L, ElemType &e) { if (L.length == 0) return false; ElemType minValue = INFINITY; int minIndex = -1; for (int i = 0; i < L.length; i++) { if (L.data[i] < minValue) { minValue = L.data[i]; minIndex = i; } } e = minValue; L.data[minIndex] = L.data[L.length - 1]; L.length--; return true; } void test(int arr1[], int length1) { SqList L = initList(arr1, length1); ElemType e; deleteList(L, e); cout << e << endl; outPutList(L); } int main() { ElemType A[] = {3, 4, 5, 0, 1, 2, 6, 7, 8}; int length1 = sizeof(A) / sizeof(int); test(A, length1); return 0; } // 输出结果: // 0 // 3 4 5 8 1 2 6 7
19.215385
61
0.536429
055620c6c6c3db9bddfaf60f0f7256185286290a
685
rs
Rust
src/kv2/delete.rs
Lol3rrr/hc-vault
adbc35dc436be1c84edf76b3f47054d298454801
[ "MIT" ]
4
2021-02-10T14:36:54.000Z
2021-10-03T21:30:19.000Z
src/kv2/delete.rs
Lol3rrr/hc-vault
adbc35dc436be1c84edf76b3f47054d298454801
[ "MIT" ]
3
2020-12-20T12:01:55.000Z
2020-12-30T01:17:07.000Z
src/kv2/delete.rs
Lol3rrr/hc-vault
adbc35dc436be1c84edf76b3f47054d298454801
[ "MIT" ]
null
null
null
use crate::Auth; use crate::Client; use crate::Error; /// This deletes the latest version of the secret, which only stops it from being /// read/returned but currently doesnt actually delete the underlying data so it /// can be undone using `undelete` /// /// [Vault-Documentation](https://www.vaultproject.io/api-docs/secret/kv/kv-v2#delete-latest-version-of-secret) pub async fn delete(client: &Client<impl Auth>, mount: &str, name: &str) -> Result<(), Error> { let path = format!("{}/data/{}", mount, name); match client .vault_request::<String>(reqwest::Method::DELETE, &path, None) .await { Err(e) => Err(e), Ok(_) => Ok(()), } }
32.619048
111
0.642336
d15fc93309330d875ad60ae0e2d109e04e4e6f0c
1,231
cs
C#
src/HomesteadManager/Core/Models/HomesteadConfig.cs
joachimdalen/HomesteadManager
3dcbc87bbb49d9737ab16dc00e7ce60a93f922d1
[ "MIT" ]
1
2017-10-08T19:14:36.000Z
2017-10-08T19:14:36.000Z
src/HomesteadManager/Core/Models/HomesteadConfig.cs
joachimdalen/HomesteadManager
3dcbc87bbb49d9737ab16dc00e7ce60a93f922d1
[ "MIT" ]
null
null
null
src/HomesteadManager/Core/Models/HomesteadConfig.cs
joachimdalen/HomesteadManager
3dcbc87bbb49d9737ab16dc00e7ce60a93f922d1
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using YamlDotNet.Serialization; namespace HomesteadManager.Core.Models { public class HomesteadConfig { [YamlMember(Alias = "ip")] public string Ip { get; set; } [YamlMember(Alias = "memory")] public int Memory { get; set; } [YamlMember(Alias = "cpus")] public int Cpus { get; set; } [YamlMember(Alias = "provider")] public string Provider { get; set; } [YamlMember(Alias = "mariadb")] public bool Mariadb { get; set; } [YamlMember(Alias = "authorize")] public string Authorize { get; set; } [YamlMember(Alias = "keys")] public string[] Keys { get; set; } [YamlMember(Alias = "folders")] public Folder[] Folders { get; set; } [YamlMember(Alias = "sites")] public Site[] Sites { get; set; } [YamlMember(Alias = "databases")] public string[] Databases { get; set; } [YamlMember(Alias = "ports")] public Port[] Ports { get; set; } [YamlMember(Alias = "networks")] public Network[] Networks { get; set; } } }
33.27027
47
0.582453
b0f78396a4dc510af0fea37e96ffb4749f3eaebd
1,033
py
Python
ayewa/templatetags/ayewa_tags.py
JoanEliot/ayewa
e36128357564cb83938b2d7096b3fe75330dc948
[ "MIT" ]
null
null
null
ayewa/templatetags/ayewa_tags.py
JoanEliot/ayewa
e36128357564cb83938b2d7096b3fe75330dc948
[ "MIT" ]
null
null
null
ayewa/templatetags/ayewa_tags.py
JoanEliot/ayewa
e36128357564cb83938b2d7096b3fe75330dc948
[ "MIT" ]
null
null
null
from django import template from wagtail.core.models import Page, Site register = template.Library() # https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/ # Retrieves the top menu items - the immediate children of the parent page # The has_menu_children method is necessary because the Foundation menu requires # a dropdown class to be applied to a parent @register.inclusion_tag('tags/index_page_menu.html', takes_context=True) def index_page_menu(context, parent, calling_page=None): menuitems = parent.get_children().live().in_menu() for menuitem in menuitems: menuitem.nav_description = 'Foobar' # We don't directly check if calling_page is None since the template # engine can pass an empty string to calling_page # if the variable passed as calling_page does not exist. return { 'calling_page': calling_page, 'menuitems': [], # required by the pageurl tag that we want to use within this template 'request': context['request'], }
41.32
80
0.725073
f5df974f3ea2fb7568b959bdbf2fd4a961f39f73
2,014
go
Go
backend/users/busqueda.go
johnbalvin/chat
813aecd2fa201d07bb0dbf73a91442870760a4b4
[ "MIT" ]
null
null
null
backend/users/busqueda.go
johnbalvin/chat
813aecd2fa201d07bb0dbf73a91442870760a4b4
[ "MIT" ]
null
null
null
backend/users/busqueda.go
johnbalvin/chat
813aecd2fa201d07bb0dbf73a91442870760a4b4
[ "MIT" ]
null
null
null
package users import ( "context" "chat/backend/errors" "log" "cloud.google.com/go/firestore" ) //ByID look for the user by id func ByID(userID string) (User, error) { ctx := context.Background() snapShops, err := clienteFS.Collection("Users").Where("ID", "==", userID).Limit(1).Documents(ctx).GetAll() if err != nil { log.Println("users -> ByID:1 -> err:", err) return User{}, err } if err != nil { log.Println("users -> ByID:2 -> err:", err) return User{}, err } if len(snapShops) == 0 { return User{}, errors.Empty } var user User if err := snapShops[0].DataTo(&user); err != nil { log.Println("users -> ByID:4 -> err:", err) return User{}, err } return user, nil } //ByIDs look for the user by id func ByIDs(userIDs map[string]bool) ([]User, error) { var refs []*firestore.DocumentRef for userID := range userIDs { refs = append(refs, clienteFS.Collection("Users").Doc(userID)) } ctx := context.Background() snapshots, err := clienteFS.GetAll(ctx, refs) if err != nil { log.Println("users -> ByIDs:1 -> err:", err) return nil, err } var users []User for _, snap := range snapshots { var user User if !snap.Exists() { //posible a user just sent a post with fake ids log.Println("users -> ByIDs:2 -> err:", err) continue } if err = snap.DataTo(&user); err != nil { log.Println("users -> ByIDs:3 -> err:", err) return nil, err } users = append(users, user) } return users, nil } //ByEmail look for the user by email func ByEmail(email string) (User, error) { ctx := context.Background() log.Println(len(email), email) snapShops, err := clienteFS.Collection("Users").Where("Email", "==", email).Limit(1).Documents(ctx).GetAll() if err != nil { log.Println("users -> ByEmail:1 -> err:", err) return User{}, err } if len(snapShops) == 0 { return User{}, errors.Empty } var user User if err = snapShops[0].DataTo(&user); err != nil { log.Println("users -> ByEmail:2 -> err:", err) return User{}, err } return user, nil }
24.864198
109
0.636048
454af8a400f3ce676cb8ac813827e1566990fb83
656
py
Python
passes/inst-count-pass/aux.py
ComputerSystemsLaboratory/Code-Size-Prediction
591c2d2be8365e5816579698670cd02a503a02e7
[ "MIT" ]
null
null
null
passes/inst-count-pass/aux.py
ComputerSystemsLaboratory/Code-Size-Prediction
591c2d2be8365e5816579698670cd02a503a02e7
[ "MIT" ]
null
null
null
passes/inst-count-pass/aux.py
ComputerSystemsLaboratory/Code-Size-Prediction
591c2d2be8365e5816579698670cd02a503a02e7
[ "MIT" ]
null
null
null
import os import yaml import argparse import numpy as np from os import listdir from os.path import isfile, join def Main(): parser = argparse.ArgumentParser() parser.add_argument("path", metavar='p1', nargs='?', const=1, help="prog path", type=str) args = parser.parse_args() programs = [f for f in listdir(args.path) if isfile(join(args.path, f))] for i in range(len(programs)): name = programs[i][:-3] os.system("python3 goal.py "+programs[i]+" > "+name+'.yaml') #break if __name__ == '__main__': Main()
24.296296
76
0.54878
54cfe7069d7a30439fa650314ef6f79f5fc4ee98
625
h
C
src/modules/mouse/ppapi/Mouse.h
binji/love-nacl
827aa23556fe1c4876e37d24aab40795871b8d81
[ "Zlib" ]
15
2015-02-26T07:38:58.000Z
2021-05-29T15:58:38.000Z
src/modules/mouse/ppapi/Mouse.h
mcanthony/love-nacl
827aa23556fe1c4876e37d24aab40795871b8d81
[ "Zlib" ]
3
2015-04-20T18:14:30.000Z
2019-08-13T22:32:27.000Z
src/modules/mouse/ppapi/Mouse.h
mcanthony/love-nacl
827aa23556fe1c4876e37d24aab40795871b8d81
[ "Zlib" ]
7
2015-10-09T20:36:26.000Z
2017-09-20T01:49:47.000Z
/** **/ #ifndef LOVE_MOUSE_PPAPI_MOUSE_H #define LOVE_MOUSE_PPAPI_MOUSE_H // LOVE #include <mouse/Mouse.h> namespace love { namespace mouse { namespace ppapi { class Mouse : public love::mouse::Mouse { public: // Implements Module. const char * getName() const; int getX() const; int getY() const; void getPosition(int & x, int & y) const; void setPosition(int x, int y); void setVisible(bool visible); bool isDown(Button * buttonlist) const; bool isVisible() const; void setGrab(bool grab); bool isGrabbed() const; }; // Mouse } // ppapi } // mouse } // love #endif // LOVE_MOUSE_PPAPI_MOUSE_H
17.361111
43
0.688
57fcda89f1072e49c4c899d5c0aad34ab0970535
770
php
PHP
database/seeds/DemoSeeder.php
Darkbelg/teamsy
b00f78e927a7f781500a2b38b93b412594c61647
[ "MIT" ]
22
2020-11-05T04:23:06.000Z
2021-12-11T11:02:59.000Z
database/seeds/DemoSeeder.php
Darkbelg/teamsy
b00f78e927a7f781500a2b38b93b412594c61647
[ "MIT" ]
null
null
null
database/seeds/DemoSeeder.php
Darkbelg/teamsy
b00f78e927a7f781500a2b38b93b412594c61647
[ "MIT" ]
14
2020-11-14T18:10:03.000Z
2021-12-29T22:16:22.000Z
<?php use App\Login; use App\Tenant; use App\User; use Illuminate\Database\Seeder; class DemoSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(Tenant::class, 3)->create(); foreach(Tenant::all() as $tenant) { factory(User::class, 20)->create([ 'tenant_id' => $tenant->id, ]); } foreach(User::all() as $user) { factory(Login::class, 5)->create([ 'user_id' => $user->id, 'tenant_id' => $user->tenant_id, ]); } factory(User::class)->create([ 'tenant_id' => null, 'email' => 'admin@admin.com', ]); } }
20.263158
48
0.466234
2586fd05b9ab21e2295c7cfea3cfab280c1d0987
798
js
JavaScript
gulp/tasks/copy.js
skazmasters/bulba
b2f640a147cfbd5e4ff167e60344183b31b92935
[ "MIT" ]
null
null
null
gulp/tasks/copy.js
skazmasters/bulba
b2f640a147cfbd5e4ff167e60344183b31b92935
[ "MIT" ]
null
null
null
gulp/tasks/copy.js
skazmasters/bulba
b2f640a147cfbd5e4ff167e60344183b31b92935
[ "MIT" ]
null
null
null
import gulp from 'gulp'; import config from '../config.js'; gulp.task('copy:fonts', function() { return gulp .src(config.src.fonts + '/*.{ttf,eot,woff,woff2}') .pipe(gulp.dest(config.dest.fonts)); }); gulp.task('copy:lib', () => gulp .src(`${config.src.lib}/**/*.*`) .pipe(gulp.dest(config.dest.lib)) ); gulp.task('copy:rootfiles', () => gulp .src(`${config.src.root}/*.*`) .pipe(gulp.dest(config.dest.root)) ); gulp.task('copy:img', () => gulp .src([ `${config.src.img}/**/*.{jpg,png,jpeg,svg,gif,mp4,webm}`, `!${config.src.img}/svgo/**/*.*` ]) .pipe(gulp.dest(config.dest.img))); gulp.task('copy', [ 'copy:img', // 'copy:rootfiles', // 'copy:lib', 'copy:fonts' ]); gulp.task('copy:watch', () => gulp.watch(`${config.src.img}/*`, ['copy']));
23.470588
75
0.56391
641f3e865a82b683f8beac9c2ce7273bfd282276
1,356
py
Python
Server/Python/src/dbs/dao/Oracle/Block/UpdateStatus.py
vkuznet/DBS
14df8bbe8ee8f874fe423399b18afef911fe78c7
[ "Apache-2.0" ]
8
2015-08-14T04:01:32.000Z
2021-06-03T00:56:42.000Z
Server/Python/src/dbs/dao/Oracle/Block/UpdateStatus.py
yuyiguo/DBS
14df8bbe8ee8f874fe423399b18afef911fe78c7
[ "Apache-2.0" ]
162
2015-01-07T21:34:47.000Z
2021-10-13T09:42:41.000Z
Server/Python/src/dbs/dao/Oracle/Block/UpdateStatus.py
yuyiguo/DBS
14df8bbe8ee8f874fe423399b18afef911fe78c7
[ "Apache-2.0" ]
16
2015-01-22T15:27:29.000Z
2021-04-28T09:23:28.000Z
#!/usr/bin/env python """ This module provides Block.UpdateStatus data access object. """ from WMCore.Database.DBFormatter import DBFormatter from dbs.utils.dbsExceptionHandler import dbsExceptionHandler from dbs.utils.dbsUtils import dbsUtils class UpdateStatus(DBFormatter): """ Block Update Status DAO class. """ def __init__(self, logger, dbi, owner): """ Add schema owner and sql. """ DBFormatter.__init__(self, logger, dbi) self.logger = logger self.owner = "%s." % owner if not owner in ("", "__MYSQL__") else "" self.sql = """UPDATE %sBLOCKS SET OPEN_FOR_WRITING = :open_for_writing , LAST_MODIFIED_BY=:myuser, LAST_MODIFICATION_DATE = :ltime where BLOCK_NAME = :block_name""" % self.owner def execute ( self, conn, block_name, open_for_writing, ltime, transaction=False ): """ for a given file """ if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Block/UpdateStatus. Expects db connection from upper layer.", self.logger.exception) binds = {"block_name": block_name ,"open_for_writing": open_for_writing , 'ltime': ltime, 'myuser': dbsUtils().getCreateBy()} self.dbi.processData(self.sql, binds, conn, transaction)
37.666667
124
0.647493
ae4547898655faa870273eb966b85c0fe7028a88
6,340
cs
C#
src/ConnectServer/ConnectServer.cs
sven-n/OpenMU
4f8ffcea64b4f93d2e09404553344ec010ea7a0a
[ "MIT" ]
null
null
null
src/ConnectServer/ConnectServer.cs
sven-n/OpenMU
4f8ffcea64b4f93d2e09404553344ec010ea7a0a
[ "MIT" ]
null
null
null
src/ConnectServer/ConnectServer.cs
sven-n/OpenMU
4f8ffcea64b4f93d2e09404553344ec010ea7a0a
[ "MIT" ]
2
2019-01-28T15:46:32.000Z
2020-06-14T15:40:48.000Z
// <copyright file="ConnectServer.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.ConnectServer { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Net; using log4net; using MUnique.OpenMU.Interfaces; /// <summary> /// The connect server. /// </summary> internal class ConnectServer : IConnectServer, OpenMU.Interfaces.IConnectServer { private static readonly ILog Logger = LogManager.GetLogger(typeof(ConnectServer)); /// <summary> /// Initializes a new instance of the <see cref="ConnectServer" /> class. /// </summary> /// <param name="settings">The settings.</param> public ConnectServer(Settings settings) { this.Settings = settings; this.ConnectInfos = new Dictionary<ushort, byte[]>(); this.ServerList = new ServerList(); this.ClientListener = new ClientListener(this); this.CreatePlugins(); } /// <inheritdoc/> public ServerState ServerState { get; private set; } /// <inheritdoc/> public string Description => "Connect Server"; /// <inheritdoc/> public int Id => SpecialServerIds.ConnectServer; /// <inheritdoc/> public IDictionary<ushort, byte[]> ConnectInfos { get; } /// <inheritdoc/> public ServerList ServerList { get; } /// <inheritdoc/> public Settings Settings { get; } /// <summary> /// Gets the client listener. /// </summary> public ClientListener ClientListener { get; } /// <summary> /// Gets the maximum allowed connections. /// </summary> public int MaximumConnections => this.Settings.MaxConnections; /// <summary> /// Gets the current connection count. /// </summary> public int CurrentConnections => this.ClientListener.Clients.Count; /// <inheritdoc/> public void Start() { Logger.Info("Begin starting"); var oldState = this.ServerState; this.ServerState = OpenMU.Interfaces.ServerState.Starting; try { this.ClientListener.StartListener(); } catch (Exception ex) { Logger.Error("Error while starting", ex); this.ServerState = oldState; } finally { this.ServerState = OpenMU.Interfaces.ServerState.Started; } Logger.Info("Finished starting"); } /// <inheritdoc/> public void Shutdown() { Logger.Info("Begin stopping"); this.ServerState = OpenMU.Interfaces.ServerState.Stopping; this.ClientListener.StopListener(); this.ServerState = OpenMU.Interfaces.ServerState.Stopped; Logger.Info("Finished stopping"); } /// <inheritdoc/> public void RegisterGameServer(IGameServerInfo gameServer, IPEndPoint publicEndPoint) { Logger.InfoFormat("GameServer {0} is registering with endpoint {1}", gameServer, publicEndPoint); try { var serverListItem = new ServerListItem(this.ServerList) { ServerId = gameServer.Id, EndPoint = publicEndPoint, ServerLoad = (byte)(gameServer.OnlinePlayerCount * 100f / gameServer.MaximumPlayers) }; if (gameServer is INotifyPropertyChanged notifier) { notifier.PropertyChanged += this.HandleServerPropertyChanged; } this.ServerList.Servers.Add(serverListItem); this.ConnectInfos.Add(serverListItem.ServerId, serverListItem.ConnectInfo); } catch (Exception ex) { Logger.Error("Error during registration process", ex); throw; } Logger.InfoFormat("GameServer {0} has registered with endpoint {1}", gameServer, publicEndPoint); } /// <inheritdoc/> public void UnregisterGameServer(IGameServerInfo gameServer) { Logger.WarnFormat("GameServer {0} is unregistering", gameServer); var serverListItem = this.ServerList.Servers.FirstOrDefault(s => s.ServerId == gameServer.Id); if (serverListItem != null) { this.ConnectInfos.Remove(serverListItem.ServerId); this.ServerList.Servers.Remove(serverListItem); this.ServerList.InvalidateCache(); } if (gameServer is INotifyPropertyChanged notifier) { notifier.PropertyChanged -= this.HandleServerPropertyChanged; } Logger.WarnFormat("GameServer {0} has unregistered", gameServer); } private void CreatePlugins() { Logger.Debug("Begin creating plugins"); this.ClientListener.ClientSocketAcceptPlugins.Add(new CheckMaximumConnectionsPlugin(this)); var clientCountPlugin = new ClientConnectionCountPlugin(this.Settings); this.ClientListener.ClientSocketAcceptPlugins.Add(clientCountPlugin); this.ClientListener.ClientSocketDisconnectPlugins.Add(clientCountPlugin); Logger.Debug("Finished creating plugins"); } private void HandleServerPropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName != "OnlinePlayerCount") { return; } var server = sender as IGameServerInfo; if (server == null) { return; } var serverListItem = this.ServerList.Servers.FirstOrDefault(s => s.ServerId == server.Id); if (serverListItem == null) { return; } serverListItem.ServerLoad = (byte)(server.OnlinePlayerCount * 100f / server.MaximumPlayers); } } }
34.27027
109
0.576341
6d6b91f3dd785d046269c053fab62ab08d70f0e5
14,644
ts
TypeScript
src/binding-post.ts
jimisaacs/samlify
824ff038d66bb53d9ab92e4f977130352212fb19
[ "MIT" ]
null
null
null
src/binding-post.ts
jimisaacs/samlify
824ff038d66bb53d9ab92e4f977130352212fb19
[ "MIT" ]
null
null
null
src/binding-post.ts
jimisaacs/samlify
824ff038d66bb53d9ab92e4f977130352212fb19
[ "MIT" ]
null
null
null
/** * @file binding-post.ts * @author tngan * @desc Binding-level API, declare the functions using POST binding */ import type { BindingContext } from './binding'; import type { Entity, ParsedLogoutRequest } from './entity'; import type { IdentityProvider, ParsedLoginRequest } from './entity-idp'; import type { ServiceProvider } from './entity-sp'; import { SamlifyError, SamlifyErrorCode } from './error'; import type { FlowResult } from './flow'; import { CustomTagReplacement, libsaml } from './libsaml'; import { BindingNamespace, StatusCode } from './urn'; import { base64Decode, base64Encode, isNonEmptyArray } from './utility'; /** * @desc Generate a base64 encoded login request * @param {string} referenceTagXPath reference uri * @param {object} entity object includes both idp and sp * @param {function} customTagReplacement used when developers have their own login response template */ function base64LoginRequest( referenceTagXPath: string, entity: { idp: IdentityProvider; sp: ServiceProvider }, customTagReplacement?: CustomTagReplacement ): BindingContext { const metadata = { idp: entity.idp.getEntityMeta(), sp: entity.sp.getEntityMeta() }; if (!metadata.idp || !metadata.sp) { throw new SamlifyError(SamlifyErrorCode.MissingMetadata); } const spSetting = entity.sp.getEntitySettings(); const template = spSetting.loginRequestTemplate ?? libsaml.defaultLoginRequestTemplate; const nameIDFormat = spSetting.nameIDFormat; const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat; let values: Record<string, any> = { ID: entity.sp.generateID(), Destination: metadata.idp.getSingleSignOnService(BindingNamespace.Post), Issuer: metadata.sp.getEntityID(), IssueInstant: new Date().toISOString(), AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(BindingNamespace.Post), EntityID: metadata.sp.getEntityID(), AllowCreate: spSetting.allowCreate, NameIDFormat: selectedNameIDFormat, }; let rawSaml = template.context ?? ''; // perform custom replacement if (customTagReplacement) { [rawSaml = rawSaml, values = values] = customTagReplacement(rawSaml, values); } // pickup any remaining rawSaml = libsaml.replaceTagsByValue(rawSaml, values); if (metadata.idp.isWantAuthnRequestsSigned()) { const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms, } = spSetting; if (!privateKey) { throw new SamlifyError( SamlifyErrorCode.MissingPrivateKey, "IdentityProvider wants AuthnRequests signed, but ServiceProvider did not provide a 'privateKey'." ); } return { id: values.ID, context: libsaml.constructSAMLSignature({ referenceTagXPath, privateKey: privateKey.toString(), privateKeyPass, signatureAlgorithm, transformationAlgorithms, rawSamlMessage: rawSaml, signingCert: metadata.sp.getX509Certificate('signing'), signatureConfig: spSetting.signatureConfig || { prefix: 'ds', location: { reference: "/*[local-name(.)='AuthnRequest']/*[local-name(.)='Issuer']", action: 'after', }, }, }), }; } // No need to embeded XML signature return { id: values.ID, context: base64Encode(rawSaml) }; } /** * @desc Generate a base64 encoded login response * @param {Partial<FlowResult>} requestInfo corresponding request, used to obtain the id * @param {object} entity object includes both idp and sp * @param {object} user current logged user (e.g. req.user) * @param {function} customTagReplacement used when developers have their own login response template * @param {boolean} encryptThenSign whether or not to encrypt then sign first (if signing). Defaults to sign-then-encrypt */ async function base64LoginResponse( requestInfo: Partial<FlowResult<ParsedLoginRequest>>, entity: { idp: IdentityProvider; sp: ServiceProvider }, user: Record<string, string> = {}, customTagReplacement?: CustomTagReplacement, encryptThenSign = false ): Promise<BindingContext> { const metadata = { idp: entity.idp.getEntityMeta(), sp: entity.sp.getEntityMeta() }; if (!metadata.idp || !metadata.sp) { throw new SamlifyError(SamlifyErrorCode.MissingMetadata); } const idpSetting = entity.idp.getEntitySettings(); const template = idpSetting.loginResponseTemplate ?? libsaml.defaultLoginResponseTemplate; const attributes = template.attributes; const spSetting = entity.sp.getEntitySettings(); const nameIDFormat = idpSetting.nameIDFormat; const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat; const base = metadata.sp.getAssertionConsumerService(BindingNamespace.Post); const nowTime = new Date(); const spEntityID = metadata.sp.getEntityID(); const fiveMinutesLaterTime = new Date(nowTime.getTime()); fiveMinutesLaterTime.setMinutes(fiveMinutesLaterTime.getMinutes() + 5); const fiveMinutesLater = fiveMinutesLaterTime.toISOString(); const now = nowTime.toISOString(); const acl = metadata.sp.getAssertionConsumerService(BindingNamespace.Post); let values: Record<string, any> = { ID: entity.idp.generateID(), AssertionID: entity.idp.generateID(), Destination: base, Audience: spEntityID, EntityID: spEntityID, SubjectRecipient: acl, Issuer: metadata.idp.getEntityID(), IssueInstant: now, AssertionConsumerServiceURL: acl, StatusCode: StatusCode.Success, // can be customized ConditionsNotBefore: now, ConditionsNotOnOrAfter: fiveMinutesLater, SubjectConfirmationDataNotOnOrAfter: fiveMinutesLater, NameIDFormat: selectedNameIDFormat, NameID: user.email || '', InResponseTo: requestInfo.extract?.request?.id ?? '', AuthnStatement: '', // First fill in attributes AttributeStatement: isNonEmptyArray(attributes) ? libsaml.replaceTagsByValue( libsaml.attributeStatementBuilder(attributes), libsaml.attributeStatementTagBuilder(attributes, user) ) : '', }; let rawSaml = template.context; // perform custom replacement if (customTagReplacement) { [rawSaml = rawSaml, values = values] = customTagReplacement(rawSaml, values); } // pickup any remaining rawSaml = libsaml.replaceTagsByValue(rawSaml, values); const getConfig = (wantsSigned: string) => { const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting; if (!privateKey) { throw new SamlifyError( SamlifyErrorCode.MissingPrivateKey, `ServiceProvider wants ${wantsSigned} signed, but IdentityProvider did not provide a 'privateKey'.` ); } return { privateKey: privateKey?.toString(), privateKeyPass, signatureAlgorithm, signingCert: metadata.idp.getX509Certificate('signing'), isBase64Output: false, }; }; // step: sign assertion ? -> encrypted ? -> sign message ? if (metadata.sp.isWantAssertionsSigned()) { // console.debug('sp wants assertion signed'); rawSaml = libsaml.constructSAMLSignature({ ...getConfig('Assertions'), rawSamlMessage: rawSaml, transformationAlgorithms: spSetting.transformationAlgorithms, referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']", signatureConfig: { prefix: 'ds', location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after', }, }, }); } // console.debug('after assertion signed', rawSaml); // SAML response must be signed sign message first, then encrypt if (!encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) { // console.debug('sign then encrypt and sign entire message'); rawSaml = libsaml.constructSAMLSignature({ ...getConfig('Message'), rawSamlMessage: rawSaml, isMessageSigned: true, transformationAlgorithms: spSetting.transformationAlgorithms, signatureConfig: spSetting.signatureConfig || { prefix: 'ds', location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after', }, }, }); } // console.debug('after message signed', rawSaml); if (idpSetting.isAssertionEncrypted) { // console.debug('idp is configured to do encryption'); const context = await libsaml.encryptAssertion(entity.idp, entity.sp, rawSaml); if (encryptThenSign) { //need to decode it rawSaml = base64Decode(context) as string; } else { return { id: values.ID, context }; } } //sign after encrypting if (encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) { rawSaml = libsaml.constructSAMLSignature({ ...getConfig('Message'), rawSamlMessage: rawSaml, isMessageSigned: true, transformationAlgorithms: spSetting.transformationAlgorithms, signatureConfig: spSetting.signatureConfig || { prefix: 'ds', location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after', }, }, }); } return { id: values.ID, context: base64Encode(rawSaml) }; } /** * @desc Generate a base64 encoded logout request * @param {object} user current logged user (e.g. req.user) * @param {string} referenceTagXPath reference uri * @param {object} entity object includes both idp and sp * @param {function} customTagReplacement used when developers have their own login response template * @return {string} base64 encoded request */ function base64LogoutRequest( user: Record<string, string>, referenceTagXPath: string, entity: { init: Entity; target: Entity }, customTagReplacement?: CustomTagReplacement ): BindingContext { const metadata = { init: entity.init.getEntityMeta(), target: entity.target.getEntityMeta() }; if (!metadata.init || !metadata.target) { throw new SamlifyError(SamlifyErrorCode.MissingMetadata); } const initSetting = entity.init.getEntitySettings(); const template = initSetting.logoutRequestTemplate ?? libsaml.defaultLogoutRequestTemplate; const nameIDFormat = initSetting.nameIDFormat; const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat; let values: Record<string, any> = { ID: entity.init.generateID(), Destination: metadata.target.getSingleLogoutService(BindingNamespace.Post), Issuer: metadata.init.getEntityID(), IssueInstant: new Date().toISOString(), EntityID: metadata.init.getEntityID(), NameIDFormat: selectedNameIDFormat, NameID: user.logoutNameID, }; let rawSaml = template.context ?? ''; // perform custom replacement if (customTagReplacement) { [rawSaml = rawSaml, values = values] = customTagReplacement(rawSaml, values); } // pickup any remaining rawSaml = libsaml.replaceTagsByValue(rawSaml, values); if (entity.target.getEntitySettings().wantLogoutRequestSigned) { // Need to embeded XML signature const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms, } = initSetting; if (!privateKey) { throw new SamlifyError( SamlifyErrorCode.MissingPrivateKey, `${entity.target.constructor.name} wants LogoutRequest signed, but ${entity.init.constructor.name} did not provide a 'privateKey'.` ); } return { id: values.ID, context: libsaml.constructSAMLSignature({ referenceTagXPath, privateKey: privateKey.toString(), privateKeyPass, signatureAlgorithm, transformationAlgorithms, rawSamlMessage: rawSaml, signingCert: metadata.init.getX509Certificate('signing'), signatureConfig: initSetting.signatureConfig || { prefix: 'ds', location: { reference: "/*[local-name(.)='LogoutRequest']/*[local-name(.)='Issuer']", action: 'after', }, }, }), }; } return { id: values.ID, context: base64Encode(rawSaml) }; } /** * @desc Generate a base64 encoded logout response * @param {Partial<FlowResult>|null} requestInfo corresponding request, used to obtain the id * @param {object} entity object includes both idp and sp * @param {string} referenceTagXPath reference uri * @param {function} customTagReplacement used when developers have their own login response template */ function base64LogoutResponse( requestInfo: Partial<FlowResult<ParsedLogoutRequest>> | null, entity: { init: Entity; target: Entity }, customTagReplacement?: CustomTagReplacement ): BindingContext { const metadata = { init: entity.init.getEntityMeta(), target: entity.target.getEntityMeta() }; if (!metadata.init || !metadata.target) { throw new SamlifyError(SamlifyErrorCode.MissingMetadata); } const initSetting = entity.init.getEntitySettings(); const template = initSetting.logoutResponseTemplate ?? libsaml.defaultLogoutResponseTemplate; let values: Record<string, any> = { ID: entity.init.generateID(), Destination: metadata.target.getSingleLogoutService(BindingNamespace.Post), EntityID: metadata.init.getEntityID(), Issuer: metadata.init.getEntityID(), IssueInstant: new Date().toISOString(), StatusCode: StatusCode.Success, InResponseTo: requestInfo?.extract?.request?.id ?? '', }; let rawSaml = template.context; // perform custom replacement if (customTagReplacement) { [rawSaml = rawSaml, values = values] = customTagReplacement(rawSaml, values); } // pickup any remaining rawSaml = libsaml.replaceTagsByValue(rawSaml, values); if (entity.target.getEntitySettings().wantLogoutResponseSigned) { const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms, } = initSetting; if (!privateKey) { throw new SamlifyError( SamlifyErrorCode.MissingPrivateKey, `${entity.target.constructor.name} wants LogoutResponse signed, but ${entity.init.constructor.name} did not provide a 'privateKey'.` ); } return { id: values.ID, context: libsaml.constructSAMLSignature({ isMessageSigned: true, transformationAlgorithms: transformationAlgorithms, privateKey: privateKey.toString(), privateKeyPass, signatureAlgorithm, rawSamlMessage: rawSaml, signingCert: metadata.init.getX509Certificate('signing'), signatureConfig: { prefix: 'ds', location: { reference: "/*[local-name(.)='LogoutResponse']/*[local-name(.)='Issuer']", action: 'after', }, }, }), }; } return { id: values.ID, context: base64Encode(rawSaml) }; } const postBinding = { base64LoginRequest, base64LoginResponse, base64LogoutRequest, base64LogoutResponse, }; export default postBinding;
35.717073
136
0.721524
7aaddfef89cd3d71d9548b348277a4bc56c2e1f0
1,935
cs
C#
Assets/Scrum/Scripts/BasePerson.cs
john95206/OneWeek
4b337a70446d1bfe87705e2cacccbe9b919f0cb4
[ "MIT" ]
null
null
null
Assets/Scrum/Scripts/BasePerson.cs
john95206/OneWeek
4b337a70446d1bfe87705e2cacccbe9b919f0cb4
[ "MIT" ]
null
null
null
Assets/Scrum/Scripts/BasePerson.cs
john95206/OneWeek
4b337a70446d1bfe87705e2cacccbe9b919f0cb4
[ "MIT" ]
null
null
null
using UnityEngine; using UniRx; using UniRx.Async; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Scrum { public class BasePerson : MonoBehaviour { protected int mitsuCount; protected float socialDistance = 0.6f; protected Animator anim; [SerializeField] protected float sensitivility = 1.0f; protected SpriteRenderer renderer; protected CircleCollider2D collider2D; public Subject<Unit> DiedAsync = new Subject<Unit>(); protected virtual void Awake() { renderer = GetComponent<SpriteRenderer>(); collider2D = GetComponent<CircleCollider2D>(); anim = GetComponent<Animator>(); } public virtual void Initialize(PersonProvider provider) { socialDistance = provider.SocialDistance; mitsuCount = provider.MitsuCount; } /// <summary> /// 密になった時 /// </summary> protected virtual void FixedUpdate() { // 決めた半径内にいる奴を全件取得 var people = Physics2D.OverlapCircleAll(transform.position, sensitivility, 1 << LayerMask.NameToLayer("RayCast")).Where(p => p.gameObject != gameObject).ToList(); // 密でなければ処理しない if (people.Count() < mitsuCount) { OnSocialDistance(); return; } // ソーシャルディスタンスを乱す輩が存在する if (people.Any(p => p != GetComponent<Collider2D>() && p.Distance(GetComponent<Collider2D>()).distance < socialDistance)) { // 密 OnMitsu(people); } else { OnSocialDistance(); } } protected virtual void OnMitsu(List<Collider2D> people) { } protected virtual void OnSocialDistance() { } } }
28.043478
174
0.560724
dd70c9222b01d8441fe0104b785d5e0d2811be31
335
java
Java
truYum/src/com/cognizant/truyum/dao/MenuItemDao.java
ishubhn/HotelManagementSystem-Java
593b7a9b402b8efeddad2f2320994ce405407b25
[ "MIT" ]
1
2020-08-21T08:48:08.000Z
2020-08-21T08:48:08.000Z
truYum/src/com/cognizant/truyum/dao/MenuItemDao.java
ishubhn/HotelManagementSystem
593b7a9b402b8efeddad2f2320994ce405407b25
[ "MIT" ]
null
null
null
truYum/src/com/cognizant/truyum/dao/MenuItemDao.java
ishubhn/HotelManagementSystem
593b7a9b402b8efeddad2f2320994ce405407b25
[ "MIT" ]
null
null
null
package com.cognizant.truyum.dao; import java.util.List; import com.cognizant.truyum.model.MenuItem; public interface MenuItemDao { public List<MenuItem> getMenuItemListAdmin(); public List<MenuItem> getMenuItemListCustomer(); public void modifyMenuItem(MenuItem menuItem); public MenuItem getMenuItem(long menuItemId); }
20.9375
49
0.797015
c6f6a724653de039caf2452d4f5ed49ec92456f2
26,719
py
Python
wsknn/model/wsknn.py
nokaut/wsknn
dd0f0c17d0e212fb47fe6ee283cb90b9d6a5ba25
[ "BSD-3-Clause" ]
1
2022-03-24T11:48:18.000Z
2022-03-24T11:48:18.000Z
wsknn/model/wsknn.py
nokaut/wsknn
dd0f0c17d0e212fb47fe6ee283cb90b9d6a5ba25
[ "BSD-3-Clause" ]
1
2022-03-29T08:53:59.000Z
2022-03-29T08:53:59.000Z
wsknn/model/wsknn.py
nokaut/wsknn
dd0f0c17d0e212fb47fe6ee283cb90b9d6a5ba25
[ "BSD-3-Clause" ]
null
null
null
import random from typing import Iterable, Union, List, Set, Dict from wsknn.weighting import weight_session_items, weight_item_score from wsknn.utils.calc import weight_set_pair from wsknn.utils.errors import check_data_dimension, check_numeric_type_instance,\ InvalidDimensionsError, InvalidTimestampError class WSKNN: """ The class represents the Weighted Session-Based k-nn model. Parameters ---------- number_of_recommendations : int, default=5 The number of recommended items. number_of_neighbors : int, default=10 The number of closest sessions to choose the items from. sampling_strategy : str, default='common_items' How to filter the initial sample of sessions. Available strategies are: - 'common_items': sample sessions with the same items as the input session, - 'recent': sample the most actual sessions, - 'random': get a random sample of sessions. sample_size : int, default=1000 How many sessions from the model are sampled to make a recommendation. weighting_func : str, default='linear' The similarity measurement between sessions. Available options: 'linear', 'log' and 'quadratic'. ranking_strategy : str, default='linear' How we calculate an item rank (based on its position in a session sequence). Available options are: 'inv', 'linear', 'log', 'quadratic'. required_sampling_event : int or str, default = None Set this paramater to the event name if sessions with it must be included in the neighbors selection. For example, this event may be a "purchase". Attributes ---------- weighting_functions: List List with weighting functions: ['linear', 'log', 'quadratic']. ranking_strategies : List List with ranking strategies: ['linear', 'log', 'quadratic', 'inv']. session_item_map : Dict sessions = { session_id: ( [sequence_of_items], [sequence_of_timestamps], [sequence_of_event_type] ) } Dict populated with fit() method. item_session_map : Dict items = { item_id: ( [sequence_of_sessions], [sequence_of_the_first_session_timestamps] ) } Dict populated with fit() method. n_of_recommendations : int Number of items recommended. number_of_closest_neighbors : int sampling_strategy : str See sampling_strategy parameter. possible_neighbors_sample_size : int See sample_size parameter. weighting_function : str See weighting_func parameter. ranking_strategy : str See ranking_strategy parameter. required_sampling_event : Union[int, str], default = None See required_sampling_event parameter. Methods ------- fit() predict() Raises ------ InvalidDimensionsError : wrong number of nested sequences within session-items or item-sessions maps. InvalidTimestampError : wrong type of timestamp - int is required. TypeError : wrong type of nested structures within session-items or item-sessions maps. """ def __init__(self, number_of_recommendations: int = 5, number_of_neighbors: int = 10, sampling_strategy: str = 'common_items', sample_size: int = 1000, weighting_func: str = 'linear', ranking_strategy: str = 'linear', required_sampling_event: Union[int, str] = None): self.sampling_strategies = ['common_items', 'recent', 'random'] self.weighting_functions = ['linear', 'log', 'quadratic'] self.ranking_strategies = ['linear', 'log', 'quadratic', 'inv'] self.session_item_map = None self.item_session_map = None self.n_of_recommendations = number_of_recommendations self.number_of_closest_neighbors = number_of_neighbors self.possible_neighbors_sample_size = sample_size self.required_sampling_event = required_sampling_event self.sampling_strategy = self._is_sampling_strategy_valid(sampling_strategy) self.weighting_function = self._is_weighting_function_valid(weighting_func) self.ranking_strategy = self._is_ranking_strategy_valid(ranking_strategy) # Core methods def fit(self, sessions: Dict, items: Dict): """Sets input session-items and item-sessions maps. Parameters ---------- sessions : Dict sessions = { session_id: ( [ sequence_of_items ], [ sequence_of_timestamps ], [ [OPTIONAL] sequence_of_event_types ] ) } items : Dict items = { item_id: ( [ sequence_of_sessions ], [ sequence_of_the_first_session_timestamps ] ) } """ # Check input data self._check_sessions_input(sessions) self._check_items_input(items) self.session_item_map = sessions self.item_session_map = items def predict(self, sessions: Dict, number_of_recommendations=None, number_of_closest_neighbors=None, session_sampling_strategy=None, possible_neighbors_sample_size=None, weighting_strategy=None, rank_strategy=None) -> Dict: """ The method predicts n next recommendations from a given session. Parameters ---------- sessions : Dict User ID (key) and sequence of viewed products and their timestamps (values). number_of_recommendations : int or None, default=None Resets the number of recommendations. number_of_closest_neighbors : int or None, default=None Resets the number of closest neighbors. session_sampling_strategy : str or None, default=None How to filter the initial sample of sessions. Available strategies are: - 'common_items': sample sessions with the same items as the input session, - 'recent': sample the most actual sessions, - 'random': get a random sample of sessions. possible_neighbors_sample_size : int or None, default=None How many sessions from the model are sampled to make a recommendation. If not set then it is the number given during the class initilization. weighting_strategy : str or None, default=None The similarity measurement between sessions. Available options: 'linear', 'log' and 'quadratic'. If not set then weighting strategy is taken from the parameter set during the class initialization. rank_strategy : str or None, default=None How we calculate an item rank (based on its position in a session sequence). Available options are: 'inv', 'linear', 'log', 'quadratic'. If not set then model uses rank strategy given during the initilization. Returns ------- : Dict ranked items in descending order - {user ID: [[item, rank] ...]} """ # Set class consts self._reset_model_params(number_of_recommendations, number_of_closest_neighbors, session_sampling_strategy, possible_neighbors_sample_size, weighting_strategy, rank_strategy) output_ranks = dict() for _key, session in sessions.items(): neighbors = self._nearest_neighbors(session) ranked_items = self._rank_items(neighbors, session) ranked_items.sort(key=lambda x: x[1], reverse=True) recommendations = ranked_items[:self.n_of_recommendations] output_ranks[_key] = recommendations return output_ranks # Settings @staticmethod def _check_sessions_input(sessions: Dict): """Check if sessions have required dimensions. Parameters ---------- sessions : Dict sessions = { session_id: ( [ sequence_of_items ], [ sequence_of_timestamps ], [ [OPTIONAL] sequence_of_event_type ] ) } Raises ------ InvalidDimensionsError Number of nested sequences per record is different than 2 or 3. InvalidTimestampError Wrong type of timestamp - int is required. TypeError Wrong type of a given structure. """ # Get sample record sample_key = random.choice(list(sessions.keys())) sample_rec = sessions[sample_key] # Check dimensions test_dims = check_data_dimension(sample_rec, 2) or check_data_dimension(sample_rec, 3) if not test_dims: raise InvalidDimensionsError('Session-items map', [2, 3]) # Check type for subrec in sample_rec: if not isinstance(subrec, Iterable): msg = f'Expected iterable as a part of session-items map record, got {type(subrec)} instead.' raise TypeError(msg) # Check timestamp type for tstamp in sample_rec[1]: if not check_numeric_type_instance(tstamp): raise InvalidTimestampError(tstamp) @staticmethod def _check_items_input(items: dict): """Check if sessions have required dimensions. Parameters ---------- items : dict items = { item_id: ( [ sequence_of_sessions ], [ sequence_of_the_first_session_timestamps ] ) } Raises ------ InvalidDimensionsError Number of nested sequences per record is different than 2. InvalidTimestampError Wrong type of timestamp - int is required. TypeError Wrong type of a given structure. """ # Get sample record sample_key = random.choice(list(items.keys())) sample_rec = items[sample_key] # Check dimensions test_dims = check_data_dimension(sample_rec, 2) if not test_dims: raise InvalidDimensionsError('Item-sessions map', 2) # Check type for subrec in sample_rec: if not isinstance(subrec, Iterable): msg = f'Expected iterable as a part of item-sessions map record, got {type(subrec)} instead.' raise TypeError(msg) # Check timestamp type for tstamp in sample_rec[1]: if not check_numeric_type_instance(tstamp): raise InvalidTimestampError(tstamp) def _is_sampling_strategy_valid(self, sampling_strategy): """Check sampling strategy. Parameters ---------- sampling_strategy : str Raises ------ KeyError Strategy not in list defined in self.sampling_strategies Returns ------- sampling_strategy : str """ if sampling_strategy in self.sampling_strategies: return sampling_strategy else: msg = f"Given sampling strategy {sampling_strategy} not implemented in the package. " \ f"Use one of {self.sampling_strategies} instead" raise KeyError(msg) def _is_ranking_strategy_valid(self, strategy: str) -> str: """Check if ranking strategy is valid. Parameters ---------- strategy : str Raises ------ KeyError Strategy not in list ['linear', 'log', 'quadratic', 'inv'] Returns strategy : str """ if strategy in self.ranking_strategies: return strategy else: msg = f"Given ranking strategy {strategy} not implemented in the package. " \ f"Use 'linear', 'log', 'quadratic', 'inv' instead" raise KeyError(msg) def _is_weighting_function_valid(self, wfunc: str) -> str: """Check if weighting function is valid. Parameters ---------- wfunc : str Raises ------ KeyError Weighting function not in list ['linear', 'log', 'quadratic'] Returns wfunc : str """ if wfunc in self.weighting_functions: return wfunc else: msg = f"Given weighting function {wfunc} is not implemented in the package. " \ f"Use 'linear', 'log', 'quadratic', instead" raise KeyError(msg) def _reset_model_params(self, number_of_recommendations, number_of_closest_neighbors, session_sampling_strategy, possible_neighbors_sample_size, weighting_strategy, rank_strategy): """Methods resets and maps new model parameters. Parameters ---------- number_of_recommendations : int number_of_closest_neighbors : int session_sampling_strategy : str possible_neighbors_sample_size : int weighting_strategy : str rank_strategy : str Raises ------- TypeError Wrong type of an input parameter. KeyError Wrong name of sampling strategy, ranking strategy or weighting function. """ if number_of_recommendations is not None: if isinstance(number_of_recommendations, int): self._set_n_of_recs(number_of_recommendations) else: raise TypeError(f'Number of output recommendations should be an integer, ' f'got {type(number_of_recommendations)} instead') if number_of_closest_neighbors is not None: if isinstance(number_of_closest_neighbors, int): self._set_number_of_closest_neighbors(number_of_closest_neighbors) else: raise TypeError(f'Number of closest neighbors should be an integer, ' f'got {type(number_of_closest_neighbors)} instead') if session_sampling_strategy is not None: if isinstance(session_sampling_strategy, str): session_sampling_strategy = self._is_sampling_strategy_valid(session_sampling_strategy) self._set_sampling_strategy(session_sampling_strategy) else: raise TypeError(f'Defined sampling strategy should be a string. ' f'Got {type(session_sampling_strategy)} instead') if possible_neighbors_sample_size is not None: if isinstance(possible_neighbors_sample_size, int): self._set_possible_neighbors_sample_size(possible_neighbors_sample_size) else: raise TypeError(f'Number of possible neighbors should be an integer, ' f'got {type(possible_neighbors_sample_size)} instead') if weighting_strategy is not None: if isinstance(weighting_strategy, str): weighting_strategy = self._is_weighting_function_valid(weighting_strategy) self._set_weighting_strategy(weighting_strategy) else: raise TypeError(f'Defined weighting function should be a string. ' f'Got {type(weighting_strategy)} instead') if rank_strategy is not None: if isinstance(rank_strategy, str): rank_strategy = self._is_ranking_strategy_valid(rank_strategy) self._set_ranking_strategy(rank_strategy) else: raise TypeError(f'Defined ranking function should be a string. ' f'Got {type(rank_strategy)} instead') def _set_n_of_recs(self, n): self.n_of_recommendations = n def _set_number_of_closest_neighbors(self, n): self.number_of_closest_neighbors = n def _set_possible_neighbors_sample_size(self, sample_size): self.possible_neighbors_sample_size = sample_size def _set_sampling_strategy(self, sampling_strategy): self.sampling_strategy = sampling_strategy def _set_weighting_strategy(self, weighting_func): weighting_func = self._is_weighting_function_valid(weighting_func) self.weighting_function = weighting_func def _set_ranking_strategy(self, rank_strategy): self.ranking_strategy = rank_strategy # Transform, sample, rank - core def _nearest_neighbors(self, session: List) -> List: """Method searches for nearest neighbors for a given session. Parameters ---------- session : List Session is a sequence of products, events (product view / click) and timestamps of those events: session = [ [sequence_of_items], [sequence_of_timestamps], [sequence_of_event_type] ] Returns ------- : List n closest sessions, where n - number of closest sessions or length of ranked session if smaller than number of closest sessions. """ possible_neighbor_sessions = self._possible_neighbors(session) items_sequence = session[0] rank = self._calculate_similarity(items_sequence, possible_neighbor_sessions) rank.sort(key=lambda x: x[1], reverse=True) length = len(rank) idx = min(self.number_of_closest_neighbors, length) return rank[0:idx] def _possible_neighbors(self, session: List) -> List: """Get set of possible neighbors based on the item similarity. Parameters ---------- session : List Session is a sequence of products, events (product view / click) and timestamps of those events: session = [ [sequence_of_items], [sequence_of_timestamps], [sequence_of_event_type] ] Returns ------- : List Sample of possible neighbors. Sampling controlled by the sampling_strategy attribute. """ session_items = set(session[0]) common_sessions = set() for s_item in session_items: if s_item in self.item_session_map: s_item_sessions = set(self.item_session_map[s_item][0]) common_sessions |= s_item_sessions # Filter session by event if needed if self.required_sampling_event is not None: common_sessions = self._get_sessions_with_event(common_sessions) sample_subset = self._sample_possible_neighbors(common_sessions, session) return sample_subset def _rank_items(self, closest_neighbors: List, session: List) -> List: """Function ranks given items to return the best recommendation results. Parameters ---------- closest_neighbors : List The closest sessions ranked by similarity to a given session. session : List User session. Returns ------- : List List of rated items in descending order. """ session_items = session[0] scores = dict() for neighbor in closest_neighbors: n_items = self.session_item_map[neighbor[0]][0] step = 1 decay = 1 for s_item in reversed(session_items): if s_item in n_items: decay = weight_item_score(self.ranking_strategy, step) break step = step + 1 for n_item in n_items: if n_item in session_items: # We do not want to score items viewed by the user # TODO: condition to control this behavior pass else: old_score = scores.get(n_item) new_score = neighbor[1] # TODO: idf weighting new_score = new_score * decay if old_score is not None: new_score = old_score + new_score scores.update({n_item: new_score}) rank = list() for k, v in scores.items(): rank.append((k, v)) return rank # Transform, sample, rank - additional def _calculate_similarity(self, session_items: List, possible_neighbours: List) -> List: """Function calculates similarity between sessions based on the items ranking. Parameters ---------- session_items : List List of items from the customer session. possible_neighbours : List List of sessions from the possible neighbors pool (based on a sampling strategy). Returns ------- neighbors : List List of similar sessions to the customer session. """ pos_weights = dict() length = len(session_items) for idx, item in enumerate(session_items): count = idx + 1 pos_weights[item] = weight_session_items(self.weighting_function, count, length) items = set(session_items) neighbours = [] for other in possible_neighbours: other_items = set(self.session_item_map[other][0]) similarity = weight_set_pair(items, other_items, pos_weights) neighbours.append([other, similarity]) return neighbours def _get_sessions_with_event(self, raw_sessions: Set) -> Set: """Method parses available input sessions based on the occurence of a specific event and returns list of unique sessions with this event. Parameters ---------- raw_sessions : Set Returns ------- unique_session_with_event : Set """ new_sessions = set() for sess in raw_sessions: session_sample = self.session_item_map[sess] if self.required_sampling_event in session_sample[2]: new_sessions.add(sess) return new_sessions def _sampling_common(self, sessions: Set, session: List) -> List: """Function gets the most similar sessions based on the number of common elements between sessions. Parameters ---------- sessions : set Unique sessions. session : List The customer session. Returns ------- : List List of n possible sessions with the same items as a customer session. """ rank = [(ses, len(set(self.session_item_map[ses][0]) & set(session[0]))) for ses in sessions] rank.sort(key=lambda x: x[1]) result = [x[0] for x in rank] sample_size = min(self.possible_neighbors_sample_size, len(sessions)) return result[:sample_size] def _sample_possible_neighbors(self, all_sessions: Set, session: List) -> List: """Method samples possible neighbors. Parameters ---------- all_sessions : set All sessions to sample possible neighbors. session : List Customer session. Returns ------- : List subset of possible neighbors """ if self.sampling_strategy == 'random': return self._sampling_random(all_sessions) elif self.sampling_strategy == 'recent': return self._sampling_recent(all_sessions) elif self.sampling_strategy == 'common_items': return self._sampling_common(all_sessions, session) else: err_msg = f'Defined sampling strategy {self.sampling_strategy} not implemented. Available strategies are:' \ f' {self.sampling_strategies}.' raise TypeError(err_msg) def _sampling_random(self, sessions: Set) -> List: """Get random sessions from the sessions space. This method is good to estimate model performance or to test it. Parameters ---------- sessions : set Unique sessions. Returns ------- : List Random sample of self.possible_neighbors_sample_size sessions. """ sample_size = min(self.possible_neighbors_sample_size, len(sessions)) sample = random.sample(sessions, sample_size) return sample def _sampling_recent(self, sessions: Set) -> List: """Get most recent sessions from the possible neighbors. Parameters ---------- sessions : set Unique sessions. Returns ------- : List Most recent sessions. Sample of size possible_neighbors_sample_size. """ rank = [(sid, self.session_item_map[sid][1]) for sid in sessions] rank.sort(key=lambda x: x[1], reverse=True) result = [x[0] for x in rank] sample_size = min(self.possible_neighbors_sample_size, len(sessions)) return result[:sample_size]
35.816354
120
0.571429
777bcce426e329c86d190822ab4ef2c740cee1bb
4,510
swift
Swift
Sources/HAR/Content.swift
rawbee/swift-har
b404d6296fea7ec46bfc2cca27a2e9255407af5a
[ "MIT" ]
9
2020-06-25T03:23:58.000Z
2021-10-31T09:13:06.000Z
Sources/HAR/Content.swift
rawbee/swift-har
b404d6296fea7ec46bfc2cca27a2e9255407af5a
[ "MIT" ]
null
null
null
Sources/HAR/Content.swift
rawbee/swift-har
b404d6296fea7ec46bfc2cca27a2e9255407af5a
[ "MIT" ]
1
2022-03-23T16:24:48.000Z
2022-03-23T16:24:48.000Z
import struct Foundation.Data public extension HAR { /// This object describes details about response content (embedded in `Response` /// object). struct Content: Equatable, Hashable, Codable, CustomStringConvertible { // MARK: Properties /// Length of the returned content in bytes. Should be equal to /// `response.bodySize` if there is no compression and bigger when the content /// has been compressed. public var size: Int /// Number of bytes saved. Leave out this field if the information is not /// available. public var compression: Int? /// MIME type of the response text (value of the Content-Type response header). /// The charset attribute of the MIME type is included (if available). public var mimeType: String /// Response body sent from the server or loaded from the browser cache. This /// field is populated with textual content only. The text field is either HTTP /// decoded text or a encoded (e.g. "base64") representation of the response /// body. Leave out this field if the information is not available. /// /// Before setting the text field, the HTTP response is decoded (decompressed & /// unchunked), than trans-coded from its original character set into UTF-8. /// Additionally, it can be encoded using e.g. base64. Ideally, the application /// should be able to unencode a base64 blob and get a byte-for-byte identical /// resource to what the browser operated on. public var text: String? /// Encoding used for response text field e.g "base64". Leave out this field if /// the text field is HTTP decoded (decompressed & unchunked), than trans-coded /// from its original character set into UTF-8. /// /// Encoding field is useful for including binary responses (e.g. images) into /// the HAR file. /// /// - Version: 1.2 public var encoding: String? /// A comment provided by the user or the application. /// /// - Version: 1.2 public var comment: String? // MARK: Computed Properties /// Get content body as Data. May return empty Data if text is encoded improperly. public var data: Data { guard let text = text else { return Data(count: 0) } switch encoding { case "base64": return Data(base64Encoded: text) ?? Data(count: 0) default: return Data(text.utf8) } } // MARK: Initializers /// Create content. public init( size: Int, compression: Int? = nil, mimeType: String, text: String? = nil, encoding: String? = nil, comment: String? = nil ) { self.size = size self.compression = compression self.mimeType = mimeType self.text = text self.encoding = encoding self.comment = comment } /// Create empty unknown response body content. public init() { self.size = 0 self.mimeType = "application/octet-stream" } /// Create HAR Content from string. public init(text: String, encoding: String? = nil, mimeType: String?) { self.init() if let mimeType = mimeType { self.mimeType = mimeType } self.encoding = encoding self.text = text self.size = data.count } /// Create HAR Content decoding HTTP Body Data. public init(decoding data: Data, mimeType: String?) { self.init() if let mimeType = mimeType { self.mimeType = mimeType } self.size = data.count if let text = String(bytes: data, encoding: .utf8) { self.text = text } else { self.text = data.base64EncodedString() self.encoding = "base64" } } /// Create HAR Content from text string. public init(_ description: String) { self.init(text: description, mimeType: "text/plain") } /// A human-readable description for the data. public var description: String { String(decoding: data, as: UTF8.self) } } }
34.96124
90
0.566075
7f9756543bbcb56693b0533dd07a67bd9e73a15b
1,221
php
PHP
resources/views/pendaftaran/edit_form.blade.php
rizkysaid/rekam-medis
b54fd1b010db27cbe6c66ccf5231674c4da86779
[ "MIT" ]
null
null
null
resources/views/pendaftaran/edit_form.blade.php
rizkysaid/rekam-medis
b54fd1b010db27cbe6c66ccf5231674c4da86779
[ "MIT" ]
null
null
null
resources/views/pendaftaran/edit_form.blade.php
rizkysaid/rekam-medis
b54fd1b010db27cbe6c66ccf5231674c4da86779
[ "MIT" ]
null
null
null
{!! Form::model($model, [ 'route' => ['pendaftaran.update', $model->id], 'method' => 'PUT' ]) !!} <div class="form-group row col-sm-12"> <label class="col-sm-3">Tanggal</label> <div class="col-sm-9 input-group"> <input type="text" name="tgl_daftar" class="form-control" id="tgl_daftar" value="{{ date('d-m-Y', strtotime($model->tgl_daftar)) }}"> <div class="input-group-append"> <span class="input-group-text fa fa-calendar"></span> </div> </div> </div> <div class="form-group row col-sm-12"> <label class="col-sm-3">Poli</label> <div class="col-sm-9"> {!! Form::select('id_poli', $poli, null, ['class' => 'form-control required', 'id'=>'id_poli', 'placeholder' => 'Pilih Poli...', 'autofocus'=>'true']); !!} </div> </div> <div class="form-group row col-sm-12"> <label class="col-sm-3">Jaminan</label> <div class="col-sm-9"> {!! Form::select('id_pasien_tp', $pasien_tp, null, ['class' => 'form-control bpjs', 'id'=>'id_pasien_tp', 'placeholder' => 'Pilih tipe...', 'autofocus'=>'true']); !!} </div> </div> {!! Form::close() !!}
43.607143
178
0.526618
851551d1f9a58655b8947d508bfe3d594d9461aa
561
cs
C#
Assets/Scripts/Visuals/DamageOverlay.cs
JacekCzupyt/engineering-thesis
1b7e0d9c23123b1481e2a9391210068216c0f272
[ "MIT" ]
null
null
null
Assets/Scripts/Visuals/DamageOverlay.cs
JacekCzupyt/engineering-thesis
1b7e0d9c23123b1481e2a9391210068216c0f272
[ "MIT" ]
null
null
null
Assets/Scripts/Visuals/DamageOverlay.cs
JacekCzupyt/engineering-thesis
1b7e0d9c23123b1481e2a9391210068216c0f272
[ "MIT" ]
null
null
null
using UnityEngine; using Image = UnityEngine.UI.Image; namespace Visuals { public class DamageOverlay : MonoBehaviour { [SerializeField] private float rate = 2; private float alpha = 0; private Image overlay; private void Start() { overlay = GetComponent<Image>(); } void Update() { alpha = Mathf.Lerp(0, alpha, 1 - (Time.deltaTime * rate)); overlay.color = new Color(1, 0, 0, alpha); } public void Trigger() { alpha = 1; } } }
22.44
70
0.541889
f53c66fc80b5561011e9bc1397107e1c4be896c9
362
swift
Swift
Sources/DataStructures/Pair/SwappablePair.swift
bwetherfield/Structure
fc7d6a9dbaeb9c750988a6a142d5f67e395ddf69
[ "MIT" ]
9
2017-08-27T19:48:17.000Z
2021-11-08T15:28:50.000Z
Sources/DataStructures/Pair/SwappablePair.swift
bwetherfield/Structure
fc7d6a9dbaeb9c750988a6a142d5f67e395ddf69
[ "MIT" ]
78
2017-07-28T16:13:21.000Z
2018-11-25T03:33:24.000Z
Sources/DataStructures/Pair/SwappablePair.swift
bwetherfield/Structure
fc7d6a9dbaeb9c750988a6a142d5f67e395ddf69
[ "MIT" ]
2
2019-06-15T18:38:54.000Z
2019-06-29T18:24:54.000Z
// // SwappablePair.swift // DataStructures // // Created by James Bean on 9/27/18. // /// A `SymmetricPair` whose values can be interchanged. public protocol SwappablePair: SymmetricPair { } extension SwappablePair { /// - Returns: A `SwappablePair` wherein the values are swapped for one another. public var swapped: Self { return .init(b,a) } }
22.625
84
0.698895
dbcfc6328217b797446dc8fa404f3b2d9311d7d1
486
php
PHP
app/Http/Controllers/Controller.php
johnghattas/espitaliaa
2018bf7bfec9ddefd8ff28a6694224873b331ba1
[ "MIT" ]
null
null
null
app/Http/Controllers/Controller.php
johnghattas/espitaliaa
2018bf7bfec9ddefd8ff28a6694224873b331ba1
[ "MIT" ]
null
null
null
app/Http/Controllers/Controller.php
johnghattas/espitaliaa
2018bf7bfec9ddefd8ff28a6694224873b331ba1
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use DateTime; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function ctDT(string $day) { return DateTime::createFromFormat('d/m/Y', $day); } }
23.142857
62
0.779835
da49bce6717a5e29398fb62403372bee19e6138a
245
php
PHP
hphp/hack/test/typecheck/reified_generics/newable_targ_consistent.php
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
9,491
2015-01-01T00:30:28.000Z
2022-03-31T20:22:11.000Z
hphp/hack/test/typecheck/reified_generics/newable_targ_consistent.php
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
4,796
2015-01-01T00:26:31.000Z
2022-03-31T01:09:05.000Z
hphp/hack/test/typecheck/reified_generics/newable_targ_consistent.php
donsbot/hhvm
ac98a590f75c569e1249b6c1145c7512c7bd240e
[ "PHP-3.01", "Zend-2.0" ]
2,126
2015-01-01T11:13:29.000Z
2022-03-28T19:58:15.000Z
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. <<__ConsistentConstruct>> abstract class ACC {} class CC extends ACC {} function f<<<__Newable>> reify T as ACC>(): void { new T(); } function g(): void { f<CC>(); }
16.333333
56
0.653061
7e30aa9bd9dff9b0edbfea0973a55d80c1cc0b1a
3,816
rb
Ruby
lib/barrister/action.rb
seinosuke/barrister
faaf38818120263431344ff4a61c3b8305ede773
[ "MIT" ]
null
null
null
lib/barrister/action.rb
seinosuke/barrister
faaf38818120263431344ff4a61c3b8305ede773
[ "MIT" ]
null
null
null
lib/barrister/action.rb
seinosuke/barrister
faaf38818120263431344ff4a61c3b8305ede773
[ "MIT" ]
null
null
null
module Barrister module Action # # Driving Slave # # The machine moves back and forward. def move(forward = true) unless @debug @slaves[:driving_right].rotate(forward) @slaves[:driving_left].rotate(forward) end @position = (Vector[*@position] + case @angle when 0 then Vector[0, forward ? 1 : -1] when 90 then Vector[forward ? 1 : -1, 0] when 180 then Vector[0, forward ? -1 : 1] when 270 then Vector[forward ? -1 : 1, 0] end).to_a @logger[:file].info("Action : move #{forward ? "forward" : "back"}") end # The machine moves back and forward. def move12(forward = true) unless @debug @slaves[:driving_right].rotate12(forward) @slaves[:driving_left].rotate12(forward) end @position = (Vector[*@position] + case @angle when 0 then Vector[0, forward ? 1 : -1] when 90 then Vector[forward ? 1 : -1, 0] when 180 then Vector[0, forward ? -1 : 1] when 270 then Vector[forward ? -1 : 1, 0] end).to_a @logger[:file].info("Action : move #{forward ? "forward" : "back"}") end # The machine turns on the spot. def turn(cw = true) unless @debug @slaves[:driving_right].turn(!cw) @slaves[:driving_left].turn(cw) end @angle += cw ? 90 : -90 @angle = 0 if @angle == 360 @angle = 270 if @angle == -90 @logger[:file].info("Action : turn #{cw ? "cw" : "ccw"}") end def stop unless @debug @slaves[:driving_right].stop @slaves[:driving_left].stop end @logger[:file].info("Action : stop") end # # Sensing Slave # # Get data of a distance from an object. def get_distance @slaves[:sensing].get_distance end # Return `true` if the machine was at a crossroads. def on_cross?(threshold = 100) @slaves[:sensing].on_cross?(threshold) end # # Collecting Slave # def collect_pylon(x, y) unless @debug phase01; phase02; phase03; phase04 end @field.remove_object(x, y) @logger[:file].info("Action : collect pylon") end def release_pylons unless @debug dc_rotate(false); sleep 0.5 dc_stop; sleep 1 dc_rotate(true); sleep 0.5 dc_stop end @logger[:file].info("Action : release pylons") end # Move back. def phase01 move(false); sleep 0.45 stop; sleep 1 end # Swing an arm to front and hold a pylon. def phase02 st_rotate(true); sleep 0.2 # wait for rising st_stop; sleep 1 swing_arm(true); sleep 2 hold_pylon(false) st_rotate(false); sleep 1 st_off; sleep 4 # wait for falling hold_pylon(true); sleep 0.5 hold_pylon(false); sleep 0.5 st_rotate(false); sleep 0.1; st_off; sleep 1 hold_pylon(true); sleep 0.5 end # Let the pylon go. def phase03 st_rotate(true); sleep 5.1 # wait for rising st_stop; sleep 1 swing_arm(false); sleep 2 st_off hold_pylon(false); sleep 1 end # Return to a previous position. def phase04 move(true) sleep 0.1 until on_cross?(@threshold) sleep 0.08 stop end def st_rotate(cw = true) @slaves[:collecting].st_rotate(cw) end def st_stop @slaves[:collecting].st_stop end def st_off @slaves[:collecting].st_off end def swing_arm(front = true) @slaves[:collecting].swing_arm(front) end def hold_pylon(hold = true) @slaves[:collecting].hold_pylon(hold) end def dc_rotate(cw = true) @slaves[:collecting].dc_rotate(cw) end def dc_stop @slaves[:collecting].dc_stop end end end
23.127273
74
0.579927
21d0e22eda9b0ee5a4dc7e8ba723da947efa8e19
517
js
JavaScript
src/count-primes.js
akuma/my-leetcode
ab2cf146bccf0c70194e88a172a709ab4fc141ef
[ "MIT" ]
null
null
null
src/count-primes.js
akuma/my-leetcode
ab2cf146bccf0c70194e88a172a709ab4fc141ef
[ "MIT" ]
null
null
null
src/count-primes.js
akuma/my-leetcode
ab2cf146bccf0c70194e88a172a709ab4fc141ef
[ "MIT" ]
null
null
null
/** * Count Primes * https://leetcode.com/problems/count-primes/ * * @param {number} n * @return {number} */ const countPrimes = function(n) { const isPrimes = [false, false] for (let i = 2; i < n; i++) { isPrimes.push(true) } for (let i = 2; i * i < n; i++) { if (!isPrimes[i]) { continue } for (let j = i * i; j < n; j += i) { isPrimes[j] = false } } let count = 0; for (let i = 2; i < n; i++) { if (isPrimes[i]) { count++ } } return count }
16.15625
46
0.483559
982d356bc8dafd7b028c5abf6dbcedc1c24720ae
642
cs
C#
Yuebon.NetCore/Yuebon.Commons/Attributes/AppDbContextFactoryAttribute.cs
JonasChan2020/DataProcess
1d565fb32eb6b276fe3b11ad9a63cd9cccc2a5b2
[ "MIT" ]
2
2021-02-07T10:16:59.000Z
2021-02-22T17:19:15.000Z
Yuebon.NetCore/Yuebon.Commons/Attributes/AppDbContextFactoryAttribute.cs
JonasChan2020/DataProcess
1d565fb32eb6b276fe3b11ad9a63cd9cccc2a5b2
[ "MIT" ]
null
null
null
Yuebon.NetCore/Yuebon.Commons/Attributes/AppDbContextFactoryAttribute.cs
JonasChan2020/DataProcess
1d565fb32eb6b276fe3b11ad9a63cd9cccc2a5b2
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Yuebon.Commons.Attributes { /// <summary> /// 数据库上下文配置 /// </summary> public class AppDbContextFactoryAttribute : Attribute { /// <summary> /// 数据库配置名称 /// </summary> public string DbConfigName { get; set; } /// <summary> /// /// </summary> /// <param name="dbConfigName">数据库配置名称</param> public AppDbContextFactoryAttribute(string dbConfigName) { DbConfigName = dbConfigName; } } }
22.137931
64
0.587227
af2810cd600fe8233d9f3cec543a347ad0b1124b
1,982
rs
Rust
src/message_handling/MessageHandler.rs
lemonrock/message-dispatch
ec4023db0781cad397a2f14b3cfecf6002199657
[ "MIT" ]
1
2021-01-29T18:03:22.000Z
2021-01-29T18:03:22.000Z
src/message_handling/MessageHandler.rs
lemonrock/message-dispatch
ec4023db0781cad397a2f14b3cfecf6002199657
[ "MIT" ]
null
null
null
src/message_handling/MessageHandler.rs
lemonrock/message-dispatch
ec4023db0781cad397a2f14b3cfecf6002199657
[ "MIT" ]
null
null
null
// This file is part of message-dispatch. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/message-dispatch/master/COPYRIGHT. No part of message-dispatch, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019-2020 The developers of message-dispatch. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/message-dispatch/master/COPYRIGHT. pub(crate) struct MessageHandler<MessageHandlerArguments, MessageHandlerReturns> { message_handler: fn(NonNull<VariablySizedMessageBody>, &MessageHandlerArguments) -> MessageHandlerReturns, } impl<MessageHandlerArguments, MessageHandlerReturns> Debug for MessageHandler<MessageHandlerArguments, MessageHandlerReturns> { #[inline(always)] fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "MessageHandler({:?})", self.message_handler as usize) } } impl<MessageHandlerArguments, MessageHandlerReturns> MessageHandler<MessageHandlerArguments, MessageHandlerReturns> { /// Creates a new instance, wrapping `function`. /// /// `function` will be moved from the stack to the heap. #[inline(always)] pub(crate) fn new<FixedSizedMessageBody: Sized>(message_handler: fn(&mut FixedSizedMessageBody, &MessageHandlerArguments) -> MessageHandlerReturns) -> Self { Self { message_handler: unsafe { transmute(message_handler) }, } } /// A very dangerous method that will fail in subtle yet fatal ways if `VariablySizedMessageBody` is not the same type as `FixedSizedMessageBody` in `new()`. #[inline(always)] pub(crate) fn call(&self, variably_sized_message_body: NonNull<VariablySizedMessageBody>, arguments: &MessageHandlerArguments) -> MessageHandlerReturns { (self.message_handler)(variably_sized_message_body, arguments) } }
49.55
403
0.787588
7974fe9cac9c12c314409dae02558752a74b74f2
276
php
PHP
app/Http/Controllers/MapController.php
yosmangel/realstat360
ca8327edf9f814f6fc48276a48298686b9c171f2
[ "MIT" ]
null
null
null
app/Http/Controllers/MapController.php
yosmangel/realstat360
ca8327edf9f814f6fc48276a48298686b9c171f2
[ "MIT" ]
2
2018-02-03T17:39:17.000Z
2018-02-03T17:52:24.000Z
app/Http/Controllers/MapController.php
rafaelgamezdiaz/proyrstp
dd38436aa5b551e4b68367f240f8d576f00fa98f
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use Mapper; class MapController extends Controller { public function index() { Mapper::map(53.381128999999990000, -1.470085000000040000); return view('map'); } }
13.142857
63
0.710145
b9e63358bb536f206b50b2c9142b2c0c1de4c419
229
rs
Rust
src/async_fuse/memfs/dist/mod.rs
uran0sH/datenlord
6ee370906487353fd6e631b87ba5ff24f86aa444
[ "MIT" ]
546
2020-01-17T07:53:20.000Z
2022-03-27T07:44:52.000Z
src/async_fuse/memfs/dist/mod.rs
uran0sH/datenlord
6ee370906487353fd6e631b87ba5ff24f86aa444
[ "MIT" ]
130
2020-06-02T05:27:33.000Z
2022-03-30T05:28:30.000Z
src/async_fuse/memfs/dist/mod.rs
uran0sH/datenlord
6ee370906487353fd6e631b87ba5ff24f86aa444
[ "MIT" ]
59
2020-01-17T11:23:26.000Z
2022-03-28T09:57:49.000Z
/// Distributed communication client pub mod client; /// Communication with etcd pub mod etcd; pub mod request; pub mod response; pub mod server; /// Tcp communication module mod tcp; /// Serializable types module pub mod types;
19.083333
36
0.759825
6b8fa9ea57e03cf2422789ae8456affe44369f2e
13,182
js
JavaScript
contrat.js
smartsas/smartsas
eab239e14fc82fc1d1da54ebe5dd4f75382dbd6e
[ "MIT" ]
null
null
null
contrat.js
smartsas/smartsas
eab239e14fc82fc1d1da54ebe5dd4f75382dbd6e
[ "MIT" ]
null
null
null
contrat.js
smartsas/smartsas
eab239e14fc82fc1d1da54ebe5dd4f75382dbd6e
[ "MIT" ]
1
2021-01-25T10:35:47.000Z
2021-01-25T10:35:47.000Z
function contratPDF(prix, commission) { let nom = document.getElementById("nom").value; let prenom = document.getElementById("prenom").value; let oeuvre = document.getElementById("description").value; //let prix = document.getElementById("prix").value; //let commission = document.getElementById("royalties").value; let compteEthereum = accounts[0]; let date = new Date(); let docDefinition = { content: [ { text: [ { text: "CONTRAT DE CESSION DE DROITS D’AUTEUR \n\n\n", alignment: 'center', bold: true }, { text: "Définitions \n\n", alignment: 'left', bold: true }, { text: "La Blockchain : désigne le dispositif d'enregistrement électronique partagé test d'Ethereum (Ropsten) ; dans sa version implémentée par le client logiciel go-ethereum.\n\n", alignment: 'left' }, { text: "Le Créateur : désigne la personne, physique ou morale, créatrice de l'oeuvre ( la Création) dont les droits sont cédés. Elle est titulaire des droits patrimoniaux et extra-patrimoniaux sur celle-ci et de l'adresse Blockchain suivante: ", alignment: 'left' }, { text: compteEthereum }, { text: "\n\n" }, { text: "Le Jeton : désigne l'actif numérique, émis, inscrit, et transférable dans la Blockchain. La fonction ownerOf(1) de son registre permet de déterminer l'adresse Blockchain détentrice du Jeton. Le registre indiquant la propriété du Jeton est déployé dans la Blockchain à l'adresse suivante : ", alignment: 'left' }, { text: addresseSmartcontract }, { text: "\n\n", }, { text: "La Création : désigne l’œuvre de l'esprit produite par le Créateur. \n\n", alignment: 'left' }, { text: "Le Détenteur : désigne la personne, physique ou morale, titulaire de l'adresse Blockchain que la fonction ownerOf(1) du registre indique être détentrice du Jeton.\n\n\n", alignment: 'left', pageBreak : "after" }, { text: "Etant préalablement rappelé que : \n\n", alignment: 'left', bold: true }, { text: [ "Le Créateur, ci-dénommé : ", nom, " ", prenom, "\n\n", "A réalisé l'œuvre de l'esprit suivante : ", oeuvre, " (ci-après la « Création »).", "\n\n", "La Création est identifiée par l'empreinte numérique suivante (hash 256) : ", hashOeuvre, "\n\n", "Le Créateur entend permettre la cession de ses droits d'auteurs à travers la Blokchain. Pour cela, il a déployé le Jeton dont la détention constitue la seule forme d'acceptation au présent contrat. \n\n", "Ainsi, toute au personne que le Créateur qui est Détenteur du Jeton, doit être considérée comme le cessionnaire de la présente cession de droits d'auteurs.\n\n\n", ] }, { text: "Il a été convenu et arrêté ce qui suit : \n\n\n", alignment: 'left', bold : true }, { text: "1. Objet de la cession \n\n", alignment: 'left', bold : true }, { text: ["Par les présentes, le Créateur cède au Détenteur, sans restriction ni réserve, les droits d’auteur ci-après énumérés, à savoir : \n\n", "le droit de reproduire sa Création, en totalité ou en partie, en tout format, sur tout support notamment imprimé, magnétique, électronique et numérique, sur tout produit, de quelque nature qu’il soit et par tout procédé matériel ou immatériel, existants ou à venir, prévisibles ou imprévisibles ; \n\n", "le droit de fabriquer ou faire fabriquer, éditer, distribuer, diffuser et commercialiser sa Création, en autant d’exemplaires qu’il plaira au Détenteur, en tout ou en partie et dans tous circuits de commercialisation ;\n\n", "le droit de représenter publiquement sa Création, en totalité ou en partie, en tout lieu physique, à travers tous médias, tous réseaux informatiques et tous moyens de diffusion, de quelque nature qu’ils soient, existants ou à venir, prévisibles ou imprévisibles, tels que, sans que cette liste soit limitative, par internet, téléphonie mobile et télédiffusion; \n\n", "le droit d’adapter, traduire, modifier, arranger, transformer et corriger sa Création, notamment, sans que cette liste soit limitative, à travers la retouche, le recadrage, le changement de format ou de couleurs sa Création ou encore l’apposition sur celles-ci, par le Détenteur, de son nom, de sa marque et de son logo, pour tenir compte en particulier de contraintes techniques, matérielles ou commerciales ou pour tout autre motif légitime, sous réserve du respect du droit moral du Créateur,\n\n", "le droit d’utiliser sa Création, en totalité ou en partie, afin de les associer avec, incorporer dans ou exploiter à travers, sans que cette liste soit limitative, tous éléments visuels, sonores et/ou textuels et tous produits, notamment tous produits multimédia ou audiovisuels, sites internet, jeux, applications ;\n\n", "le droit d’utiliser tout ou partie sa Création aux fins d’exploitations dérivées (communément désignées sous le nom de « merchandising »), notamment en vue de fabriquer et diffuser des produits commerciaux, de quelque nature que ce soit, et de les distribuer, en particulier dans les domaines des jeux, jouets, objets ou œuvres d'art plastique ou arts appliqués, papeterie, bureautique, fonds d’écran, articles de bureau, habillement, ameublement, articles de décoration, arts de la table, toilette, hygiène, alimentation ; \n\n", "Cette cession, consentie à titre exclusif, vaut pour toute la durée légale du droit d'auteur et pour le monde entier.\n\n\n" ] }, { text: "2. Objet de la cession \n\n", alignment: 'left', bold : true }, { text: ["Le Créateur garantit au Détenteur la jouissance entière et paisible des droits cédés contre tous troubles, actions revendications ou évictions quelconques. \n\n", "Il garantit ainsi notamment au Détenteur qu’il dispose de tous les droits et autorisations nécessaires pour consentir la présente cession et que sa Création ne contient rien qui puisse tomber sous le coup des lois et règlements relatifs notamment à la contrefaçon, la concurrence déloyale, la vie privée, le droit à l'image, les droits de la personnalité et plus généralement, contrevenir aux droits des tiers.\n\n", "Le Créateur garantit le Détenteur contre toutes plaintes, réclamations et/ou revendications quelconques de la part d’un tiers que le Détenteur pourrait subir du fait de la violation, par Le Créateur, des garanties ci-dessus. Il s’engage à indemniser le Détenteur de tout préjudice qu’il subirait et à lui payer tous les frais, indemnités, charges et/ou condamnations qu’il pourrait avoir à supporter de ce fait. \n\n\n" ] }, { text: "3. Paiement \n\n", alignment: 'left', bold : true }, { text: ["En contrepartie de la cession des droits d’auteur, le Détenteur verse au Créateur une rémunération forfaitaire d’un montant de ", prix, " euros.\n\n ", "Par la suite, le Détenteur peut revendre ses droits à des tiers au prix auquel il l'entend. Il s'engage toutefois à verser une commission de ", commission, " % au Créateur sur la vente. \n\n", "Modalités de paiement : \n\n", "Le paiement au Créateur est effectué par un transfert d'ethers, unité monétaire virtuelle de la Blockchain, vers son adresse Blockchain. \n\n\n", ] }, { text: "4. Cession de contrat à des tiers \n\n", alignment: 'left', bold : true }, { text: ["Le Créateur autorise à ce que le Détenteur cède sa qualité de partie au présent contrat à un tiers. \n\n", "La détention du Jeton par le tiers vaut acceptation par ce dernier aux stipulations des présentes.\n\n", "Il est alors Détenteur du Jeton et peut à son tour céder sa qualité de Partie au présent contrat. \n\n\n" ] }, { text: "5. Loi applicable et juridiction \n\n", alignment: 'left', bold : true }, { text: ["Le présent contrat est soumis au droit français et sera régi et interprété selon ce droit. \n\n", "Tout litige pouvant naître à l'occasion de sa validité, de son interprétation ou de son exécution sera soumis à la compétence exclusive des Tribunaux de Paris, sauf règle de procédure impérative contraire.\n\n\n" ] }, { text: "ACTE DE CESSION DE CONTRAT\n\n\n", alignment: 'center', bold : true }, { text: ["Conformément à l'article 1216 du code civil, le présent acte vaut constatation écrite de la cession de contrat opérant lorsque le Détenteur transfère le Jeton à un tiers. \n\n", "Par cette opération, le Détenteur du Jeton cède au tiers sa qualité de partie au contrat de cession de droits d'auteur ci-dessus mentionné. \n\n", "L'acceptation à cet acte de cession ne peut prendre que la forme suivante : \n\n", "- Pour le tiers cessionnaire, elle consiste à utiliser la fonction buyDA() du Jeton pour l'acheter et en devenir le détenteur.\n\n", "- Pour le Détenteur du Jeton, elle consiste à approuver l'adresse du tiers cessionnaire dans la Blockchain afin qu'il puisse détenir le Jeton.\n\n", "Lorsque ces deux conditions sont remplies, le tiers et le Détenteur sont réputés avoir consenti à la présente cession de contrat.\n\n", "Le tiers cessionnaire devient alors partie au contrat de cession de droits d'auteur ci-dessus mentionné en tant que Détenteur du Jeton." ] }, ] } ] } const pdfDocGenerator = pdfMake.createPdf(docDefinition); return new Promise(function (resolve, reject) { pdfDocGenerator.telecharger().then((blob)=> { blob.lastModifiedDate = new Date(); blob.name = "contrat-cession-da" var reader = new FileReader(); reader.readAsArrayBuffer(blob); reader.onload = function () { var file_result = this.result; // this == reader, get the loaded file "result" var file_wordArr = CryptoJS.lib.WordArray.create(file_result); //convert blob to WordArray , see https://code.google.com/p/crypto-js/issues/detail?id=67 var sha256_hash = CryptoJS.SHA256(file_wordArr); //calculate SHA1 hash var Hash = sha256_hash.toString(); //output result saveAs(blob); resolve (Hash); }; }); }) }
44.234899
559
0.545592
8534858d52a477bf55b517dccc4b1929a29ee23f
264
cs
C#
src/Domain/Events/BudgetCreatedEvent.cs
gayankanishka/budgetly-api
900b337cef9a8874480007a97bf3db98a7722cf9
[ "MIT" ]
null
null
null
src/Domain/Events/BudgetCreatedEvent.cs
gayankanishka/budgetly-api
900b337cef9a8874480007a97bf3db98a7722cf9
[ "MIT" ]
null
null
null
src/Domain/Events/BudgetCreatedEvent.cs
gayankanishka/budgetly-api
900b337cef9a8874480007a97bf3db98a7722cf9
[ "MIT" ]
null
null
null
using Budgetly.Domain.Common; using Budgetly.Domain.Entities; namespace Budgetly.Domain.Events; public class BudgetCreatedEvent : DomainEvent { public BudgetCreatedEvent(Budget budget) { Budget = budget; } public Budget Budget { get; } }
18.857143
45
0.719697
44758aff9616b14583078b1405c0e1e11d71f51f
1,892
py
Python
mach_cad/model_obj/dimensions/dim_base.py
Severson-Group/MachEval
dbb7999188133f8744636da53cab475ae538ce80
[ "BSD-3-Clause" ]
6
2021-11-02T20:12:32.000Z
2021-11-13T10:50:35.000Z
mach_cad/model_obj/dimensions/dim_base.py
Severson-Group/MachEval
dbb7999188133f8744636da53cab475ae538ce80
[ "BSD-3-Clause" ]
18
2021-11-29T20:14:55.000Z
2022-03-02T07:17:37.000Z
mach_cad/model_obj/dimensions/dim_base.py
Severson-Group/MachEval
dbb7999188133f8744636da53cab475ae538ce80
[ "BSD-3-Clause" ]
1
2022-01-29T00:52:38.000Z
2022-01-29T00:52:38.000Z
from abc import abstractmethod, ABC class DimBase(float, ABC): @abstractmethod def _conversion_factor(self): pass def __new__(cls, value): return float.__new__(cls, value) def __add__(self, other): add = self._to_dimensionless() + other._to_dimensionless() return type(self)._from_dimensionless(type(self), add) def __sub__(self, other): sub = self._to_dimensionless() - other._to_dimensionless() return type(self)._from_dimensionless(type(self), sub) def __mul__(self, other): if isinstance(self, DimBase) and isinstance(other, DimBase): raise Exception('Multiplication Not valid') if isinstance(self, DimBase): mul = other * (self._to_dimensionless()) return type(self)._from_dimensionless(type(self), mul) def __rmul__(self, other): if isinstance(self, DimBase) and isinstance(other, DimBase): raise Exception('Multiplication Not valid') if isinstance(self, DimBase): mul = other * (self._to_dimensionless()) type(self)._from_dimensionless(type(self), mul) def __truediv__(self, other): if isinstance(other, DimBase): div = self._to_dimensionless() / other._to_dimensionless() return div else: div = (self._to_dimensionless()) / (other) return type(self)._from_dimensionless(type(self), div) def __rtruediv__(self, other): raise Exception('Division not valid') def _to_dimensionless(self): return float(self) * self._conversion_factor def _from_dimensionless(cls, value): x = value / cls._conversion_factor return cls(x) def __neg__(self): return self * -1 def __pos__(self): if self < 0: return self * -1 else: return self
29.5625
70
0.623679
24b45af6f6d73ba67c168f1a12f896bd84dc6f68
1,883
php
PHP
app/Http/Controllers/VaccineController.php
Piphiz/ControleVacina
8bfe738382bd6fb159c56a0d8a030d2eacfb3e6e
[ "MIT" ]
null
null
null
app/Http/Controllers/VaccineController.php
Piphiz/ControleVacina
8bfe738382bd6fb159c56a0d8a030d2eacfb3e6e
[ "MIT" ]
null
null
null
app/Http/Controllers/VaccineController.php
Piphiz/ControleVacina
8bfe738382bd6fb159c56a0d8a030d2eacfb3e6e
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Http\Requests\UpdateVaccineRequest; use App\Http\Requests\VaccineRequest; use App\Models\Vaccine; use App\Services\VaccineService; use Carbon\Carbon; use Illuminate\Http\Request; class VaccineController extends Controller { protected $vaccine; protected $vaccineService; public function __construct(Vaccine $vaccine, VaccineService $vaccineService) { $this->vaccine = $vaccine; $this->vaccineService = $vaccineService; } public function index() { $vaccine = $this->vaccine->paginate(10); return response()->json($vaccine, 200); } public function store(VaccineRequest $request) { try { $this->vaccineService->checkList(); $data = $request->all(); $this->vaccine->create($data); return response()->json( ['message' => 'Usuario criado com sucesso'], 201 ); } catch (\Exception $e) { return response()->json( ['Error' => $e->getMessage()], $e->getCode() ); } } public function show(Vaccine $vaccine, $id) { $vaccine = $this->vaccine->findOrFail($id); return response()->json($vaccine, 200); } public function update(UpdateVaccineRequest $request, $id) { $vaccine = $this->vaccine->findOrFail($id); try { $data = $request->all(); $vaccine->update($data); return response()->json([],200); } catch (\Exception $e) { return response()->json([],404); } } public function destroy($id) { $vaccine = $this->vaccine->findOrFail($id); $vaccine->destroy(); return response()->json(['message' => 'Usuario deletado com sucesso'],204); } }
25.445946
83
0.558152
257aa74a9ddda1e45cdd367f106d678fa9eb460d
11,087
cs
C#
Structure.Sketching/Formats/Bmp/Format/Header.cs
JaCraig/Structure.Sketching
3ef7cf83a825b7bd962dfe6682475e8fceade597
[ "Apache-2.0" ]
81
2016-10-11T20:21:20.000Z
2022-01-31T18:58:40.000Z
Structure.Sketching/Formats/Bmp/Format/Header.cs
prepare/Structure.Sketching
01fa7932f897c564d71a6a8f65d3e04e5066019c
[ "Apache-2.0" ]
48
2016-09-16T00:36:53.000Z
2017-01-15T21:31:06.000Z
Structure.Sketching/Formats/Bmp/Format/Header.cs
prepare/Structure.Sketching
01fa7932f897c564d71a6a8f65d3e04e5066019c
[ "Apache-2.0" ]
7
2016-12-02T02:35:54.000Z
2021-07-29T03:25:34.000Z
/* Copyright 2016 James Craig Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; namespace Structure.Sketching.Formats.Bmp.Format { /// <summary> /// BMP Header /// </summary> public class Header { /// <summary> /// Initializes a new instance of the <see cref="Header"/> class. /// </summary> /// <param name="data">The header data.</param> public Header(byte[] data) : this( BitConverter.ToInt32(data, 4), BitConverter.ToInt32(data, 8), BitConverter.ToInt16(data, 14), BitConverter.ToInt32(data, 20), BitConverter.ToInt32(data, 24), BitConverter.ToInt32(data, 28), BitConverter.ToInt32(data, 32), BitConverter.ToInt32(data, 36), (Compression)BitConverter.ToInt32(data, 16), BitConverter.ToInt32(data, 0), BitConverter.ToInt32(data, 16) == 3 ? BitConverter.ToInt32(data, 40) : 0, BitConverter.ToInt32(data, 16) == 3 ? BitConverter.ToInt32(data, 44) : 0, BitConverter.ToInt32(data, 16) == 3 ? BitConverter.ToInt32(data, 48) : 0, BitConverter.ToInt32(data, 16) == 3 ? BitConverter.ToInt32(data, 52) : 0 ) { } /// <summary> /// Initializes a new instance of the <see cref="Header" /> class. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="bpp">The BPP.</param> /// <param name="imageSize">Size of the image.</param> /// <param name="xppm">The XPPM.</param> /// <param name="yppm">The yppm.</param> /// <param name="colorsUsed">The number of colors used.</param> /// <param name="colorsImportant">The number of important colors.</param> /// <param name="compression">The compression.</param> /// <param name="size">The size.</param> /// <param name="redMask">The red mask.</param> /// <param name="greenMask">The green mask.</param> /// <param name="blueMask">The blue mask.</param> /// <param name="alphaMask">The alpha mask.</param> public Header(int width, int height, short bpp, int imageSize, int xppm, int yppm, int colorsUsed, int colorsImportant, Compression compression, int size = 40, int redMask = 0, int greenMask = 0, int blueMask = 0, int alphaMask = 0) { AlphaMask = alphaMask; BlueMask = blueMask; GreenMask = greenMask; RedMask = redMask; Size = size; Width = width; Height = height; BPP = bpp; ImageSize = imageSize; XPPM = xppm; YPPM = yppm; ColorsUsed = colorsUsed; ColorsImportant = colorsImportant; Compression = compression; AlphaOffset = GetOffset(alphaMask); RedOffset = GetOffset(redMask); GreenOffset = GetOffset(greenMask); BlueOffset = GetOffset(blueMask); AlphaMultiplier = GetMultiplier(alphaMask, AlphaOffset); RedMultiplier = GetMultiplier(redMask, RedOffset); GreenMultiplier = GetMultiplier(greenMask, GreenOffset); BlueMultiplier = GetMultiplier(blueMask, BlueOffset); } /// <summary> /// Gets or sets the alpha mask. /// </summary> /// <value> /// The alpha mask. /// </value> public int AlphaMask { get; set; } /// <summary> /// Gets or sets the alpha multiplier. /// </summary> /// <value> /// The alpha multiplier. /// </value> public double AlphaMultiplier { get; set; } /// <summary> /// Gets or sets the alpha offset. /// </summary> /// <value> /// The alpha offset. /// </value> public int AlphaOffset { get; set; } /// <summary> /// Gets or sets the blue mask. /// </summary> /// <value> /// The blue mask. /// </value> public int BlueMask { get; set; } /// <summary> /// Gets or sets the blue multiplier. /// </summary> /// <value> /// The blue multiplier. /// </value> public double BlueMultiplier { get; set; } /// <summary> /// Gets or sets the blue offset. /// </summary> /// <value> /// The blue offset. /// </value> public int BlueOffset { get; set; } /// <summary> /// The bits per pixel /// </summary> /// <value> /// The bits per pixel /// </value> public short BPP { get; private set; } /// <summary> /// Gets the number of important colors. /// </summary> /// <value>The number of important colors.</value> public int ColorsImportant { get; private set; } /// <summary> /// Gets the number of colors used. /// </summary> /// <value>The number of colors used.</value> public int ColorsUsed { get; private set; } /// <summary> /// Gets or sets the compression. /// </summary> /// <value>The compression.</value> public Compression Compression { get; private set; } /// <summary> /// Gets or sets the green mask. /// </summary> /// <value> /// The green mask. /// </value> public int GreenMask { get; set; } /// <summary> /// Gets or sets the green multiplier. /// </summary> /// <value> /// The green multiplier. /// </value> public double GreenMultiplier { get; set; } /// <summary> /// Gets or sets the green offset. /// </summary> /// <value> /// The green offset. /// </value> public int GreenOffset { get; set; } /// <summary> /// Gets the height. /// </summary> /// <value>The height.</value> public int Height { get; private set; } /// <summary> /// Gets the size of the image. /// </summary> /// <value>The size of the image.</value> public int ImageSize { get; private set; } /// <summary> /// Gets the number of planes. /// </summary> /// <value>The number of planes.</value> public short Planes => 1; /// <summary> /// Gets or sets the red mask. /// </summary> /// <value> /// The red mask. /// </value> public int RedMask { get; set; } /// <summary> /// Gets or sets the red multiplier. /// </summary> /// <value> /// The red multiplier. /// </value> public double RedMultiplier { get; set; } /// <summary> /// Gets or sets the red offset. /// </summary> /// <value> /// The red offset. /// </value> public int RedOffset { get; set; } /// <summary> /// Gets the size of the header /// </summary> /// <value>The size of the header</value> public int Size { get; private set; } /// <summary> /// Gets the width. /// </summary> /// <value>The width.</value> public int Width { get; private set; } /// <summary> /// Pels Per Meter in the X direction /// </summary> /// <value>The XPPM.</value> public int XPPM { get; private set; } /// <summary> /// Pels Per Meter in the Y direction /// </summary> /// <value>The yppm.</value> public int YPPM { get; private set; } /// <summary> /// Reads the header information from the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <returns>The header information.</returns> public static Header Read(Stream stream) { byte[] HeaderSize = new byte[4]; stream.Read(HeaderSize, 0, 4); var Size = BitConverter.ToInt32(HeaderSize, 0); byte[] data = new byte[Size]; stream.Read(data, 4, Size - 4); data[0] = HeaderSize[0]; data[1] = HeaderSize[1]; data[2] = HeaderSize[2]; data[3] = HeaderSize[3]; return new Header(data); } /// <summary> /// Writes the data to the specified writer. /// </summary> /// <param name="writer">The writer.</param> public void Write(BinaryWriter writer) { writer.Write(Size); writer.Write(Width); writer.Write(Height); writer.Write(Planes); writer.Write(BPP); writer.Write((int)Compression); writer.Write(ImageSize); writer.Write(XPPM); writer.Write(YPPM); writer.Write(ColorsUsed); writer.Write(ColorsImportant); } /// <summary> /// Gets the multiplier. /// </summary> /// <param name="mask">The mask.</param> /// <param name="offset">The offset.</param> /// <returns> /// The multiplier /// </returns> private double GetMultiplier(int mask, int offset) { if (mask != 0) { mask = mask >> offset; return 255d / (double)mask; } return 1; } /// <summary> /// Gets the offset. /// </summary> /// <param name="mask">The mask.</param> /// <returns>The offset</returns> private int GetOffset(int mask) { int Offset = 0; if (mask != 0) { while ((mask & 1) == 0) { ++Offset; mask = mask >> 1; } } return Offset; } } }
32.89911
107
0.486967
b0e5eeb1c554a1cb41e4ecdb9b90692bb0fa492d
604
swift
Swift
SwiftStart/Classes/UIKit/Common/View Controllers/UncodableTabBarController.swift
jakekrog/SwiftStart
a5453b7be8dfaebfa3fbc32556f9112e11b8fd04
[ "MIT" ]
null
null
null
SwiftStart/Classes/UIKit/Common/View Controllers/UncodableTabBarController.swift
jakekrog/SwiftStart
a5453b7be8dfaebfa3fbc32556f9112e11b8fd04
[ "MIT" ]
null
null
null
SwiftStart/Classes/UIKit/Common/View Controllers/UncodableTabBarController.swift
jakekrog/SwiftStart
a5453b7be8dfaebfa3fbc32556f9112e11b8fd04
[ "MIT" ]
null
null
null
// // UncodableTabBarController.swift // MandalifyKit // // Created by Jake Krog on 11/30/20. // Copyright © 2020 Jake Krog. All rights reserved. // import UIKit open class UncodableTabBarController: UITabBarController { // MARK: - Initialization public init() { super.init(nibName: nil, bundle: nil) } @available(*, unavailable) public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public convenience init(_ initializer: (UncodableTabBarController) -> Void) { self.init() initializer(self) } }
24.16
81
0.660596
e739a17d3198873d6a929fe681b764452697c457
1,465
php
PHP
database/migrations/2017_03_25_174048_create_sponsor_infos_table.php
nobleach/luform-api
996907f8cb84397f89384aa1caaff6e8d2083b02
[ "MIT" ]
null
null
null
database/migrations/2017_03_25_174048_create_sponsor_infos_table.php
nobleach/luform-api
996907f8cb84397f89384aa1caaff6e8d2083b02
[ "MIT" ]
null
null
null
database/migrations/2017_03_25_174048_create_sponsor_infos_table.php
nobleach/luform-api
996907f8cb84397f89384aa1caaff6e8d2083b02
[ "MIT" ]
null
null
null
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSponsorInfosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sponsor_infos', function (Blueprint $table) { $table->uuid('id'); $table->primary('id'); $table->text('fullname'); $table->text('address'); $table->text('city'); $table->text('state'); $table->text('zip'); $table->text('email'); $table->text('phone'); $table->text('bestcalltime'); $table->text('applicantfullname'); $table->boolean('baptizedlutheran'); $table->boolean('hadcursillospousediscussion'); $table->boolean('bothspousesattending'); $table->text('singlespouseexplanation'); $table->text('cursilloattitude'); $table->text('plantosupport'); $table->text('otherapplicantinfo'); $table->text('goodcandidatereason'); $table->text('applicantexpectations'); $table->boolean('signed'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sponsor_infos'); } }
28.173077
69
0.540614
b8d407a0e53ba4c448cf77b464af8d4881ea1964
435
h
C
objective-curl/src/objective-curl.h
S035779/objective-curl
b00dc8f8d6ca7edf712d18a34a7b7c25a04eb8ff
[ "curl", "Unlicense", "MIT" ]
13
2015-04-29T07:34:19.000Z
2020-12-15T03:34:44.000Z
objective-curl/src/objective-curl.h
S035779/objective-curl
b00dc8f8d6ca7edf712d18a34a7b7c25a04eb8ff
[ "curl", "Unlicense", "MIT" ]
1
2018-05-03T08:08:01.000Z
2018-05-03T08:08:01.000Z
objective-curl/src/objective-curl.h
S035779/objective-curl
b00dc8f8d6ca7edf712d18a34a7b7c25a04eb8ff
[ "curl", "Unlicense", "MIT" ]
3
2015-05-27T06:22:16.000Z
2020-05-18T15:55:40.000Z
/*! @header objective-curl.h @abstract Main framework include file. @discussion This header file includes all public classes referenced by the framework. */ #import "CurlS3.h" #import "CurlSFTP.h" #import "CurlUpload.h" #import "CurlUploadDelegate.h" #import "CurlFileTransfer.h" #import "CurlConnectionDelegate.h" #import "CurlRemoteFile.h" #import "CurlRemoteFolder.h" #import "CurlTransferStatus.h" #import "CurlClientType.h"
27.1875
86
0.772414
46f03430890001a4973dc399ca602b2466562119
188
swift
Swift
Chapter 3/FirstAppExtended/Sources/App/Controllers/NewController.swift
ftitreefly/Hands-On-Swift-5-Microservices-Development
025a5044fd7e979599c382b29bb89574f4dcbf98
[ "MIT" ]
39
2020-03-05T23:48:19.000Z
2021-12-21T00:37:56.000Z
Chapter 3/FirstAppExtended/Sources/App/Controllers/NewController.swift
ftitreefly/Hands-On-Swift-5-Microservices-Development
025a5044fd7e979599c382b29bb89574f4dcbf98
[ "MIT" ]
7
2020-03-04T13:53:54.000Z
2020-07-21T11:16:32.000Z
Chapter 3/FirstAppExtended/Sources/App/Controllers/NewController.swift
ftitreefly/Hands-On-Swift-5-Microservices-Development
025a5044fd7e979599c382b29bb89574f4dcbf98
[ "MIT" ]
16
2020-03-23T15:00:36.000Z
2021-12-09T19:03:07.000Z
import Fluent import Vapor struct NewController { func newFunction(req: Request) throws -> EventLoopFuture<HTTPStatus> { return req.eventLoop.makeSucceededFuture(.ok) } }
20.888889
74
0.728723
b4213988ce88eafd51e2ff5601c6a754ccf5d49f
210
rb
Ruby
db/migrate/20190701083558_create_identifier_types.rb
ministryofjustice/hmpps-book-secure-move-api
79e1012dfdc535dfcab0e2540896cdae63e09b9c
[ "MIT" ]
11
2020-01-09T13:12:09.000Z
2022-02-14T15:04:52.000Z
db/migrate/20190701083558_create_identifier_types.rb
ministryofjustice/hmpps-book-secure-move-api
79e1012dfdc535dfcab0e2540896cdae63e09b9c
[ "MIT" ]
305
2019-08-06T08:10:01.000Z
2022-03-28T08:59:43.000Z
db/migrate/20190701083558_create_identifier_types.rb
ministryofjustice/hmpps-book-secure-move-api
79e1012dfdc535dfcab0e2540896cdae63e09b9c
[ "MIT" ]
4
2020-02-21T13:42:10.000Z
2021-04-11T06:13:57.000Z
class CreateIdentifierTypes < ActiveRecord::Migration[5.2] def change create_table :identifier_types, id: :string do |t| t.string "title", null: false t.string "description" end end end
23.333333
58
0.690476
a9fcb0b14eca2eeb422e7e813fb65cfcc0432076
2,820
php
PHP
resources/views/monster-hunter.blade.php
luken35/laravelApp
0e818771626445f6c406cbac1f7dd4a474e69e24
[ "MIT" ]
null
null
null
resources/views/monster-hunter.blade.php
luken35/laravelApp
0e818771626445f6c406cbac1f7dd4a474e69e24
[ "MIT" ]
null
null
null
resources/views/monster-hunter.blade.php
luken35/laravelApp
0e818771626445f6c406cbac1f7dd4a474e69e24
[ "MIT" ]
null
null
null
@extends('layouts.layout') @section('title', 'Vue Sandbox') <?php $approute = "/panelapp/public";?> <head> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet"> <style> *{ font-family: 'Raleway' , serif; } h1{ text-align: center; font-size: 40px; text-decoration: underline; } button{ width:20%; padding:20px 40px 20px 40px; font-size: 20px; margin-left: 4%; } #battleLog{ text-align: center; font-size: 20px; list-style-type: none; } #battleLog li{ padding: 5px; list-style-type: none; } ul>li:nth-child(odd){ border-top: 2px solid grey; } .win-box{ padding:10px; font-size: 30px; text-decoration: underline; color: red; } </style> </head> <script src="../resources/views/js/game.js"></script> @section('content') <div> <section style="margin-bottom: 60px; border-bottom: 3px solid white;"> <h1 style="">Monster Hunter</h1> </section> <button id="startButton" style="margin-left: 40%; margin-right: auto;">Start Game</button> </div> <div id="game"> <section> <h1>Player Health</h1> <div style="border: 5px solid white;"> <div id="p-hp" style="height:60px; background-color: darkred;" :style="{width: playerHealth + '%'}"></div> </div> <h1>Monster Health</h1> <div style="border: 5px solid white;"> <div id="m-hp" style="height:60px; background-color: darkred;" :style="{width: monsterHealth + '%'}"></div> </div> </section> <section class="win-box" v-if="winner"> <h1 v-if="winner === 'Monster'">You Lost!</h1> <h1 v-else>You Win!</h1> <button style="margin-left: 28%;" @click="startNewRound">Carry On?</button> <button @click="endGame">End Game</button> </section> <section style="margin-top:20px;" v-else> <button @click="attackMonster">Attack</button> <button @click="heavyAttack" >Heavy Attack</button> <button @click="block">Block</button> <button @click="heal">Heal</button> </section> <section id="battleLog"> <h1>Battle Log</h1> <ul> <li v-for="logMessage in logMessages"> @{{ logMessage.actionBy }} - @{{ logMessage.actionType }} - @{{ logMessage.actionValue }} HP </li> </ul> </section> </div> @endsection
30.652174
119
0.534397
9d7a4610a1b529186f487a51a1796b35333ab749
4,098
c
C
src/main.c
aristizabal95/SinestesIA
c48b10ffc88ff80326e6988ca98b9cd22089c3c6
[ "Apache-2.0" ]
null
null
null
src/main.c
aristizabal95/SinestesIA
c48b10ffc88ff80326e6988ca98b9cd22089c3c6
[ "Apache-2.0" ]
3
2021-05-20T02:17:52.000Z
2022-02-26T04:58:15.000Z
src/main.c
aristizabal95/SinestesIA
c48b10ffc88ff80326e6988ca98b9cd22089c3c6
[ "Apache-2.0" ]
null
null
null
/*************************************************************** * M.O.N.I.K.Av2 * * Motirized, Omniscient, Network Independent Kinect Assistant * * * * HARDWARE SERVER * * This server will handle 3 separate tasks: * * 1. Configure kinect and stream video/audio data with RTMP * * 2. Create TCP Server for listening to commands * * 3. Handle commands. * * Each of this tasks will have its own thread. In addition, * * the servo will have an isolated thread to handle speed * ***************************************************************/ #include <stdio.h> #include <stdlib.h> #include <signal.h> // #include <pigpio.h> #include <string.h> #include "libfreenect.h" // #include <libfreenect/libfreenect.h> #include <pthread.h> #include <math.h> #include <unistd.h> #include "globals.h" #include "kinect_stream.h" #include "ffmpeg_stream.h" #ifndef SIGQUIT #define SIGQUIT SIGTERM #endif // Declare threads pthread_t kinect_streaming_thread; pthread_t server_thread; //pthread_t move_servo_thread; // Mutex for handling servo position update //thread_mutex_t servo_pos_mutex = PTHREAD_MUTEX_INITIALIZER; // Mutex for handling message preparation vs message send pthread_mutex_t streaming_mutex = PTHREAD_MUTEX_INITIALIZER; volatile int die = 0; int g_argc; char **g_argv; // Freenect global variables, remember to define them in globals.h freenect_context *f_ctx; freenect_device *f_dev; /****************************************************************** * FUNCTION DECLARATION * ******************************************************************/ int freenect_config(); int freenect_stream(); void *freenect_main(); int server_config(); int server_run(); void *server_main(); int issueCommand(); int moveServo(); void *servo_main(); void handler(int sig); int main(int argc, char *argv[]){ int rc; // return code signal(SIGINT, handler); printf("Okay everyone! I'm peering into your reality! Ahaha!\n"); g_argc = argc; g_argv = argv; rc = freenect_init(&f_ctx, NULL); if (rc < 0){ printf("No! I can't see! Something's wrong!\n"); printf("Wait! Don't let me go!\n"); sleep(1); for(int i=0;i<3;i++){ printf("."); sleep(1); } printf("Fix me.\n"); return 1; } // select subdevices. Check documentation for selecting microphone array too. freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING); freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA)); int nr_devices = freenect_num_devices (f_ctx); int user_device_number = 0; if (nr_devices < 1) { freenect_shutdown(f_ctx); printf("Can't find my eyes! Everything's dark! Connect me!\n"); return 1; } rc = freenect_open_device(f_ctx, &f_dev, user_device_number); if (rc < 0) { printf("Can't open my eyes!\n"); for(int i=0;i<3;i++){ printf("."); fflush(stdout); sleep(1); } printf("Help me.\n"); freenect_shutdown(f_ctx); return 1; } // Freenect is now working. printf("I can see through, with burning retinas. Is someone there? Are you there?\n"); // Create kinect thread rc = pthread_create(&kinect_streaming_thread, NULL, freenect_threadfunc, NULL); if (rc){ printf("ERROR creating kinect streaming thread. Code is %d\n", rc); exit(-1); } // ffmpeg thread rc = pthread_create(&server_thread, NULL, ffmpeg_threadfunc, NULL); if(rc){ printf("ERROR creating server thread. Code is %d\n", rc); exit(-1); } //Create command handler thread // rc = pthread_create(&move_servo_thread, NULL, tcp_threadfunc, NULL); // if(rc){ // printf("Error creating command handler thread. Code is %d\n", rc); // exit(-1); // } // pthread_exit(NULL); pause() ; return 0; } void handler(int sig){ if (sig == SIGINT || sig == SIGTERM || sig == SIGQUIT){ die = 1; printf("Wait, not yet!\n"); signal(sig, handler); } }
27.503356
108
0.608834
82e6d015d0cc5a7904ea8a78caf965b48384a069
2,687
lua
Lua
minetest/games/minebase/mods/stairs/stairs_mtg/init.lua
ShadyFox2004/minetest-server
1310fd2a8c0bee9e9e718257ed136040e34d213e
[ "MIT" ]
1
2021-06-30T20:50:19.000Z
2021-06-30T20:50:19.000Z
minetest/games/minebase/mods/stairs/stairs_mtg/init.lua
ShadyFox2004/minetest-server
1310fd2a8c0bee9e9e718257ed136040e34d213e
[ "MIT" ]
null
null
null
minetest/games/minebase/mods/stairs/stairs_mtg/init.lua
ShadyFox2004/minetest-server
1310fd2a8c0bee9e9e718257ed136040e34d213e
[ "MIT" ]
null
null
null
-- stairs_mtg/init.lua -- Register aliases for new pine node names minetest.register_alias("stairs:stair_pinewood", "tree_stairs:pine_wood_stair") minetest.register_alias("stairs:slab_pinewood", "tree_stairs:pine_wood_slab") local tmp = { clay_stairs = {"brick"}, earth_stairs = { cobble = "stone_cobble", stonebrick = "stone_brick", desert_cobble = "desert_stone_cobble", desert_stonebrick = "desert_stone_brick", sandstonebrick = "sandstone_brick", "stone", "stone_block", "desert_stone", "desert_stone_block", "sandstone", "sandstone_block", "desert_sandstone", "desert_sandstone_brick", "desert_sandstone_block", "silver_sandstone", "silver_sandstone_brick", "silver_sandstone_block", }, glass_stairs = {glass = "common_glass","obsidian_glass"}, liquid_stairs = { obsidianbrick = "obsidian_brick", "obsidian", "obsidian_block", "ice", "snowblock", }, mossy_stairs = {mossycobble = "stone_cobble"}, ore_stairs = { steelblock = "steel_block", tinblock = "tin_block", copperblock = "copper_block", bronzeblock = "bronze_block", goldblock = "gold_block" }, tree_stairs = { wood = "apple_wood", junglewood = "jungle_wood", "pine_wood", "acacia_wood", "aspen_wood", }, wheat_stairs = {"straw"} } -- Get setting for replace ABM local replace = minetest.settings:get_bool("enable_stairs_replace_abm") local function upside_down(oldName, newName) minetest.register_node(oldName .. "upside_down", { replace_name = newName, groups = {slabs_replace = 1}, }) end for mod, map in pairs(tmp) do for oldName, name in pairs(map) do oldName = type(oldName) == "string" and oldName or name newName = mod .. ":" .. name minetest.register_alias("stairs:stair_" .. oldName, newName.. "_stair") minetest.register_alias("stairs:slab_" .. oldName, newName .. "_slab") minetest.register_alias("stairs:stair_outer_" .. oldName, newName .. "_outer_stair") minetest.register_alias("stairs:stair_inner_" .. oldName, newName .. "_inner_stair") if replace then upside_down(":stairs:stair_" .. oldName, newName .. "_stair") upside_down(":stairs:slab_" .. oldName, newName .. "_slab") end end end -- Optionally replace old "upside_down" nodes with new param2 versions. -- Disabled by default. if replace then minetest.register_abm({ label = "Slab replace", nodenames = {"group:slabs_replace"}, interval = 16, chance = 1, action = function(pos, node) node.name = minetest.registered_nodes[node.name].replace_name node.param2 = node.param2 + 20 if node.param2 == 21 then node.param2 = 23 elseif node.param2 == 23 then node.param2 = 21 end minetest.set_node(pos, node) end, }) end
30.885057
79
0.71083
b2cbcf8e28c25611ede47ada9c6af3f9bedf4122
6,875
lua
Lua
plugins/lua/dfusion/tools.lua
theit8514/dfhack
1e5bca087f4e68eb8f807b9569c986858e412cc2
[ "BSD-2-Clause" ]
2
2015-08-17T07:40:44.000Z
2016-11-10T22:16:07.000Z
plugins/lua/dfusion/tools.lua
VOID001/dfhack
15c2d99a3e54a6ca1a0b5f3c5dfc80f38dded428
[ "BSD-2-Clause" ]
4
2019-03-28T10:12:06.000Z
2019-03-28T10:12:06.000Z
plugins/lua/dfusion/tools.lua
Falconne/dfhack
d07e1b681682b4d2c6e3901c7e6db4459286620f
[ "BSD-2-Clause" ]
2
2015-03-23T12:32:37.000Z
2016-04-16T04:40:06.000Z
local _ENV = mkmodule('plugins.dfusion.tools') local dfu=require("plugins.dfusion") local ms=require "memscan" menu=dfu.SimpleMenu() RaceNames={} function build_race_names() if #RaceNames~=0 then return RaceNames else for k,v in pairs(df.global.world.raws.creatures.all) do RaceNames[v.creature_id]=k end dfhack.onStateChange.invalidate_races=function(change_id) --todo does this work? if change_id==SC_WORLD_UNLOADED then dfhack.onStateChange.invalidate_races=nil RaceNames={} end end return RaceNames end end function setrace(name) local RaceTable=build_race_names() print("Your current race is:"..df.global.world.raws.creatures.all[df.global.ui.race_id].creature_id) local id if name == nil then print("Type new race's token name in full caps (q to quit):") repeat local entry=dfhack.lineedit() if entry=="q" then return end id=RaceTable[entry] until id~=nil else id=RaceTable[name] if id==nil then error("Name not found!") end end df.global.ui.race_id=id end menu:add("Set current race",setrace) function GiveSentience(names) local RaceTable=build_race_names() --slow.If loaded don't load again local id,ids if names ==nil then ids={} print("Type race's token name in full caps to give sentience to:") repeat id=dfhack.lineedit() id=RaceTable[entry] if id~=nil then table.insert(ids,id) end until id==nil else ids={} for _,name in pairs(names) do id=RaceTable[name] table.insert(ids,id) end end for _,id in pairs(ids) do local races=df.global.world.raws.creatures.all local castes=races[id].caste print(string.format("Caste count:%i",#castes)) for i =0,#castes-1 do print("Caste name:"..castes[i].caste_id.."...") local flags=castes[i].flags --print(string.format("%x",flagoffset)) if flags.CAN_SPEAK then print("\tis sentient.") else print("\tnon sentient. Allocating IQ...") flags.CAN_SPEAK=true end end end end menu:add("Give Sentience",GiveSentience) function MakeFollow(unit,trgunit) if unit == nil then unit=dfhack.gui.getSelectedUnit() end if unit== nil then error("Invalid creature") end if trgunit==nil then trgunit=df.global.world.units.active[0] end unit.relations.group_leader_id=trgunit.id local u_nem=dfhack.units.getNemesis(unit) local t_nem=dfhack.units.getNemesis(trgunit) if u_nem then u_nem.group_leader_id=t_nem.id end if t_nem and u_nem then t_nem.companions:insert(#t_nem.companions,u_nem.id) end end menu:add("Make creature follow",MakeFollow) function project(unit,trg) --TODO add to menu? if unit==nil then unit=getCreatureAtPointer() end if unit==nil then error("Failed to project unit. Unit not selected/valid") end -- todo: add projectile to world, point to unit, add flag to unit, add gen-ref to projectile. local p=df.proj_unitst:new() local startpos={x=unit.pos.x,y=unit.pos.y,z=unit.pos.z} p.origin_pos=startpos p.target_pos=trg p.cur_pos=startpos p.prev_pos=startpos p.unit=unit --- wtf stuff p.unk14=100 p.unk16=-1 p.unk23=-1 p.fall_delay=5 p.fall_counter=5 p.collided=true -- end wtf local citem=df.global.world.proj_list local maxid=1 local newlink=df.proj_list_link:new() newlink.item=p while citem.item~= nil do if citem.item.id>maxid then maxid=citem.item.id end if citem.next ~= nil then citem=citem.next else break end end p.id=maxid+1 newlink.prev=citem citem.next=newlink local proj_ref=df.general_ref_projectile:new() proj_ref.projectile_id=p.id unit.general_refs:insert(#unit.general_refs,proj_ref) unit.flags1.projectile=true end function empregnate(unit) if unit==nil then unit=dfhack.gui.getSelectedUnit() end if unit==nil then error("Failed to empregnate. Unit not selected/valid") end if unit.curse then unit.curse.add_tags2.STERILE=false end local genes = unit.appearance.genes if unit.relations.pregnancy_genes == nil then print("creating preg ptr.") if false then print(string.format("%x %x",df.sizeof(unit.relations:_field("pregnancy_genes")))) return end unit.relations.pregnancy_genes = { new = true, assign = genes } end local ngenes = unit.relations.pregnancy_genes if #ngenes.appearance ~= #genes.appearance or #ngenes.colors ~= #genes.colors then print("Array sizes incorrect, fixing.") ngenes:assign(genes); end print("Setting preg timer.") unit.relations.pregnancy_timer=10 unit.relations.pregnancy_caste=1 end menu:add("Empregnate",empregnate) function healunit(unit) if unit==nil then unit=dfhack.gui.getSelectedUnit() end if unit==nil then error("Failed to Heal unit. Unit not selected/valid") end unit.body.wounds:resize(0) -- memory leak here :/ unit.body.blood_count=unit.body.blood_max --set flags for standing and grasping... unit.status2.limbs_stand_max=4 unit.status2.limbs_stand_count=4 unit.status2.limbs_grasp_max=4 unit.status2.limbs_grasp_count=4 --should also set temperatures, and flags for breath etc... unit.flags1.dead=false unit.flags2.calculated_bodyparts=false unit.flags2.calculated_nerves=false unit.flags2.circulatory_spray=false unit.flags2.vision_good=true unit.flags2.vision_damaged=false unit.flags2.vision_missing=false unit.counters.winded=0 unit.counters.unconscious=0 for k,v in pairs(unit.body.components) do for kk,vv in pairs(v) do if k == 'body_part_status' then v[kk].whole = 0 else v[kk] = 0 end end end end menu:add("Heal unit",healunit) function powerup(unit,labor_rating,military_rating,skills) if unit==nil then unit=dfhack.gui.getSelectedUnit() end if unit==nil then error("Failed to power up unit. Unit not selected/valid") end if unit.status.current_soul== nil then error("Failed to power up unit. Unit has no soul") end local utils = require 'utils' labor_rating = labor_rating or 15 military_rating = military_rating or 70 skill =skill or { 0,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,41,42,43,44,45,46,47,48,49,54,55,57,58,59,60,61,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,95,96,97,98,99,100,101,102,103,104,105,109,110,111,112,113,114,115 } local military = { 38,39,41,42,43,44,45,46,54,99,100,101,102,103,104,105 } for sk,sv in ipairs(skill) do local new_rating = labor_rating for _,v in ipairs(military) do if v == sv then local new_rating = military_rating end end utils.insert_or_update(unit.status.current_soul.skills, { new = true, id = sv, rating = new_rating, experience = (new_rating * 500) + (new_rating * (new_rating - 1)) * 50}, 'id') end end menu:add("Power up",powerup) return _ENV
28.17623
324
0.709527
9396351479e5c9a7bbae043a8d047513093b6e69
746
ps1
PowerShell
BambooHr/Public/BambooHrServer/Invoke-BambooHrApiQuery.ps1
LockstepGroup/BambooHr
1c3507b5f863211dfbf810fba30b1133765f705e
[ "MIT" ]
null
null
null
BambooHr/Public/BambooHrServer/Invoke-BambooHrApiQuery.ps1
LockstepGroup/BambooHr
1c3507b5f863211dfbf810fba30b1133765f705e
[ "MIT" ]
null
null
null
BambooHr/Public/BambooHrServer/Invoke-BambooHrApiQuery.ps1
LockstepGroup/BambooHr
1c3507b5f863211dfbf810fba30b1133765f705e
[ "MIT" ]
null
null
null
function Invoke-BambooHrApiQuery { [CmdletBinding()] Param ( [Parameter(Mandatory = $False)] [string]$UriPath, [Parameter(Mandatory = $false)] [hashtable]$Query = @{}, [Parameter(Mandatory = $false)] [string]$Method = 'GET' ) BEGIN { $VerbosePrefix = "Invoke-BambooHrApiQuery:" } PROCESS { if (-not $Global:BambooHrServer) { Throw "$VerbosePrefix no active connection to BambooHr, please use Connect-BambooHrServer to get started." } else { $Global:BambooHrServer.UriPath = $UriPath $ReturnObject = $Global:BambooHrServer.invokeApiQuery($Query, $Method) } } END { $ReturnObject } }
24.866667
118
0.575067
b028a5b737cc53d8029456fcfba67977d9936d1e
32,857
py
Python
cinder/volume/drivers/violin/v6000_common.py
rlucio/cinder-violin-driver-icehouse
1632bf1bdf67f7e26a586c819dd836f6541c4f3d
[ "Apache-2.0" ]
null
null
null
cinder/volume/drivers/violin/v6000_common.py
rlucio/cinder-violin-driver-icehouse
1632bf1bdf67f7e26a586c819dd836f6541c4f3d
[ "Apache-2.0" ]
1
2021-01-12T23:22:22.000Z
2021-01-12T23:22:22.000Z
cinder/volume/drivers/violin/v6000_common.py
rlucio/cinder-violin-driver-icehouse
1632bf1bdf67f7e26a586c819dd836f6541c4f3d
[ "Apache-2.0" ]
null
null
null
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2014 Violin Memory, Inc. # All Rights Reserved. # # 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. """ Violin Memory 6000 Series All-Flash Array Common Driver for Openstack Cinder Uses Violin REST API via XG-Tools to manage a standard V6000 series flash array to provide network block-storage services. by Ryan Lucio Senior Software Engineer Violin Memory """ import re import time from oslo.config import cfg from cinder import context from cinder import exception from cinder.openstack.common import log as logging from cinder import utils from cinder.volume.drivers.san import san from cinder.volume import volume_types LOG = logging.getLogger(__name__) # support vmos versions V6.3.0.4 or newer # support vmos versions V6.3.1 or newer VMOS_SUPPORTED_VERSION_PATTERNS = ['V6.3.0.[4-9]', 'V6.3.[1-9].?[0-9]?'] try: import vxg except ImportError: LOG.exception( _("The Violin V6000 driver for Cinder requires the presence of " "the Violin 'XG-Tools', python libraries for facilitating " "communication between applications and the v6000 XML API. " "The libraries can be downloaded from the Violin Memory " "support website at http://www.violin-memory.com/support")) raise else: LOG.info(_("Running with xg-tools version: %s"), vxg.__version__) violin_opts = [ cfg.StrOpt('gateway_vip', default='', help='IP address or hostname of the v6000 master VIP'), cfg.StrOpt('gateway_mga', default='', help='IP address or hostname of mg-a'), cfg.StrOpt('gateway_mgb', default='', help='IP address or hostname of mg-b'), cfg.StrOpt('gateway_user', default='admin', help='User name for connecting to the Memory Gateway'), cfg.StrOpt('gateway_password', default='', help='User name for connecting to the Memory Gateway', secret=True), cfg.BoolOpt('use_igroups', default=False, help='Use igroups to manage targets and initiators'), cfg.BoolOpt('use_thin_luns', default=False, help='Use thin luns instead of thick luns'), ] CONF = cfg.CONF CONF.register_opts(violin_opts) class InvalidBackendConfig(exception.CinderException): message = _("Volume backend config is invalid: %(reason)s") class RequestRetryTimeout(exception.CinderException): message = _("Backend service retry timeout hit: %(timeout)s sec") class ViolinBackendErr(exception.CinderException): message = _("Backend reports: %(message)s") class ViolinBackendErrExists(exception.CinderException): message = _("Backend reports: item already exists") class ViolinBackendErrNotFound(exception.CinderException): message = _("Backend reports: item not found") class V6000CommonDriver(san.SanDriver): """Executes commands relating to Violin Memory Arrays.""" def __init__(self, *args, **kwargs): super(V6000CommonDriver, self).__init__(*args, **kwargs) self.request_timeout = 300 self.vmem_vip = None self.vmem_mga = None self.vmem_mgb = None self.container = "" self.stats = {} self.config = kwargs.get('configuration', None) self.context = None self.lun_tracker = LunIdList(self.db) if self.config: self.config.append_config_values(violin_opts) def do_setup(self, context): """Any initialization the driver does while starting.""" if not self.config.gateway_vip: raise exception.InvalidInput( reason=_('Gateway VIP is not set')) if not self.config.gateway_mga: raise exception.InvalidInput( reason=_('Gateway IP for mg-a is not set')) if not self.config.gateway_mgb: raise exception.InvalidInput( reason=_('Gateway IP for mg-b is not set')) self.vmem_vip = vxg.open(self.config.gateway_vip, self.config.gateway_user, self.config.gateway_password, keepalive=True) self.vmem_mga = vxg.open(self.config.gateway_mga, self.config.gateway_user, self.config.gateway_password, keepalive=True) self.vmem_mgb = vxg.open(self.config.gateway_mgb, self.config.gateway_user, self.config.gateway_password, keepalive=True) self.context = context vip = self.vmem_vip.basic ret_dict = vip.get_node_values("/vshare/state/local/container/*") if ret_dict: self.container = ret_dict.items()[0][1] ret_dict = vip.get_node_values( "/vshare/state/local/container/%s/lun/*" % self.container) if ret_dict: self.lun_tracker.update_from_volume_ids(ret_dict.values()) ret_dict = vip.get_node_values( "/vshare/state/snapshot/container/%s/lun/*" % self.container) if ret_dict: for vol_id in ret_dict.values(): snaps = vip.get_node_values( "/vshare/state/snapshot/container/%s/lun/%s/snap/*" % (self.container, vol_id)) self.lun_tracker.update_from_snapshot_ids(snaps.values()) def check_for_setup_error(self): """Returns an error if prerequisites aren't met.""" vip = self.vmem_vip.basic if len(self.container) == 0: raise InvalidBackendConfig(reason=_('container is missing')) if not self._is_supported_vmos_version(self.vmem_vip.version): msg = _('VMOS version is not supported') raise InvalidBackendConfig(reason=msg) bn1 = ("/vshare/state/local/container/%s/threshold/usedspace" "/threshold_hard_val" % self.container) bn2 = ("/vshare/state/local/container/%s/threshold/provision" "/threshold_hard_val" % self.container) ret_dict = vip.get_node_values([bn1, bn2]) for node in ret_dict: # The infrastructure does not support space reclamation so # ensure it is disabled. When used space exceeds the hard # limit, snapshot space reclamation begins. Default is 0 # => no space reclamation. # if node.endswith('/usedspace/threshold_hard_val'): if ret_dict[node] != 0: msg = _('space reclamation threshold is enabled') raise InvalidBackendConfig(reason=msg) # The infrastructure does not support overprovisioning so # ensure it is disabled. When provisioned space exceeds # the hard limit, further provisioning is stopped. # Default is 100 => provisioned space equals usable space. # elif node.endswith('/provision/threshold_hard_val'): if ret_dict[node] != 100: msg = _('provisioned space threshold not equal to ' 'usable space') raise InvalidBackendConfig(reason=msg) def create_volume(self, volume): """Creates a volume.""" self._create_lun(volume) def delete_volume(self, volume): """Deletes a volume.""" self._delete_lun(volume) def create_snapshot(self, snapshot): """Creates a snapshot from an existing volume.""" self._create_lun_snapshot(snapshot) def delete_snapshot(self, snapshot): """Deletes a snapshot.""" self._delete_lun_snapshot(snapshot) def create_volume_from_snapshot(self, volume, snapshot): """Creates a volume from a snapshot.""" snapshot['size'] = snapshot['volume']['size'] self._create_lun(volume) self.copy_volume_data(self.context, snapshot, volume) def create_cloned_volume(self, volume, src_vref): """Creates a full clone of the specified volume.""" self._create_lun(volume) self.copy_volume_data(self.context, src_vref, volume) def extend_volume(self, volume, new_size): """Extend an existing volume's size. The equivalent CLI command is "lun resize container <container_name> name <lun_name> size <gb>" Arguments: volume -- volume object provided by the Manager new_size -- new (increased) size in GB to be applied """ v = self.vmem_vip LOG.info(_("Extending lun %(id)s, from %(size)s to %(new_size)s GB") % {'id': volume['id'], 'size': volume['size'], 'new_size': new_size}) try: self._send_cmd(v.lun.resize_lun, 'Success', self.container, volume['id'], new_size) except Exception: LOG.exception(_("LUN extend failed!")) raise @utils.synchronized('vmem-lun') def _create_lun(self, volume): """Creates a new lun. The equivalent CLI command is "lun create container <container_name> name <lun_name> size <gb>" Arguments: volume -- volume object provided by the Manager """ lun_type = '0' v = self.vmem_vip LOG.info(_("Creating lun %(name)s, %(size)s GB") % volume) if self.config.use_thin_luns: lun_type = '1' # using the defaults for fields: quantity, nozero, # readonly, startnum, blksize, naca, alua, preferredport # try: self._send_cmd(v.lun.create_lun, 'LUN create: success!', self.container, volume['id'], volume['size'], 1, '0', lun_type, 'w', 1, 512, False, False, None) except ViolinBackendErrExists: LOG.info(_("Lun %s already exists, continuing"), volume['id']) except Exception: LOG.warn(_("Lun create failed!")) raise @utils.synchronized('vmem-lun') def _delete_lun(self, volume): """Deletes a lun. The equivalent CLI command is "no lun create container <container_name> name <lun_name>" Arguments: volume -- volume object provided by the Manager """ v = self.vmem_vip success_msgs = ['lun deletion started', ''] LOG.info(_("Deleting lun %s"), volume['id']) try: self._send_cmd(v.lun.bulk_delete_luns, success_msgs, self.container, volume['id']) except ViolinBackendErrNotFound: LOG.info(_("Lun %s already deleted, continuing"), volume['id']) except ViolinBackendErrExists: LOG.warn(_("Lun %s has dependent snapshots, skipping"), volume['id']) raise exception.VolumeIsBusy(volume_name=volume['id']) except Exception: LOG.exception(_("Lun delete failed!")) raise self.lun_tracker.free_lun_id_for_volume(volume) @utils.synchronized('vmem-snap') def _create_lun_snapshot(self, snapshot): """Creates a new snapshot for a lun. The equivalent CLI command is "snapshot create container <container> lun <volume_name> name <snapshot_name>" Arguments: snapshot -- snapshot object provided by the Manager """ v = self.vmem_vip LOG.info(_("Creating snapshot %s"), snapshot['id']) try: self._send_cmd(v.snapshot.create_lun_snapshot, 'Snapshot create: success!', self.container, snapshot['volume_id'], snapshot['id']) except ViolinBackendErrExists: LOG.info(_("Snapshot %s already exists, continuing"), snapshot['id']) except Exception: LOG.exception(_("LUN snapshot create failed!")) raise @utils.synchronized('vmem-snap') def _delete_lun_snapshot(self, snapshot): """Deletes an existing snapshot for a lun. The equivalent CLI command is "no snapshot create container <container> lun <volume_name> name <snapshot_name>" Arguments: snapshot -- snapshot object provided by the Manager """ v = self.vmem_vip LOG.info(_("Deleting snapshot %s"), snapshot['id']) try: self._send_cmd(v.snapshot.delete_lun_snapshot, 'Snapshot delete: success!', self.container, snapshot['volume_id'], snapshot['id']) except ViolinBackendErrNotFound: LOG.info(_("Snapshot %s already deleted, continuing"), snapshot['id']) except Exception: LOG.exception(_("LUN snapshot delete failed!")) raise self.lun_tracker.free_lun_id_for_snapshot(snapshot) def _send_cmd(self, request_func, success_msgs, *args): """Run an XG request function, and retry until the request returns a success message, a failure message, or the global request timeout is hit. This wrapper is meant to deal with backend requests that can fail for any variety of reasons, for instance, when the system is already busy handling other LUN requests. It is also smart enough to give up if clustering is down (eg no HA available), there is no space left, or other "fatal" errors are returned (see _fatal_error_code() for a list of all known error conditions). Arguments: request_func -- XG api method to call success_msgs -- Success messages expected from the backend *args -- argument array to be passed to the request_func Returns: The response dict from the last XG call. """ resp = {} start = time.time() done = False if isinstance(success_msgs, basestring): success_msgs = [success_msgs] while not done: if time.time() - start >= self.request_timeout: raise RequestRetryTimeout(timeout=self.request_timeout) resp = request_func(*args) if not resp['message']: # XG requests will return None for a message if no message # string is passed int the raw response resp['message'] = '' for msg in success_msgs: if not resp['code'] and msg in resp['message']: done = True break self._fatal_error_code(resp) return resp def _send_cmd_and_verify(self, request_func, verify_func, request_success_msgs='', rargs=[], vargs=[]): """Run an XG request function, and verify success using an additional verify function. If the verification fails, then retry the request/verify cycle until both functions are successful, the request function returns a failure message, or the global request timeout is hit. This wrapper is meant to deal with backend requests that can fail for any variety of reasons, for instance, when the system is already busy handling other LUN requests. It is also smart enough to give up if clustering is down (eg no HA available), there is no space left, or other "fatal" errors are returned (see _fatal_error_code() for a list of all known error conditions). Arguments: request_func -- XG api method to call verify_func -- function to call to verify request was completed successfully (eg for export) request_success_msg -- Success message expected from the backend for the request_func *rargs -- argument array to be passed to the request_func *vargs -- argument array to be passed to the verify_func Returns: The response dict from the last XG call. """ resp = {} start = time.time() request_needed = True verify_needed = True if isinstance(request_success_msgs, basestring): request_success_msgs = [request_success_msgs] while request_needed or verify_needed: if time.time() - start >= self.request_timeout: raise RequestRetryTimeout(timeout=self.request_timeout) if request_needed: resp = request_func(*rargs) if not resp['message']: # XG requests will return None for a message if no message # string is passed int the raw response resp['message'] = '' for msg in request_success_msgs: if not resp['code'] and msg in resp['message']: # XG request func was completed request_needed = False break self._fatal_error_code(resp) elif verify_needed: success = verify_func(*vargs) if success: # XG verify func was completed verify_needed = False else: # try sending the request again request_needed = True return resp def _get_igroup(self, volume, connector): """Gets the igroup that should be used when configuring a volume. Arguments: volume -- volume object used to determine the igroup name Returns: igroup_name -- name of igroup (for configuring targets & initiators) """ v = self.vmem_vip # Use the connector's primary hostname and use that as the # name of the igroup. The name must follow syntax rules # required by the array: "must contain only alphanumeric # characters, dashes, and underscores. The first character # must be alphanumeric". # igroup_name = re.sub(r'[\W]', '_', connector['host']) # verify that the igroup has been created on the backend, and # if it doesn't exist, create it! # bn = "/vshare/config/igroup/%s" % igroup_name resp = v.basic.get_node_values(bn) if not len(resp): v.igroup.create_igroup(igroup_name) return igroup_name def _get_volume_type_extra_spec(self, volume, spec_key): """Parse data stored in a volume_type's extra_specs table. Code adapted from examples in cinder/volume/drivers/solidfire.py and cinder/openstack/common/scheduler/filters/capabilities_filter.py. Arguments: volume -- volume object containing volume_type to query spec_key -- the metadata key to search for Returns: spec_value -- string value associated with spec_key """ spec_value = None ctxt = context.get_admin_context() typeid = volume['volume_type_id'] if typeid: volume_type = volume_types.get_volume_type(ctxt, typeid) volume_specs = volume_type.get('extra_specs') for key, val in volume_specs.iteritems(): # Havana release altered extra_specs to require a # prefix on all non-host-capability related extra # specs, so that prefix is stripped here before # checking the key. # if ':' in key: scope = key.split(':') key = scope[1] if key == spec_key: spec_value = val break return spec_value def _wait_for_exportstate(self, volume_name, state=False): """Polls backend to verify volume's export configuration. XG sets/queries following a request to create or delete a lun export may fail on the backend if vshared is still processing the export action (or times out). We can check whether it is done by polling the export binding for a lun to ensure it is created or deleted. This function will try to verify the creation or removal of export state on both gateway nodes of the array every 5 seconds for up to 30 seconds. Arguments: volume_name -- name of volume to be polled state -- True to poll for existence, False for lack of Returns: True if the export state was correctly added or removed (depending on 'state' param) """ status = [False, False] mg_conns = [self.vmem_mga.basic, self.vmem_mgb.basic] success = False bn = "/vshare/config/export/container/%s/lun/%s" \ % (self.container, volume_name) for i in xrange(6): for node_id in xrange(2): if not status[node_id]: resp = mg_conns[node_id].get_node_values(bn) if state and len(resp.keys()): status[node_id] = True elif (not state) and (not len(resp.keys())): status[node_id] = True if status[0] and status[1]: success = True break else: time.sleep(5) return success def _is_supported_vmos_version(self, version_string): """Check that the version of VMOS running on the gateways is valid for use with the OpenStack drivers.""" for pattern in VMOS_SUPPORTED_VERSION_PATTERNS: if re.match(pattern, version_string): LOG.debug("Verified VMOS version %s is supported" % version_string) return True return False def _fatal_error_code(self, response): """Check the error code in a XG response for a fatal error, and returns an appropriate exception. Error codes extracted from vdmd_mgmt.c. Arguments: response -- a response dict result from an XG request """ # known non-fatal response codes # retry_codes = {1024: 'lun deletion in progress, try again later', 14032: 'lc_err_lock_busy'} if response['code'] == 14000: # lc_generic_error raise ViolinBackendErr(message=response['message']) elif response['code'] == 14002: # lc_err_assertion_failed raise ViolinBackendErr(message=response['message']) elif response['code'] == 14004: # lc_err_not_found raise ViolinBackendErrNotFound() elif response['code'] == 14005: # lc_err_exists raise ViolinBackendErrExists() elif response['code'] == 14008: # lc_err_unexpected_arg raise ViolinBackendErr(message=response['message']) elif response['code'] == 14014: # lc_err_io_error raise ViolinBackendErr(message=response['message']) elif response['code'] == 14016: # lc_err_io_closed raise ViolinBackendErr(message=response['message']) elif response['code'] == 14017: # lc_err_io_timeout raise ViolinBackendErr(message=response['message']) elif response['code'] == 14021: # lc_err_unexpected_case raise ViolinBackendErr(message=response['message']) elif response['code'] == 14025: # lc_err_no_fs_space raise ViolinBackendErr(message=response['message']) elif response['code'] == 14035: # lc_err_range raise ViolinBackendErr(message=response['message']) elif response['code'] == 14036: # lc_err_invalid_param raise ViolinBackendErr(message=response['message']) elif response['code'] == 14121: # lc_err_cancelled_err raise ViolinBackendErr(message=response['message']) elif response['code'] == 512: # Not enough free space in container (vdmd bug) raise ViolinBackendErr(message=response['message']) elif response['code'] == 1 and 'LUN ID conflict' \ in response['message']: # lun id conflict while attempting to export raise ViolinBackendErr(message=response['message']) class LunIdList(object): """Tracks available lun_ids for use when exporting a new lun for the first time. After instantiating a new LunIdList object, it should be updated (basically quiescing volumes/snapshot lun ID allocation between the array and the corresponding Openstack DB metadata). After that, the object can be queried to capture the next 'available' lun ID for use with exporting a new volume or snapshot. Only when the volume/snapshot is deleted entirely, the lun ID should be freed. Lun IDs are montonically increasing up to a max value of 16k, after which the selection will loop around to lun ID 1 and will continue to increment until an available ID is found. """ def __init__(self, db, *args, **kwargs): self.max_lun_id = 16000 self.lun_id_list = [0] * self.max_lun_id self.lun_id_list[0] = 1 self.prev_index = 1 self.free_index = 1 self.context = context.get_admin_context() self.db = db def update_from_volume_ids(self, id_list=[]): """Walk a list of volumes collected that the array knows about and check for any saved lun_id metadata for each of those volumes to fully sync the list. Note that the metadata keys are stored as strings. Arguments: id_list -- array containing names of volumes that exist on the backend (volume 'names' are UUIDs if they were made via the VMEM driver API) """ for item in id_list: try: metadata = self.db.volume_metadata_get(self.context, item) except exception.VolumeNotFound: LOG.warn(_("No db state for lun %s, skipping lun_id update"), item) else: if metadata and 'lun_id' in metadata: index = int(metadata['lun_id']) self.lun_id_list[index] = 1 LOG.debug("Set lun_id=%d for volume_id=%s" % (index, item)) self.update_free_index(index) def update_from_snapshot_ids(self, id_list=[]): """Walk a list of snapshots collected that the array knows about and check for any saved lun_id metadata for each of those snapshots to fully sync the list. Note that the metadata keys are stored as strings. Arguments: id_list -- array containing names of snapshots that exist on the backend (snapshot 'names' are UUIDs if they were made via the VMEM driver API) """ for item in id_list: try: metadata = self.db.snapshot_metadata_get(self.context, item) except exception.SnapshotNotFound: LOG.warn(_("No db state for snap %s, skipping lun_id update"), item) else: if metadata and 'lun_id' in metadata: index = int(metadata['lun_id']) self.lun_id_list[index] = 1 LOG.debug("Set lun_id=%d for snapshot_id=%s" % (index, item)) self.update_free_index(index) def get_lun_id_for_volume(self, volume): """Allocate a free a lun ID to a volume and create a lun_id tag in the volume's metadata. Arguments: volume -- the volume object to allocate a lun_id to """ metadata = self.db.volume_metadata_get(self.context, volume['id']) if not metadata or 'lun_id' not in metadata: metadata = {} metadata['lun_id'] = self.get_next_lun_id_str() self.db.volume_metadata_update(self.context, volume['id'], metadata, False) LOG.debug("Assigned lun_id %s to volume %s" % (metadata['lun_id'], volume['id'])) return metadata['lun_id'] def get_lun_id_for_snapshot(self, snapshot): """Allocate a free a lun ID to a snapshot and create a lun_id tag in the snapshot's metadata. Arguments: snapshot -- the snapshot object to allocate a lun_id to """ metadata = self.db.snapshot_metadata_get(self.context, snapshot['id']) if not metadata or 'lun_id' not in metadata: metadata = {} metadata['lun_id'] = self.get_next_lun_id_str() self.db.snapshot_metadata_update(self.context, snapshot['id'], metadata, False) LOG.debug("Assigned lun_id %s to volume %s" % (metadata['lun_id'], snapshot['id'])) return metadata['lun_id'] def free_lun_id_for_volume(self, volume): """Remove the lun_id tag saved in the volume's metadata and free the lun ID in the internal tracking array. Arguments: volume -- the volume object with a lun ID to be free'd """ metadata = self.db.volume_metadata_get(self.context, volume['id']) if metadata and 'lun_id' in metadata: self.free_lun_id_str(metadata['lun_id']) def free_lun_id_for_snapshot(self, snapshot): """Remove the lun_id tag saved in the snapshot's metadata and free the lun ID in the internal tracking array. Arguments: snapshot -- the snapshot object with a lun ID to be free'd """ metadata = self.db.snapshot_metadata_get(self.context, snapshot['id']) if metadata and 'lun_id' in metadata: self.free_lun_id_str(metadata['lun_id']) def get_next_lun_id_str(self): """Mark the next available lun_id as allocated and return it to the caller. Returns: next_id -- the lun ID that being allocated to the caller """ next_id = self.free_index self.lun_id_list[next_id] = 1 self.update_free_index() return str(next_id) def free_lun_id_str(self, value_str): """Mark a lun_id as now available, as if the lun was de-allocated. Arguments: value_str -- lun ID to free (in string format) """ value = int(value_str) self.lun_id_list[value] = 0 self.update_free_index() def update_free_index(self, index=None): """Update the free index, monotonically increasing, and looping back to 1 after the max lun ID value is hit. Arguments: index -- assume that all values below this number may be already allocated, so start searching at that value if it is higher than the free_index """ i = 0 count = 0 max_size = len(self.lun_id_list) if index and index > self.free_index: i = index + 1 else: i = self.free_index # avoid possibility of indexError if i >= max_size: i = 1 while self.lun_id_list[i] == 1 and count < max_size: count += 1 i += 1 if i >= max_size: i = 1 self.free_index = i if count == max_size: raise exception.Error("Cannot find free lun_id, giving up!")
38.028935
79
0.586268
af591b506fe28c1a707bf36868bda964a74627c5
457
rs
Rust
aizuonlinejudge/ITP1_3_D.rs
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2019-11-06T15:17:48.000Z
2019-11-06T15:17:48.000Z
aizuonlinejudge/ITP1_3_D.rs
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
null
null
null
aizuonlinejudge/ITP1_3_D.rs
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2018-11-13T08:43:26.000Z
2018-11-13T08:43:26.000Z
/*input 5 14 80 */ fn read_line() -> String { let mut return_ = format!(""); std::io::stdin().read_line(&mut return_).ok(); return_ } fn main() { let v: Vec<u32> = read_line() .trim() .split_whitespace() .map(|x| x.parse().expect("")) .collect(); let mut count: u32 = 0; for i in v[0]..v[1] + 1 { if v[2] % i == 0 { count = count + 1; } } println!("{}", count); }
19.041667
50
0.452954
da478179a2dcf0e6df9f423d7ff7467fa139b1d3
537
ts
TypeScript
Restaurant-front/src/app/modules/principal/principal.module.ts
ronaldosjr/Restaurant
e1a4031871fc3ecef4acbcd39814c37c802c45be
[ "MIT" ]
null
null
null
Restaurant-front/src/app/modules/principal/principal.module.ts
ronaldosjr/Restaurant
e1a4031871fc3ecef4acbcd39814c37c802c45be
[ "MIT" ]
null
null
null
Restaurant-front/src/app/modules/principal/principal.module.ts
ronaldosjr/Restaurant
e1a4031871fc3ecef4acbcd39814c37c802c45be
[ "MIT" ]
null
null
null
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {PrincipalComponent} from './pages/principal/principal.component'; import {CoreModule} from '../core/core.module'; import {PrincipalRoutingModule} from './principal-routing.module'; import { ImageComponent } from './pages/image/image.component'; @NgModule({ imports: [ CommonModule, PrincipalRoutingModule, CoreModule ], declarations: [ PrincipalComponent, ImageComponent ] }) export class PrincipalModule { }
25.571429
73
0.724395
b1e72624824f63be80a801d44393622f44b75665
98
lua
Lua
_manifest.lua
tritao/premake-emscripten
049809f6b3870d13704ebb4ced6d94517ad8ea2d
[ "BSD-3-Clause" ]
681
2020-11-04T17:18:10.000Z
2022-03-30T05:14:25.000Z
_manifest.lua
tritao/premake-emscripten
049809f6b3870d13704ebb4ced6d94517ad8ea2d
[ "BSD-3-Clause" ]
147
2020-11-03T08:35:42.000Z
2022-03-28T23:10:18.000Z
_manifest.lua
tritao/premake-emscripten
049809f6b3870d13704ebb4ced6d94517ad8ea2d
[ "BSD-3-Clause" ]
63
2020-11-08T20:21:00.000Z
2022-03-29T21:25:15.000Z
return { "_preload.lua", "emscripten.lua", "emscripten_emcc.lua", "emscripten_vstudio.lua", }
14
26
0.704082
24c40073c608db85fe7f33857c5e7a0e83c277fd
4,431
lua
Lua
packages/orp/server/drug/cmds_s.lua
AliLogic/orp-game
28c4b07ca1382455dadb4860d61feefe508cd1ce
[ "BSD-2-Clause" ]
4
2020-07-09T13:14:36.000Z
2021-05-05T17:50:31.000Z
packages/orp/server/drug/cmds_s.lua
AliLogic/orp-game
28c4b07ca1382455dadb4860d61feefe508cd1ce
[ "BSD-2-Clause" ]
null
null
null
packages/orp/server/drug/cmds_s.lua
AliLogic/orp-game
28c4b07ca1382455dadb4860d61feefe508cd1ce
[ "BSD-2-Clause" ]
null
null
null
--[[ Copyright (C) 2019 Onset Roleplay Developers: * Bork * Logic_ Contributors: * Blue Mountains GmbH ]]-- -- Variables local colour = ImportPackage('colours') -- Commands AddCommand("harvest", function (playerid) local plantid = Plant_Nearest(playerid) if plantid == 0 then return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You are not near any plants.</>") end if DrugData[plantid].stage ~= 10 then return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: This plant is not ready to be harvested yet.</>") end if not IsPlayerCrouched(playerid) then return AddPlayerChatError(playerid, "You must be crouched to harvest.") end if PlayerData[playerid].harvesting ~= 0 then return AddPlayerChatError(playerid, "You are already harvesting a plant.") end AddPlayerChatAction(playerid, "" .. GetPlayerName(playerid) .. " begins to harvest the drug plant.") PlayerData[playerid].harvesting = 1 ShowFooterMessage(playerid, "Harvesting...", colour.COLOUR_DARKGREEN(), 3) Delay(3000, function () PlayerData[playerid].harvesting = 0 if (plantid ~= Plant_Nearest(playerid) or not IsPlayerCrouched(playerid) or not IsValidPlant(plantid)) then return end SetPlayerAnimation(playerid, "SLAP01") local type = GetPlantTypeId(plantid) local amount = Random(DRUG_TYPE_AMOUNT[type][1], DRUG_TYPE_AMOUNT[type][2]) AddPlayerChatAction(playerid, "" .. GetPlayerName(playerid) .. " has harvested " .. amount .." grams of marijuana."); AddPlayerChat(playerid, "You have harvested "..amount.." gm of "..GetPlantTypeName(plantid)..".") Inventory_GiveItem(playerid, DRUG_TYPE_ITEM[type], amount) Plant_Destroy(plantid) end) return end) AddCommand("plant", function (playerid, drug) if drug ~= nil then drug = string.lower(drug) end local slot = false local x, y, z = GetPlayerLocation(playerid) if not IsPlayerCrouched(playerid) then return AddPlayerChatError(playerid, "You must be crouched to plant something.") end if drug == "marijuana" then slot = Inventory_HasItem(playerid, INV_ITEM_WEEDSEED) if slot == false then return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You do not have any of these seeds.</>") end AddPlayerChatAction(playerid, "" .. GetPlayerName(playerid) .. " plants a marijuana seed into the ground.") SetPlayerAnimation(playerid, "SLAP01") Inventory_TakeItem(playerid, INV_ITEM_WEEDSEED, 1) CreatePlant(DRUG_TYPE_WEED, x, y, z) elseif drug == "cocaine" then slot = Inventory_HasItem(playerid, INV_ITEM_COKESEED) if slot == false then return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You do not have any of these seeds.</>") end AddPlayerChatAction(playerid, "" .. GetPlayerName(playerid) .. " plants a poppy seed into the ground.") SetPlayerAnimation(playerid, "SLAP01") Inventory_TakeItem(playerid, INV_ITEM_COKESEED, 1) CreatePlant(DRUG_TYPE_COKE, x, y, z) else AddPlayerChatUsage(playerid, "/plant <drug>") AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Drug:</> marijuana, cocaine") end return end) AddCommand("adestroyplant", function (playerid, plantid) if (PlayerData[playerid].admin < 5) then return AddPlayerChatError(playerid, "You don't have permission to use this command.") end if plantid == nil then return AddPlayerChatUsage(playerid, "/adestroyplant <plant>") end plantid = tonumber(plantid) if DrugData[plantid] == nil then return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You have specified an invalid plant ID.</>") end Plant_Destroy(plantid); AddPlayerChat(playerid, "You have successfully destroyed plant ID: " .. plantid .. ".") return end) AddCommand("gotoplant", function (playerid, plantid) if (PlayerData[playerid].admin < 3) then return AddPlayerChatError(playerid, "You don't have permission to use this command.") end if plantid == nil then return AddPlayerChatUsage(playerid, "/gotoplant <plant>") end plantid = tonumber(plantid) if DrugData[plantid] == nil then return AddPlayerChatError(playerid, "Plant " .. plantid .. " doesn't exist.") end SetPlayerLocation(playerid, DrugData[plantid].x, DrugData[plantid].y, DrugData[plantid].z) AddPlayerChat(playerid, "You have been teleported to plant ID: " .. plantid ..".") end)
28.587097
137
0.72715
1d9455f3468250103c21f919df5222021ab3bc26
2,152
kt
Kotlin
core/src/main/kotlin/roost/models/Camera.kt
InkApplications/Roost
cc73d21556483ec6aeddd8db3d7d4cd3430b4f5d
[ "MIT" ]
1
2018-06-25T14:41:55.000Z
2018-06-25T14:41:55.000Z
core/src/main/kotlin/roost/models/Camera.kt
InkApplications/Roost
cc73d21556483ec6aeddd8db3d7d4cd3430b4f5d
[ "MIT" ]
null
null
null
core/src/main/kotlin/roost/models/Camera.kt
InkApplications/Roost
cc73d21556483ec6aeddd8db3d7d4cd3430b4f5d
[ "MIT" ]
null
null
null
package roost.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import org.threeten.bp.Instant @JsonClass(generateAdapter = true) data class Camera( @Json(name="device_id") override val id: String, @Json(name = "software_version") val softwareVersion: String, @Json(name = "structure_id") val structureId: String, val name: String, @Json(name = "name_long") val longName: String, @Json(name = "is_online") val isOnline: Boolean, @Json(name = "where_id") val whereId: String, @Json(name = "where_name") val whereName: String, @Json(name = "last_connection") val lastConnection: Instant?, val locale: String?, @Json(name = "is_streaming") val isStreaming: Boolean?, @Json(name = "is_audio_input_enabled") val isAudioInputEnabled: Boolean?, @Json(name = "last_is_online_change") val lastIsOnlineChange: Instant?, @Json(name = "is_video_history_enabled") val isVideoHistoryEnabled: Boolean?, @Json(name = "web_url") val webUrl: String?, @Json(name = "app_url") val appUrl: String?, @Json(name = "is_public_share_enabled") val isPublicShareEnabled: Boolean?, @Json(name = "activity_zones") val activityZones: List<Where>?, @Json(name = "public_share_url") val publicShareUrl: String?, @Json(name = "snapshot_url") val snapshotUrl: String?, @Json(name = "last_event") val lastEvent: Event? ): Identifiable { @JsonClass(generateAdapter = true) data class Event( @Json(name = "has_sound") val hasSound: Boolean, @Json(name = "has_motion") val hasMotion: Boolean, @Json(name = "has_person") val hasPerson: Boolean, @Json(name = "start_time") val startTime: Instant, @Json(name = "end_time") val endTime: Instant?, @Json(name = "urls_expire_time") val urlsExpireTime: Instant, @Json(name = "web_url") val webUrl: String, @Json(name = "app_url") val appUrl: String, @Json(name = "imageUrl") val imageUrl: String?, @Json(name = "animated_image_url") val animatedImageUrl: String?, @Json(name = "activity_zone_ids") val activityZoneIds: List<String>? ) }
46.782609
81
0.682156