repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
brino/larablog
resources/views/admin/article/edit.blade.php
1196
<?php /** * Created by PhpStorm. * User: bmix * Date: 5/18/16 * Time: 8:44 AM */ ?> @extends('layouts.app') @section('title') Edit Article @stop @section('heading') <span class="icon is-medium"><i class="fa fa-pencil-square-o"></i></span> Edit Article @can('update-article',$article) <span class="pull-right"> {!! Form::model($article, ['id'=>'delete-form','method' => 'DELETE', 'files' => true, 'action' => ['Admin\ArticleController@destroy',$article]]) !!} {!! Form::submit('Delete',['class'=>'button is-danger']) !!} {!! Form::close() !!} </span> @endcan @stop @section('content') <div class="container"> {!! Form::model($article, ['id'=>'edit-form','method' => 'PATCH', 'files' => true, 'action' => ['Admin\ArticleController@update',$article]]) !!} @include('admin.article.forms.info') @include('admin.article.forms.body') @include('admin.article.forms.image') {!! Form::submit('Save',['class'=>'button is-primary is-large']) !!} <a class="button is-large" href="{{ URL::previous() }}"> Back </a> {!! Form::close() !!} </div> @endsection
mit
RaveNoX/ConsoleShell
src/ConsoleShell/Readline/Readline.cs
36251
#region Usings using System; using System.Collections; using System.IO; using System.Text; #endregion namespace ConsoleShell.Readline { internal class Readline { public Readline(ShellHistory history) { _history = history; } #region Fields // Internal state. // Line input buffer. private readonly char[] _buffer = new char[256]; private readonly byte[] _widths = new byte[256]; private readonly string _newLine = "\n"; private int _posn, _length, _column, _lastColumn; private bool _overwrite; private int _historyPosn; private string _historySave; private string _yankedString; private static char[] _wordBreakChars = {' ', '\n'}; private readonly ShellHistory _history; private ReadlineState _state = ReadlineState.None; private readonly StringBuilder _lastWord = new StringBuilder(); private int _savePosn; private int _tabCount = -1; #endregion #region Events /// <summary> /// Event that is emitted to allow for tab completion. /// </summary> /// <remarks> /// If there are no attached handlers, then the Tab key will do /// normal tabbing. /// </remarks> public event EventHandler<TabCompleteEventArgs> TabComplete; /// <summary> /// Event that is emitted to inform of the Ctrl+C command. /// </summary> public event EventHandler Interrupt; /// <summary> /// Event that is emmited to write prompt /// </summary> public event EventHandler WritePrompt; public event EventHandler<PrintAlternativesEventArgs> PrintAlternatives; #endregion #region Properties /// <summary> /// Gets or sets a flag that indicates if CTRL-D is an EOF indication /// or the "delete character" key. /// </summary> /// <remarks> /// The default is true (i.e. EOF). /// </remarks> public bool CtrlDIsEOF { get; set; } = true; /// <summary> /// Gets or sets a flag that indicates if CTRL-Z is an EOF indication. /// </summary> /// <remarks> /// The default is true on Windows system, false otherwise. /// </remarks> public bool CtrlZIsEOF { get; set; } = Path.DirectorySeparatorChar == '\\'; /// <summary> /// Gets or sets a flag that indicates if CTRL-C is an EOF indication. /// </summary> /// <remarks> /// The default is true on Unix system, false otherwise. /// </remarks> public bool CtrlCInterrupts { get; set; } = Path.DirectorySeparatorChar == '/'; public string LineBuffer => new string(_buffer, 0, _length); public char[] WordBreakCharacters { get { return _wordBreakChars; } set { if (value == null || value.Length == 0) { throw new ArgumentNullException(nameof(value)); } _wordBreakChars = value; } } #endregion #region Private Methods /// <summary> /// Makes room for one more character in the input buffer. /// </summary> private void MakeRoom() { if (_length >= _buffer.Length) { var newBuffer = new char[_buffer.Length*2]; var newWidths = new byte[_buffer.Length*2]; Array.Copy(_buffer, 0, newBuffer, 0, _buffer.Length); Array.Copy(_widths, 0, newWidths, 0, _buffer.Length); } } /// <summary> /// Repaint the line starting at the current character. /// </summary> /// <param name="step"></param> /// <param name="moveToEnd"></param> private void Repaint(bool step, bool moveToEnd) { var posn = _posn; var column = _column; int width; // Paint the characters in the line. while (posn < _length) { if (_buffer[posn] == '\t') { width = 8 - (column%8); _widths[posn] = (byte) width; while (width > 0) { Console.Write(' '); --width; ++column; } } else if (_buffer[posn] < 0x20) { Console.Write('^'); Console.Write((char) (_buffer[posn] + 0x40)); _widths[posn] = 2; column += 2; } else if (_buffer[posn] == '\u007F') { Console.Write('^'); Console.Write('?'); _widths[posn] = 2; column += 2; } else { Console.Write(_buffer[posn]); _widths[posn] = 1; ++column; } ++posn; } // Adjust the position of the last column. if (column > _lastColumn) { _lastColumn = column; } else if (column < _lastColumn) { // We need to clear some characters beyond this point. width = _lastColumn - column; _lastColumn = column; while (width > 0) { Console.Write(' '); --width; ++column; } } // Backspace to the initial cursor position. if (moveToEnd) { width = column - _lastColumn; _posn = _length; } else if (step) { width = column - (_column + _widths[_posn]); _column += _widths[_posn]; ++(_posn); } else { width = column - _column; } while (width > 0) { Console.Write('\u0008'); --width; } } /// <summary> /// Add a character to the input buffer. /// </summary> /// <param name="ch"></param> private void AddChar(char ch) { if (_overwrite && _posn < _length) { _buffer[_posn] = ch; Repaint(true, false); } else { MakeRoom(); if (_posn < _length) { Array.Copy(_buffer, _posn, _buffer, _posn + 1, _length - _posn); } _buffer[_posn] = ch; ++_length; Repaint(true, false); } if (Array.IndexOf(_wordBreakChars, ch) != -1) { CollectLastWord(ch); } } private void CollectLastWord(char ch) { var chars = new ArrayList(); for (var i = _length - 1; i >= 0; i--) { var c = _buffer[i]; if (ch != '\0' && c == ch) break; if (Array.IndexOf(_wordBreakChars, c) != -1) break; chars.Add(c); } chars.Reverse(); _lastWord.Length = 0; _lastWord.Append((char[]) chars.ToArray(typeof (char))); } // Go back a specific number of characters. private void GoBack(int num) { while (num > 0) { --_posn; var width = _widths[_posn]; _column -= width; while (width > 0) { Console.Write('\u0008'); --width; } --num; } } // Backspace one character. private void Backspace() { if (_posn > 0) { GoBack(1); Delete(); } } // Delete the character under the cursor. // Delete a number of characters under the cursor. private void Delete(int num = 1) { Array.Copy(_buffer, _posn + num, _buffer, _posn, _length - _posn - num); _length -= num; Repaint(false, false); //TODO: check... var chars = new ArrayList(); for (var i = _length - 1; i >= 0; i--) { var c = _buffer[i]; if (Array.IndexOf(_wordBreakChars, c) != -1) break; chars.Add(c); } chars.Reverse(); _lastWord.Length = 0; _lastWord.Append((char[]) chars.ToArray(typeof (char))); } private void ResetComplete(ReadlineState newState) { if (_state == ReadlineState.Completing) { _tabCount = -1; _savePosn = -1; } _state = newState; } // Tab across to the next stop, or perform tab completion. private void Tab() { if (TabComplete == null) { // Add the TAB character and repaint the line. AddChar('\t'); } else { if (_state != ReadlineState.Completing) { CollectLastWord('\0'); _state = ReadlineState.Completing; } // Perform tab completion and insert the results. var e = new TabCompleteEventArgs(_lastWord.ToString(), ++_tabCount); TabComplete(this, e); if (e.Insert != null) { _savePosn = _posn; // Insert the value that we found. var saveOverwrite = _overwrite; _overwrite = false; _savePosn = e.Insert.Length; _state = ReadlineState.Completing; foreach (var ch in e.Insert) { AddChar(ch); } _overwrite = saveOverwrite; } else if (e.Alternatives != null && e.Alternatives.Length > 0) { // Print the alternatives for the user. _savePosn = _posn; EndLine(); PrintAlternatives?.Invoke(this, new PrintAlternativesEventArgs(e.Alternatives)); WritePrompt?.Invoke(this, EventArgs.Empty); _posn = _savePosn; _state = ReadlineState.Completing; Redraw(); } else { if (e.Error) { ResetComplete(ReadlineState.MoreInput); } // No alternatives, or alternatives not supplied yet. Console.Beep(); } } } // End the current line. private void EndLine() { // Repaint the line and move to the end. Repaint(false, true); // Output the line terminator to the terminal. Console.Write(_newLine); } // Move left one character. private void MoveLeft() { if (_posn > 0) { GoBack(1); } } // Move right one character. private void MoveRight() { if (_posn < _length) { Repaint(true, false); } } // Set the current buffer contents to a historical string. private void SetCurrent(string line) { if (line == null) { line = string.Empty; } Clear(); foreach (var ch in line) { AddChar(ch); } } // Move up one line in the history. private void MoveUp() { if (_history == null) { Console.Beep(); return; } if (_historyPosn == -1) { if (_history.Count > 0) { _historySave = new string(_buffer, 0, _length); _historyPosn = 0; SetCurrent(_history.GetItemAt(_historyPosn)); } } else if ((_historyPosn + 1) < _history.Count) { ++_historyPosn; SetCurrent(_history.GetItemAt(_historyPosn)); } else { Console.Beep(); } } // Move down one line in the history. private void MoveDown() { if (_history == null) { Console.Beep(); return; } if (_historyPosn == 0) { _historyPosn = -1; SetCurrent(_historySave); } else if (_historyPosn > 0) { --_historyPosn; SetCurrent(_history.GetItemAt(_historyPosn)); } else { Console.Beep(); } } // Move to the beginning of the current line. private void MoveHome() { GoBack(_posn); } // Move to the end of the current line. private void MoveEnd() { Repaint(false, true); } // Clear the entire line. private void Clear() { GoBack(_posn); _length = 0; Repaint(false, false); } // Cancel the current line and start afresh with a new prompt. private void CancelLine() { EndLine(); WritePrompt?.Invoke(this, EventArgs.Empty); _posn = 0; _length = 0; _column = 0; _lastColumn = 0; _historyPosn = -1; } // Redraw the current line. private void Redraw() { var str = new string(_buffer, 0, _length); var savePosn = _posn; _posn = 0; _length = 0; _column = 0; _lastColumn = 0; foreach (var ch in str) { AddChar(ch); } GoBack(_length - savePosn); } // Erase all characters until the start of the current line. private void EraseToStart() { if (_posn > 0) { var savePosn = _posn; _yankedString = new string(_buffer, 0, _posn); GoBack(savePosn); Delete(savePosn); } } // Erase all characters until the end of the current line. private void EraseToEnd() { _yankedString = new string(_buffer, _posn, _length - _posn); _length = _posn; Repaint(false, false); _lastWord.Length = 0; } // Erase the previous word on the current line (delimited by whitespace). private void EraseWord() { var temp = _posn; while (temp > 0 && char.IsWhiteSpace(_buffer[temp - 1])) { --temp; } while (temp > 0 && !char.IsWhiteSpace(_buffer[temp - 1])) { --temp; } if (temp < _posn) { temp = _posn - temp; GoBack(temp); _yankedString = new string(_buffer, _posn, temp); Delete(temp); } if (_state != ReadlineState.Completing) _lastWord.Length = 0; } // Determine if a character is a "word character" (letter or digit). private bool IsWordCharacter(char ch) { return char.IsLetterOrDigit(ch); } // Erase to the end of the current word. private void EraseToEndWord() { var temp = _posn; while (temp < _length && !IsWordCharacter(_buffer[temp])) { ++temp; } while (temp < _length && IsWordCharacter(_buffer[temp])) { ++temp; } if (temp > _posn) { temp -= _posn; _yankedString = new string(_buffer, _posn, temp); Delete(temp); } } // Erase to the start of the current word. private void EraseToStartWord() { var temp = _posn; while (temp > 0 && !IsWordCharacter(_buffer[temp - 1])) { --temp; } while (temp > 0 && IsWordCharacter(_buffer[temp - 1])) { --temp; } if (temp < _posn) { temp = _posn - temp; GoBack(temp); _yankedString = new string(_buffer, _posn, temp); Delete(temp); } } // Move forward one word in the input line. private void MoveForwardWord() { while (_posn < _length && !IsWordCharacter(_buffer[_posn])) { MoveRight(); } while (_posn < _length && IsWordCharacter(_buffer[_posn])) { MoveRight(); } } // Move backward one word in the input line. private void MoveBackwardWord() { while (_posn > 0 && !IsWordCharacter(_buffer[_posn - 1])) { MoveLeft(); } while (_posn > 0 && IsWordCharacter(_buffer[_posn - 1])) { MoveLeft(); } } #endregion #region Public Methods // Read the next line of input using line editing. Returns "null" // if an EOF indication is encountered in the input. public string ReadLine() { var treatControlCAsInterrupt = Console.TreatControlCAsInput; Console.TreatControlCAsInput = !CtrlCInterrupts; try { // Output the prompt. WritePrompt?.Invoke(this, EventArgs.Empty); // Enter the main character input loop. _posn = 0; _length = 0; _column = 0; _lastColumn = 0; _overwrite = false; _historyPosn = -1; var ctrlv = false; _state = ReadlineState.MoreInput; do { var key = ConsoleExtensions.ReadKey(true); var ch = key.KeyChar; if (ctrlv) { ctrlv = false; if ((ch >= 0x0001 && ch <= 0x001F) || ch == 0x007F) { // Insert a control character into the buffer. AddChar(ch); continue; } } if (ch != '\0') { switch (ch) { case '\u0001': { // CTRL-A: move to the home position. MoveHome(); } break; case '\u0002': { // CTRL-B: go back one character. MoveLeft(); } break; case '\u0003': { // CTRL-C encountered in "raw" mode. if (CtrlCInterrupts) { EndLine(); Interrupt?.Invoke(null, EventArgs.Empty); return null; } CancelLine(); _lastWord.Length = 0; } break; case '\u0004': { // CTRL-D: EOF or delete the current character. if (CtrlDIsEOF) { _lastWord.Length = 0; // Signal an EOF if the buffer is empty. if (_length == 0) { EndLine(); return null; } } else { Delete(); ResetComplete(ReadlineState.MoreInput); } } break; case '\u0005': { // CTRL-E: move to the end position. MoveEnd(); } break; case '\u0006': { // CTRL-F: go forward one character. MoveRight(); } break; case '\u0007': { // CTRL-G: ring the terminal bell. Console.Beep(); } break; case '\u0008': case '\u007F': { if (key.Key == ConsoleKey.Delete) { // Delete the character under the cursor. Delete(); } else { // Delete the character before the cursor. Backspace(); } ResetComplete(ReadlineState.MoreInput); } break; case '\u0009': { // Process a tab. Tab(); } break; case '\u000A': case '\u000D': { // Line termination. EndLine(); ResetComplete(ReadlineState.Done); _lastWord.Length = 0; } break; case '\u000B': { // CTRL-K: erase until the end of the line. EraseToEnd(); } break; case '\u000C': { // CTRL-L: clear screen and redraw. Console.Clear(); WritePrompt?.Invoke(this, EventArgs.Empty); Redraw(); } break; case '\u000E': { // CTRL-N: move down in the history. MoveDown(); } break; case '\u0010': { // CTRL-P: move up in the history. MoveUp(); } break; case '\u0015': { // CTRL-U: erase to the start of the line. EraseToStart(); ResetComplete(ReadlineState.None); } break; case '\u0016': { // CTRL-V: prefix a control character. ctrlv = true; } break; case '\u0017': { // CTRL-W: erase the previous word. EraseWord(); ResetComplete(ReadlineState.MoreInput); } break; case '\u0019': { // CTRL-Y: yank the last erased string. if (_yankedString != null) { foreach (var ch2 in _yankedString) { AddChar(ch2); } } } break; case '\u001A': { // CTRL-Z: Windows end of file indication. if (CtrlZIsEOF && _length == 0) { EndLine(); return null; } } break; case '\u001B': { // Escape is "clear line". Clear(); ResetComplete(ReadlineState.MoreInput); } break; default: { if (ch >= ' ') { // Ordinary character. AddChar(ch); ResetComplete(ReadlineState.MoreInput); } } break; } } else if (key.Modifiers == 0) { switch (key.Key) { case ConsoleKey.Backspace: { // Delete the character before the cursor. Backspace(); ResetComplete(ReadlineState.MoreInput); } break; case ConsoleKey.Delete: { // Delete the character under the cursor. Delete(); ResetComplete(ReadlineState.MoreInput); } break; case ConsoleKey.Enter: { // Line termination. EndLine(); ResetComplete(ReadlineState.Done); } break; case ConsoleKey.Escape: { // Clear the current line. Clear(); ResetComplete(ReadlineState.None); } break; case ConsoleKey.Tab: { // Process a tab. Tab(); } break; case ConsoleKey.LeftArrow: { // Move left one character. MoveLeft(); } break; case ConsoleKey.RightArrow: { // Move right one character. MoveRight(); } break; case ConsoleKey.UpArrow: { // Move up one line in the history. MoveUp(); } break; case ConsoleKey.DownArrow: { // Move down one line in the history. MoveDown(); } break; case ConsoleKey.Home: { // Move to the beginning of the line. MoveHome(); } break; case ConsoleKey.End: { // Move to the end of the line. MoveEnd(); } break; case ConsoleKey.Insert: { // Toggle insert/overwrite mode. _overwrite = !_overwrite; } break; } } else if ((key.Modifiers & ConsoleModifiers.Alt) != 0) { switch (key.Key) { case ConsoleKey.F: { // ALT-F: move forward a word. MoveForwardWord(); } break; case ConsoleKey.B: { // ALT-B: move backward a word. MoveBackwardWord(); } break; case ConsoleKey.D: { // ALT-D: erase until the end of the word. EraseToEndWord(); } break; case ConsoleKey.Backspace: case ConsoleKey.Delete: { // ALT-DEL: erase until the start of the word. EraseToStartWord(); } break; } } } while (_state != ReadlineState.Done); return new string(_buffer, 0, _length); } finally { Console.TreatControlCAsInput = treatControlCAsInterrupt; } } public string ReadPassword() { var treatControlCAsInterrupt = Console.TreatControlCAsInput; Console.TreatControlCAsInput = !CtrlCInterrupts; try { // Output the prompt. WritePrompt?.Invoke(this, EventArgs.Empty); var pass = new Stack(); for (var consKeyInfo = Console.ReadKey(true); consKeyInfo.Key != ConsoleKey.Enter; consKeyInfo = Console.ReadKey(true)) { if (consKeyInfo.Key == ConsoleKey.Backspace) { try { Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); Console.Write(" "); Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); pass.Pop(); } catch (InvalidOperationException) { Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); } } else { Console.Write("*"); pass.Push(consKeyInfo.KeyChar.ToString()); } } var chars = pass.ToArray(); var password = new string[chars.Length]; Array.Copy(chars, password, chars.Length); Array.Reverse(password); return string.Join(string.Empty, password); } finally { Console.TreatControlCAsInput = treatControlCAsInterrupt; } } #endregion } }
mit
ASzot/Wumpus-XNA-Game-Engine
HTW Game Engine/BaseLogic/Editor/Forms/Object Editors/Game Play/SoundEffectEditorForm.Designer.cs
7577
namespace BaseLogic.Editor.Forms.Object_Editors { partial class SoundEffectEditorForm { /// <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 Windows Form 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.closeBtn = new System.Windows.Forms.Button(); this.soundFilenameTxtBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.pitchTxtBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.panTxtBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.volumeTxtBox = new System.Windows.Forms.TextBox(); this.acceptBtn = new System.Windows.Forms.Button(); this.SuspendLayout(); // // closeBtn // this.closeBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.closeBtn.Location = new System.Drawing.Point(210, 161); this.closeBtn.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.closeBtn.Name = "closeBtn"; this.closeBtn.Size = new System.Drawing.Size(112, 35); this.closeBtn.TabIndex = 15; this.closeBtn.Text = "Close"; this.closeBtn.UseVisualStyleBackColor = true; this.closeBtn.Click += new System.EventHandler(this.closeBtn_Click); // // soundFilenameTxtBox // this.soundFilenameTxtBox.Location = new System.Drawing.Point(147, 6); this.soundFilenameTxtBox.Name = "soundFilenameTxtBox"; this.soundFilenameTxtBox.Size = new System.Drawing.Size(134, 26); this.soundFilenameTxtBox.TabIndex = 16; this.soundFilenameTxtBox.TextChanged += new System.EventHandler(this.txtBox_TextChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(129, 20); this.label1.TabIndex = 17; this.label1.Text = "Sound Filename:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(74, 105); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(67, 20); this.label2.TabIndex = 19; this.label2.Text = "Volume:"; // // pitchTxtBox // this.pitchTxtBox.Location = new System.Drawing.Point(147, 70); this.pitchTxtBox.Name = "pitchTxtBox"; this.pitchTxtBox.Size = new System.Drawing.Size(134, 26); this.pitchTxtBox.TabIndex = 18; this.pitchTxtBox.TextChanged += new System.EventHandler(this.txtBox_TextChanged); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(100, 41); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(41, 20); this.label3.TabIndex = 21; this.label3.Text = "Pan:"; // // panTxtBox // this.panTxtBox.Location = new System.Drawing.Point(147, 38); this.panTxtBox.Name = "panTxtBox"; this.panTxtBox.Size = new System.Drawing.Size(134, 26); this.panTxtBox.TabIndex = 20; this.panTxtBox.TextChanged += new System.EventHandler(this.txtBox_TextChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(93, 73); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(48, 20); this.label4.TabIndex = 23; this.label4.Text = "Pitch:"; // // volumeTxtBox // this.volumeTxtBox.Location = new System.Drawing.Point(147, 102); this.volumeTxtBox.Name = "volumeTxtBox"; this.volumeTxtBox.Size = new System.Drawing.Size(134, 26); this.volumeTxtBox.TabIndex = 22; this.volumeTxtBox.TextChanged += new System.EventHandler(this.txtBox_TextChanged); // // acceptBtn // this.acceptBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.acceptBtn.Location = new System.Drawing.Point(13, 161); this.acceptBtn.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.acceptBtn.Name = "acceptBtn"; this.acceptBtn.Size = new System.Drawing.Size(112, 35); this.acceptBtn.TabIndex = 24; this.acceptBtn.Text = "Accept"; this.acceptBtn.UseVisualStyleBackColor = true; this.acceptBtn.Click += new System.EventHandler(this.acceptBtn_Click); // // SoundEffectEditorForm // this.AcceptButton = this.acceptBtn; this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.closeBtn; this.ClientSize = new System.Drawing.Size(335, 210); this.ControlBox = false; this.Controls.Add(this.acceptBtn); this.Controls.Add(this.label4); this.Controls.Add(this.volumeTxtBox); this.Controls.Add(this.label3); this.Controls.Add(this.panTxtBox); this.Controls.Add(this.label2); this.Controls.Add(this.pitchTxtBox); this.Controls.Add(this.label1); this.Controls.Add(this.soundFilenameTxtBox); this.Controls.Add(this.closeBtn); this.Name = "SoundEffectEditorForm"; this.Text = "Sound Effect Editor"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button closeBtn; private System.Windows.Forms.TextBox soundFilenameTxtBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox pitchTxtBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox panTxtBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox volumeTxtBox; private System.Windows.Forms.Button acceptBtn; } }
mit
gmarty/natural
lib/natural/trie/trie.js
4780
/* Copyright (c) 2014 Ken Koch 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. */ /** * The basis of the TRIE structure. **/ function Trie(caseSensitive) { this.dictionary = {}; this.$ = false; if(typeof caseSensitive === "undefined") { caseSensitive = true; } this.cs = caseSensitive; } /** * Add a single string to the TRIE, returns true if the word was already in the * trie. **/ Trie.prototype.addString = function(string) { if(this.cs === false) { string = string.toLowerCase(); } // If the string has only one letter, mark this as a word. if(string.length === 0) { var wasWord = this.$; this.$ = true; return wasWord; } // Make sure theres a Trie node in our dictionary var next = this.dictionary[string[0]]; if(!next) { this.dictionary[string[0]] = new Trie(this.cs); next = this.dictionary[string[0]]; } // Continue adding the string return next.addString(string.substring(1)); }; /** * Add multiple strings to the TRIE **/ Trie.prototype.addStrings = function(list) { for(var i in list) { this.addString(list[i]); } }; /** * A function to search the given string and return true if it lands * on on a word. Essentially testing if the word exists in the database. **/ Trie.prototype.contains = function(string) { if(this.cs === false) { string = string.toLowerCase(); } if(string.length === 0) { return this.$; } // Otherwise, we need to continue searching var firstLetter = string[0]; var next = this.dictionary[firstLetter]; // If we don't have a node, this isn't a word if(!next) { return false; } // Otherwise continue the search at the next node return next.contains(string.substring(1)); } /** * A function to search the TRIE and return an array of words which were encountered along the way. * This will only return words with full prefix matches. * for example if we had the following words in our database: * a, ab, bc, cd, abc * and we searched the string: abcd * we would get only: * [a, ab, abc] **/ Trie.prototype.findMatchesOnPath = function(search, stringAgg, resultsAgg) { if(this.cs === false) { search = search.toLowerCase(); } function recurse(node, search, stringAgg, resultsAgg) { // Check if this is a word. if(node.$) { resultsAgg.push(stringAgg); } // Check if the have completed the seearch if(search.length === 0) { return resultsAgg; } // Otherwise, continue searching var next = node.dictionary[search[0]]; if(!next) { return resultsAgg; } return recurse(next, search.substring(1), stringAgg + search[0], resultsAgg); }; return recurse(this, search, "", []); }; /** * Returns the longest match and the remaining part that could not be matched. * inspired by [NLTK containers.trie.find_prefix](http://nltk.googlecode.com/svn-/trunk/doc/api/nltk.containers.Trie-class.html). **/ Trie.prototype.findPrefix = function(search) { if(this.cs === false) { search = search.toLowerCase(); } function recurse(node, search, stringAgg, lastWord) { // Check if this is a word if(node.$) { lastWord = stringAgg; } // Check if we have no more to search if(search.length === 0) { return [lastWord, search]; } // Continue searching var next = node.dictionary[search[0]]; if(!next) { return [lastWord, search]; } return recurse(next, search.substring(1), stringAgg + search[0], lastWord); }; return recurse(this, search, "", null); }; /** * Computes the number of actual nodes from this node to the end. * Note: This involves traversing the entire structure and may not be * good for frequent use. **/ Trie.prototype.getSize = function() { var total = 1; for(var c in this.dictionary) { total += this.dictionary[c].getSize(); } return total; }; /** * EXPORT THE TRIE **/ module.exports = Trie;
mit
mwean/sublime_jump_along_indent
tests/helper.py
897
import sublime from unittest import TestCase class TestHelper(TestCase): def setUp(self): self.view = sublime.active_window().new_file() self.view.settings().set("tab_size", 2) def tearDown(self): if self.view: self.view.set_scratch(True) self.view.window().run_command('close_file') def set_text(self, lines): for line in lines: self.view.run_command('move_to', { 'to': 'bol', 'extend': True }) self.view.run_command('insert', { 'characters': line + "\n" }) def check_command(self, text, start, end, extend_selection=False, indent_offset=0): self.set_text(text) self.view.sel().clear() self.view.sel().add(sublime.Region(start[0], start[1])) self.view.run_command(self.command(), { 'extend_selection': extend_selection, 'indent_offset': indent_offset }) self.assertEqual(self.view.sel()[0], sublime.Region(end[0], end[1]))
mit
jinxiaodan/credit-center-webpack
src/js/main.js
877
(function ($, window, document, undefined){ var tree = [{ text: 'Parent1', nodes: [{ text: 'Child1', nodes: [{ text: 'Grandchild1' }, { text: 'Grandchild2' }] }, { text: 'Child2' }] }, { text: 'Parent2' }, { text: 'Parent3' }, { text: 'Parent4' }, { text: 'Parent5' }]; function getTree() { // Some logic to retrieve, or generate tree structure return tree; } $('#viewTree').treeview({data: getTree(),showBorder:false}); //绑定树形菜单的点击事件 $('#viewTree').on('nodeSelected',function(event,node){ console.log(node); $(this).addTab({id:node.text,title:node.text,content:node.text +'<br>'+ node.text}); }) //初始化tab状态 $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { e.target // newly activated tab e.relatedTarget // previous active tab }) }(jQuery, window, document))
mit
efuquen/coreutils
src/id/id.rs
11913
#![crate_name = "id"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <alan.andradec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Synced with: * http://ftp-archive.freebsd.org/mirror/FreeBSD-Archive/old-releases/i386/1.0-RELEASE/ports/shellutils/src/id.c * http://www.opensource.apple.com/source/shell_cmds/shell_cmds-118/id/id.c */ #![allow(non_camel_case_types)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use libc::{getgid, getuid, uid_t, getegid, geteuid, getlogin}; use std::ffi::CStr; use std::io::Write; use std::ptr::read; use uucore::c_types::{ c_passwd, c_group, get_groups, get_group_list, get_pw_from_args, getpwuid, group }; #[cfg(not(target_os = "linux"))] mod audit { pub use std::mem::uninitialized; use libc::{uid_t, pid_t, c_int, c_uint, uint64_t, dev_t}; pub type au_id_t = uid_t; pub type au_asid_t = pid_t; pub type au_event_t = c_uint; pub type au_emod_t = c_uint; pub type au_class_t = c_int; #[repr(C)] pub struct au_mask { pub am_success: c_uint, pub am_failure: c_uint } pub type au_mask_t = au_mask; #[repr(C)] pub struct au_tid_addr { pub port: dev_t, } pub type au_tid_addr_t = au_tid_addr; #[repr(C)] pub struct c_auditinfo_addr { pub ai_auid: au_id_t, /* Audit user ID */ pub ai_mask: au_mask_t, /* Audit masks. */ pub ai_termid: au_tid_addr_t, /* Terminal ID. */ pub ai_asid: au_asid_t, /* Audit session ID. */ pub ai_flags: uint64_t /* Audit session flags */ } pub type c_auditinfo_addr_t = c_auditinfo_addr; extern { pub fn getaudit(auditinfo_addr: *mut c_auditinfo_addr_t) -> c_int; } } extern { fn getgrgid(gid: uid_t) -> *const c_group; } static NAME: &'static str = "id"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "", "Show help"); opts.optflag("A", "", "Display the process audit (not available on Linux)"); opts.optflag("G", "", "Display the different group IDs"); opts.optflag("g", "", "Display the effective group ID as a number"); opts.optflag("n", "", "Display the name of the user or group ID for the -G, -g and -u options"); opts.optflag("P", "", "Display the id as a password file entry"); opts.optflag("p", "", "Make the output human-readable"); opts.optflag("r", "", "Display the real ID for the -g and -u options"); opts.optflag("u", "", "Display the effective user ID as a number"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }, Err(_) => { println!("{}", opts.usage(NAME)); return 1; } }; if matches.opt_present("h") { println!("{}", opts.usage(NAME)); return 0; } if matches.opt_present("A") { auditid(); return 0; } let possible_pw = get_pw_from_args(&matches.free); let nflag = matches.opt_present("n"); let uflag = matches.opt_present("u"); let gflag = matches.opt_present("g"); let rflag = matches.opt_present("r"); if gflag { let id = if possible_pw.is_some() { possible_pw.unwrap().pw_gid } else { if rflag { unsafe { getgid() } } else { unsafe { getegid() } } }; let gr = unsafe { getgrgid(id) }; if nflag && !gr.is_null() { let gr_name = unsafe { String::from_utf8_lossy(CStr::from_ptr(read(gr).gr_name).to_bytes()).to_string() }; println!("{}", gr_name); } else { println!("{}", id); } return 0; } if uflag { let id = if possible_pw.is_some() { possible_pw.unwrap().pw_uid } else if rflag { unsafe { getgid() } } else { unsafe { getegid() } }; let pw = unsafe { getpwuid(id) }; if nflag && !pw.is_null() { let pw_name = unsafe { String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() }; println!("{}", pw_name); } else { println!("{}", id); } return 0; } if matches.opt_present("G") { group(possible_pw, nflag); return 0; } if matches.opt_present("P") { pline(possible_pw); return 0; }; if matches.opt_present("p") { pretty(possible_pw); return 0; } if possible_pw.is_some() { id_print(possible_pw, false, false) } else { id_print(possible_pw, true, true) } 0 } fn pretty(possible_pw: Option<c_passwd>) { if possible_pw.is_some() { let pw = possible_pw.unwrap(); let pw_name = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_name).to_bytes()).to_string() }; print!("uid\t{}\ngroups\t", pw_name); group(possible_pw, true); } else { let login = unsafe { String::from_utf8_lossy(CStr::from_ptr((getlogin() as *const i8)).to_bytes()).to_string() }; let rid = unsafe { getuid() }; let pw = unsafe { getpwuid(rid) }; let is_same_user = unsafe { String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() == login }; if pw.is_null() || is_same_user { println!("login\t{}", login); } if !pw.is_null() { println!( "uid\t{}", unsafe { String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() }) } else { println!("uid\t{}\n", rid); } let eid = unsafe { getegid() }; if eid == rid { let pw = unsafe { getpwuid(eid) }; if !pw.is_null() { println!( "euid\t{}", unsafe { String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() }); } else { println!("euid\t{}", eid); } } let rid = unsafe { getgid() }; if rid != eid { let gr = unsafe { getgrgid(rid) }; if !gr.is_null() { println!( "rgid\t{}", unsafe { String::from_utf8_lossy(CStr::from_ptr(read(gr).gr_name).to_bytes()).to_string() }); } else { println!("rgid\t{}", rid); } } print!("groups\t"); group(None, true); } } #[cfg(any(target_os = "macos", target_os = "freebsd"))] fn pline(possible_pw: Option<c_passwd>) { let pw = if possible_pw.is_none() { unsafe { read(getpwuid(getuid())) } } else { possible_pw.unwrap() }; let pw_name = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_name ).to_bytes()).to_string()}; let pw_passwd = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_passwd).to_bytes()).to_string()}; let pw_class = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_class ).to_bytes()).to_string()}; let pw_gecos = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_gecos ).to_bytes()).to_string()}; let pw_dir = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_dir ).to_bytes()).to_string()}; let pw_shell = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_shell ).to_bytes()).to_string()}; println!( "{}:{}:{}:{}:{}:{}:{}:{}:{}:{}", pw_name, pw_passwd, pw.pw_uid, pw.pw_gid, pw_class, pw.pw_change, pw.pw_expire, pw_gecos, pw_dir, pw_shell); } #[cfg(target_os = "linux")] fn pline(possible_pw: Option<c_passwd>) { let pw = if possible_pw.is_none() { unsafe { read(getpwuid(getuid())) } } else { possible_pw.unwrap() }; let pw_name = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_name ).to_bytes()).to_string()}; let pw_passwd = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_passwd).to_bytes()).to_string()}; let pw_gecos = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_gecos ).to_bytes()).to_string()}; let pw_dir = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_dir ).to_bytes()).to_string()}; let pw_shell = unsafe { String::from_utf8_lossy(CStr::from_ptr(pw.pw_shell ).to_bytes()).to_string()}; println!( "{}:{}:{}:{}:{}:{}:{}", pw_name, pw_passwd, pw.pw_uid, pw.pw_gid, pw_gecos, pw_dir, pw_shell); } #[cfg(target_os = "linux")] fn auditid() { } #[cfg(not(target_os = "linux"))] fn auditid() { let mut auditinfo: audit::c_auditinfo_addr_t = unsafe { audit::uninitialized() }; let address = &mut auditinfo as *mut audit::c_auditinfo_addr_t; if unsafe { audit::getaudit(address) } < 0 { println!("couldn't retrieve information"); return; } println!("auid={}", auditinfo.ai_auid); println!("mask.success=0x{:x}", auditinfo.ai_mask.am_success); println!("mask.failure=0x{:x}", auditinfo.ai_mask.am_failure); println!("termid.port=0x{:x}", auditinfo.ai_termid.port); println!("asid={}", auditinfo.ai_asid); } fn id_print(possible_pw: Option<c_passwd>, p_euid: bool, p_egid: bool) { let uid; let gid; if possible_pw.is_some() { uid = possible_pw.unwrap().pw_uid; gid = possible_pw.unwrap().pw_gid; } else { uid = unsafe { getuid() }; gid = unsafe { getgid() }; } let groups = match possible_pw { Some(pw) => Ok(get_group_list(pw.pw_name, pw.pw_gid)), None => get_groups(), }; let groups = groups.unwrap_or_else(|errno| { crash!(1, "failed to get group list (errno={})", errno); }); if possible_pw.is_some() { print!( "uid={}({})", uid, unsafe { String::from_utf8_lossy(CStr::from_ptr(possible_pw.unwrap().pw_name).to_bytes()).to_string() }); } else { print!("uid={}", unsafe { getuid() }); } print!(" gid={}", gid); let gr = unsafe { getgrgid(gid) }; if !gr.is_null() { print!( "({})", unsafe { String::from_utf8_lossy(CStr::from_ptr(read(gr).gr_name).to_bytes()).to_string() }); } let euid = unsafe { geteuid() }; if p_euid && (euid != uid) { print!(" euid={}", euid); let pw = unsafe { getpwuid(euid) }; if !pw.is_null() { print!( "({})", unsafe { String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() }); } } let egid = unsafe { getegid() }; if p_egid && (egid != gid) { print!(" egid={}", egid); unsafe { let grp = getgrgid(egid); if !grp.is_null() { print!("({})", String::from_utf8_lossy(CStr::from_ptr(read(grp).gr_name).to_bytes()).to_string()); } } } if groups.len() > 0 { print!(" groups="); let mut first = true; for &gr in groups.iter() { if !first { print!(",") } print!("{}", gr); let group = unsafe { getgrgid(gr) }; if !group.is_null() { let name = unsafe { String::from_utf8_lossy(CStr::from_ptr(read(group).gr_name).to_bytes()).to_string() }; print!("({})", name); } first = false } } println!(""); } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
mit
windbender/wildlife-camera-machine
src/main/java/com/github/windbender/dao/EventDAO.java
7106
package com.github.windbender.dao; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; import org.joda.time.DateTime; import com.github.windbender.domain.ImageEvent; import com.github.windbender.domain.User; import com.yammer.dropwizard.hibernate.AbstractDAO; public class EventDAO extends AbstractDAO<ImageEvent> { public EventDAO(SessionFactory sessionFactory) { super(sessionFactory); } public ImageEvent findById(Long id) { return get(id); } public long create(ImageEvent ir) { return persist(ir).getId(); } public List<ImageEvent> findEventsForUserToID(User u, int number) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select * from ( select count(y.image_event_id) as totalActions, events.id as eventId from events left join (select * from identifications where user_id != ?) y on y.image_event_id = events.id group by events.id ) x where x.totalActions < ? order by totalActions,eventId"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); int limit = 2; Query query = sqlQuery.setParameter(0, u.getId()).setParameter(1, limit); List<Object[]> l = query.list(); int count = 0; for(Object[] oa: l) { int numberOfIdentifications = 0; Long event_id = null; BigInteger numberOfIdentifications_bi = (BigInteger)oa[0]; Integer event_id_bi = (Integer)oa[1]; if(numberOfIdentifications_bi != null) { numberOfIdentifications = numberOfIdentifications_bi.intValue(); } if(event_id_bi != null) { event_id = event_id_bi.longValue(); } if(event_id != null) { ImageEvent e = this.findById(event_id); list.add(e); count++; if(count > number) break; } } return list; } public List<ImageEvent> findEventsBetween(DateTime before, DateTime after) { Session currentSession = this.currentSession(); Criteria crit = currentSession.createCriteria(ImageEvent.class); crit.add(Restrictions.ge("eventStartTime", before)); crit.add(Restrictions.le("eventStartTime", after)); crit.addOrder( Property.forName("eventStartTime").desc() ); List<ImageEvent> findList = crit.list(); return findList; } public List<ImageEvent> findEventsBetween(long l, DateTime before, DateTime after) { Session currentSession = this.currentSession(); Criteria crit = currentSession.createCriteria(ImageEvent.class); crit.add(Restrictions.ge("eventStartTime", before)); crit.add(Restrictions.le("eventStartTime", after)); crit.add(Restrictions.eq("cameraID",l)); crit.addOrder( Property.forName("eventStartTime").desc() ); List<ImageEvent> findList = crit.list(); return findList; } public void save(ImageEvent ie) { this.currentSession().saveOrUpdate(ie); } public List<ImageEvent> findAll() { Session currentSession = this.currentSession(); Criteria crit = currentSession.createCriteria(ImageEvent.class); crit.addOrder( Property.forName("eventStartTime").desc() ); List<ImageEvent> findList = crit.list(); return findList; } public List<Integer> findEventIdsDoneByUser(User u) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select image_event_id from identifications where user_id=? group by image_event_id order by image_event_id"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); Query query = sqlQuery.setParameter(0, u.getId()); List<Integer> l = query.list(); return l; } public List<Integer> findEventsIdsWithFewerThanIdentifications(int number) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select eventId from (select count(identifications.image_event_id) as totalActions, events.id as eventId from events left join identifications on identifications.image_event_id = events.id group by events.id ) x where x.totalActions < ? order by totalActions,eventId"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); Query query = sqlQuery.setParameter(0, number); List<Integer> l = query.list(); return l; } public List<Integer> findEventIdsIdentifiedByUser(Long project_id, User u) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select image_event_id from identifications i, events e, cameras c where i.image_event_id=e.id and e.camera_id = c.id and c.project_id=? and user_id=? group by e.id order by e.id"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); Query query = sqlQuery.setParameter(0, project_id).setParameter(1, u.getId()); List<Integer> l = query.list(); return l; } public List<Integer> findEventIdsUploadedByUser(Long project_id, User u) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select e.id from images i, events e, cameras c where i.event_id = e.id and e.camera_id = c.id and c.project_id=? and i.user_id=? group by e.id order by e.id"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); Query query = sqlQuery.setParameter(0, project_id).setParameter(1, u.getId()); List<Integer> l = query.list(); return l; } public List<Integer> findEventsIdsWithFewerThanIdentifications(Long project_id, int number) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select eventId from (select count(i.image_event_id) as totalActions, e.id as eventId from cameras c, events e left join identifications i on i.image_event_id = e.id where c.id = e.camera_id and c.project_id=? group by e.id ) x where x.totalActions < ? order by totalActions,eventId"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); Query query = sqlQuery.setParameter(0, project_id).setParameter(1, number); List<Integer> l = query.list(); return l; } public List<Integer> findFlaggedEventsIdsWithFewerThanIdentifications(Long project_id,int number) { List<ImageEvent> list = new ArrayList<ImageEvent>(); String sql = "select eventId from ( "+ "select count(i.image_event_id) as totalActions, e.id as eventId "+ "from cameras c, events e left join identifications i on i.image_event_id = e.id "+ "where c.id = e.camera_id and c.project_id=? group by e.id "+ ") x, "+ "(select image_event_id ,count(*) flags from event_review_needed, events "+ "where event_review_needed.image_event_id = events.id and event_review_needed.flagged=1 group by events.id "+ ") y where x.eventId= y.image_event_id and totalActions < flags+? order by totalActions,eventId"; SQLQuery sqlQuery = this.currentSession().createSQLQuery(sql); Query query = sqlQuery.setParameter(0, project_id).setParameter(1, number); List<Integer> l = query.list(); return l; } }
mit
Numerico-Informatic-Systems-Pvt-Ltd/arnojobportal
src/JobPortal/FrontBundle/Entity/Users.php
6389
<?php namespace JobPortal\FrontBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Users */ class Users { /** * @var string */ private $name; /** * @var string */ private $email; /** * @var string */ private $phone; /** * @var string */ private $address; /** * @var string */ private $pinCode; /** * @var string */ private $city; /** * @var string */ private $country; /** * @var \DateTime */ private $dob; /** * @var string */ private $password; /** * @var string */ private $image; /** * @var string */ private $cv; /** * @var integer */ private $forgetPasswordOtp; /** * @var string */ private $facebookId; /** * @var boolean */ private $status; /** * @var boolean */ private $isDeleted; /** * @var integer */ private $id; /** * Set name * * @param string $name * @return Users */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set email * * @param string $email * @return Users */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set phone * * @param string $phone * @return Users */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * Get phone * * @return string */ public function getPhone() { return $this->phone; } /** * Set address * * @param string $address * @return Users */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } /** * Set pinCode * * @param string $pinCode * @return Users */ public function setPinCode($pinCode) { $this->pinCode = $pinCode; return $this; } /** * Get pinCode * * @return string */ public function getPinCode() { return $this->pinCode; } /** * Set city * * @param string $city * @return Users */ public function setCity($city) { $this->city = $city; return $this; } /** * Get city * * @return string */ public function getCity() { return $this->city; } /** * Set country * * @param string $country * @return Users */ public function setCountry($country) { $this->country = $country; return $this; } /** * Get country * * @return string */ public function getCountry() { return $this->country; } /** * Set dob * * @param \DateTime $dob * @return Users */ public function setDob($dob) { $this->dob = $dob; return $this; } /** * Get dob * * @return \DateTime */ public function getDob() { return $this->dob; } /** * Set password * * @param string $password * @return Users */ public function setPassword($password) { $this->password = $password; return $this; } /** * Get password * * @return string */ public function getPassword() { return $this->password; } /** * Set image * * @param string $image * @return Users */ public function setImage($image) { $this->image = $image; return $this; } /** * Get image * * @return string */ public function getImage() { return $this->image; } /** * Set cv * * @param string $cv * @return Users */ public function setCv($cv) { $this->cv = $cv; return $this; } /** * Get cv * * @return string */ public function getCv() { return $this->cv; } /** * Set forgetPasswordOtp * * @param integer $forgetPasswordOtp * @return Users */ public function setForgetPasswordOtp($forgetPasswordOtp) { $this->forgetPasswordOtp = $forgetPasswordOtp; return $this; } /** * Get forgetPasswordOtp * * @return integer */ public function getForgetPasswordOtp() { return $this->forgetPasswordOtp; } /** * Set facebookId * * @param string $facebookId * @return Users */ public function setFacebookId($facebookId) { $this->facebookId = $facebookId; return $this; } /** * Get facebookId * * @return string */ public function getFacebookId() { return $this->facebookId; } /** * Set status * * @param boolean $status * @return Users */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return boolean */ public function getStatus() { return $this->status; } /** * Set isDeleted * * @param boolean $isDeleted * @return Users */ public function setIsDeleted($isDeleted) { $this->isDeleted = $isDeleted; return $this; } /** * Get isDeleted * * @return boolean */ public function getIsDeleted() { return $this->isDeleted; } /** * Get id * * @return integer */ public function getId() { return $this->id; } }
mit
js-diaz/sistrans
src/rfc/ListaContenedoraInfoZonaCategoriaProducto.java
1001
package rfc; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Clase usada para contener información.<br> * @author jc161 * */ public class ListaContenedoraInfoZonaCategoriaProducto { /** * Información utilizada. */ @JsonProperty(value="informacion") private List<ContenedoraZonaCategoriaProducto> informacion; /** * Constructor de una nueva conteendora.<br> * @param list Información de la contenedora. */ public ListaContenedoraInfoZonaCategoriaProducto(List<ContenedoraZonaCategoriaProducto>list) { informacion=list; } /** * Obtiene información del sistema.<br> * @return informacion */ public List<ContenedoraZonaCategoriaProducto> getInformacion() { return informacion; } /** * Modifica la información al valor dado por parámetro.<br> * @param informacion */ public void setInformacion(List<ContenedoraZonaCategoriaProducto> informacion) { this.informacion = informacion; } }
mit
lunny/gitea
routers/repo/pull.go
31204
// Copyright 2018 The Gitea Authors. // Copyright 2014 The Gogs Authors. // All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package repo import ( "container/list" "fmt" "io" "net/url" "path" "strings" "code.gitea.io/git" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/setting" "github.com/Unknwon/com" ) const ( tplFork base.TplName = "repo/pulls/fork" tplComparePull base.TplName = "repo/pulls/compare" tplPullCommits base.TplName = "repo/pulls/commits" tplPullFiles base.TplName = "repo/pulls/files" pullRequestTemplateKey = "PullRequestTemplate" ) var ( pullRequestTemplateCandidates = []string{ "PULL_REQUEST_TEMPLATE.md", "pull_request_template.md", ".gitea/PULL_REQUEST_TEMPLATE.md", ".gitea/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/pull_request_template.md", } ) func getForkRepository(ctx *context.Context) *models.Repository { forkRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid")) if err != nil { if models.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) } else { ctx.ServerError("GetRepositoryByID", err) } return nil } perm, err := models.GetUserRepoPermission(forkRepo, ctx.User) if err != nil { ctx.ServerError("GetUserRepoPermission", err) return nil } if forkRepo.IsBare || !perm.CanRead(models.UnitTypeCode) { ctx.NotFound("getForkRepository", nil) return nil } ctx.Data["repo_name"] = forkRepo.Name ctx.Data["description"] = forkRepo.Description ctx.Data["IsPrivate"] = forkRepo.IsPrivate canForkToUser := forkRepo.OwnerID != ctx.User.ID && !ctx.User.HasForkedRepo(forkRepo.ID) if err = forkRepo.GetOwner(); err != nil { ctx.ServerError("GetOwner", err) return nil } ctx.Data["ForkFrom"] = forkRepo.Owner.Name + "/" + forkRepo.Name ctx.Data["ForkFromOwnerID"] = forkRepo.Owner.ID if err := ctx.User.GetOwnedOrganizations(); err != nil { ctx.ServerError("GetOwnedOrganizations", err) return nil } var orgs []*models.User for _, org := range ctx.User.OwnedOrgs { if forkRepo.OwnerID != org.ID && !org.HasForkedRepo(forkRepo.ID) { orgs = append(orgs, org) } } var traverseParentRepo = forkRepo for { if ctx.User.ID == traverseParentRepo.OwnerID { canForkToUser = false } else { for i, org := range orgs { if org.ID == traverseParentRepo.OwnerID { orgs = append(orgs[:i], orgs[i+1:]...) break } } } if !traverseParentRepo.IsFork { break } traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return nil } } ctx.Data["CanForkToUser"] = canForkToUser ctx.Data["Orgs"] = orgs if canForkToUser { ctx.Data["ContextUser"] = ctx.User } else if len(orgs) > 0 { ctx.Data["ContextUser"] = orgs[0] } return forkRepo } // Fork render repository fork page func Fork(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("new_fork") getForkRepository(ctx) if ctx.Written() { return } ctx.HTML(200, tplFork) } // ForkPost response for forking a repository func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_fork") ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } forkRepo := getForkRepository(ctx) if ctx.Written() { return } ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { ctx.HTML(200, tplFork) return } var err error var traverseParentRepo = forkRepo for { if ctxUser.ID == traverseParentRepo.OwnerID { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form) return } repo, has := models.HasForkedRepo(ctxUser.ID, traverseParentRepo.ID) if has { ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name) return } if !traverseParentRepo.IsFork { break } traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return } } // Check ownership of organization. if ctxUser.IsOrganization() { isOwner, err := ctxUser.IsOwnedBy(ctx.User.ID) if err != nil { ctx.ServerError("IsOwnedBy", err) return } else if !isOwner { ctx.Error(403) return } } repo, err := models.ForkRepository(ctx.User, ctxUser, forkRepo, form.RepoName, form.Description) if err != nil { ctx.Data["Err_RepoName"] = true switch { case models.IsErrRepoAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form) case models.IsErrNameReserved(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplFork, &form) case models.IsErrNamePatternNotAllowed(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplFork, &form) default: ctx.ServerError("ForkPost", err) } return } log.Trace("Repository forked[%d]: %s/%s", forkRepo.ID, ctxUser.Name, repo.Name) ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name) } func checkPullInfo(ctx *context.Context) *models.Issue { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { ctx.NotFound("GetIssueByIndex", err) } else { ctx.ServerError("GetIssueByIndex", err) } return nil } ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title) ctx.Data["Issue"] = issue if !issue.IsPull { ctx.NotFound("ViewPullCommits", nil) return nil } if err = issue.PullRequest.GetHeadRepo(); err != nil { ctx.ServerError("GetHeadRepo", err) return nil } if ctx.IsSigned { // Update issue-user. if err = issue.ReadBy(ctx.User.ID); err != nil { ctx.ServerError("ReadBy", err) return nil } } return issue } func setMergeTarget(ctx *context.Context, pull *models.PullRequest) { if ctx.Repo.Owner.Name == pull.HeadUserName { ctx.Data["HeadTarget"] = pull.HeadBranch } else if pull.HeadRepo == nil { ctx.Data["HeadTarget"] = pull.HeadUserName + ":" + pull.HeadBranch } else { ctx.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch } ctx.Data["BaseTarget"] = pull.BaseBranch } // PrepareMergedViewPullInfo show meta information for a merged pull request view page func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo { pull := issue.PullRequest setMergeTarget(ctx, pull) ctx.Data["HasMerged"] = true prInfo, err := ctx.Repo.GitRepo.GetPullRequestInfo(ctx.Repo.Repository.RepoPath(), pull.MergeBase, pull.GetGitRefName()) if err != nil { if strings.Contains(err.Error(), "fatal: Not a valid object name") { ctx.Data["IsPullRequestBroken"] = true ctx.Data["BaseTarget"] = "deleted" ctx.Data["NumCommits"] = 0 ctx.Data["NumFiles"] = 0 return nil } ctx.ServerError("GetPullRequestInfo", err) return nil } ctx.Data["NumCommits"] = prInfo.Commits.Len() ctx.Data["NumFiles"] = prInfo.NumFiles return prInfo } // PrepareViewPullInfo show meta information for a pull request preview page func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo { repo := ctx.Repo.Repository pull := issue.PullRequest var err error if err = pull.GetHeadRepo(); err != nil { ctx.ServerError("GetHeadRepo", err) return nil } setMergeTarget(ctx, pull) var headGitRepo *git.Repository if pull.HeadRepo != nil { headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath()) if err != nil { ctx.ServerError("OpenRepository", err) return nil } } if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) { ctx.Data["IsPullRequestBroken"] = true ctx.Data["HeadTarget"] = "deleted" ctx.Data["NumCommits"] = 0 ctx.Data["NumFiles"] = 0 return nil } prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(repo.Owner.Name, repo.Name), pull.BaseBranch, pull.HeadBranch) if err != nil { if strings.Contains(err.Error(), "fatal: Not a valid object name") { ctx.Data["IsPullRequestBroken"] = true ctx.Data["BaseTarget"] = "deleted" ctx.Data["NumCommits"] = 0 ctx.Data["NumFiles"] = 0 return nil } ctx.ServerError("GetPullRequestInfo", err) return nil } if pull.IsWorkInProgress() { ctx.Data["IsPullWorkInProgress"] = true ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix() } ctx.Data["NumCommits"] = prInfo.Commits.Len() ctx.Data["NumFiles"] = prInfo.NumFiles return prInfo } // ViewPullCommits show commits for a pull request func ViewPullCommits(ctx *context.Context) { ctx.Data["PageIsPullList"] = true ctx.Data["PageIsPullCommits"] = true issue := checkPullInfo(ctx) if ctx.Written() { return } pull := issue.PullRequest var commits *list.List if pull.HasMerged { prInfo := PrepareMergedViewPullInfo(ctx, issue) if ctx.Written() { return } else if prInfo == nil { ctx.NotFound("ViewPullCommits", nil) return } ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name commits = prInfo.Commits } else { prInfo := PrepareViewPullInfo(ctx, issue) if ctx.Written() { return } else if prInfo == nil { ctx.NotFound("ViewPullCommits", nil) return } ctx.Data["Username"] = pull.HeadUserName ctx.Data["Reponame"] = pull.HeadRepo.Name commits = prInfo.Commits } commits = models.ValidateCommitsWithEmails(commits) commits = models.ParseCommitsWithSignature(commits) commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository) ctx.Data["Commits"] = commits ctx.Data["CommitCount"] = commits.Len() ctx.HTML(200, tplPullCommits) } // ViewPullFiles render pull request changed files list page func ViewPullFiles(ctx *context.Context) { ctx.Data["PageIsPullList"] = true ctx.Data["PageIsPullFiles"] = true issue := checkPullInfo(ctx) if ctx.Written() { return } pull := issue.PullRequest whitespaceFlags := map[string]string{ "ignore-all": "-w", "ignore-change": "-b", "ignore-eol": "--ignore-space-at-eol", "": ""} var ( diffRepoPath string startCommitID string endCommitID string gitRepo *git.Repository ) var headTarget string if pull.HasMerged { prInfo := PrepareMergedViewPullInfo(ctx, issue) if ctx.Written() { return } else if prInfo == nil { ctx.NotFound("ViewPullFiles", nil) return } diffRepoPath = ctx.Repo.GitRepo.Path gitRepo = ctx.Repo.GitRepo headCommitID, err := gitRepo.GetRefCommitID(pull.GetGitRefName()) if err != nil { ctx.ServerError("GetRefCommitID", err) return } startCommitID = prInfo.MergeBase endCommitID = headCommitID headTarget = path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name } else { prInfo := PrepareViewPullInfo(ctx, issue) if ctx.Written() { return } else if prInfo == nil { ctx.NotFound("ViewPullFiles", nil) return } headRepoPath := models.RepoPath(pull.HeadUserName, pull.HeadRepo.Name) headGitRepo, err := git.OpenRepository(headRepoPath) if err != nil { ctx.ServerError("OpenRepository", err) return } headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch) if err != nil { ctx.ServerError("GetBranchCommitID", err) return } diffRepoPath = headRepoPath startCommitID = prInfo.MergeBase endCommitID = headCommitID gitRepo = headGitRepo headTarget = path.Join(pull.HeadUserName, pull.HeadRepo.Name) ctx.Data["Username"] = pull.HeadUserName ctx.Data["Reponame"] = pull.HeadRepo.Name } diff, err := models.GetDiffRangeWithWhitespaceBehavior(diffRepoPath, startCommitID, endCommitID, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, whitespaceFlags[ctx.Data["WhitespaceBehavior"].(string)]) if err != nil { ctx.ServerError("GetDiffRangeWithWhitespaceBehavior", err) return } if err = diff.LoadComments(issue, ctx.User); err != nil { ctx.ServerError("LoadComments", err) return } ctx.Data["Diff"] = diff ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 commit, err := gitRepo.GetCommit(endCommitID) if err != nil { ctx.ServerError("GetCommit", err) return } ctx.Data["IsImageFile"] = commit.IsImageFile ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", endCommitID) ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", startCommitID) ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", endCommitID) ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireTribute"] = true if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil { ctx.ServerError("GetAssignees", err) return } ctx.Data["CurrentReview"], err = models.GetCurrentReview(ctx.User, issue) if err != nil && !models.IsErrReviewNotExist(err) { ctx.ServerError("GetCurrentReview", err) return } ctx.HTML(200, tplPullFiles) } // MergePullRequest response for merging pull request func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) { issue := checkPullInfo(ctx) if ctx.Written() { return } if issue.IsClosed { ctx.NotFound("MergePullRequest", nil) return } pr, err := models.GetPullRequestByIssueID(issue.ID) if err != nil { if models.IsErrPullRequestNotExist(err) { ctx.NotFound("GetPullRequestByIssueID", nil) } else { ctx.ServerError("GetPullRequestByIssueID", err) } return } pr.Issue = issue if !pr.CanAutoMerge() || pr.HasMerged { ctx.NotFound("MergePullRequest", nil) return } if pr.IsWorkInProgress() { ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip")) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) return } if ctx.HasError() { ctx.Flash.Error(ctx.Data["ErrorMsg"].(string)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) return } message := strings.TrimSpace(form.MergeTitleField) if len(message) == 0 { if models.MergeStyle(form.Do) == models.MergeStyleMerge { message = pr.GetDefaultMergeMessage() } if models.MergeStyle(form.Do) == models.MergeStyleSquash { message = pr.GetDefaultSquashMessage() } } form.MergeMessageField = strings.TrimSpace(form.MergeMessageField) if len(form.MergeMessageField) > 0 { message += "\n\n" + form.MergeMessageField } pr.Issue = issue pr.Issue.Repo = ctx.Repo.Repository noDeps, err := models.IssueNoDependenciesLeft(issue) if err != nil { return } if !noDeps { ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked")) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) return } if err = pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil { if models.IsErrInvalidMergeStyle(err) { ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option")) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) return } ctx.ServerError("Merge", err) return } notification.NotifyMergePullRequest(pr, ctx.User, ctx.Repo.GitRepo) log.Trace("Pull request merged: %d", pr.ID) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) } // ParseCompareInfo parse compare info between two commit for preparing pull request func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) { baseRepo := ctx.Repo.Repository // Get compared branches information // format: <base branch>...[<head repo>:]<head branch> // base<-head: master...head:feature // same repo: master...feature var ( headUser *models.User headBranch string isSameRepo bool infoPath string err error ) infoPath, err = url.QueryUnescape(ctx.Params("*")) if err != nil { ctx.NotFound("QueryUnescape", err) } infos := strings.Split(infoPath, "...") if len(infos) != 2 { log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos) ctx.NotFound("CompareAndPullRequest", nil) return nil, nil, nil, nil, "", "" } baseBranch := infos[0] ctx.Data["BaseBranch"] = baseBranch // If there is no head repository, it means pull request between same repository. headInfos := strings.Split(infos[1], ":") if len(headInfos) == 1 { isSameRepo = true headUser = ctx.Repo.Owner headBranch = headInfos[0] } else if len(headInfos) == 2 { headUser, err = models.GetUserByName(headInfos[0]) if err != nil { if models.IsErrUserNotExist(err) { ctx.NotFound("GetUserByName", nil) } else { ctx.ServerError("GetUserByName", err) } return nil, nil, nil, nil, "", "" } headBranch = headInfos[1] isSameRepo = headUser.ID == ctx.Repo.Owner.ID } else { ctx.NotFound("CompareAndPullRequest", nil) return nil, nil, nil, nil, "", "" } ctx.Data["HeadUser"] = headUser ctx.Data["HeadBranch"] = headBranch ctx.Repo.PullRequest.SameRepo = isSameRepo // Check if base branch is valid. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) { ctx.NotFound("IsBranchExist", nil) return nil, nil, nil, nil, "", "" } // Check if current user has fork of repository or in the same repository. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID) if !has && !isSameRepo { log.Trace("ParseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID) ctx.NotFound("ParseCompareInfo", nil) return nil, nil, nil, nil, "", "" } var headGitRepo *git.Repository if isSameRepo { headRepo = ctx.Repo.Repository headGitRepo = ctx.Repo.GitRepo } else { headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name)) if err != nil { ctx.ServerError("OpenRepository", err) return nil, nil, nil, nil, "", "" } } perm, err := models.GetUserRepoPermission(headRepo, ctx.User) if err != nil { ctx.ServerError("GetUserRepoPermission", err) return nil, nil, nil, nil, "", "" } if !perm.CanWrite(models.UnitTypeCode) { log.Trace("ParseCompareInfo[%d]: does not have write access or site admin", baseRepo.ID) ctx.NotFound("ParseCompareInfo", nil) return nil, nil, nil, nil, "", "" } // Check if head branch is valid. if !headGitRepo.IsBranchExist(headBranch) { ctx.NotFound("IsBranchExist", nil) return nil, nil, nil, nil, "", "" } headBranches, err := headGitRepo.GetBranches() if err != nil { ctx.ServerError("GetBranches", err) return nil, nil, nil, nil, "", "" } ctx.Data["HeadBranches"] = headBranches prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch) if err != nil { ctx.ServerError("GetPullRequestInfo", err) return nil, nil, nil, nil, "", "" } ctx.Data["BeforeCommitID"] = prInfo.MergeBase return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch } // PrepareCompareDiff render pull request preview diff page func PrepareCompareDiff( ctx *context.Context, headUser *models.User, headRepo *models.Repository, headGitRepo *git.Repository, prInfo *git.PullRequestInfo, baseBranch, headBranch string) bool { var ( repo = ctx.Repo.Repository err error ) // Get diff information. ctx.Data["CommitRepoLink"] = headRepo.Link() headCommitID, err := headGitRepo.GetBranchCommitID(headBranch) if err != nil { ctx.ServerError("GetBranchCommitID", err) return false } ctx.Data["AfterCommitID"] = headCommitID if headCommitID == prInfo.MergeBase { ctx.Data["IsNothingToCompare"] = true return true } diff, err := models.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name), prInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) if err != nil { ctx.ServerError("GetDiffRange", err) return false } ctx.Data["Diff"] = diff ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 headCommit, err := headGitRepo.GetCommit(headCommitID) if err != nil { ctx.ServerError("GetCommit", err) return false } prInfo.Commits = models.ValidateCommitsWithEmails(prInfo.Commits) prInfo.Commits = models.ParseCommitsWithSignature(prInfo.Commits) prInfo.Commits = models.ParseCommitsWithStatus(prInfo.Commits, headRepo) ctx.Data["Commits"] = prInfo.Commits ctx.Data["CommitCount"] = prInfo.Commits.Len() ctx.Data["Username"] = headUser.Name ctx.Data["Reponame"] = headRepo.Name ctx.Data["IsImageFile"] = headCommit.IsImageFile headTarget := path.Join(headUser.Name, repo.Name) ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", headCommitID) ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", prInfo.MergeBase) ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", headCommitID) return false } // CompareAndPullRequest render pull request preview page func CompareAndPullRequest(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") ctx.Data["PageIsComparePull"] = true ctx.Data["IsDiffCompare"] = true ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireTribute"] = true ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates) renderAttachmentSettings(ctx) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx) if ctx.Written() { return } pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch) if err != nil { if !models.IsErrPullRequestNotExist(err) { ctx.ServerError("GetUnmergedPullRequest", err) return } } else { ctx.Data["HasPullRequest"] = true ctx.Data["PullRequest"] = pr ctx.HTML(200, tplComparePull) return } nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch) if ctx.Written() { return } if !nothingToCompare { // Setup information for new form. RetrieveRepoMetas(ctx, ctx.Repo.Repository) if ctx.Written() { return } } ctx.HTML(200, tplComparePull) } // CompareAndPullRequestPost response for creating pull request func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) { ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") ctx.Data["PageIsComparePull"] = true ctx.Data["IsDiffCompare"] = true ctx.Data["RequireHighlightJS"] = true ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes renderAttachmentSettings(ctx) var ( repo = ctx.Repo.Repository attachments []string ) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx) if ctx.Written() { return } labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true) if ctx.Written() { return } if setting.AttachmentEnabled { attachments = form.Files } if ctx.HasError() { auth.AssignForm(form, ctx.Data) // This stage is already stop creating new pull request, so it does not matter if it has // something to compare or not. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch) if ctx.Written() { return } ctx.HTML(200, tplComparePull) return } patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch) if err != nil { ctx.ServerError("GetPatch", err) return } pullIssue := &models.Issue{ RepoID: repo.ID, Index: repo.NextIssueIndex(), Title: form.Title, PosterID: ctx.User.ID, Poster: ctx.User, MilestoneID: milestoneID, IsPull: true, Content: form.Content, } pullRequest := &models.PullRequest{ HeadRepoID: headRepo.ID, BaseRepoID: repo.ID, HeadUserName: headUser.Name, HeadBranch: headBranch, BaseBranch: baseBranch, HeadRepo: headRepo, BaseRepo: repo, MergeBase: prInfo.MergeBase, Type: models.PullRequestGitea, } // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt // instead of 500. if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch, assigneeIDs); err != nil { if models.IsErrUserDoesNotHaveAccessToRepo(err) { ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error()) return } ctx.ServerError("NewPullRequest", err) return } else if err := pullRequest.PushToBaseRepo(); err != nil { ctx.ServerError("PushToBaseRepo", err) return } notification.NotifyNewPullRequest(pullRequest) log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index)) } // TriggerTask response for a trigger task request func TriggerTask(ctx *context.Context) { pusherID := ctx.QueryInt64("pusher") branch := ctx.Query("branch") secret := ctx.Query("secret") if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 { ctx.Error(404) log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid") return } owner, repo := parseOwnerAndRepo(ctx) if ctx.Written() { return } if secret != base.EncodeMD5(owner.Salt) { ctx.Error(404) log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name) return } pusher, err := models.GetUserByID(pusherID) if err != nil { if models.IsErrUserNotExist(err) { ctx.Error(404) } else { ctx.ServerError("GetUserByID", err) } return } log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name) go models.HookQueue.Add(repo.ID) go models.AddTestPullRequestTask(pusher, repo.ID, branch, true) ctx.Status(202) } // CleanUpPullRequest responses for delete merged branch when PR has been merged func CleanUpPullRequest(ctx *context.Context) { issue := checkPullInfo(ctx) if ctx.Written() { return } pr, err := models.GetPullRequestByIssueID(issue.ID) if err != nil { if models.IsErrPullRequestNotExist(err) { ctx.NotFound("GetPullRequestByIssueID", nil) } else { ctx.ServerError("GetPullRequestByIssueID", err) } return } // Allow cleanup only for merged PR if !pr.HasMerged { ctx.NotFound("CleanUpPullRequest", nil) return } if err = pr.GetHeadRepo(); err != nil { ctx.ServerError("GetHeadRepo", err) return } else if pr.HeadRepo == nil { // Forked repository has already been deleted ctx.NotFound("CleanUpPullRequest", nil) return } else if pr.GetBaseRepo(); err != nil { ctx.ServerError("GetBaseRepo", err) return } else if pr.HeadRepo.GetOwner(); err != nil { ctx.ServerError("HeadRepo.GetOwner", err) return } perm, err := models.GetUserRepoPermission(pr.HeadRepo, ctx.User) if err != nil { ctx.ServerError("GetUserRepoPermission", err) return } if !perm.CanWrite(models.UnitTypeCode) { ctx.NotFound("CleanUpPullRequest", nil) return } fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath()) if err != nil { ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err) return } gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath()) if err != nil { ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err) return } defer func() { ctx.JSON(200, map[string]interface{}{ "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index), }) }() if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) { ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName)) return } // Check if branch is not protected if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected { if err != nil { log.Error(4, "HeadRepo.IsProtectedBranch: %v", err) } ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName)) return } // Check if branch has no new commits headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName()) if err != nil { log.Error(4, "GetRefCommitID: %v", err) ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName)) return } branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch) if err != nil { log.Error(4, "GetBranchCommitID: %v", err) ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName)) return } if headCommitID != branchCommitID { ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName)) return } if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{ Force: true, }); err != nil { log.Error(4, "DeleteBranch: %v", err) ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName)) return } if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil { // Do not fail here as branch has already been deleted log.Error(4, "DeleteBranch: %v", err) } ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName)) } // DownloadPullDiff render a pull's raw diff func DownloadPullDiff(ctx *context.Context) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { ctx.NotFound("GetIssueByIndex", err) } else { ctx.ServerError("GetIssueByIndex", err) } return } // Return not found if it's not a pull request if !issue.IsPull { ctx.NotFound("DownloadPullDiff", fmt.Errorf("Issue is not a pull request")) return } pr := issue.PullRequest if err = pr.GetBaseRepo(); err != nil { ctx.ServerError("GetBaseRepo", err) return } patch, err := pr.BaseRepo.PatchPath(pr.Index) if err != nil { ctx.ServerError("PatchPath", err) return } ctx.ServeFileContent(patch) } // DownloadPullPatch render a pull's raw patch func DownloadPullPatch(ctx *context.Context) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { ctx.NotFound("GetIssueByIndex", err) } else { ctx.ServerError("GetIssueByIndex", err) } return } // Return not found if it's not a pull request if !issue.IsPull { ctx.NotFound("DownloadPullDiff", fmt.Errorf("Issue is not a pull request")) return } pr := issue.PullRequest if err = pr.GetHeadRepo(); err != nil { ctx.ServerError("GetHeadRepo", err) return } headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath()) if err != nil { ctx.ServerError("OpenRepository", err) return } patch, err := headGitRepo.GetFormatPatch(pr.MergeBase, pr.HeadBranch) if err != nil { ctx.ServerError("GetFormatPatch", err) return } _, err = io.Copy(ctx, patch) if err != nil { ctx.ServerError("io.Copy", err) return } }
mit
ofer987/transit.tips
ttc_notices/app/models/event.rb
540
class Event < ActiveRecord::Base # google_event_id, NVARCHAR, NOT NULL # calendar_id, INTEGER, INDEX, FOREIGN KEY, NOT NULL # ttc_closure_id, INTEGER, INDEX, FOREIGN KEY, NOT NULL # name, NVARCHAR, NOT NULL # description, TEXT, NOT NULL, DEFAULT: '' belongs_to :calendar belongs_to :ttc_closure, foreign_key: 'ttc_closure_id', class_name: Ttc::Closure def google_event calendar = Calendar.find(calendar_id) poller = Poller::TtcClosures.new(calendar, Time.zone.now) poller.get_event(google_event_id) end end
mit
zoowii/readerproxy
RP/src/RP/core/HttpSession.php
354
<?php /** * Created by PhpStorm. * User: zoowii * Date: 14-3-12 * Time: 上午12:18 */ namespace RP\core; class HttpSession { private static $sessionStarted = false; public static function startSession() { if (!self::$sessionStarted) { session_start(); self::$sessionStarted = true; } } }
mit
Vitre/visy-admin-bundle
DependencyInjection/Core.php
610
<?php namespace Visy\Visy\Admin\Bundle\DependencyInjection; use Symfony\Component\HttpKernel\Event\FilterControllerEvent; class Core { protected $session; protected $container; public function __construct($container) { $this->container = $container; } public function onKernelController(FilterControllerEvent $event) { $this->sessionStart(); } public function sessionStart() { $this->session = $this->container->get('session'); $this->session->start(); } public function getSession() { return $this->session; } }
mit
ExpressenAB/exp-amqp-connection
examples/subscribe-tmpqueue.js
714
"use strict"; // Subscribe with temporary queue which will // be deleted once the amqp connection is lost. const init = require(".."); const amqpBehaviour = { url: "amqp://localhost", exchange: "my-excchange", ack: "true" }; const broker = init(amqpBehaviour); broker.on("error", (err) => console.log(`AMQP Error: ${err}`)); broker.on("connected", () => { console.log("Connected to amqp server"); }); function handleMessage(message, meta, notify) { console.log("Got message", message, "with routing key", meta.fields.routingKey); notify.ack(); } broker.subscribeTmp("some-routing-key", handleMessage); setInterval(() => { broker.publish("some-routing-key", `Hello ${new Date()}`); }, 1000);
mit
dom96/BrokenBonez
BrokenBonez/app/src/main/java/com/dragonfruitstudios/brokenbonez/Game/Scenes/MenuScene.java
1132
package com.dragonfruitstudios.brokenbonez.Game.Scenes; import android.view.MotionEvent; import com.dragonfruitstudios.brokenbonez.AssetLoading.AssetLoader; import com.dragonfruitstudios.brokenbonez.Game.GameView; import com.dragonfruitstudios.brokenbonez.GameSceneManager; import com.dragonfruitstudios.brokenbonez.Menu.MenuState; public class MenuScene extends Scene { MenuState state; public MenuScene(AssetLoader assetLoader, GameSceneManager gameSceneManager) { super(assetLoader, gameSceneManager); this.state = new MenuState(assetLoader, gameSceneManager); } public void draw(GameView view) { state.draw(view); } public void update(float lastUpdate) { state.update(lastUpdate); } public void updateSize(int w, int h) { state.updateSize(w, h); } public void onTouchEvent(MotionEvent event) { state.onTouchEvent(event); } @Override public void activate(){ if (assetLoader.getSoundByName("brokenboneztheme.ogg").isPlaying()) { assetLoader.getSoundByName("brokenboneztheme.ogg").pause(); } } }
mit
Woorank/boilerpipe
app.js
326
var path = require('path'); var config = require('config'); var server = require(path.join(__dirname, 'src/server')); var instance = server.createServer().listen(config.httpPort, function() { 'use strict'; var address = instance.address(); console.log('listening at http://%s:%s', address.address, address.port); });
mit
WeHaveCookie/EnchantedForest
Classes/Actions/CommandMove.cpp
2568
#include "stdafx.h" #include "CommandMove.h" #include "Entity/Entity.h" #include "Manager/Game/GameMgr.h" #include "Manager/Entity/EntityMgr.h" void CommandMove::init(Entity* ent, void* data) { Command::init(ent); m_motion = *static_cast<Vector2*>(data); free(data); } void CommandMove::execute() { Entity* entity = getEntity(); m_lastPosition = entity->getPosition(); if (m_motion.x < 0.0f) { EntityMgr::getSingleton()->moveEntity(MoveDirection::Left, entity); } else if (m_motion.x > 0.0f) { EntityMgr::getSingleton()->moveEntity(MoveDirection::Right, entity); } else if (m_motion.y < 0.0f) { EntityMgr::getSingleton()->moveEntity(MoveDirection::Up, entity); } else if (m_motion.y > 0.0f) { EntityMgr::getSingleton()->moveEntity(MoveDirection::Down, entity); } } void CommandMove::undo() { getEntity()->setPosition(m_lastPosition); } void CommandMoveLeft::init(Entity* ent, void* data) { float vx; if (data != NULL) { vx = -*(float*)data; } else { vx = -(float)GameMgr::getSingleton()->getMovementSpeed(); } CommandMove::init(ent, (void*)new Vector2(vx, 0.0f)); } void* CommandMoveLeft::makeCopy() { return (void*)new CommandMoveLeft(); } void CommandMoveRight::init(Entity* ent, void* data) { float vx; if (data != NULL) { vx = *(float*)data; } else { vx = (float)GameMgr::getSingleton()->getMovementSpeed(); } CommandMove::init(ent, (void*)new Vector2(vx, 0.0f)); } void* CommandMoveRight::makeCopy() { return (void*)new CommandMoveRight(); } void CommandMoveUp::init(Entity* ent, void* data) { float vy; if (data != NULL) { vy = -*(float*)data; } else { vy = -(float)GameMgr::getSingleton()->getMovementSpeed(); } CommandMove::init(ent, (void*)new Vector2(0.0f, vy)); } void* CommandMoveUp::makeCopy() { return (void*)new CommandMoveUp(); } void CommandMoveDown::init(Entity* ent, void* data) { float vy; if (data != NULL) { vy = *(float*)data; } else { vy = (float)GameMgr::getSingleton()->getMovementSpeed(); } CommandMove::init(ent, (void*)new Vector2(0.0f, vy)); } void* CommandMoveDown::makeCopy() { return (void*)new CommandMoveDown(); } void CommandMoveXAxis::init(Entity* ent, void* data) { CommandMove::init(ent, (void*)new Vector2(*static_cast<float*>(data), 0.0f)); } void* CommandMoveXAxis::makeCopy() { return (void*)new CommandMoveXAxis(); } void CommandMoveYAxis::init(Entity* ent, void* data) { CommandMove::init(ent, (void*)new Vector2(0.0f, *static_cast<float*>(data))); } void* CommandMoveYAxis::makeCopy() { return (void*)new CommandMoveYAxis(); }
mit
zegl/goriak
keys_in_index_test.go
1606
package goriak import ( "testing" ) func TestKeysInIndex(t *testing.T) { type tt struct { Val string } for _, key := range []string{"A", "B", "C", "D", "E", "F", "G"} { _, err := Bucket("json", "default").SetJSON(tt{Val: key}).AddToIndex("indextest_bin", "AAAA").Key(key).Run(con()) if err != nil { t.Error(err) } } fetches := 0 keyCount := 0 cb := func(r SecondaryIndexQueryResult) { if !r.IsComplete { keyCount++ } } var cont []byte for { res, err := Bucket("json", "default"). KeysInIndex("indextest_bin", "AAAA", cb). Limit(3). IndexContinuation(cont). Run(con()) if err != nil { t.Error(err) } fetches++ if len(res.Continuation) == 0 { break } cont = res.Continuation } if fetches != 3 { t.Error("Did not do 3 fetches") } if keyCount != 7 { t.Error("did not find 7 keys") } } func TestKeysInIndexRange(t *testing.T) { type tt struct { Val string } for _, indexVal := range []string{"a", "b", "c", "d", "e"} { for _, key := range []string{"A", "B", "C", "D", "E", "F", "G"} { _, err := Bucket("json", "default").SetJSON(tt{Val: key}).AddToIndex("rangetest_bin", indexVal).Key(indexVal + key).Run(con()) if err != nil { t.Error(err) } } } keyCount := 0 cb := func(r SecondaryIndexQueryResult) { //t.Logf("%+v", r) if !r.IsComplete { keyCount++ } } res, err := Bucket("json", "default"). KeysInIndexRange("rangetest_bin", "b", "d", cb). Limit(1000). Run(con()) if err != nil { t.Error(err) } if keyCount != 21 { t.Error("unexpected count") } t.Logf("%+v", res) }
mit
mysterycommand/Bearshirt
Assets/Anima2D/Scripts/Editor/TimeLine/ZoomableArea.cs
24158
using System; using UnityEngine; namespace Anima2D { [Serializable] public class ZoomableArea { [Serializable] public class Styles { public GUIStyle horizontalScrollbar; public GUIStyle horizontalMinMaxScrollbarThumb; public GUIStyle horizontalScrollbarLeftButton; public GUIStyle horizontalScrollbarRightButton; public GUIStyle verticalScrollbar; public GUIStyle verticalMinMaxScrollbarThumb; public GUIStyle verticalScrollbarUpButton; public GUIStyle verticalScrollbarDownButton; public float sliderWidth; public float visualSliderWidth; public Styles(bool minimalGUI) { if (minimalGUI) { this.visualSliderWidth = 0f; this.sliderWidth = 15f; } else { this.visualSliderWidth = 15f; this.sliderWidth = 15f; } } public void InitGUIStyles(bool minimalGUI) { if (minimalGUI) { this.horizontalMinMaxScrollbarThumb = "MiniMinMaxSliderHorizontal"; this.horizontalScrollbarLeftButton = GUIStyle.none; this.horizontalScrollbarRightButton = GUIStyle.none; this.horizontalScrollbar = GUIStyle.none; this.verticalMinMaxScrollbarThumb = "MiniMinMaxSlidervertical"; this.verticalScrollbarUpButton = GUIStyle.none; this.verticalScrollbarDownButton = GUIStyle.none; this.verticalScrollbar = GUIStyle.none; } else { this.horizontalMinMaxScrollbarThumb = "horizontalMinMaxScrollbarThumb"; this.horizontalScrollbarLeftButton = "horizontalScrollbarLeftbutton"; this.horizontalScrollbarRightButton = "horizontalScrollbarRightbutton"; this.horizontalScrollbar = GUI.skin.horizontalScrollbar; this.verticalMinMaxScrollbarThumb = "verticalMinMaxScrollbarThumb"; this.verticalScrollbarUpButton = "verticalScrollbarUpbutton"; this.verticalScrollbarDownButton = "verticalScrollbarDownbutton"; this.verticalScrollbar = GUI.skin.verticalScrollbar; } } } private static Vector2 m_MouseDownPosition = new Vector2(-1000000f, -1000000f); private static int zoomableAreaHash = "ZoomableArea".GetHashCode(); private bool m_HRangeLocked; private bool m_VRangeLocked; private float m_HBaseRangeMin; private float m_HBaseRangeMax = 1f; private float m_VBaseRangeMin; private float m_VBaseRangeMax = 1f; private bool m_HAllowExceedBaseRangeMin = true; private bool m_HAllowExceedBaseRangeMax = true; private bool m_VAllowExceedBaseRangeMin = true; private bool m_VAllowExceedBaseRangeMax = true; private float m_HScaleMin = 0.001f; private float m_HScaleMax = 100000f; private float m_VScaleMin = 0.001f; private float m_VScaleMax = 100000f; private bool m_ScaleWithWindow; private bool m_HSlider = true; private bool m_VSlider = true; public bool m_UniformScale; private bool m_IgnoreScrollWheelUntilClicked; private Rect m_DrawArea = new Rect(0f, 0f, 100f, 100f); internal Vector2 m_Scale = new Vector2(1f, -1f); internal Vector2 m_Translation = new Vector2(0f, 0f); private float m_MarginLeft; private float m_MarginRight; private float m_MarginTop; private float m_MarginBottom; private Rect m_LastShownAreaInsideMargins = new Rect(0f, 0f, 100f, 100f); private int verticalScrollbarID; private int horizontalScrollbarID; private bool m_MinimalGUI; private ZoomableArea.Styles styles; public bool hRangeLocked { get { return this.m_HRangeLocked; } set { this.m_HRangeLocked = value; } } public bool vRangeLocked { get { return this.m_VRangeLocked; } set { this.m_VRangeLocked = value; } } public float hBaseRangeMin { get { return this.m_HBaseRangeMin; } set { this.m_HBaseRangeMin = value; } } public float hBaseRangeMax { get { return this.m_HBaseRangeMax; } set { this.m_HBaseRangeMax = value; } } public float vBaseRangeMin { get { return this.m_VBaseRangeMin; } set { this.m_VBaseRangeMin = value; } } public float vBaseRangeMax { get { return this.m_VBaseRangeMax; } set { this.m_VBaseRangeMax = value; } } public bool hAllowExceedBaseRangeMin { get { return this.m_HAllowExceedBaseRangeMin; } set { this.m_HAllowExceedBaseRangeMin = value; } } public bool hAllowExceedBaseRangeMax { get { return this.m_HAllowExceedBaseRangeMax; } set { this.m_HAllowExceedBaseRangeMax = value; } } public bool vAllowExceedBaseRangeMin { get { return this.m_VAllowExceedBaseRangeMin; } set { this.m_VAllowExceedBaseRangeMin = value; } } public bool vAllowExceedBaseRangeMax { get { return this.m_VAllowExceedBaseRangeMax; } set { this.m_VAllowExceedBaseRangeMax = value; } } public float hRangeMin { get { return (!this.hAllowExceedBaseRangeMin) ? this.hBaseRangeMin : float.NegativeInfinity; } set { this.SetAllowExceed(ref this.m_HBaseRangeMin, ref this.m_HAllowExceedBaseRangeMin, value); } } public float hRangeMax { get { return (!this.hAllowExceedBaseRangeMax) ? this.hBaseRangeMax : float.PositiveInfinity; } set { this.SetAllowExceed(ref this.m_HBaseRangeMax, ref this.m_HAllowExceedBaseRangeMax, value); } } public float vRangeMin { get { return (!this.vAllowExceedBaseRangeMin) ? this.vBaseRangeMin : float.NegativeInfinity; } set { this.SetAllowExceed(ref this.m_VBaseRangeMin, ref this.m_VAllowExceedBaseRangeMin, value); } } public float vRangeMax { get { return (!this.vAllowExceedBaseRangeMax) ? this.vBaseRangeMax : float.PositiveInfinity; } set { this.SetAllowExceed(ref this.m_VBaseRangeMax, ref this.m_VAllowExceedBaseRangeMax, value); } } public bool scaleWithWindow { get { return this.m_ScaleWithWindow; } set { this.m_ScaleWithWindow = value; } } public bool hSlider { get { return this.m_HSlider; } set { Rect rect = this.rect; this.m_HSlider = value; this.rect = rect; } } public bool vSlider { get { return this.m_VSlider; } set { Rect rect = this.rect; this.m_VSlider = value; this.rect = rect; } } public bool uniformScale { get { return this.m_UniformScale; } set { this.m_UniformScale = value; } } public bool ignoreScrollWheelUntilClicked { get { return this.m_IgnoreScrollWheelUntilClicked; } set { this.m_IgnoreScrollWheelUntilClicked = value; } } public Vector2 scale { get { return this.m_Scale; } } public float margin { set { this.m_MarginBottom = value; this.m_MarginTop = value; this.m_MarginRight = value; this.m_MarginLeft = value; } } public float leftmargin { get { return this.m_MarginLeft; } set { this.m_MarginLeft = value; } } public float rightmargin { get { return this.m_MarginRight; } set { this.m_MarginRight = value; } } public float topmargin { get { return this.m_MarginTop; } set { this.m_MarginTop = value; } } public float bottommargin { get { return this.m_MarginBottom; } set { this.m_MarginBottom = value; } } public Rect rect { get { return new Rect(this.drawRect.x, this.drawRect.y, this.drawRect.width + ((!this.m_VSlider) ? 0f : this.styles.visualSliderWidth), this.drawRect.height + ((!this.m_HSlider) ? 0f : this.styles.visualSliderWidth)); } set { Rect rect = new Rect(value.x, value.y, value.width - ((!this.m_VSlider) ? 0f : this.styles.visualSliderWidth), value.height - ((!this.m_HSlider) ? 0f : this.styles.visualSliderWidth)); if (rect != this.m_DrawArea) { if (this.m_ScaleWithWindow) { this.m_DrawArea = rect; this.shownAreaInsideMargins = this.m_LastShownAreaInsideMargins; } else { this.m_Translation += new Vector2((rect.width - this.m_DrawArea.width) / 2f, (rect.height - this.m_DrawArea.height) / 2f); this.m_DrawArea = rect; } } this.EnforceScaleAndRange(); } } public Rect drawRect { get { return this.m_DrawArea; } } public Rect shownArea { get { return new Rect(-this.m_Translation.x / this.m_Scale.x, -(this.m_Translation.y - this.drawRect.height) / this.m_Scale.y, this.drawRect.width / this.m_Scale.x, this.drawRect.height / -this.m_Scale.y); } set { this.m_Scale.x = this.drawRect.width / value.width; this.m_Scale.y = -this.drawRect.height / value.height; this.m_Translation.x = -value.x * this.m_Scale.x; this.m_Translation.y = this.drawRect.height - value.y * this.m_Scale.y; this.EnforceScaleAndRange(); } } public Rect shownAreaInsideMargins { get { return this.shownAreaInsideMarginsInternal; } set { this.shownAreaInsideMarginsInternal = value; this.EnforceScaleAndRange(); } } private Rect shownAreaInsideMarginsInternal { get { float num = this.leftmargin / this.m_Scale.x; float num2 = this.rightmargin / this.m_Scale.x; float num3 = this.topmargin / this.m_Scale.y; float num4 = this.bottommargin / this.m_Scale.y; Rect shownArea = this.shownArea; shownArea.x += num; shownArea.y -= num3; shownArea.width -= num + num2; shownArea.height += num3 + num4; return shownArea; } set { this.m_Scale.x = (this.drawRect.width - this.leftmargin - this.rightmargin) / value.width; this.m_Scale.y = -(this.drawRect.height - this.topmargin - this.bottommargin) / value.height; this.m_Translation.x = -value.x * this.m_Scale.x + this.leftmargin; this.m_Translation.y = this.drawRect.height - value.y * this.m_Scale.y - this.topmargin; } } public virtual Bounds drawingBounds { get { return new Bounds(new Vector3((this.hBaseRangeMin + this.hBaseRangeMax) * 0.5f, (this.vBaseRangeMin + this.vBaseRangeMax) * 0.5f, 0f), new Vector3(this.hBaseRangeMax - this.hBaseRangeMin, this.vBaseRangeMax - this.vBaseRangeMin, 1f)); } } public Matrix4x4 drawingToViewMatrix { get { return Matrix4x4.TRS(this.m_Translation, Quaternion.identity, new Vector3(this.m_Scale.x, this.m_Scale.y, 1f)); } } public Vector2 mousePositionInDrawing { get { return this.ViewToDrawingTransformPoint(Event.current.mousePosition); } } public ZoomableArea() { this.m_MinimalGUI = false; this.styles = new ZoomableArea.Styles(false); } public ZoomableArea(bool minimalGUI) { this.m_MinimalGUI = minimalGUI; this.styles = new ZoomableArea.Styles(minimalGUI); } private void SetAllowExceed(ref float rangeEnd, ref bool allowExceed, float value) { if (value == float.NegativeInfinity || value == float.PositiveInfinity) { rangeEnd = (float)((value != float.NegativeInfinity) ? 1 : 0); allowExceed = true; } else { rangeEnd = value; allowExceed = false; } } internal void SetDrawRectHack(Rect r, bool scrollbars) { this.m_DrawArea = r; this.m_VSlider = scrollbars; this.m_HSlider = scrollbars; } public void OnEnable() { this.styles = new ZoomableArea.Styles(this.m_MinimalGUI); } public void SetShownHRangeInsideMargins(float min, float max) { this.m_Scale.x = (this.drawRect.width - this.leftmargin - this.rightmargin) / (max - min); this.m_Translation.x = -min * this.m_Scale.x + this.leftmargin; this.EnforceScaleAndRange(); } public void SetShownHRange(float min, float max) { this.m_Scale.x = this.drawRect.width / (max - min); this.m_Translation.x = -min * this.m_Scale.x; this.EnforceScaleAndRange(); } public void SetShownVRangeInsideMargins(float min, float max) { this.m_Scale.y = -(this.drawRect.height - this.topmargin - this.bottommargin) / (max - min); this.m_Translation.y = this.drawRect.height - min * this.m_Scale.y - this.topmargin; this.EnforceScaleAndRange(); } public void SetShownVRange(float min, float max) { this.m_Scale.y = -this.drawRect.height / (max - min); this.m_Translation.y = this.drawRect.height - min * this.m_Scale.y; this.EnforceScaleAndRange(); } public Vector2 DrawingToViewTransformPoint(Vector2 lhs) { return new Vector2(lhs.x * this.m_Scale.x + this.m_Translation.x, lhs.y * this.m_Scale.y + this.m_Translation.y); } public Vector3 DrawingToViewTransformPoint(Vector3 lhs) { return new Vector3(lhs.x * this.m_Scale.x + this.m_Translation.x, lhs.y * this.m_Scale.y + this.m_Translation.y, 0f); } public Vector2 ViewToDrawingTransformPoint(Vector2 lhs) { return new Vector2((lhs.x - this.m_Translation.x) / this.m_Scale.x, (lhs.y - this.m_Translation.y) / this.m_Scale.y); } public Vector3 ViewToDrawingTransformPoint(Vector3 lhs) { return new Vector3((lhs.x - this.m_Translation.x) / this.m_Scale.x, (lhs.y - this.m_Translation.y) / this.m_Scale.y, 0f); } public Vector2 DrawingToViewTransformVector(Vector2 lhs) { return new Vector2(lhs.x * this.m_Scale.x, lhs.y * this.m_Scale.y); } public Vector3 DrawingToViewTransformVector(Vector3 lhs) { return new Vector3(lhs.x * this.m_Scale.x, lhs.y * this.m_Scale.y, 0f); } public Vector2 ViewToDrawingTransformVector(Vector2 lhs) { return new Vector2(lhs.x / this.m_Scale.x, lhs.y / this.m_Scale.y); } public Vector3 ViewToDrawingTransformVector(Vector3 lhs) { return new Vector3(lhs.x / this.m_Scale.x, lhs.y / this.m_Scale.y, 0f); } public Vector2 NormalizeInViewSpace(Vector2 vec) { vec = Vector2.Scale(vec, this.m_Scale); vec /= vec.magnitude; return Vector2.Scale(vec, new Vector2(1f / this.m_Scale.x, 1f / this.m_Scale.y)); } private bool IsZoomEvent() { return Event.current.button == 1 && Event.current.alt; } private bool IsPanEvent() { return (Event.current.button == 0 && Event.current.alt) || (Event.current.button == 2 && !Event.current.command); } public void BeginViewGUI() { if (this.styles.horizontalScrollbar == null) { this.styles.InitGUIStyles(this.m_MinimalGUI); } this.HandleZoomAndPanEvents(this.m_DrawArea); this.horizontalScrollbarID = GUIUtility.GetControlID(EditorGUIExtra.s_MinMaxSliderHash, FocusType.Passive); this.verticalScrollbarID = GUIUtility.GetControlID(EditorGUIExtra.s_MinMaxSliderHash, FocusType.Passive); if (!this.m_MinimalGUI || Event.current.type != EventType.Repaint) { this.SliderGUI(); } } public void HandleZoomAndPanEvents(Rect area) { GUILayout.BeginArea(area); area.x = 0f; area.y = 0f; int controlID = GUIUtility.GetControlID(ZoomableArea.zoomableAreaHash, FocusType.Passive, area); switch (Event.current.GetTypeForControl(controlID)) { case EventType.MouseDown: if (area.Contains(Event.current.mousePosition)) { GUIUtility.keyboardControl = controlID; if (this.IsZoomEvent() || this.IsPanEvent()) { GUIUtility.hotControl = controlID; ZoomableArea.m_MouseDownPosition = this.mousePositionInDrawing; Event.current.Use(); } } break; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; ZoomableArea.m_MouseDownPosition = new Vector2(-1000000f, -1000000f); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { if (this.IsZoomEvent()) { this.Zoom(ZoomableArea.m_MouseDownPosition, false); Event.current.Use(); } else { if (this.IsPanEvent()) { this.Pan(); Event.current.Use(); } } } break; case EventType.ScrollWheel: if (area.Contains(Event.current.mousePosition)) { if (!this.m_IgnoreScrollWheelUntilClicked || GUIUtility.keyboardControl == controlID) { this.Zoom(this.mousePositionInDrawing, true); Event.current.Use(); } } break; } GUILayout.EndArea(); } public void EndViewGUI() { if (this.m_MinimalGUI && Event.current.type == EventType.Repaint) { this.SliderGUI(); } } private void SliderGUI() { if (!this.m_HSlider && !this.m_VSlider) { return; } Bounds drawingBounds = this.drawingBounds; Rect shownAreaInsideMargins = this.shownAreaInsideMargins; float num = this.styles.sliderWidth - this.styles.visualSliderWidth; float num2 = (!this.vSlider || !this.hSlider) ? 0f : num; Vector2 a = this.m_Scale; if (this.m_HSlider) { Rect position = new Rect(this.drawRect.x + 1f, this.drawRect.yMax - num, this.drawRect.width - num2, this.styles.sliderWidth); float width = shownAreaInsideMargins.width; float xMin = shownAreaInsideMargins.xMin; EditorGUIExtra.MinMaxScroller(position, this.horizontalScrollbarID, ref xMin, ref width, drawingBounds.min.x, drawingBounds.max.x, float.NegativeInfinity, float.PositiveInfinity, this.styles.horizontalScrollbar, this.styles.horizontalMinMaxScrollbarThumb, this.styles.horizontalScrollbarLeftButton, this.styles.horizontalScrollbarRightButton, true); float num3 = xMin; float num4 = xMin + width; if (num3 > shownAreaInsideMargins.xMin) { num3 = Mathf.Min(num3, num4 - this.m_HScaleMin); } if (num4 < shownAreaInsideMargins.xMax) { num4 = Mathf.Max(num4, num3 + this.m_HScaleMin); } this.SetShownHRangeInsideMargins(num3, num4); } if (this.m_VSlider) { Rect position2 = new Rect(this.drawRect.xMax - num, this.drawRect.y, this.styles.sliderWidth, this.drawRect.height - num2); float height = shownAreaInsideMargins.height; float num5 = -shownAreaInsideMargins.yMax; EditorGUIExtra.MinMaxScroller(position2, this.verticalScrollbarID, ref num5, ref height, -drawingBounds.max.y, -drawingBounds.min.y, float.NegativeInfinity, float.PositiveInfinity, this.styles.verticalScrollbar, this.styles.verticalMinMaxScrollbarThumb, this.styles.verticalScrollbarUpButton, this.styles.verticalScrollbarDownButton, false); float num3 = -(num5 + height); float num4 = -num5; if (num3 > shownAreaInsideMargins.yMin) { num3 = Mathf.Min(num3, num4 - this.m_VScaleMin); } if (num4 < shownAreaInsideMargins.yMax) { num4 = Mathf.Max(num4, num3 + this.m_VScaleMin); } this.SetShownVRangeInsideMargins(num3, num4); } if (this.uniformScale) { float num6 = this.drawRect.width / this.drawRect.height; a -= this.m_Scale; Vector2 b = new Vector2(-a.y * num6, -a.x / num6); this.m_Scale -= b; this.m_Translation.x = this.m_Translation.x - a.y / 2f; this.m_Translation.y = this.m_Translation.y - a.x / 2f; this.EnforceScaleAndRange(); } } private void Pan() { if (!this.m_HRangeLocked) { this.m_Translation.x = this.m_Translation.x + Event.current.delta.x; } if (!this.m_VRangeLocked) { this.m_Translation.y = this.m_Translation.y + Event.current.delta.y; } this.EnforceScaleAndRange(); } private void Zoom(Vector2 zoomAround, bool scrollwhell) { float num = Event.current.delta.x + Event.current.delta.y; if (scrollwhell) { num = -num; } float num2 = Mathf.Max(0.01f, 1f + num * 0.01f); if (!this.m_HRangeLocked) { this.m_Translation.x = this.m_Translation.x - zoomAround.x * (num2 - 1f) * this.m_Scale.x; this.m_Scale.x = this.m_Scale.x * num2; } if (!this.m_VRangeLocked) { this.m_Translation.y = this.m_Translation.y - zoomAround.y * (num2 - 1f) * this.m_Scale.y; this.m_Scale.y = this.m_Scale.y * num2; } this.EnforceScaleAndRange(); } private void EnforceScaleAndRange() { float hScaleMin = this.m_HScaleMin; float vScaleMin = this.m_VScaleMin; float value = this.m_HScaleMax; float value2 = this.m_VScaleMax; if (this.hRangeMax != float.PositiveInfinity && this.hRangeMin != float.NegativeInfinity) { value = Mathf.Min(this.m_HScaleMax, this.hRangeMax - this.hRangeMin); } if (this.vRangeMax != float.PositiveInfinity && this.vRangeMin != float.NegativeInfinity) { value2 = Mathf.Min(this.m_VScaleMax, this.vRangeMax - this.vRangeMin); } Rect lastShownAreaInsideMargins = this.m_LastShownAreaInsideMargins; Rect shownAreaInsideMargins = this.shownAreaInsideMargins; if (shownAreaInsideMargins == lastShownAreaInsideMargins) { return; } float num = 1E-05f; if (shownAreaInsideMargins.width < lastShownAreaInsideMargins.width - num) { float t = Mathf.InverseLerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, hScaleMin); shownAreaInsideMargins = new Rect(Mathf.Lerp(lastShownAreaInsideMargins.x, shownAreaInsideMargins.x, t), shownAreaInsideMargins.y, Mathf.Lerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, t), shownAreaInsideMargins.height); } if (shownAreaInsideMargins.height < lastShownAreaInsideMargins.height - num) { float t2 = Mathf.InverseLerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, vScaleMin); shownAreaInsideMargins = new Rect(shownAreaInsideMargins.x, Mathf.Lerp(lastShownAreaInsideMargins.y, shownAreaInsideMargins.y, t2), shownAreaInsideMargins.width, Mathf.Lerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, t2)); } if (shownAreaInsideMargins.width > lastShownAreaInsideMargins.width + num) { float t3 = Mathf.InverseLerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, value); shownAreaInsideMargins = new Rect(Mathf.Lerp(lastShownAreaInsideMargins.x, shownAreaInsideMargins.x, t3), shownAreaInsideMargins.y, Mathf.Lerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, t3), shownAreaInsideMargins.height); } if (shownAreaInsideMargins.height > lastShownAreaInsideMargins.height + num) { float t4 = Mathf.InverseLerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, value2); shownAreaInsideMargins = new Rect(shownAreaInsideMargins.x, Mathf.Lerp(lastShownAreaInsideMargins.y, shownAreaInsideMargins.y, t4), shownAreaInsideMargins.width, Mathf.Lerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, t4)); } if (shownAreaInsideMargins.xMin < this.hRangeMin) { shownAreaInsideMargins.x = this.hRangeMin; } if (shownAreaInsideMargins.xMax > this.hRangeMax) { shownAreaInsideMargins.x = this.hRangeMax - shownAreaInsideMargins.width; } if (shownAreaInsideMargins.yMin < this.vRangeMin) { shownAreaInsideMargins.y = this.vRangeMin; } if (shownAreaInsideMargins.yMax > this.vRangeMax) { shownAreaInsideMargins.y = this.vRangeMax - shownAreaInsideMargins.height; } this.shownAreaInsideMarginsInternal = shownAreaInsideMargins; this.m_LastShownAreaInsideMargins = shownAreaInsideMargins; } public float PixelToTime(float pixelX, Rect rect) { return (pixelX - rect.x) * this.shownArea.width / rect.width + this.shownArea.x; } public float TimeToPixel(float time, Rect rect) { return (time - this.shownArea.x) / this.shownArea.width * rect.width + rect.x; } public float PixelDeltaToTime(Rect rect) { return this.shownArea.width / rect.width; } } }
mit
selvasingh/azure-sdk-for-java
sdk/appservice/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/appservice/v2019_08_01/implementation/ServerfarmHybridConnectionImpl.java
2946
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice.v2019_08_01.implementation; import com.microsoft.azure.management.appservice.v2019_08_01.ServerfarmHybridConnection; import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; import rx.Observable; class ServerfarmHybridConnectionImpl extends IndexableRefreshableWrapperImpl<ServerfarmHybridConnection, HybridConnectionInner> implements ServerfarmHybridConnection { private final AppServiceManager manager; private String resourceGroupName; private String name; private String namespaceName; private String relayName; ServerfarmHybridConnectionImpl(HybridConnectionInner inner, AppServiceManager manager) { super(null, inner); this.manager = manager; // set resource ancestor and positional variables this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); this.name = IdParsingUtils.getValueFromIdByName(inner.id(), "serverfarms"); this.namespaceName = IdParsingUtils.getValueFromIdByName(inner.id(), "hybridConnectionNamespaces"); this.relayName = IdParsingUtils.getValueFromIdByName(inner.id(), "relays"); } @Override public AppServiceManager manager() { return this.manager; } @Override protected Observable<HybridConnectionInner> getInnerAsync() { AppServicePlansInner client = this.manager().inner().appServicePlans(); return client.getHybridConnectionAsync(this.resourceGroupName, this.name, this.namespaceName, this.relayName); } @Override public String hostname() { return this.inner().hostname(); } @Override public String id() { return this.inner().id(); } @Override public String kind() { return this.inner().kind(); } @Override public String name() { return this.inner().name(); } @Override public Integer port() { return this.inner().port(); } @Override public String relayArmUri() { return this.inner().relayArmUri(); } @Override public String relayName() { return this.inner().relayName(); } @Override public String sendKeyName() { return this.inner().sendKeyName(); } @Override public String sendKeyValue() { return this.inner().sendKeyValue(); } @Override public String serviceBusNamespace() { return this.inner().serviceBusNamespace(); } @Override public String serviceBusSuffix() { return this.inner().serviceBusSuffix(); } @Override public String type() { return this.inner().type(); } }
mit
DSchana/Artemis-Engine
Artemis.Tests/Animation/AAMLTest.cs
2311
using Artemis.Engine; using Artemis.Engine.Graphics.Animation; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Artemis.Tests.Animation { [TestClass] public class AAMLFileReaderTests { [TestMethod] public void AAMLLoadTileTest() { ArtemisEngine.Setup("game.constants", Setup); ArtemisEngine.Begin(Initialize); AAMLFileReader fileReader = new AAMLFileReader("../../Animation/LoadTileAAMLTestFile.aaml"); try { fileReader.Read(); Assert.AreEqual(1, fileReader.Map.SpriteSheet.LoadedTextures.Count); } catch (Exception e) { Assert.Fail(e.Message + "\nAt:\n" + e.StackTrace); } } [TestMethod] public void AAMLLoadDirectoryTest() { ArtemisEngine.Setup("game.constants", Setup); ArtemisEngine.Begin(Initialize); AAMLFileReader fileReader = new AAMLFileReader("../../Animation/LoadDirectoryAAMLTestFile.aaml"); try { fileReader.Read(); Assert.AreEqual(20, fileReader.Map.SpriteSheet.LoadedTextures.Count); } catch(Exception e) { Assert.Fail(e.Message + "\nAt:\n" + e.StackTrace); } } [TestMethod] public void AAMLLoadDirectoryFullTest() { ArtemisEngine.Setup("game.constants", Setup); ArtemisEngine.Begin(Initialize); AAMLFileReader fileReader = new AAMLFileReader("../../Animation/LoadDirectoryFullAAMLTestFile.aaml"); try { fileReader.Read(); } catch (Exception e) { Assert.Fail(e.Message + "\nAt:\n" + e.StackTrace); } } static void Setup() { } static void Initialize() { ArtemisEngine.RegisterMultiforms(new MultiformTemplate()); ArtemisEngine.StartWith("MultiformTemplate"); } } }
mit
pymalch/news
src/app/card/card.ts
164
export class Card { id: number; category: number; agencies: any[]; keywords: string; type: number; theme: number; refresh_time: number }
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_89/safe/CWE_89__unserialize__func_floatval__select_from_where-interpretation.php
1542
<?php /* Safe sample input : Get a serialize string in POST and unserialize it sanitize : use of floatval construction : interpretation */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $string = $_POST['UserData'] ; $tainted = unserialize($string); $tainted = floatval($tainted); $query = "SELECT * FROM student where id= $tainted "; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
mit
bacta/pre-cu
src/main/java/com/ocdsoft/bacta/swg/server/object/login/PopulationStatus.java
661
package com.ocdsoft.bacta.swg.server.object.login; import com.ocdsoft.bacta.engine.buffer.ByteBufferWritable; import lombok.Getter; import java.nio.ByteBuffer; /** * Created by Kyle on 8/15/2014. */ public enum PopulationStatus implements ByteBufferWritable { PS_LOWEST(0x0), PS_very_light(0x0), PS_light(0x1), PS_medium(0x2), PS_heavy(0x3), PS_very_heavy(0x4), PS_extremely_heavy(0x5), PS_full(0x6), PS_HIGHEST(0x6); @Getter int value; PopulationStatus(int value) { this.value = value; } @Override public void writeToBuffer(ByteBuffer buffer) { buffer.putInt(value); } }
mit
alanszlosek/voxeling
src/lib/object-pool.js
1838
var pool = {}; // Don't really need to keep track of those I've allocated, do I? var bytes = 0; var mallocs = 0; var news = 0; var frees = 0; var create = function(type, size) { news++; switch (type) { case 'float32': return new Float32Array(size); case 'uint8': return new Uint8Array(size); // Generic array of 3 elements case 'array': return new Array(size); } throw new Exception('Unexpected type: ' + type); }; var getSize = function(type, o) { switch (type) { case 'float32': case 'uint8': case 'array': return o.length; } // unknown return 0; }; module.exports = { malloc: function(type, size) { var current; var o; mallocs++; if (type in pool) { current = pool[type]; // Any types of this size available? if (size in current && current[size].length > 0) { o = current[size].pop(); bytes -= getSize(type, o); return o; } else { current[size] = []; } } else { current = pool[type] = {}; current[size] = []; } return create(type, size); }, free: function(type, o) { var size = getSize(type, o); pool[type][size].push(o); bytes += size; frees++; }, // Return number of bytes in the pool. If it's high, perhaps we want to free these items manually bytesAvailable: function() { return bytes; }, stats: function() { return 'mallocs: ' + mallocs + ' news: ' + news + ' frees: ' + frees + ' bytesInPool: ' + bytes; }, // Give it up to the garbage collector clear: function() { bytes = 0; pool = {}; } };
mit
azu/ecmascript-version-detector
data/LogicalExpression/index.js
134
module.exports = { "selector": "//LogicalExpression", "version": "3", "en": { "name": "LogicalExpression" } };
mit
sharat543/sharat543.github.io
decibelVision/bower_components/prism/components/prism-d.js
2705
Prism.languages.d = Prism.languages.extend('clike', { 'string': [ // r"", x"" /\b[rx]"(\\.|[^\\"])*"[cwd]?/, // q"[]", q"()", q"<>", q"{}" /\bq"(?:\[[\s\S]*?\]|\([\s\S]*?\)|<[\s\S]*?>|\{[\s\S]*?\})"/, // q"IDENT // ... // IDENT" /\bq"([_a-zA-Z][_a-zA-Z\d]*)(?:\r?\n|\r)[\s\S]*?(?:\r?\n|\r)\1"/, // q"//", q"||", etc. /\bq"(.)[\s\S]*?\1"/, // Characters /'(?:\\'|\\?[^']+)'/, /(["`])(\\.|(?!\1)[^\\])*\1[cwd]?/ ], 'number': [ // The lookbehind and the negative look-ahead try to prevent bad highlighting of the .. operator // Hexadecimal numbers must be handled separately to avoid problems with exponent "e" /\b0x\.?[a-f\d_]+(?:(?!\.\.)\.[a-f\d_]*)?(?:p[+-]?[a-f\d_]+)?[ulfi]*/i, { pattern: /((?:\.\.)?)(?:\b0b\.?|\b|\.)\d[\d_]*(?:(?!\.\.)\.[\d_]*)?(?:e[+-]?\d[\d_]*)?[ulfi]*/i, lookbehind: true } ], // In order: $, keywords and special tokens, globally defined symbols 'keyword': /\$|\b(?:abstract|alias|align|asm|assert|auto|body|bool|break|byte|case|cast|catch|cdouble|cent|cfloat|char|class|const|continue|creal|dchar|debug|default|delegate|delete|deprecated|do|double|else|enum|export|extern|false|final|finally|float|for|foreach|foreach_reverse|function|goto|idouble|if|ifloat|immutable|import|inout|int|interface|invariant|ireal|lazy|long|macro|mixin|module|new|nothrow|null|out|override|package|pragma|private|protected|public|pure|real|ref|return|scope|shared|short|static|struct|super|switch|synchronized|template|this|throw|true|try|typedef|typeid|typeof|ubyte|ucent|uint|ulong|union|unittest|ushort|version|void|volatile|wchar|while|with|__(?:(?:FILE|MODULE|LINE|FUNCTION|PRETTY_FUNCTION|DATE|EOF|TIME|TIMESTAMP|VENDOR|VERSION)__|gshared|traits|vector|parameters)|string|wstring|dstring|size_t|ptrdiff_t)\b/, 'operator': /\|[|=]?|&[&=]?|\+[+=]?|-[-=]?|\.?\.\.|=[>=]?|!(?:i[ns]\b|<>?=?|>=?|=)?|\bi[ns]\b|(?:<[<>]?|>>?>?|\^\^|[*\/%^~])=?/ }); Prism.languages.d.comment = [ // Shebang /^\s*#!.+/, // /+ +/ { // Allow one level of nesting pattern: /(^|[^\\])\/\+(?:\/\+[\s\S]*?\+\/|[\s\S])*?\+\//, lookbehind: true } ].concat(Prism.languages.d.comment); Prism.languages.insertBefore('d', 'comment', { 'token-string': { // Allow one level of nesting pattern: /\bq\{(?:|\{[^}]*\}|[^}])*\}/, alias: 'string' } }); Prism.languages.insertBefore('d', 'keyword', { 'property': /\B@\w*/ }); Prism.languages.insertBefore('d', 'function', { 'register': { // Iasm registers pattern: /\b(?:[ABCD][LHX]|E[ABCD]X|E?(?:BP|SP|DI|SI)|[ECSDGF]S|CR[0234]|DR[012367]|TR[3-7]|X?MM[0-7]|R[ABCD]X|[BS]PL|R[BS]P|[DS]IL|R[DS]I|R(?:[89]|1[0-5])[BWD]?|XMM(?:[89]|1[0-5])|YMM(?:1[0-5]|\d))\b|\bST(?:\([0-7]\)|\b)/, alias: 'variable' } });
mit
jugglinmike/es6draft
src/test/scripts/suite/syntax/lexical/string_noctal_escape.js
1648
/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // noctal for (let i = 8; i <= 9; ++i) { let n = i.toString(10); assertSame(eval(`"\\${n}"`), n); assertSame(eval(`"\\0${n}"`), ("\0" + n)); assertSame(eval(`"\\00${n}"`), ("\0" + n)); assertSame(eval(`"\\000${n}"`), ("\0" + n)); } // Trailing 8-9 for (let j = 8; j <= 9; ++j) { for (let i = 0; i <= 07; ++i) { let n = i.toString(8); let s = String.fromCharCode(i); assertSame(eval(`"\\${n}${j}"`), s + j); assertSame(eval(`"\\0${n}${j}"`), s + j); assertSame(eval(`"\\00${n}${j}"`), s + j); assertSame(eval(`"\\000${n}${j}"`), ("\0" + n + j)); } } for (let j = 8; j <= 9; ++j) { for (let i = 010; i <= 077; ++i) { let n = i.toString(8); let s = String.fromCharCode(i); assertSame(eval(`"\\${n}${j}"`), s + j); assertSame(eval(`"\\0${n}${j}"`), s + j); assertSame(eval(`"\\00${n}${j}"`), (String.fromCharCode(i >> 3) + n.slice(-1) + j)); assertSame(eval(`"\\000${n}${j}"`), ("\0" + n + j)); } } for (let j = 8; j <= 9; ++j) { for (let i = 0100; i <= 0377; ++i) { let n = i.toString(8); let s = String.fromCharCode(i); assertSame(eval(`"\\${n}${j}"`), s + j); assertSame(eval(`"\\0${n}${j}"`), (String.fromCharCode(i >> 3) + n.slice(-1) + j)); assertSame(eval(`"\\00${n}${j}"`), (String.fromCharCode(i >> 6) + n.slice(-2) + j)); assertSame(eval(`"\\000${n}${j}"`), ("\0" + n + j)); } }
mit
victorsantoss/angular-grid
docs/angular-grid-sorting/index.php
976
<?php $key = "Sorting"; $pageTitle = "AngularJS Angular Grid Sorting"; $pageDescription = "AngularJS Angular Grid Sorting"; $pageKeyboards = "AngularJS Angular Grid Sorting"; include '../documentation_header.php'; ?> <div> <h2>Sorting</h2> <h4>Enable Sorting</h4> <p> Turn sorting on for the grid by enabling sorting in the grid options. </p> <p> Sort a column by clicking on the column header. To do multi-column sorting, hold down shift while clicking the column header. </p> <h4>Custom Sorting</h4> <p> Custom sorting is provided at a column level by configuring a comparator on the column definition. The sort methods gets the value as well as the entire data row. </p> <pre> colDef.comparator = function (value1, value2, data1, data2) { return value1 - value2; }</pre> <show-example example="example1"></show-example> </div> <?php include '../documentation_footer.php';?>
mit
luckyfishlab/foundry
examples/pipeline_example.rb
1459
$: << File.expand_path("./lib") require 'resque' require 'foundry' require './examples/sleepyjob' class CommitPhase < Foundry::QueuedPhase def executePhase(context) puts "Start commit phase." puts "Commit -- #{context.class}:#{context} " processor = Foundry::Processor.new(SleepyJob.new()) ret = processor.execute(context) puts "End commit phase with context: #{context.class}:#{context} return value #{ret}" ret end end class SecondaryPhase < Foundry::QueuedPhase def executePhase(context) puts "Start secondary phase." puts "secondary -- #{context.class}:#{context} " job = SleepyJob.new() processor = Foundry::ParallelProcessor.new([job,job]) context["sleep"] = context["sleep"] * 2 processor.execute(context) puts "End secondary phase with context: #{context.class}:#{context} " true end end def tickle_me(x) while 1 #puts "Tickle tickle ... sleep for 5" sleep(5) end end def join_all main = Thread.main current = Thread.current all = Thread.list all.each { |t| t.join unless t == current or t == main } end p2 = SecondaryPhase.new(nil) p1 = CommitPhase.new(p2) t3 = Thread.new(1) { tickle_me(1) } job1 = Hash.new() job1["ID"] = 1 job1["sleep"] = 10 job2 = {"ID"=> 2, "sleep" => 25} job3 = {"ID"=> 3, "sleep" => 13} job4 = {"ID"=> 4, "sleep" => 3} p1.execute(job1) p1.execute(job2) p1.execute(job3) sleep(15) p1.execute(job4) join_all
mit
vynci/laserx
src/client/app/app.routes.ts
484
import { Routes } from '@angular/router'; import { LoginRoutes } from './login/index'; import { DashboardRoutes } from './dashboard/index'; import { TermsAndConditionsRoutes } from './terms-and-conditions/index'; import { LoginComponent } from './login/index'; import { TermsAndConditionsComponent } from './terms-and-conditions/index'; export const routes: Routes = [ ...LoginRoutes, ...DashboardRoutes, ...TermsAndConditionsRoutes, { path: '', component: LoginComponent } ];
mit
danielbeckmann/NFCBasics
NfcBasics/Properties/AssemblyInfo.cs
1084
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Diese Attributwerte ändern, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("NfcBasics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NfcBasics")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Es können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // mithilfe von '*' wie unten dargestellt übernommen werden: // [Assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
mit
Promotion-System/jrpg
dominio/src/main/java/promotionSystem/razas/castas/undertale/Chara.java
1268
package promotionSystem.razas.castas.undertale; import promotionSystem.Constantes; import promotionSystem.razas.PersonajeDeUndertale; public class Chara extends PersonajeDeUndertale{ public Chara(){ casta="Chara"; energia=Constantes.ENERGIA_CHARA; energiaMaxima=Constantes.ENERGIA_MAXIMA_CHARA; salud=Constantes.SALUD_CHARA; saludMaxima=Constantes.SALUD_MAXIMA_CHARA; ataque=Constantes.ATAQUE_CHARA; defensa=Constantes.DEFENSA_CHARA; magia=Constantes.MAGIA_CHARA; velocidad=Constantes.VELOCIDAD_CHARA; } @Override public void subirStats(int cantidadDeNivelesSubidos) { energia+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; energiaMaxima+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; saludMaxima+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; salud+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; ataque+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_ESPECIAL; defensa+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; magia+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; velocidad+=cantidadDeNivelesSubidos*Constantes.MULTIPLICADOR_DE_NIVEL_NORMAL; } }
mit
nicolaihenriksen/SimpleClipboardManager
SimpleClipboardManager/Properties/AssemblyInfo.cs
1108
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleClipboardManager")] [assembly: AssemblyDescription("Simple Clipboard Manager for copy/pasting multiple strings")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleClipboardManager")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("786eae12-626d-4190-bbb0-41f26bfdfb22")] [assembly: AssemblyVersion("1.9.0.0")] [assembly: AssemblyFileVersion("1.9.0.0")]
mit
seangeo/auth-hmac
lib/auth-hmac/version.rb
138
class AuthHMAC module VERSION #:nodoc: MAJOR = 1 MINOR = 1 TINY = 1 STRING = [MAJOR, MINOR, TINY].join('.') end end
mit
dnl-jst/ownsocial
application/controller/Admin.php
719
<?php namespace Application\Controller; use Core\Controller; use Service\User; class Admin extends Controller { public function init() { if ($this->_currentUser->getType() !== 'admin') { $this->redirect('/'); return; } } public function acceptUserAction() { $userId = $this->getRequest()->getPost('id'); $user = User::getById($userId); $user->setAccountConfirmed(1); User::store($user); User::sendAdminAcceptMail($this->getTranslator(), $this->getRequest(), $user); $this->json(array( 'success' => true )); } public function declineUserAction() { $userId = $this->getRequest()->getPost('id'); User::delete($userId); $this->json(array( 'success' => true )); } }
mit
anvk/redux-portal-boilerplate
src/components/Followers/Followers.js
1517
import React, { Component, PropTypes } from 'react'; import LaddaButton from 'react-ladda'; import { UsersTable } from '../'; class Followers extends Component { render() { const { followers } = this.props; return ( <div> <div className="page-header"> <h1>Followers</h1> </div> <div className="row"> <em> * This data is pulled from server upon request </em> </div> <br /> <div className="row"> <div className="col-md-2"> <p className="lead"> GitHub <strong>{this.props.username}</strong> Followers </p> </div> <div className="col-md-2"> <LaddaButton buttonStyle="expand-left" className="btn btn-lg btn-primary btn-block" loading={this.props.isFetching} disabled={this.props.isFetching} onClick={this.props.onSearch} > Refresh </LaddaButton> </div> </div> <div className="row"> <div className="col-md-4"> <UsersTable users={followers} /> </div> </div> </div> ); } } Followers.defaultProps = { followers: [], isFetching: false, username: undefined }; Followers.propTypes = { followers: PropTypes.array, isFetching: PropTypes.bool, username: PropTypes.string, onSearch: PropTypes.func.isRequired }; export default Followers;
mit
cfmdobbie/HTML5-Gamepad-StreetView
math_utils.js
186
// Convert degrees to radians function d2r(degrees) { return degrees * (Math.PI / 180); } // Convert radians to degrees function r2d(radians) { return radians * (180 / Math.PI); }
mit
rubiety/message_block
lib/message_block/helpers.rb
2122
module MessageBlock module Helpers def message_block(options = {}) options[:model_error_type] ||= :error options[:flash_types] ||= [:notice, :back, :confirm, :error, :alert, :info, :warn].sort_by(&:to_s) options[:on] ||= controller.controller_name.split('/').last.gsub(/\_controller$/, '').singularize.to_sym options[:html] ||= {:id => "message_block", :class => "message_block"} options[:html][:id] = options[:id] if options[:id] options[:html][:class] = options[:class] if options[:class] options[:container] = :div if options[:container].nil? flash_messages = {} options[:flash_types].each do |type| entries = flash[type.to_sym] next if entries.nil? entries = [entries] unless entries.is_a?(Array) flash_messages[type.to_sym] ||= [] flash_messages[type.to_sym] += entries end options[:on] = [options[:on]] unless options[:on].is_a?(Array) model_objects = options[:on].map do |model_object| if model_object == :all assigns.values.select {|o| o.respond_to?(:errors) && o.errors.is_a?(ActiveModel::Errors) } elsif model_object.instance_of?(String) or model_object.instance_of?(Symbol) instance_variable_get("@#{model_object}") else model_object end end.flatten.select {|m| !m.nil? } model_errors = model_objects.inject([]) {|b, m| b += m.errors.full_messages } flash_messages[options[:model_error_type].to_sym] ||= [] flash_messages[options[:model_error_type].to_sym] += model_errors contents = flash_messages.keys.sort_by(&:to_s).select {|type| !flash_messages[type.to_sym].empty? }.map do |type| "<ul class=\"#{type}\">" + flash_messages[type.to_sym].map {|message| "<li>#{message}</li>" }.join + "</ul>" end.join unless contents.blank? if options[:container] content_tag(options[:container], contents, options[:html], false) else contents end end end end end
mit
mateidavid/hpptools
include/tpool.hpp
5043
/// @author Matei David, Ontario Institute for Cancer Research /// @version 1.0 /// @date 2015 /// @copyright MIT Public License /// /// A C++11 thread pool. /// /// Inspired by: /// http://stackoverflow.com/a/29742586/717706 #ifndef __TPOOL_HPP #define __TPOOL_HPP #include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <queue> #include <functional> #include <chrono> #include "logger.hpp" namespace tpool { class tpool { public: // create threads tpool(unsigned num_threads = 0) { resize(num_threads); } // wait for work to be done, then destroy threads ~tpool() { clear(); } void clear() { LOG("tpool", info) << "clearing thread pool" << std::endl; { // Unblock any threads and tell them to stop std::unique_lock< std::mutex > l(_queue_mtx); _shutdown = true; _work_cv.notify_all(); } // Wait for all threads to stop for (auto& thread : _threads) { thread.join(); } _threads.clear(); } // change the number of threads void resize(unsigned num_threads) { if (num_threads == size()) { return; } if (size() > 0) { clear(); } if (num_threads == 0) { return; } LOG("tpool", info) << "creating pool of " << num_threads << " threads" << std::endl; // Create the specified number of threads _n_idle = 0; _shutdown = false; _threads.reserve(num_threads); for (unsigned i = 0; i < num_threads; ++i) { _threads.emplace_back(std::bind(&tpool::worker, this, i)); } } // number of threads unsigned size() const { return _threads.size(); } // add a job to process // the single argument passed will be the thread id void add_job(std::function< void(unsigned) > job) { if (size() > 0) { // Place a job on the queue and unblock a thread std::unique_lock< std::mutex > l(_queue_mtx); _jobs.emplace(std::move(job)); _work_cv.notify_one(); } else { // no threads in pool; run job in main thread, with argument 0 job(0); } } // wait until the jobs are done void wait_jobs() { if (size() > 0) { std::unique_lock< std::mutex > l(_queue_mtx); LOG("tpool", debug) << "start waiting for jobs" << std::endl; while (not (_jobs.empty() and _n_idle == _threads.size())) { _wait_cv.wait(l); } LOG("tpool", debug) << "end waiting for jobs" << std::endl; } } private: void worker(unsigned i) { std::function< void(unsigned) > job; LOG("tpool", debug) << "thread " << i << ": start" << std::endl; while (true) { { LOG("tpool", debug) << "thread " << i << ": waiting for job" << std::endl; std::unique_lock< std::mutex > l(_queue_mtx); ++_n_idle; while (not _shutdown and _jobs.empty()) { _wait_cv.notify_all(); _work_cv.wait(l); } if (_jobs.empty()) { // No jobs to do and we are shutting down LOG("tpool", debug) << "thread " << i << ": end" << std::endl; return; } job = std::move(_jobs.front()); _jobs.pop(); --_n_idle; LOG("tpool", debug) << "thread " << i << ": starting job" << std::endl; } job(i); } } // data std::queue< std::function< void(unsigned) > > _jobs; std::vector< std::thread > _threads; std::mutex _queue_mtx; std::condition_variable _work_cv; std::condition_variable _wait_cv; unsigned _n_idle; bool _shutdown; }; // class tpool } // namespace tpool #endif #ifdef SAMPLE_TPOOL /* g++ -std=c++11 -pthread -D SAMPLE_TPOOL -x c++ tpool.hpp -o test-tpool */ using namespace std; using namespace std::placeholders; void zzz(unsigned tid, unsigned i) { // A silly job for demonstration purposes LOG(info) << "tid=" << tid << " i=" << i << " sleep=" << i % 3 << endl; this_thread::sleep_for(chrono::seconds(i % 3)); } int main() { logger::Logger::set_default_level(logger::debug); // Create two threads tpool::tpool p(2); for (unsigned r = 0; r < 2; ++r) { LOG(info) << "start round " << r << endl; // Assign them 4 jobs for (unsigned i = 0; i < 10; i += 2) { p.add_job(bind(zzz, _1, i)); p.add_job([&,i] (unsigned tid) { zzz(tid, i + 1); }); } p.wait_jobs(); LOG(info) << "end iteration " << r << endl; } } #endif
mit
dugooder/a-microservice
src/service.home/HomeNancyModule.cs
794
using Nancy; using Ninject; using Nancy.Responses; namespace service.home { using lib.logging; public class HomeNancyModule : NancyModule { readonly ILogProvider log; [Inject] public HomeNancyModule(ILogProvider log) : base("/") { this.log = log; using (this.log.PushContextInfo("home")) { Get["/"] = parameters => { return View["index"]; }; Get["/humans"] = parameters => { return (new GenericFileResponse("content/humans.txt", "text/plain")) .WithStatusCode(HttpStatusCode.OK); }; } } } }
mit
guibec/rpgcraft
unity/Assets/Scripts/Game/Inventory/Inventory.cs
3025
using System; public class Inventory { private Inventory_Data m_inventoryData; public Inventory_Data InventoryData { get { return m_inventoryData; } set { m_inventoryData = value; OnChanged(); } } public readonly int MAX_ITEMS_PER_SLOT = 99; public delegate void InventoryChangedEventHandler(object sender, EventArgs e); public event InventoryChangedEventHandler Changed; public Inventory() { Inventory_Data inventoryData; inventoryData.m_itemSlots = new ItemCount[10]; for (int i = 0; i < inventoryData.m_itemSlots.Length; ++i) inventoryData.m_itemSlots[i] = new ItemCount(); // default inventory inventoryData.m_itemSlots[0].Count = 1; inventoryData.m_itemSlots[0].Item = ETile.PickAxe; inventoryData.m_itemSlots[1].Count = 1; inventoryData.m_itemSlots[1].Item = ETile.Sword; inventoryData.m_itemSlots[2].Count = 1; inventoryData.m_itemSlots[2].Item = ETile.Copper_Axe; inventoryData.m_itemSlots[3].Count = 10; inventoryData.m_itemSlots[3].Item = ETile.Bomb; inventoryData.m_itemSlots[4].Count = 10; inventoryData.m_itemSlots[4].Item = ETile.Arrow; InventoryData = inventoryData; } public void Start() { OnChanged(); } public bool Carry(ETile item) { int index = FindBestSlotFor(item); if (index == -1) return false; InventoryData.m_itemSlots[index].Item = item; InventoryData.m_itemSlots[index].Count++; //UnityEngine.Debug.Log("Adding item " + item + " to slot " + index + " with count of " + m_itemSlots[index].Count); OnChanged(); return true; } public bool Use(int slotIndex) { if (InventoryData.m_itemSlots[slotIndex].Count >= 1) { InventoryData.m_itemSlots[slotIndex].Count--; if (InventoryData.m_itemSlots[slotIndex].Count == 0) { InventoryData.m_itemSlots[slotIndex].Item = ETile.Invalid; } OnChanged(); return true; } return false; } private int FindBestSlotFor(ETile item) { // look for existing slot for (int i = 0; i < InventoryData.m_itemSlots.Length; ++i) { if (InventoryData.m_itemSlots[i].Item == item && InventoryData.m_itemSlots[i].Count < MAX_ITEMS_PER_SLOT) return i; } // try to find an empty slot for (int i = 0; i < InventoryData.m_itemSlots.Length; ++i) { if (InventoryData.m_itemSlots[i].Item == ETile.Invalid) return i; } return -1; } private void OnChanged() { Changed?.Invoke(this, EventArgs.Empty); } public ItemCount GetSlotInformation(int index_) { return InventoryData.m_itemSlots[index_]; } }
mit
stepchud/town_crier
test/dummy/app/helpers/start_helper.rb
45
module StartHelper include SMSFuHelper end
mit
brianseitel/ook
src/Ook/XmlParser.php
4811
<?php namespace Ook; class XMLParser { /** * The XML object that we will parse * @var SimpleXMLElement */ private $xml = null; /** * The options passed into the parser. * @var array */ private $options = []; /** * The namespace separator. Usually a colon. * @var string */ private $namespaceSeparator = ':'; /** * Accepts an XML input to convert to an array. This respects namespaces, attributes, * and values. * * @param SimpleXmlElement $xml * @param array $options * @return void */ public function __construct($xml, $options = array()) { $defaults = array( 'attributePrefix' => '@', //to distinguish between attributes and nodes with the same name 'alwaysArray' => array(), //array of xml tag names which should always become arrays 'autoArray' => true, //only create arrays for tags which appear more than once 'textContent' => '$', //key used for the text content of elements 'autoText' => true, //skip textContent key if node has no attributes or child nodes ); $this->options = array_merge($defaults, $options); $this->xml = $xml; } /** * Converts XML into an array, respecting namespaces, attributes, and text values. * * @return array */ public function parse() { $namespaces = $this->xml->getDocNamespaces(); $namespaces[''] = null; //add base (empty) namespace $attributes = $this->getAttributes($namespaces); //get child nodes from all namespaces $tags = array(); foreach ($namespaces as $prefix => $namespace) { foreach ($this->xml->children($namespace) as $childXml) { $new_parser = new XmlParser($childXml, $this->options); $child = $new_parser->parse(); list($childTag, $childProperties) = each($child); //add namespace prefix, if any if ($prefix) { $childTag = $prefix . $this->namespaceSeparator . $childTag; } if (!isset($tags[$childTag])) { $alwaysArray = $this->options['alwaysArray']; $autoArray = $this->options['autoArray']; $tags[$childTag] = $childProperties; if (in_array($childTag, $alwaysArray) || !$autoArray) { $tags[$childTag] = [$childProperties]; } } elseif ($this->isIntegerIndexedArray($tags[$childTag])) { $tags[$childTag][] = $childProperties; } else { //key exists so convert to integer indexed array with previous value in position 0 $tags[$childTag] = array($tags[$childTag], $childProperties); } } } //get text content of node $textContent = array(); $plainText = trim((string)$this->xml); if ($plainText !== '') { $textContent[$this->options['textContent']] = $plainText; } //stick it all together $properties = $plainText; if (!$this->options['autoText'] || $attributes || $tags || ($plainText === '')) { $properties = array_merge($attributes, $tags, $textContent); } //return node as array return array( $this->xml->getName() => $properties ); } /** * Helper function to determine whether an array is index with integers. * @param array $array * @return bool True if indexed by integers */ private function isIntegerIndexedArray($array) { if (!is_array($array)) { return false; } $actual_keys = array_keys($array); $expected_keys = range(0, count($array) - 1); return $actual_keys === $expected_keys; } /** * Retrieves the attributes for namespaces * * @param array $namespaces * @return array */ private function getAttributes($namespaces = []) { //get attributes from all namespaces $attributes = array(); foreach ($namespaces as $prefix => $namespace) { foreach ($this->xml->attributes($namespace) as $attributeName => $attribute) { //replace characters in attribute name $attributeKey = $this->options['attributePrefix'] . ($prefix ? $prefix . $this->namespaceSeparator : '') . $attributeName; $attributes[$attributeKey] = (string)$attribute; } } return $attributes; } }
mit
nearspears/vue-nav
webpack.config.js
1418
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'vue-nav.js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) }
mit
yurii-sychov/ci
application/core/MY_Model.php
5092
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Model extends CI_Model { /** * [$order Sort fields. Example: name ASC or name DESC or name] * @var string */ public $order = ''; /** * [$table Name of the table] * @var string */ public $table = ''; /** * [$idTable Id of the table] * @var [type] */ public $idTable; /** * [$style_th Style of the tag th] * @var array */ public $styleTh = []; /** * [$style_td Style of the tag td] * @var array */ public $styleTd = []; /** * [$hide Hide fields of table] * @var array */ public $hideField = []; /** * [$fieldsValidation description] * @var array */ public $fieldsValidation = []; /** * [$perPage Number of entries per page] * @var integer */ public $perPage = 5; /** * [__construct description] */ public function __construct() { parent::__construct(); } /** * [pagination_config description] * @return [type] [description] */ function pagination_config() { $this->load->library('pagination'); // Выбираем количество строк в таблице $config['total_rows'] = $this->db->count_all($this->table); $config['num_links'] = 1; $config['base_url'] = base_url($this->uri->segment(1). '/index'); $config['total_rows'] = $config['total_rows']; $config['per_page'] = $this->perPage; $config['full_tag_open'] = '<ul class="pagination pagination-sm" id="ajax">'; $config['full_tag_close'] = '</ul>'; $config['first_tag_open'] = '<li>'; $config['first_link'] = lang('first_link') ? lang('first_link') : 'first_link_l'; $config['first_tag_close'] = '</li>'; $config['last_tag_open'] = '<li>'; $config['last_link'] = lang('last_link') ? lang('last_link') : 'last_link_l'; $config['last_tag_close'] = '</li>'; $config['prev_tag_open'] = '<li>'; $config['prev_link'] = lang('prev_link') ? lang('prev_link') : 'prev_link_l'; $config['prev_tag_close'] = '</li>'; $config['next_tag_open'] = '<li>'; $config['next_link'] = lang('next_link') ? lang('next_link') : 'next_link_l'; $config['next_tag_close'] = '</li>'; $config['cur_tag_open'] = '<li class="active"><a href=""><strong>'; $config['cur_tag_close'] = '</strong></a></li>'; $config['num_tag_open'] = '<li>'; $config['num_tag_close'] = '</li>'; return $config; } /** * [get_all Get all records in the table] * @return [array] [Returns data as an array] */ function get_all() { $this->db->order_by($this->order); $query = $this->db->get($this->table, $this->perPage, $this->uri->segment(3)); return $query->result_array(); } /** * [get_id Get one record in the table] * @param integer $id [Id of the table] * @return [array] [Returns data as an array] */ function get_id($id) { $this->db->where($this->id, $id); $query = $this->db->get($this->table); return $query->result_array(); } /** * [create Creating an entry in a table] * @param array $post [Form data] * @return [type] [description] */ function create($post = []) { $this->db->set($post); // $query = $this->db->get_compiled_insert($this->table); // echo $query; $query = $this->db->insert($this->table); } function update($id, $post = []) { $this->db->set($post); $this->db->where($this->id, $id); // $query = $this->db->get_compiled_update($this->table); // echo $query; $query = $this->db->update($this->table); } /** * [delete Deleting an entry in a table] * @param integer $id [Id of the table] * @return [type] [description] */ function delete($id) { $this->db->where($this->id, $id); // $this->db->get_compiled_delete($this->table); $this->db->delete($this->table); } /** * [validation description] * @return [type] [description] */ function validation() { $this->load->library('form_validation'); $this->config->set_item('language', $this->session->userdata('language')); foreach ($this->fieldsValidation as $fieldsValidation) { $this->form_validation->set_rules($fieldsValidation, lang($fieldsValidation) ? lang($fieldsValidation) : $fieldsValidation. '_l', 'required'); } } /** * [fields description] * @return [type] [description] */ function fields() { $listFields = $this->db->list_fields($this->table); foreach ($listFields as $field) { $fieldsAll[$field] = lang($field) ? lang($field) : mb_strtoupper($field. '_l'); $fieldsShow[$field] = lang($field) ? lang($field) : mb_strtoupper($field. '_l'); $fieldsTh[$field] = 'class="header_' .$field. ' text-center" ' .$this->styleTh[$field]; $fieldsTd[$field] = 'class="' .$field. ' text-center"'; } $fieldsTh['action'] = 'class="header_' .$field. ' text-center" ' .$this->styleTh['action']; $count = count($this->hide); for ($i=0; $i<$count; $i++) { unset($fieldsShow[$this->hide[$i]]); } return [ 'fieldsAll' => $fieldsAll, 'fieldsShow' => $fieldsShow, 'fieldsTh' => $fieldsTh, 'fieldsTd' => $fieldsTd ]; } }
mit
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGeneratorAutoconfigurationIT.java
1713
package org.zalando.nakadiproducer.snapshots; import static org.junit.Assert.fail; import java.util.Collections; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.zalando.nakadiproducer.BaseMockedExternalCommunicationIT; import org.zalando.nakadiproducer.snapshots.impl.SnapshotCreationService; @ContextConfiguration(classes=SnapshotEventGeneratorAutoconfigurationIT.Config.class) public class SnapshotEventGeneratorAutoconfigurationIT extends BaseMockedExternalCommunicationIT { @Autowired private SnapshotCreationService snapshotCreationService; @Test public void picksUpDefinedSnapshotEventProviders() { // expect no exceptions snapshotCreationService.createSnapshotEvents("A", ""); // expect no exceptions snapshotCreationService.createSnapshotEvents("B", ""); try { snapshotCreationService.createSnapshotEvents("not defined", ""); } catch (final UnknownEventTypeException e) { return; } fail("unknown event type did not result in an exception"); } @Configuration public static class Config { @Bean public SnapshotEventGenerator snapshotEventProviderA() { return new SimpleSnapshotEventGenerator("A", (x) -> Collections.emptyList()); } @Bean public SnapshotEventGenerator snapshotEventProviderB() { return new SimpleSnapshotEventGenerator("B", (x) -> Collections.emptyList()); } } }
mit
aswitalski/chromium-reactor
test/diff-calculate.test.js
39227
describe('Diff => calculate patches', () => { const VirtualNode = Reactor.VirtualNode; const ComponentTree = Reactor.ComponentTree; const Diff = Reactor.Diff; const Patch = Reactor.Patch; const Component = Symbol.for('Component'); const Subcomponent = Symbol.for('Subcomponent'); const OtherComponent = Symbol.for('OtherComponent'); const ComponentClass = class extends Reactor.Component { render() { return this.children[0] || null; } }; const SubcomponentClass = class extends Reactor.Component { render() { return null; } }; const OtherComponentClass = class extends Reactor.Component { render() { return null; } }; const createDummyInstance = def => { switch (def) { case Component: return new ComponentClass(); case Subcomponent: return new SubcomponentClass(); case OtherComponent: return new OtherComponentClass(); } }; describe('=> on an Element', () => { const createTrees = (...templates) => { let currentTemplate; return templates.map( template => ComponentTree.createFromTemplate(template)); }; it('adds an attribute', () => { // given const template = [ 'input', {} ]; const nextTemplate = [ 'input', { value: 'next' } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_ATTRIBUTE); assert(patches[0].target.isElement()); assert.equal(patches[0].name, 'value'); assert.equal(patches[0].value, 'next'); }); it('replaces an attribute', () => { // given const template = [ 'span', { name: 'prev' } ]; const nextTemplate = [ 'span', { name: 'next' } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REPLACE_ATTRIBUTE); assert(patches[0].target.isElement()); assert.equal(patches[0].name, 'name'); assert.equal(patches[0].value, 'next'); }); it('removes an attribute', () => { // given const template = [ 'span', { name: 'prev' } ]; const nextTemplate = [ 'span', {} ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REMOVE_ATTRIBUTE); assert(patches[0].target.isElement()); assert.equal(patches[0].name, 'name'); }); it('adds a data attribute', () => { // given const template = [ 'input', {} ]; const nextTemplate = [ 'input', { dataset: { reactorId: 666 } } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_DATA_ATTRIBUTE); assert.equal(patches[0].name, 'reactorId'); assert.equal(patches[0].value, '666'); assert(patches[0].target.isElement()); }); it('replaces a data attribute', () => { // given const template = [ 'div', { dataset: { customAttrName: 'foo', }, }, ]; const nextTemplate = [ 'div', { dataset: { customAttrName: ['foo', 'bar'], }, }, ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REPLACE_DATA_ATTRIBUTE); assert.equal(patches[0].name, 'customAttrName'); assert.equal(patches[0].value, 'foobar'); assert(patches[0].target.isElement()); }); it('removes a data attribute', () => { // given const template = [ 'div', { dataset: { id: 42, }, }, ]; const nextTemplate = [ 'div' ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REMOVE_DATA_ATTRIBUTE); assert.equal(patches[0].name, 'id'); assert(patches[0].target.isElement()); }); it('adds a style property', () => { // given const template = [ 'input', {} ]; const nextTemplate = [ 'input', { style: { width: [100, 'px'] } } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_STYLE_PROPERTY); assert.equal(patches[0].property, 'width'); assert.equal(patches[0].value, '100px'); assert(patches[0].target.isElement()); }); it('replaces a style property', () => { // given const template = [ 'div', { style: { height: '100%', }, }, ]; const nextTemplate = [ 'div', { style: { height: '50%', }, }, ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REPLACE_STYLE_PROPERTY); assert.equal(patches[0].property, 'height'); assert.equal(patches[0].value, '50%'); assert(patches[0].target.isElement()); }); it('removes a style property', () => { // given const template = [ 'div', { style: { animationDelay: '.666s', }, }, ]; const nextTemplate = [ 'div' ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REMOVE_STYLE_PROPERTY); assert.equal(patches[0].property, 'animationDelay'); assert(patches[0].target.isElement()); }); it('adds a class name', () => { // given const template = [ 'div', { class: 'one', }, ]; const nextTemplate = [ 'div', { class: 'one two', }, ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_CLASS_NAME); assert.equal(patches[0].name, 'two'); assert(patches[0].target.isElement()); }); it('removes a class name', () => { // given const template = [ 'div', { class: 'some-name', }, ]; const nextTemplate = [ 'div', {}, ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REMOVE_CLASS_NAME); assert.equal(patches[0].name, 'some-name'); assert(patches[0].target.isElement()); }); it('adds a listener', () => { // given const listener = () => {}; const template = [ 'span', {} ]; const nextTemplate = [ 'span', { onClick: listener } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_LISTENER); assert(patches[0].target.isElement()); assert.equal(patches[0].event, 'click'); assert.equal(patches[0].listener, listener); }); it('replaces a listener', () => { // given const listener = () => {}; const anotherListener = () => {}; const template = [ 'span', { onClick: listener } ]; const nextTemplate = [ 'span', { onClick: anotherListener } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REPLACE_LISTENER); assert(patches[0].target.isElement()); assert.equal(patches[0].event, 'click'); assert.equal(patches[0].removed, listener); assert.equal(patches[0].added, anotherListener); }); it('removes a listener', () => { // given const listener = () => {}; const template = [ 'span', { onClick: listener } ]; const nextTemplate = [ 'span', {} ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REMOVE_LISTENER); assert(patches[0].target.isElement()); assert.equal(patches[0].event, 'click'); assert.equal(patches[0].listener, listener); }); describe('reconcile children', () => { const assertInsertChildNode = (patch, id, at) => { assert.equal(patch.type, Patch.Type.INSERT_CHILD_NODE); if (typeof id === 'function') { assert.equal(patch.node.constructor, id); } else if (typeof id === 'string') { assert.equal(patch.node.name, id); } assert.equal(patch.at, at); }; const assertMoveChildNode = (patch, id, from, to) => { assert.equal(patch.type, Patch.Type.MOVE_CHILD_NODE); if (typeof id === 'function') { assert.equal(patch.node.constructor, id); } else if (typeof id === 'string') { assert.equal(patch.node.name, id); } assert.equal(patch.from, from); assert.equal(patch.to, to); }; const assertRemoveChildNode = (patch, id, at) => { assert.equal(patch.type, Patch.Type.REMOVE_CHILD_NODE); if (typeof id === 'function') { assert.equal(patch.node.constructor, id); } else if (typeof id === 'string') { assert.equal(patch.node.name, id); } assert.equal(patch.at, at); }; const assertUpdateComponent = (patch, id, props) => { assert.equal(patch.type, Patch.Type.UPDATE_COMPONENT); assert.equal(patch.props, props); }; const createChildren = ({ keys }) => ({ from: (...items) => items.map(name => [ name, { key: (keys === true ? name : undefined) } ]) }); describe('=> with keys', () => { const getChildren = (...items) => { return createChildren({ keys: true }).from(...items); }; it('inserts element at the beginning', () => { // given const template = [ 'section', ...getChildren('div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('X', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertInsertChildNode(patches[0], 'X', 0); }); it('inserts element at the end', () => { // given const template = [ 'section', ...getChildren('div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('div', 'span', 'X') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertInsertChildNode(patches[0], 'X', 2); }); it('moves an element up', () => { // given const template = [ 'section', ...getChildren('section', 'p', 'div', 'X', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'X', 'p', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertMoveChildNode(patches[0], 'X', 3, 1); }); it('moves an element down', () => { // given const template = [ 'section', ...getChildren('section', 'X', 'p', 'div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'p', 'div', 'X', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertMoveChildNode(patches[0], 'X', 1, 3); }); it('moves an element to the beginning', () => { // given const template = [ 'section', ...getChildren('section', 'p', 'div', 'span', 'X') ]; const nextTemplate = [ 'section', ...getChildren('X', 'section', 'p', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertMoveChildNode(patches[0], 'X', 4, 0); }); it('moves an element to the end', () => { // given const template = [ 'section', ...getChildren('X', 'section', 'p', 'div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'p', 'div', 'span', 'X') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertMoveChildNode(patches[0], 'X', 0, 4); }); it('swaps two elements', () => { // given const template = [ 'section', ...getChildren('section', 'X', 'div', 'Y', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'Y', 'div', 'X', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 2); assertMoveChildNode(patches[0], 'Y', 3, 1); assertMoveChildNode(patches[1], 'div', 3, 2); }); it('swaps three elements', () => { // given const template = [ 'section', ...getChildren('section', 'Z', 'p', 'X', 'div', 'Y', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'X', 'p', 'Y', 'div', 'Z', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 3); assertMoveChildNode(patches[0], 'Z', 1, 5); assertMoveChildNode(patches[1], 'div', 3, 4); assertMoveChildNode(patches[2], 'p', 1, 2); }); it('removes an element', () => { // given const template = [ 'section', ...getChildren('section', 'p', 'div', 'X', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'p', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertRemoveChildNode(patches[0], 'X', 3); }); it('inserts and removes elements', () => { // given const template = [ 'section', ...getChildren('section', 'p', 'div', 'X', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'Y', 'p', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 2); assertRemoveChildNode(patches[0], 'X', 3); assertInsertChildNode(patches[1], 'Y', 1); }); it('inserts, moves and removes elements', () => { // given const template = [ 'section', ...getChildren('X', 'section', 'p', 'div', 'Y', 'span') ]; const nextTemplate = [ 'section', ...getChildren('section', 'p', 'div', 'Z', 'span', 'X') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 4); assertRemoveChildNode(patches[0], 'Y', 4); assertInsertChildNode(patches[1], 'Z', 3); assertMoveChildNode(patches[2], 'X', 0, 5); assertMoveChildNode(patches[3], 'Z', 2, 3); }); }); describe('=> without keys', () => { const getChildren = (...items) => createChildren({ keys: false }).from(...items); beforeEach(() => { ComponentTree.createComponentInstance = createDummyInstance; }); it('inserts an element', () => { // given const template = [ 'section', ...getChildren('p', 'div') ]; const nextTemplate = [ 'section', ...getChildren('p', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertInsertChildNode(patches[0], 'span', 2); }); it('removes an element', () => { // given const template = [ 'section', ...getChildren('p', 'div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('p', 'div') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertRemoveChildNode(patches[0], 'span', 2); }); it('replaces reordered elements', () => { // given const template = [ 'section', ...getChildren('p', 'div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('div', 'span', 'p') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 6); assertRemoveChildNode(patches[0], 'p', 0); assertInsertChildNode(patches[1], 'div', 0); assertRemoveChildNode(patches[2], 'div', 1); assertInsertChildNode(patches[3], 'span', 1); assertRemoveChildNode(patches[4], 'span', 2); assertInsertChildNode(patches[5], 'p', 2); }); it('replaces and inserts elements', () => { // given const template = [ 'section', ...getChildren('p', 'span') ]; const nextTemplate = [ 'section', ...getChildren('p', 'div', 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 3); assertInsertChildNode(patches[0], 'span', 2); assertRemoveChildNode(patches[1], 'span', 1); assertInsertChildNode(patches[2], 'div', 1); }); it('replaces and removes elements', () => { // given const template = [ 'section', ...getChildren('p', 'div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('div', 'div') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 3); assertRemoveChildNode(patches[0], 'span', 2); assertRemoveChildNode(patches[1], 'p', 0); assertInsertChildNode(patches[2], 'div', 0); }); describe('replaces an element', () => { it('with an element', () => { // given const template = [ 'section', ...getChildren('p', 'div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('p', 'div', 'a') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 2); assertRemoveChildNode(patches[0], 'span', 2); assertInsertChildNode(patches[1], 'a', 2); }); it('with a component', () => { // given const template = [ 'section', ...getChildren('div', 'span') ]; const nextTemplate = [ 'section', ...getChildren('div', Component) ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 2); assertRemoveChildNode(patches[0], 'span', 1); assertInsertChildNode(patches[1], ComponentClass, 1); }); }); describe('replaces a component', () => { it('with an element', () => { // given const template = [ 'section', ...getChildren('p', 'div', 'span', Component) ]; const nextTemplate = [ 'section', ...getChildren('p', 'div', 'span', 'a') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 2); assertRemoveChildNode(patches[0], ComponentClass, 3); assertInsertChildNode(patches[1], 'a', 3); }); it('with a component', () => { // given const template = [ 'section', ...getChildren('div', Component, 'span') ]; const nextTemplate = [ 'section', ...getChildren('div', Subcomponent, 'span') ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 2); assertRemoveChildNode(patches[0], ComponentClass, 1); assertInsertChildNode(patches[1], SubcomponentClass, 1); }); }); }); describe('update child nodes', () => { it('skips a component', () => { // given const props = { value: 'universal' }; const template = [ 'section', [ Component, props ] ]; // when const [tree, nextTree] = createTrees(template, template); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 0); }); it('updates a component', () => { // given const props = { value: 'old' }; const template = [ 'section', [ Component, props ] ]; const nextProps = { value: 'new' }; const nextTemplate = [ 'section', [ Component, nextProps ] ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assertUpdateComponent(patches[0], SubcomponentClass, nextProps); }); it('adds an attribute', () => { // given const template = [ 'section' ]; const nextTemplate = [ 'section', { name: 'value' } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_ATTRIBUTE); assert.equal(patches[0].name, 'name'); assert.equal(patches[0].value, 'value'); }); it('adds a listener', () => { // given const onClick = () => {}; const template = [ 'section' ]; const nextTemplate = [ 'section', { onClick } ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); // then assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.ADD_LISTENER); assert.equal(patches[0].event, 'click'); assert.equal(patches[0].listener, onClick); }); }); }); describe('set text content', () => { it('sets text on an empty element', () => { const template = [ 'section' ]; const nextTemplate = [ 'section', 'some text', ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.SET_TEXT_CONTENT); assert.equal(patches[0].text, 'some text'); }); it('replaces existing text content', () => { const template = [ 'section', 'some text', ]; const nextTemplate = [ 'section', 'another text', ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.SET_TEXT_CONTENT); assert.equal(patches[0].text, 'another text'); }); it('replaces existing child nodes', () => { const template = [ 'section', [ 'div' ] ]; const nextTemplate = [ 'section', 'some text', ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 2); assert.equal(patches[0].type, Patch.Type.REMOVE_CHILD_NODE); assert.equal(patches[0].parent, tree); assert.equal(patches[0].at, 0); assert.equal(patches[0].node, tree.children[0]); assert.equal(patches[1].type, Patch.Type.SET_TEXT_CONTENT); assert.equal(patches[1].text, 'some text'); }); }); describe('remove text content', () => { it('removes existing text content', () => { const template = [ 'section', 'some text', ]; const nextTemplate = [ 'section', ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); console.log(patches); assert.equal(patches.length, 1); assert.equal(patches[0].type, Patch.Type.REMOVE_TEXT_CONTENT); }); it('removes text content before appending child nodes', () => { const template = [ 'section', 'some text', ]; const nextTemplate = [ 'section', [ 'div' ] ]; // when const [tree, nextTree] = createTrees(template, nextTemplate); const patches = Diff.calculate(tree, nextTree); assert.equal(patches.length, 2); assert.equal(patches[0].type, Patch.Type.REMOVE_TEXT_CONTENT); assert.equal(patches[1].type, Patch.Type.INSERT_CHILD_NODE); assert.equal(patches[1].parent, tree); assert.equal(patches[1].at, 0); assert.equal(patches[1].node, nextTree.children[0]); }); }); }); describe('=> on a Component', () => { const createComponents = (props, children, nextProps, nextChildren) => { return [ ComponentTree.create(Component, props, children), ComponentTree.create(Component, nextProps, nextChildren) ]; }; beforeEach(() => { ComponentTree.createComponentInstance = createDummyInstance; }); const assertComponentUpdate = (patch, component, props) => { assert.equal(patch.type, Patch.Type.UPDATE_COMPONENT); assert.equal(patch.target, component); assert.equal(patch.props, props); }; it('adds an element', () => { // given const props = {}; const children = []; const nextProps = { child: true }; const nextChildren = [ ['div'] ]; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 2); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.ADD_ELEMENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].element.isElement()); assert.equal(patches[1].element.name, 'div'); }); it('removes an element', () => { // given const props = { child: true }; const children = [ ['div'] ]; const nextProps = {}; const nextChildren = []; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 2); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.REMOVE_ELEMENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].element.isElement()); assert.equal(patches[1].element.name, 'div'); }); it('adds a component', () => { // given const props = {}; const children = []; const nextProps = { child: true }; const nextChildren = [ [Subcomponent] ]; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 2); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.ADD_COMPONENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].component.isComponent()); assert.equal(patches[1].component.constructor, SubcomponentClass); }); it('removes a component', () => { // given const props = { child: true }; const children = [ [Subcomponent] ]; const nextProps = {}; const nextChildren = []; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 2); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.REMOVE_COMPONENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].component.isComponent()); assert.equal(patches[1].component.constructor, SubcomponentClass); }); describe('replaces a child element', () => { it('with an element', () => { // given const props = { child: 'div' }; const children = [ ['div'] ]; const nextProps = { child: 'span' }; const nextChildren = [ ['span'] ]; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 3); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.REMOVE_ELEMENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].element.isElement()); assert.equal(patches[1].element.name, 'div'); assert.equal(patches[2].type, Patch.Type.ADD_ELEMENT); assert(patches[2].parent.isComponent()); assert.equal(patches[2].parent, component); assert(patches[2].element.isElement()); assert.equal(patches[2].element.name, 'span'); }); it('with a component', () => { // given const props = { child: 'div' }; const children = [ ['div'] ]; const nextProps = { child: 'component' }; const nextChildren = [ [Subcomponent] ]; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 3); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.REMOVE_ELEMENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].element.isElement()); assert.equal(patches[1].element.name, 'div'); assert.equal(patches[2].type, Patch.Type.ADD_COMPONENT); assert(patches[2].parent.isComponent()); assert.equal(patches[2].parent, component); assert(patches[2].component.isComponent()); assert.equal(patches[2].component.constructor, SubcomponentClass); }); }); describe('replaces a child component', () => { it('with an element', () => { // given const props = { child: 'subcomponent' }; const children = [ [Subcomponent] ]; const nextProps = { child: 'div' }; const nextChildren = [ ['div'] ]; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 3); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.REMOVE_COMPONENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].component.isComponent()); assert.equal(patches[1].component.constructor, SubcomponentClass); assert.equal(patches[2].type, Patch.Type.ADD_ELEMENT); assert(patches[2].parent.isComponent()); assert.equal(patches[2].parent, component); assert(patches[2].element.isElement()); assert.equal(patches[2].element.name, 'div'); }); it('with a component', () => { // given const props = { child: 'subcomponent' }; const children = [ [Subcomponent] ]; const nextProps = { child: 'other-component' }; const nextChildren = [ [OtherComponent] ]; // when const [component, nextComponent] = createComponents( props, children, nextProps, nextChildren, ); const patches = Diff.calculate(component, nextComponent); // then assert.equal(patches.length, 3); assertComponentUpdate(patches[0], component, nextProps); assert.equal(patches[1].type, Patch.Type.REMOVE_COMPONENT); assert(patches[1].parent.isComponent()); assert.equal(patches[1].parent, component); assert(patches[1].component.isComponent()); assert.equal(patches[1].component.constructor, SubcomponentClass); assert.equal(patches[2].type, Patch.Type.ADD_COMPONENT); assert(patches[2].parent.isComponent()); assert.equal(patches[2].parent, component); assert(patches[2].component.isComponent()); assert.equal(patches[2].component.constructor, OtherComponentClass); }); }); }); });
mit
elminsterjimmy/PSN-API
PSN-API/src/main/java/com/elminster/retrieve/psn/service/IPSNApi.java
1038
package com.elminster.retrieve.psn.service; import java.util.List; import com.elminster.retrieve.psn.data.game.PSNGame; import com.elminster.retrieve.psn.data.game.PSNTrophy; import com.elminster.retrieve.psn.data.user.PSNUserGame; import com.elminster.retrieve.psn.data.user.PSNUserProfile; import com.elminster.retrieve.psn.data.user.PSNUserTrophy; import com.elminster.retrieve.psn.exception.ServiceException; public interface IPSNApi { public PSNUserProfile getPSNUserProfile(String psnUsername) throws ServiceException; public List<PSNUserGame> getPSNUserGameList(String psnUsername) throws ServiceException; public List<PSNUserTrophy> getPSNUserGameTrophies(String psnUsername, String psnGameId) throws ServiceException; // depending on aggregation in background. Need to think what happened if the game id is not being retrieved before. public List<PSNTrophy> getPSNGameTrophies(String psnGameId) throws ServiceException; public PSNGame getPSNGameSummary(String psnGameId) throws ServiceException; }
mit
arcstone/Credentials
src/Credentials.php
2101
<?php /* * This file is part of Laravel Credentials. * * (c) Graham Campbell <graham@mineuk.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\Credentials; use Cartalyst\Sentry\Sentry; use McCool\LaravelAutoPresenter\PresenterDecorator; /** * This is the credentials class. * * @author Graham Campbell <graham@mineuk.com> */ class Credentials { /** * The cache of the check method. * * @var mixed */ protected $cache; /** * The sentry instance. * * @var \Cartalyst\Sentry\Sentry */ protected $sentry; /** * The decorator instance. * * @var \McCool\LaravelAutoPresenter\PresenterDecorator */ protected $decorator; /** * Create a new instance. * * @param \Cartalyst\Sentry\Sentry $sentry * @param \McCool\LaravelAutoPresenter\PresenterDecorator $decorator * * @return void */ public function __construct(Sentry $sentry, PresenterDecorator $decorator) { $this->sentry = $sentry; $this->decorator = $decorator; } /** * Call Sentry's check method or load of cached value. * * @return bool */ public function check() { if ($this->cache === null) { $this->cache = $this->sentry->check(); } return $this->cache && $this->getUser(); } /** * Get the decorated current user. * * @return \GrahamCampbell\Credentials\Presenters\UserPresenter */ public function getDecoratedUser() { if ($user = $this->sentry->getUser()) { return $this->decorator->decorate($user); } } /** * Dynamically pass all other methods to sentry. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { return call_user_func_array([$this->sentry, $method], $parameters); } }
mit
MahjongRepository/tenhou-python-bot
project/game/ai/defence/yaku_analyzer/yakuhai.py
913
from game.ai.defence.yaku_analyzer.yaku_analyzer import YakuAnalyzer class YakuhaiAnalyzer(YakuAnalyzer): id = "yakuhai" def __init__(self, enemy): self.enemy = enemy def serialize(self): return {"id": self.id} def is_yaku_active(self): return len(self._get_suitable_melds()) > 0 def melds_han(self): han = 0 suitable_melds = self._get_suitable_melds() for x in suitable_melds: tile_34 = x.tiles[0] // 4 # we need to do that to support double winds yakuhais han += len([x for x in self.enemy.valued_honors if x == tile_34]) return han def _get_suitable_melds(self): suitable_melds = [] for x in self.enemy.melds: tile_34 = x.tiles[0] // 4 if tile_34 in self.enemy.valued_honors: suitable_melds.append(x) return suitable_melds
mit
kalibao/kalibao-framework
kalibao/backend/modules/cms/components/cmsImage/crud/Edit.php
4436
<?php /** * @copyright Copyright (c) 2015 Kévin Walter <walkev13@gmail.com> - Kalibao * @license https://github.com/kalibao/kalibao-framework/blob/master/LICENSE */ namespace kalibao\backend\modules\cms\components\cmsImage\crud; use Yii; use yii\helpers\Url; use kalibao\common\components\crud\SimpleValueField; use kalibao\common\components\crud\InputField; use kalibao\common\components\i18n\I18N; use kalibao\common\models\cmsImageGroup\CmsImageGroupI18n; /** * Class Edit * * @package kalibao\backend\modules\cms\components\cmsImage\crud * @version 1.0 * @author Kevin Walter <walkev13@gmail.com> */ class Edit extends \kalibao\common\components\crud\Edit { /** * @inheritdoc */ public function init() { parent::init(); // set titles $this->setCreateTitle(Yii::t('kalibao.backend', 'cms_image_create_title')); $this->setUpdateTitle(Yii::t('kalibao.backend', 'cms_image_update_title')); // models $models = $this->getModels(); // language $language = $this->getLanguage(); // get drop down list methods $dropDownList = $this->getDropDownList(); // upload config $uploadConfig['main'] = $this->uploadConfig[(new \ReflectionClass($models['main']))->getName()]; // set items $items = []; if (!$models['main']->isNewRecord) { $items[] = new SimpleValueField([ 'model' => $models['main'], 'attribute' => 'id', 'value' => $models['main']->id, ]); } $items[] = new InputField([ 'model' => $models['i18n'], 'attribute' => 'title', 'type' => 'activeTextInput', 'options' => [ 'class' => 'form-control input-sm', 'maxlength' => true, 'placeholder' => $models['main']->getAttributeLabel('title'), ] ]); $items[] = new InputField([ 'model' => $models['main'], 'attribute' => 'cms_image_group_id', 'type' => 'activeHiddenInput', 'options' => [ 'class' => 'form-control input-sm input-ajax-select', 'data-action' => Url::to([ 'advanced-drop-down-list', 'id' => 'cms_image_group_i18n.title', ]), 'data-add-action' => Url::to('/cms/cms-image-group/create'), 'data-update-action' => Url::to('/cms/cms-image-group/update'), 'data-update-argument' => 'id', 'data-related-field' => '.link_cms_image_group_title', 'data-allow-clear' => 1, 'data-placeholder' => Yii::t('kalibao', 'input_select'), 'data-text' => !empty($models['main']->cms_image_group_id) ? CmsImageGroupI18n::findOne([ 'cms_image_group_id' => $models['main']->cms_image_group_id, 'i18n_id' => $language ])->title : '', ] ]); $items[] = new InputField([ 'model' => $models['main'], 'attribute' => 'file_path', 'type' => 'activeFileInput', 'options' => [ 'class' => 'input-advanced-uploader', 'placeholder' => $models['main']->getAttributeLabel('file_path'), 'data-type-uploader' => $uploadConfig['main']['file_path']['type'], 'data-img-src' => ($models['main']->file_path != '') ? $uploadConfig['main']['file_path']['baseUrl'] . '/min/' . $models['main']->file_path : '', 'data-img-size-width' => '300px', ] ]); if (!$models['main']->isNewRecord) { $items[] = new SimpleValueField([ 'model' => $models['main'], 'attribute' => 'created_at', 'value' => Yii::$app->formatter->asDatetime($models['main']->created_at, I18N::getDateFormat()) ]); } if (!$models['main']->isNewRecord) { $items[] = new SimpleValueField([ 'model' => $models['main'], 'attribute' => 'updated_at', 'value' => Yii::$app->formatter->asDatetime($models['main']->updated_at, I18N::getDateFormat()) ]); } $this->setItems($items); } }
mit
akhilcjacob/Robot_2016_Ver2.0
src/org/usfirst/frc/team2791/abstractSubsystems/AbstractShakerDriveTrain.java
16726
package org.usfirst.frc.team2791.abstractSubsystems; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team2791.overridenClasses.BasicPID; import org.usfirst.frc.team2791.util.Constants; import org.usfirst.frc.team2791.util.Util; /** * Created by Akhil on 4/7/2016. * This class is designed to control the driveTrain it is runnable, * so that it can run on its own thread for higher angle,stationary, * and distance pid **/ public class AbstractShakerDriveTrain extends ShakerSubsystem implements Runnable { private static final float WHEEL_DIAMETER = (float) (8.0 / 12.0); //Number of ticks in one rotation of the encoder private static final double encoderTicks = 128; //control loops to control the driveTrain accurately private static BasicPID movingAnglePID; private static BasicPID distancePID; private static BasicPID stationaryAnglePID; //Encoders - Distance sensors on the robot protected Encoder leftDriveEncoder = null; protected Encoder rightDriveEncoder = null; // this should be instantiated by the extending class protected RobotDrive robotDrive = null; //Distance PID flags private boolean useDistancePID = false; private boolean distancePID_useFastExit = false; private double distancePID_maxOutput = 1.0; private double distancePID_distanceSetpoint; private double distancePID_movingAngleSetpoint = 0; private boolean distancePID_atTarget = false; private boolean distancePID_holdSetpoint = false; //Angle PID flags private boolean useAnglePID = false; private boolean anglePID_useFastExit = false; private double anglePID_maxOutput = 1.0; private double anglePID_angleSetpoint = 0; private boolean anglePID_atTarget = false; private boolean anglePID_holdSetPoint = false; //miscellaneous private Timer anglePIDTimer; private Timer distancePIDTimer; private boolean busy = false; public AbstractShakerDriveTrain() { } /** * Init method needs to be called by the extending class, * this is so that the extending class can instantiate anything * that is necessary for the init method to work */ protected void init() { System.out.println("Updating driveTrain preference..."); //zero the encoders leftDriveEncoder.reset(); rightDriveEncoder.reset(); //set how many ticks equals one foot leftDriveEncoder.setDistancePerPulse(Util.tickToFeet(encoderTicks, WHEEL_DIAMETER)); rightDriveEncoder.setDistancePerPulse(-Util.tickToFeet(encoderTicks, WHEEL_DIAMETER)); //create the control loops using default values movingAnglePID = new BasicPID(Constants.DRIVE_ANGLE_P, Constants.DRIVE_ANGLE_I, Constants.DRIVE_ANGLE_D); distancePID = new BasicPID(Constants.DRIVE_DISTANCE_P, Constants.DRIVE_DISTANCE_I, Constants.DRIVE_DISTANCE_D); stationaryAnglePID = new BasicPID(Constants.STATIONARY_ANGLE_P, Constants.STATIONARY_ANGLE_I, Constants.STATIONARY_ANGLE_D); //PID preferences movingAnglePID.setInvertOutput(true); stationaryAnglePID.setInvertOutput(true); stationaryAnglePID.setIZone(4); distancePID.setIZone(0.25); movingAnglePID.setIZone(4); //timer anglePIDTimer = new Timer(); distancePIDTimer = new Timer(); } /** * This runs on its own thread, originally for higher accuracy * in the PID */ public void run() { while (true) { try { //busy mode pretty much makes sure nothing else should run //while pid's are running busy = useAnglePID || useDistancePID; if (useAnglePID || anglePID_holdSetPoint) { //global variable is returned when something calls the public setAngle anglePID_atTarget = setAngleInternal(anglePID_angleSetpoint, anglePID_maxOutput, anglePID_useFastExit); //if the target value is reached break out of the pid useAnglePID = !anglePID_atTarget; } if (useDistancePID || distancePID_holdSetpoint) { //global variable is returned when something calls the public setDistance distancePID_atTarget = setDistanceInternal(distancePID_distanceSetpoint, distancePID_movingAngleSetpoint, distancePID_maxOutput, distancePID_useFastExit); //if the target value is reached break out of the pid useDistancePID = !distancePID_atTarget; } Thread.sleep(updateDelayMs);//Run at updateDelayMs hertz } catch (Exception e) { //print the error e.printStackTrace(); //re-run if a problem occurs this.run(); } } } /**************INTERNAL RUN METHODS****************/ /** * These methods are only to be used by the run method!! */ private boolean setAngleInternal(double angle, double maxOutput, boolean fastExit) { //update some pid values stationaryAnglePID.setSetPoint(angle); stationaryAnglePID.setMaxOutput(maxOutput); stationaryAnglePID.setMinOutput(-maxOutput); //get the ouptut from the pid double anglePIDOutput = stationaryAnglePID.updateAndGetOutput(getAngleEncoder()); //set the pid values in voltage to the driveTrain setLeftRightVoltage(anglePIDOutput, -anglePIDOutput); //fast exit doesnt wait for time for the bot to be good if (fastExit) { return (Math.abs(stationaryAnglePID.getError()) < 0.5) && getEncoderAngleRate() < 0.5; } //this exit method uses time for pid to be good for(more accurate) if (!(Math.abs(stationaryAnglePID.getError()) < 0.5)) { // Makes sure pid is good error is minimal anglePIDTimer.reset(); anglePIDTimer.start(); } else if (anglePIDTimer.get() > 0.5) { // then makes sure that certain time has passed to be absolutely // positive return true; } return false; } private boolean setDistanceInternal(double distance, double angle, double maxOutput, boolean fastExit) { //PID - update values distancePID.setSetPoint(distance); movingAnglePID.setSetPoint(angle); distancePID.setMaxOutput(maxOutput); distancePID.setMinOutput(-maxOutput); movingAnglePID.setMaxOutput(maxOutput / 2); movingAnglePID.setMinOutput(-maxOutput / 2); //get pid output double drivePIDOutput = -distancePID.updateAndGetOutput(getAverageDist()); double anglePIDOutput = movingAnglePID.updateAndGetOutput(getAngleEncoder()); //set the voltages setLeftRightVoltage(drivePIDOutput + anglePIDOutput, drivePIDOutput - anglePIDOutput); System.out.println("distError: " + distancePID.getError() + " output: " + drivePIDOutput); System.out.println("angleError: " + movingAnglePID.getError() + " output: " + anglePIDOutput); //fast exit doesnt wait for time for the shot to be good if (fastExit) { return ((Math.abs(distancePID.getError()) < 0.05) || (Math.abs(movingAnglePID.getError()) < 1.5)) && getAverageVelocity() < 0.5; } //this exit method uses time for pid to be good for(more accurate if (!(Math.abs(distancePID.getError()) < 0.05) || !(Math.abs(movingAnglePID.getError()) < 1.5)) { // Makes sure pid is good error is minimal distancePIDTimer.reset(); distancePIDTimer.start(); } else if (distancePIDTimer.get() > 0.5) { // then makes sure that certain time has passed to be absolutely positive return true; } return false; } /************* * END INTERNAL RUN METHODS ************/ public void setLeftRight(double left, double right) { //This sets the voltages from -1 to 1 robotDrive.setLeftRightMotorOutputs(left, right); } public void setToggledLeftRight(double left, double right) { //setLeftRight values when the drive train is not busy if (!busy) setLeftRight(left, right); } public void setLeftRightVoltage(double leftVoltage, double rightVoltage) { //takes in input as voltages and uses current voltage state to vary output accordingly leftVoltage *= 12; rightVoltage *= 12; //this reads the current voltage and then sets based on reading //used to be divided by ControllerPower.getInputVoltage() --> DriverStation.getInstance().getBatteryVoltage() leftVoltage /= DriverStation.getInstance().getBatteryVoltage(); rightVoltage /= DriverStation.getInstance().getBatteryVoltage(); setLeftRight(leftVoltage, rightVoltage); } /** * This method is called in teleop and sets variables that are used in the * run method to run our angle PID. * * @param angle The angle you want to robot to turn to * @param maxOutput The maximum output to use for this turn * @param holdSetPoint If this is true the angle code will hold the angle even after reaching it, must be * call method releaseAnglePID() to break out of it * @param fastExit If this is true this method returns true when the drive train * stop moving quickly. If this is false the default behavior of * returning true if the error is less than 0.5 for longer than * 0.5s. * @return whether or not the target angle has been reached */ public boolean setAngle(double angle, double maxOutput, boolean holdSetPoint, boolean fastExit) { useAnglePID = true; anglePID_angleSetpoint = angle; anglePID_maxOutput = maxOutput; anglePID_useFastExit = fastExit; anglePID_holdSetPoint = holdSetPoint; return anglePID_atTarget; } public boolean setAngle(double angle, double maxOutput) { return setAngle(angle, maxOutput, false, false); } public void releaseAnglePID() { anglePID_holdSetPoint = false; } /** * This method is called in teleop and sets variables that are used in the * run method to run our distance PID. * * @param distance The distance you want the pid to go * @param angle The angle you want the robot to maintain while going the distance * @param maxOutput The max output for driving * @param holdSetPoint If this is true the robot will continue to hold the distance until it is released, using * method releaseDistancePID() * @param fastExit If this is true this method returns true when the drive train * stop moving quickly. If this is false the default behavior of * returning true if the error is less than 0.5 for longer than * 0.5s. * @return whether the distance has been reached */ public boolean setDistance(double distance, double angle, double maxOutput, boolean holdSetPoint, boolean fastExit) { useDistancePID = true; distancePID_distanceSetpoint = distance; distancePID_movingAngleSetpoint = angle; distancePID_maxOutput = maxOutput; distancePID_useFastExit = fastExit; distancePID_holdSetpoint = holdSetPoint; return distancePID_atTarget; } public boolean setDistance(double distance, double angle, double maxOutput) { return setDistance(distance, angle, maxOutput, false, false); } public void releaseDistancePID() { distancePID_holdSetpoint = false; } public boolean getIfBusy() { return busy; } public void forceBreakAnglePID() { //forcefully breaks out of the angle pid even if hasnt reached the target useAnglePID = false; releaseAnglePID(); } public void forceBreakDistancePID() { //forcefully break out of the distance pid even if setpoint hasnt been reaced useDistancePID = false; releaseDistancePID(); } public void forceBreakPID() { //break out of any running pid forceBreakAnglePID(); forceBreakDistancePID(); } public void resetEncoders() { leftDriveEncoder.reset(); rightDriveEncoder.reset(); } public double getStationaryPIDError() { return stationaryAnglePID.getError(); } public double getDistancePIDError() { return distancePID.getError(); } public double getLeftVelocity() { //Left encoder velocity in ft/s return leftDriveEncoder.getRate(); } public double getRightVelocity() { //Right encoder velocity in ft/s return rightDriveEncoder.getRate(); } public double getAverageVelocity() { //the average of both encoder velocities return (getLeftVelocity() + getRightVelocity()) / 2; } public double getLeftDistance() { // distance of left encoder in feet return leftDriveEncoder.getDistance(); } public double getRightDistance() { // distance of right encoder in feet return rightDriveEncoder.getDistance(); } public double getAverageDist() { // average distance of both encoders return (getLeftDistance() + getRightDistance()) / 2; } public double getAngle() { return getAngleEncoder(); } public double getAngleEncoder() { //returns the angle using encoder values return (90 / 2.3) * (getLeftDistance() - getRightDistance()) / 2.0; } public double getEncoderAngleRate() { //return the rate at which we are spinning return (90 / 2.3) * (leftDriveEncoder.getRate() - rightDriveEncoder.getRate()) / 2.0; } public void disable() { // Stops all the motors robotDrive.stopMotor(); forceBreakPID(); } /** * This updates PID values from the SmartDashboard */ public void updatePIDGains() { //Get values from the smartdashboard Constants.STATIONARY_ANGLE_P = SmartDashboard.getNumber("Stat Angle P"); Constants.STATIONARY_ANGLE_I = SmartDashboard.getNumber("Stat Angle I"); Constants.STATIONARY_ANGLE_D = SmartDashboard.getNumber("Stat Angle D"); Constants.DRIVE_ANGLE_P = SmartDashboard.getNumber("Angle P"); Constants.DRIVE_ANGLE_I = SmartDashboard.getNumber("Angle I"); Constants.DRIVE_ANGLE_D = SmartDashboard.getNumber("Angle D"); Constants.DRIVE_DISTANCE_P = SmartDashboard.getNumber("DISTANCE P"); Constants.DRIVE_DISTANCE_I = SmartDashboard.getNumber("DISTANCE I"); Constants.DRIVE_DISTANCE_D = SmartDashboard.getNumber("Distance D"); //update the control loops movingAnglePID.changeGains(Constants.DRIVE_ANGLE_P, Constants.DRIVE_ANGLE_I, Constants.DRIVE_ANGLE_D); distancePID.changeGains(Constants.DRIVE_DISTANCE_P, Constants.DRIVE_DISTANCE_I, Constants.DRIVE_DISTANCE_D); stationaryAnglePID.changeGains(Constants.STATIONARY_ANGLE_P, Constants.STATIONARY_ANGLE_I, Constants.STATIONARY_ANGLE_D); } public void updateSmartDash() { updatePIDGains(); } public void debug() { SmartDashboard.putNumber("Left Drive Encoders Rate", leftDriveEncoder.getRate()); SmartDashboard.putNumber("Right Drive Encoders Rate", rightDriveEncoder.getRate()); SmartDashboard.putNumber("Encoder Angle", getAngleEncoder()); SmartDashboard.putNumber("Encoder Angle Rate Change", getEncoderAngleRate()); SmartDashboard.putNumber("Angle PID Error", stationaryAnglePID.getError()); SmartDashboard.putNumber("Angle PID Output", stationaryAnglePID.getOutput()); SmartDashboard.putNumber("Average Encoder Distance", getAverageDist()); SmartDashboard.putNumber("Left Encoder Distance", getLeftDistance()); SmartDashboard.putNumber("Right Encoder Distance", getRightDistance()); SmartDashboard.putNumber("Distance PID output", distancePID.getOutput()); SmartDashboard.putNumber("Distance PID error", distancePID.getError()); } }
mit
chrkon/helix-toolkit
Source/HelixToolkit.SharpDX.Shared/Utilities/Octrees/RenderableBoundingOctree.cs
10321
using SharpDX; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; #if !NETFX_CORE namespace HelixToolkit.Wpf.SharpDX #else #if CORE namespace HelixToolkit.SharpDX.Core #else namespace HelixToolkit.UWP #endif #endif { namespace Utilities { using Model.Scene; public class BoundableNodeOctree : DynamicOctreeBase<SceneNode> { /// <summary> /// Only root contains dictionary /// </summary> private Dictionary<Guid, IDynamicOctree> OctantDictionary = null; public BoundableNodeOctree(List<SceneNode> objList, Stack<KeyValuePair<int, IDynamicOctree[]>> queueCache = null) : this(objList, null, queueCache) { } public BoundableNodeOctree(List<SceneNode> objList, OctreeBuildParameter paramter, Stack<KeyValuePair<int, IDynamicOctree[]>> queueCache = null) : base(null, paramter, queueCache) { Objects = objList; if (Objects != null && Objects.Count > 0) { var bound = GetBoundingBoxFromItem(Objects[0]); foreach (var item in Objects) { var b = GetBoundingBoxFromItem(item); BoundingBox.Merge(ref b, ref bound, out bound); } this.Bound = bound; } } protected BoundableNodeOctree(BoundingBox bound, List<SceneNode> objList, IDynamicOctree parent, OctreeBuildParameter paramter, Stack<KeyValuePair<int, IDynamicOctree[]>> queueCache) : base(ref bound, objList, parent, paramter, queueCache) { } public override bool HitTestCurrentNodeExcludeChild(HitTestContext context, object model, Geometry3D geometry, Matrix modelMatrix, ref Ray rayModel, ref List<HitTestResult> hits, ref bool isIntersect, float hitThickness) { isIntersect = false; if (!this.treeBuilt) { return false; } bool isHit = false; //var bound = Bound.Transform(modelMatrix);// BoundingBox.FromPoints(Bound.GetCorners().Select(x => Vector3.TransformCoordinate(x, modelMatrix)).ToArray()); var bound = Bound; var tempHits = new List<HitTestResult>(); var rayWS = context.RayWS; if (rayWS.Intersects(ref bound)) { isIntersect = true; foreach (var r in this.Objects) { isHit |= r.HitTest(context, ref tempHits); hits.AddRange(tempHits); tempHits.Clear(); } } return isHit; } protected override BoundingBox GetBoundingBoxFromItem(SceneNode item) { return item.BoundsWithTransform; } protected override IDynamicOctree CreateNodeWithParent(ref BoundingBox bound, List<SceneNode> objList, IDynamicOctree parent) { return new BoundableNodeOctree(bound, objList, parent, parent.Parameter, this.stack); } public override void BuildTree() { if (IsRoot) { OctantDictionary = new Dictionary<Guid, IDynamicOctree>(Objects.Count); } base.BuildTree(); if (IsRoot) { TreeTraversal(this, stack, null, (node) => { foreach (var item in (node as DynamicOctreeBase<SceneNode>).Objects) { OctantDictionary.Add(item.GUID, node); } }, null); } } public IDynamicOctree FindItemByGuid(Guid guid, SceneNode item, out int index) { var root = FindRoot(this) as BoundableNodeOctree; index = -1; if (root.OctantDictionary.ContainsKey(guid)) { var node = root.OctantDictionary[guid]; index = (node as DynamicOctreeBase<SceneNode>).Objects.IndexOf(item); return root.OctantDictionary[guid]; } else { return null; } } public bool RemoveByGuid(Guid guid, SceneNode item) { var root = FindRoot(this); return RemoveByGuid(guid, item, root as BoundableNodeOctree); } public bool RemoveByGuid(Guid guid, SceneNode item, BoundableNodeOctree root) { if (root.OctantDictionary.ContainsKey(guid)) { (OctantDictionary[guid] as BoundableNodeOctree).RemoveSafe(item, root); return true; } else { return false; } } public override bool Add(SceneNode item, out IDynamicOctree octant) { if (base.Add(item, out octant)) { if (octant == null) { throw new Exception("Output octant is null"); }; var root = FindRoot(this) as BoundableNodeOctree; if (!root.OctantDictionary.ContainsKey(item.GUID)) { root.OctantDictionary.Add(item.GUID, octant); } return true; } else { return false; } } public override bool PushExistingToChild(int index, out IDynamicOctree octant) { var item = Objects[index]; if (base.PushExistingToChild(index, out octant)) { var root = FindRoot(this) as BoundableNodeOctree; root.OctantDictionary[item.GUID] = octant; return true; } else { return false; } } public override bool RemoveSafe(SceneNode item) { var root = FindRoot(this); return RemoveSafe(item, root); } public bool RemoveSafe(SceneNode item, IDynamicOctree root) { if (base.RemoveSafe(item)) { RemoveFromRootDictionary(root, item.GUID); return true; } else { return false; } } public override bool RemoveAt(int index) { var root = FindRoot(this); return RemoveAt(index, root); } public bool RemoveAt(int index, IDynamicOctree root) { var id = this.Objects[index].GUID; if (base.RemoveAt(index)) { RemoveFromRootDictionary(root, id); return true; } else { return false; } } public override bool RemoveByBound(SceneNode item, ref BoundingBox bound) { var root = FindRoot(this); return RemoveByBound(item, ref bound, root); } public bool RemoveByBound(SceneNode item, ref BoundingBox bound, IDynamicOctree root) { if (base.RemoveByBound(item, ref bound)) { RemoveFromRootDictionary(root, item.GUID); return true; } else { return false; } } public override IDynamicOctree Expand(ref Vector3 direction) { //Debug.WriteLine("Expaned"); var root = this; if (!IsRoot) { root = FindRoot(this) as BoundableNodeOctree; } var newRoot = Expand(root, ref direction, CreateNodeWithParent); (newRoot as BoundableNodeOctree).TransferOctantDictionary(root, ref root.OctantDictionary);//Transfer the dictionary to new root return newRoot; } public override IDynamicOctree Shrink() { var root = this; if (!IsRoot) { root = FindRoot(this) as BoundableNodeOctree; } var newRoot = Shrink(root); (newRoot as BoundableNodeOctree).TransferOctantDictionary(root, ref root.OctantDictionary);//Transfer the dictionary to new root return newRoot; } private void TransferOctantDictionary(IDynamicOctree source, ref Dictionary<Guid, IDynamicOctree> dictionary) { if (source == this) { return; } this.OctantDictionary = dictionary; dictionary = null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RemoveFromRootDictionary(IDynamicOctree node, Guid guid) { node = FindRoot(node); var root = node as BoundableNodeOctree; if (root.OctantDictionary.ContainsKey(guid)) { root.OctantDictionary.Remove(guid); } } public override bool FindNearestPointBySphereExcludeChild(HitTestContext context, ref global::SharpDX.BoundingSphere sphere, ref List<HitTestResult> points, ref bool isIntersect) { throw new NotImplementedException(); } } } }
mit
ethaMont/3days
src/reducer.js
653
import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; // Reducers import { authReducer } from 'modules/auth'; import { firebaseReducer } from 'modules/firebase'; import { notificationReducer } from 'modules/notification'; import { tripsReducer } from 'modules/trips'; import { tripReducer } from 'modules/trip'; import { createTripModalReducer } from 'modules/create-trip'; export default combineReducers({ auth: authReducer, firebase: firebaseReducer, notification: notificationReducer, routing: routerReducer, trips: tripsReducer, trip: tripReducer, createTripModal: createTripModalReducer, });
mit
mcamis/drive.vote.driver
scripts/start.js
5316
process.env.NODE_ENV = 'development'; var path = require('path'); var chalk = require('chalk'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var execSync = require('child_process').execSync; var opn = require('opn'); var detect = require('./utils/detectPort'); var prompt = require('./utils/prompt'); var config = require('../config/webpack.config.dev'); // Tools like Cloud9 rely on this var DEFAULT_PORT = process.env.PORT || 3000; var compiler; // TODO: hide this behind a flag and eliminate dead code on eject. // This shouldn't be exposed to the user. var handleCompile; var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1); if (isSmokeTest) { handleCompile = function (err, stats) { if (err || stats.hasErrors() || stats.hasWarnings()) { process.exit(1); } else { process.exit(0); } }; } var friendlySyntaxErrorLabel = 'Syntax error:'; function isLikelyASyntaxError(message) { return message.indexOf(friendlySyntaxErrorLabel) !== -1; } // This is a little hacky. // It would be easier if webpack provided a rich error object. function formatMessage(message) { return message // Make some common errors shorter: .replace( // Babel syntax error 'Module build failed: SyntaxError:', friendlySyntaxErrorLabel ) .replace( // Webpack file not found error /Module not found: Error: Cannot resolve 'file' or 'directory'/, 'Module not found:' ) // Internal stacks are generally useless so we strip them .replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y // Webpack loader names obscure CSS filenames .replace('./~/css-loader!./~/postcss-loader!', ''); } function clearConsole() { process.stdout.write('\x1bc'); } function setupCompiler(port) { compiler = webpack(config, handleCompile); compiler.plugin('invalid', function() { clearConsole(); console.log('Compiling...'); }); compiler.plugin('done', function(stats) { clearConsole(); var hasErrors = stats.hasErrors(); var hasWarnings = stats.hasWarnings(); if (!hasErrors && !hasWarnings) { console.log(chalk.green('Compiled successfully!')); console.log(); console.log('The app is running at http://localhost:' + port + '/'); console.log(); return; } var json = stats.toJson(); var formattedErrors = json.errors.map(message => 'Error in ' + formatMessage(message) ); var formattedWarnings = json.warnings.map(message => 'Warning in ' + formatMessage(message) ); if (hasErrors) { console.log(chalk.red('Failed to compile.')); console.log(); if (formattedErrors.some(isLikelyASyntaxError)) { // If there are any syntax errors, show just them. // This prevents a confusing ESLint parsing error // preceding a much more useful Babel syntax error. formattedErrors = formattedErrors.filter(isLikelyASyntaxError); } formattedErrors.forEach(message => { console.log(message); console.log(); }); // If errors exist, ignore warnings. return; } if (hasWarnings) { console.log(chalk.yellow('Compiled with warnings.')); console.log(); formattedWarnings.forEach(message => { console.log(message); console.log(); }); console.log('You may use special comments to disable some warnings.'); console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.'); console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.'); } }); } function openBrowser(port) { if (process.platform === 'darwin') { try { // Try our best to reuse existing tab // on OS X Google Chrome with AppleScript execSync('ps cax | grep "Google Chrome"'); execSync( 'osascript ' + path.resolve(__dirname, './utils/chrome.applescript') + // TODO: Rails-specific environmant vars to control this ' http://localhost:3000/driving' // ' http://localhost:' + port + '/driving' ); return; } catch (err) { // Ignore errors. } } // Fallback to opn // (It will always open new tab) opn('http://localhost:' + port + '/'); } function runDevServer(port) { new WebpackDevServer(compiler, { historyApiFallback: true, hot: true, // Note: only CSS is currently hot reloaded publicPath: config.output.publicPath, quiet: true, watchOptions: { ignored: /node_modules/ } }).listen(port, (err, result) => { if (err) { return console.log(err); } clearConsole(); console.log(chalk.cyan('Starting the development server...')); console.log(); openBrowser(port); }); } function run(port) { setupCompiler(port); runDevServer(port); } detect(DEFAULT_PORT).then(port => { if (port === DEFAULT_PORT) { run(port); return; } clearConsole(); var question = chalk.yellow('Something is already running at port ' + DEFAULT_PORT + '.') + '\n\nWould you like to run the app at another port instead?'; prompt(question, true).then(shouldChangePort => { if (shouldChangePort) { run(port); } }); });
mit
chamerling/dockerhub2slack
Gruntfile.js
2714
'use strict'; module.exports = function(grunt) { var packageJSON = grunt.file.readJSON('package.json'); var CI = grunt.option('ci'); grunt.initConfig({ pkg: packageJSON, project: { lib: 'server', test: 'test', dist: 'dist', bin: 'bin', data: 'data', name: packageJSON.name }, babel: { options: { sourceMap: false, presets: ['es2015'], plugins: ['add-module-exports'] }, dist: { files: [ { expand: true, src: [ '<%= project.lib %>/**/*.js', '<%= project.bin %>/**/*.js', '<%= project.test %>/**/*.js' ], dest: '<%= project.dist %>/' } ] } }, jshint: { options: { jshintrc: '.jshintrc', reporter: CI && 'checkstyle', reporterOutput: CI && 'jshint.xml' }, all: { src: [ 'Gruntfile.js', '<%= project.test %>/**/*.js', '<%= project.lib %>/**/*.js', '<%= project.bin %>/**/*.js' ] } }, mochaTest: { test: { options: { reporter: 'spec', captureFile: 'results.txt', quiet: false, clearRequireCache: false }, src: ['<%= project.dist %>/test/**/*.js'] } }, watch: { files: ['<%= jshint.all.src %>'], tasks: ['test'] }, jscs: { lint: { options: { config: '.jscsrc', esnext: true }, src: ['<%= jshint.all.src %>'] }, fix: { options: { config: '.jscsrc', esnext: true, fix: true }, src: ['<%= jshint.all.src %>'] } }, lint_pattern: { options: { rules: [ { pattern: /(describe|it)\.only/, message: 'Must not use .only in tests' } ] }, all: { src: ['<%= jshint.all.src %>'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '<%= project.dist %>/*', '!<%= project.dist %>/.git*' ] }] } }, release: { options: { tagName: 'v<%= version %>' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('compile', 'Compile from ES6 to ES5', ['clean:dist', 'babel']); grunt.registerTask('linters', 'Check code for lint', ['jshint:all', 'jscs:lint', 'lint_pattern:all']); grunt.registerTask('package', 'Package module', ['clean:dist', 'linters', 'babel']); grunt.registerTask('default', ['package']); };
mit
blcktqq/ng-ui
src/typings.d.ts
131
/* SystemJS module definition */ declare var module: NodeModule; interface NodeModule { id: string; } declare var easyrtc: any;
mit
bramr/tor-exits
src/Parser/BlutMagieParser.php
864
<?php namespace BramR\TorExits\Parser; use BramR\TorExits\IpList; use Psr\Http\Message\StreamInterface; /** * Class BlutMagieParser */ class BlutMagieParser extends BaseParser { /** * {@inheritdoc} */ public function parse(StreamInterface $data = null) { $ips = explode("\n", $this->getStreamData($data)->getContents()); $ips = array_filter($ips, 'ip2long'); if (count($ips) < $this->getParseWarningThreshold()) { $this->logger->warning( 'Number of Tor exit nodes found when parsing is low.', ['exit-node-count' => count($ips)] ); } else { $this->logger->info( 'Tor exit nodes parsed from blutmagie.de', ['exit-node-count' => count($ips)] ); } return new IpList($ips); } }
mit
hillinworks/echoisles
Client/app/+examples/examples.routes.ts
1459
import { Routes, RouterModule } from '@angular/router'; import { ExamplesComponent } from './examples.component'; const routes: Routes = [ { path: '', component: ExamplesComponent, children: [ { path: 'animationexamples', loadChildren: './animations/animations.module#AnimationsModule' }, { path: 'reactiveforms', loadChildren: './reactive-forms/product.module#ReactiveFormsExampleModules' }, { path: 'components', loadChildren: './component/component-home.module#ComponentModule' }, { path: 'directives', loadChildren: './directives/directives.module#DirectivesModule' }, { path: 'uibootstrap', loadChildren: './uibootstrap/uibootstrap.module#UiBootstrapModule' }, { path: 'weather', loadChildren: './weather-search/weather.module#WeatherModule' }, { path: 'jquery', loadChildren: './jquery/jquery.module#JqueryModule' }, { path: 'googlemaps', loadChildren: './google-maps/google-maps.module#GoogleMapsModule' }, { path: 'texteditor', loadChildren: './text-editor/text-editor.module#TextEditorModule' }, { path: 'markdowneditor', loadChildren: './markdown-editor/markdown-editor.module#MarkdownEditorModule' }, { path: 'stripepayment', loadChildren: './stripe-payment/stripe-payment.module#StripePaymentModule' } ] }, ]; export const routing = RouterModule.forChild(routes);
mit
askl56/Challenges
Maths/Project Euler/05-Smallest-Multiple/solutions/askl56-lowest-common-multiple.rb
65
# Simplest way of doing it (1..20).inject(:lcm) # => 232792560
mit
danielgimenes/Sunshine
app/src/main/java/br/com/dgimenes/sunshine/DetailFragment.java
9949
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.dgimenes.sunshine; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.ShareActionProvider; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import br.com.dgimenes.sunshine.data.WeatherContract; /** * A placeholder fragment containing a simple view. */ public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String LOG_TAG = DetailFragment.class.getSimpleName(); static final String DETAIL_URI = "URI"; private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp"; private ShareActionProvider mShareActionProvider; private String mForecast; private Uri mUri; private static final int DETAIL_LOADER = 0; private static final String[] DETAIL_COLUMNS = { WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID, WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, WeatherContract.WeatherEntry.COLUMN_HUMIDITY, WeatherContract.WeatherEntry.COLUMN_PRESSURE, WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, WeatherContract.WeatherEntry.COLUMN_DEGREES, WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, // This works because the WeatherProvider returns location data joined with // weather data, even though they're stored in two different tables. WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING }; // These indices are tied to DETAIL_COLUMNS. If DETAIL_COLUMNS changes, these // must change. public static final int COL_WEATHER_ID = 0; public static final int COL_WEATHER_DATE = 1; public static final int COL_WEATHER_DESC = 2; public static final int COL_WEATHER_MAX_TEMP = 3; public static final int COL_WEATHER_MIN_TEMP = 4; public static final int COL_WEATHER_HUMIDITY = 5; public static final int COL_WEATHER_PRESSURE = 6; public static final int COL_WEATHER_WIND_SPEED = 7; public static final int COL_WEATHER_DEGREES = 8; public static final int COL_WEATHER_CONDITION_ID = 9; private ImageView mIconView; private TextView mFriendlyDateView; private TextView mDateView; private TextView mDescriptionView; private TextView mHighTempView; private TextView mLowTempView; private TextView mHumidityView; private TextView mWindView; private TextView mPressureView; public DetailFragment() { setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle arguments = getArguments(); if (arguments != null) { mUri = arguments.getParcelable(DetailFragment.DETAIL_URI); } View rootView = inflater.inflate(R.layout.fragment_detail, container, false); mIconView = (ImageView) rootView.findViewById(R.id.forecast_icon); mDateView = (TextView) rootView.findViewById(R.id.date_view); mFriendlyDateView = (TextView) rootView.findViewById(R.id.friendly_date_view); mDescriptionView = (TextView) rootView.findViewById(R.id.forecast_view); mHighTempView = (TextView) rootView.findViewById(R.id.max_temp_view); mLowTempView = (TextView) rootView.findViewById(R.id.min_temp_view); mHumidityView = (TextView) rootView.findViewById(R.id.humidity_view); mWindView = (TextView) rootView.findViewById(R.id.wind_view); mPressureView = (TextView) rootView.findViewById(R.id.pressure_view); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.detailfragment, menu); // Retrieve the share menu item MenuItem menuItem = menu.findItem(R.id.action_share); // Get the provider and hold onto it to set/change the share intent. mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem); // If onLoadFinished happens before this, we can go ahead and set the share intent now. if (mForecast != null) { mShareActionProvider.setShareIntent(createShareForecastIntent()); } } private Intent createShareForecastIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG); return shareIntent; } @Override public void onActivityCreated(Bundle savedInstanceState) { getLoaderManager().initLoader(DETAIL_LOADER, null, this); super.onActivityCreated(savedInstanceState); } void onLocationChanged( String newLocation ) { // replace the uri, since the location has changed Uri uri = mUri; if (null != uri) { long date = WeatherContract.WeatherEntry.getDateFromUri(uri); Uri updatedUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(newLocation, date); mUri = updatedUri; getLoaderManager().restartLoader(DETAIL_LOADER, null, this); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if ( null != mUri ) { // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. return new CursorLoader( getActivity(), mUri, DETAIL_COLUMNS, null, null, null ); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { // Read weather condition ID from cursor int weatherId = data.getInt(COL_WEATHER_CONDITION_ID); // Use weather art image mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId)); // Read date from cursor and update views for day of week and date long date = data.getLong(COL_WEATHER_DATE); String friendlyDateText = Utility.getDayName(getActivity(), date); String dateText = Utility.getFormattedMonthDay(getActivity(), date); mFriendlyDateView.setText(friendlyDateText); mDateView.setText(dateText); // Read description from cursor and update view String description = data.getString(COL_WEATHER_DESC); mDescriptionView.setText(description); // Read high temperature from cursor and update view boolean isMetric = Utility.isMetric(getActivity()); double high = data.getDouble(COL_WEATHER_MAX_TEMP); String highString = Utility.formatTemperature(getActivity(), high, isMetric); mHighTempView.setText(highString); // Read low temperature from cursor and update view double low = data.getDouble(COL_WEATHER_MIN_TEMP); String lowString = Utility.formatTemperature(getActivity(), low, isMetric); mLowTempView.setText(lowString); // Read humidity from cursor and update view float humidity = data.getFloat(COL_WEATHER_HUMIDITY); mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity)); // Read wind speed and direction from cursor and update view float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED); float windDirStr = data.getFloat(COL_WEATHER_DEGREES); mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr)); // Read pressure from cursor and update view float pressure = data.getFloat(COL_WEATHER_PRESSURE); mPressureView.setText(getActivity().getString(R.string.format_pressure, pressure)); // We still need this for the share intent mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low); // If onCreateOptionsMenu has already happened, we need to update the share intent now. if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(createShareForecastIntent()); } } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
mit
jnunemaker/bin
lib/bin.rb
86
require 'active_support/cache/bin' module Bin Store = ActiveSupport::Cache::Bin end
mit
avalax/FitBuddy
src/main/java/de/avalax/fitbuddy/domain/model/finished_workout/BasicFinishedWorkout.java
1968
package de.avalax.fitbuddy.domain.model.finished_workout; import java.util.List; import de.avalax.fitbuddy.domain.model.finished_exercise.FinishedExercise; import de.avalax.fitbuddy.domain.model.workout.WorkoutId; public class BasicFinishedWorkout implements FinishedWorkout { private FinishedWorkoutId finishedWorkoutId; private WorkoutId workoutId; private String workoutName; private Long created; private List<FinishedExercise> finishedExercises; public BasicFinishedWorkout( FinishedWorkoutId finishedWorkoutId, WorkoutId workoutId, String workoutName, Long created, List<FinishedExercise> finishedExercises) { this.finishedWorkoutId = finishedWorkoutId; this.workoutId = workoutId; this.workoutName = workoutName; this.created = created; this.finishedExercises = finishedExercises; } @Override public FinishedWorkoutId getFinishedWorkoutId() { return finishedWorkoutId; } @Override public Long getCreated() { return created; } @Override public List<FinishedExercise> getFinishedExercises() { return finishedExercises; } @Override public WorkoutId getWorkoutId() { return workoutId; } @Override public String getName() { return workoutName; } @Override public String toString() { return "BasicFinishedWorkout [name=" + workoutName + ", finishedWorkoutId=" + finishedWorkoutId.toString() + ", workoutId=" + workoutId.toString() + ", created=" + created + "]"; } @Override public boolean equals(Object obj) { return obj instanceof FinishedWorkout && finishedWorkoutId.equals(((FinishedWorkout) obj).getFinishedWorkoutId()); } @Override public int hashCode() { return finishedWorkoutId.hashCode(); } }
mit
kambojajs/kamboja
packages/moringa/test/type-converter/models/models.ts
439
import { val, type } from "kamboja-foundation" import { mongoose } from "../../../src" @mongoose.shortid() export class ShortModel { @type("string") name:string } export class DefaultIdModel{ @type("string") name:string } export class ParentModel { @type("string") name:string @type("ShortModel, models/models") short:ShortModel @type("DefaultIdModel, models/models") defaultId:DefaultIdModel }
mit
jglrxavpok/0xC1
src/main/java/org/c1/client/gui/editor/ShipEditorComponent.java
854
package org.c1.client.gui.editor; import org.c1.client.render.*; import org.c1.maths.Vec2f; import org.c1.utils.CardinalDirection; public abstract class ShipEditorComponent { private Vec2f pos; protected Vec2f size; public ShipEditorComponent(float x, float y) { pos = new Vec2f(x,y); size = new Vec2f(1,1); } public abstract void render(double delta, RenderEngine engine); public abstract void update(double delta); public abstract int getWidth(); public abstract int getHeight(); public abstract CardinalDirection getDirection(); public abstract void setDirection(CardinalDirection dir); public void rotate() { setDirection(getDirection().next()); } public Vec2f getPos() { return pos; } public Vec2f getSize() { return size; } }
mit
ManuelRauber/ShortUrl
ShortUrl/Controllers/UrlController.cs
1939
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Caching; using System.Web.Http; using ShortUrl.Common; using Microsoft.SqlServer.Server; using ShortUrl.Model; using ShortUrl.Services.Contracts; namespace ShortUrl.Controllers { public class UrlController : ApiController { private readonly IUrlService _urlService; private static readonly string _baseUrlConfigurationName = "BaseUrl"; private static readonly string _baseUrl; static UrlController() { _baseUrl = ConfigurationManager.AppSettings[_baseUrlConfigurationName]; if (String.IsNullOrWhiteSpace(_baseUrl)) { throw new ConfigurationErrorsException("BaseUrl is not set!"); } } public UrlController(IUrlService urlService) { _urlService = urlService; } [HttpGet] public string Add(string longUrl, DateTime? expirationDate = null) { if (String.IsNullOrWhiteSpace(longUrl)) { return null; } var url = _urlService.Add(longUrl, expirationDate); return FormatUrl(url); } [HttpGet] public string Add(string longUrl, string timeString) { if (String.IsNullOrWhiteSpace(longUrl)) { return null; } var url = _urlService.Add(longUrl, timeString); return FormatUrl(url); } [HttpGet] public object Get(string id) { return Get(id, false); } [HttpGet] public object Get(string id, bool verbose) { var url = _urlService.Get(id); if (null == url) { throw new HttpResponseException(HttpStatusCode.NotFound); } if (verbose) { return url; } var message = Request.CreateResponse(HttpStatusCode.Redirect); message.Headers.Location = new Uri(url.LongUrl); return message; } private string FormatUrl(Url url) { if (url == null) { return String.Empty; } return String.Format("{0}{1}", _baseUrl, url.Id); } } }
mit
dmemoing/app-fronted
app/js/components/version/version-directive.js
198
'use strict'; angular.module('sher.version.version-directive', []) .directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]);
mit
erykpiast/appetite
node_modules/express/node_modules/stylus/node_modules/cssom/node_modules/jake/lib/utils/index.js
7851
/* * Jake JavaScript build tool * Copyright 2112 Matthew Eernisse (mde@fleegix.org) * * 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. * */ var exec = require('child_process').exec , spawn = require('child_process').spawn , EventEmitter = require('events').EventEmitter , fileUtils = require('./file') , utils , Exec , _mix, _trim, _truncate; _mix = function (targ, src, merge, includeProto) { for (var p in src) { // Don't copy stuff from the prototype if (src.hasOwnProperty(p) || includeProto) { if (merge && // Assumes the source property is an Object you can // actually recurse down into (typeof src[p] == 'object') && (src[p] !== null) && !(src[p] instanceof Array)) { // Create the source property if it doesn't exist // TODO: What if it's something weird like a String or Number? if (typeof targ[p] == 'undefined') { targ[p] = {}; } _mix(targ[p], src[p], merge, includeProto); // Recurse } // If it's not a merge-copy, just set and forget else { targ[p] = src[p]; } } } }; _trim = function (s) { var str = s || ''; return str.replace(/^\s*|\s*$/g, ''); }; _truncate = function (s) { var str = s ? s.replace(/\n$/, '') : ''; return str; }; /** @name jake @namespace jake */ utils = new (function () { /** @name jake.exec @static @function @description Executes shell-commands asynchronously with an optional final callback. ` @param {String[]} cmds The list of shell-commands to execute @param {Function} [callback] Callback to run after executing the commands @param {Object} [opts] @param {Boolean} [opts.stdout=false] Print stdout from each command @param {Boolean} [opts.stderr=false] Print stderr from each command @param {Boolean} [opts.breakOnError=true] Stop further execution on the first error. @example var cmds = [ 'echo "showing directories"' , 'ls -al | grep ^d' , 'echo "moving up a directory"' , 'cd ../' ] , callback = function () { console.log('Finished running commands.'); } jake.exec(cmds, callback, {stdout: true}); */ this.exec = function (a, b, c) { var ex = new Exec(a, b, c); ex.addListener('error', function (msg, code) { if (ex._config.breakOnError) { fail(msg, code); } }); ex.run(); }; this.createExec = function (a, b, c) { return new Exec(a, b, c); }; this.objectToString = function (object) { var objectArray = []; for (var key in object) { if ('object' == typeof object[key]) { objectArray.push(this.objectToString(object[key])); } else { objectArray.push(key + '=' + object[key]); } } return objectArray.join(', '); }; /* * Mix in the properties on an object to another object * yam.mixin(target, source, [source,] [source, etc.] [merge-flag]); * 'merge' recurses, to merge object sub-properties together instead * of just overwriting with the source object. */ this.mixin = (function () { return function () { var args = Array.prototype.slice.apply(arguments), merge = false, targ, sources; if (args.length > 2) { if (typeof args[args.length - 1] == 'boolean') { merge = args.pop(); } } targ = args.shift(); sources = args; for (var i = 0, ii = sources.length; i < ii; i++) { _mix(targ, sources[i], merge); } return targ; }; }).call(this); this.enhance = (function () { return function () { var args = Array.prototype.slice.apply(arguments), merge = false, targ, sources; if (args.length > 2) { if (typeof args[args.length - 1] == 'boolean') { merge = args.pop(); } } targ = args.shift(); sources = args; for (var i = 0, ii = sources.length; i < ii; i++) { _mix(targ, sources[i], merge, true); } return targ; }; }).call(this); })(); Exec = function () { var args , arg , cmds , callback , opts = {}; args = Array.prototype.slice.call(arguments); cmds = args.shift(); // Arrayize if passed a single string command if (typeof cmds == 'string') { cmds = [cmds]; } // Make a copy if it's an actual list else { cmds = cmds.slice(); } // Get optional callback or opts while((arg = args.shift())) { if (typeof arg == 'function') { callback = arg; } else if (typeof arg == 'object') { opts = arg; } } // Backward-compat shim if (typeof opts.stdout != 'undefined') { opts.printStdout = opts.stdout; } if (typeof opts.stderr != 'undefined') { opts.printStderr = opts.stderr; } this._cmds = cmds; this._callback = callback; this._config = { printStdout: false , printStderr: false , breakOnError: true }; utils.mixin(this._config, opts); }; Exec.prototype = new EventEmitter(); Exec.prototype.constructor = Exec; utils.mixin(Exec.prototype, new (function () { var _run = function () { var self = this , sh , cmd , args , next = this._cmds.shift() , config = this._config , errData = ''; // Keep running as long as there are commands in the array if (next) { this.emit('cmdStart', next); // Ganking part of Node's child_process.exec to get cmdline args parsed cmd = '/bin/sh'; args = ['-c', next]; if (process.platform == 'win32') { cmd = 'cmd'; args = ['/c', next]; } // Spawn a child-process, set up output sh = spawn(cmd, args); // Out sh.stdout.on('data', function (data) { if (config.printStdout) { console.log(_truncate(data.toString())); } self.emit('stdout', data); }); // Err sh.stderr.on('data', function (data) { var d = data.toString(); if (config.printStderr) { console.error(_truncate(d)); } self.emit('stderr', data); // Accumulate the error-data so we can use it as the // stack if the process exits with an error errData += d; }); // Exit, handle err or run next sh.on('exit', function (code) { var msg; if (code != 0) { msg = errData || 'Process exited with error.'; msg = _trim(msg); self.emit('error', msg, code); } if (code == 0 || !config.breakOnError) { self.emit('cmdEnd', next); _run.call(self); } }); } else { self.emit('end'); if (typeof self._callback == 'function') { self._callback(); } } }; this.append = function (cmd) { this._cmds.push(cmd); }; this.run = function () { _run.call(this); }; })()); utils.Exec = Exec; // Hang all the file utils off this too utils.mixin(utils, fileUtils); module.exports = utils;
mit
twinone/rubik-web
assets/vendor/cubejs/async.js
2133
// Generated by CoffeeScript 1.10.0 (function() { var Cube, Extend, Include, key, value; Cube = this.Cube || require('./cube'); Extend = { asyncOK: !!window.Worker, _asyncSetup: function(workerURI) { if (this._worker) { return; } this._worker = new window.Worker(workerURI); this._worker.addEventListener('message', (function(_this) { return function() { return _this._asyncEvent.apply(_this, arguments); }; })(this)); return this._asyncCallbacks = {}; }, _asyncEvent: function(e) { var callback, callbacks; callbacks = this._asyncCallbacks[e.data.cmd]; if (!(callbacks && callbacks.length)) { return; } callback = callbacks[0]; callbacks.splice(0, 1); return callback(e.data); }, _asyncCallback: function(cmd, callback) { var base; (base = this._asyncCallbacks)[cmd] || (base[cmd] = []); return this._asyncCallbacks[cmd].push(callback); }, asyncInit: function(workerURI, callback) { this._asyncSetup(workerURI); this._asyncCallback('init', function() { return callback(); }); return this._worker.postMessage({ cmd: 'init' }); }, _asyncSolve: function(cube, callback) { this._asyncSetup(); this._asyncCallback('solve', function(data) { return callback(data.algorithm); }); return this._worker.postMessage({ cmd: 'solve', cube: cube.toJSON() }); }, asyncScramble: function(callback) { this._asyncSetup(); this._asyncCallback('solve', function(data) { return callback(Cube.inverse(data.algorithm)); }); return this._worker.postMessage({ cmd: 'solve', cube: Cube.random().toJSON() }); } }; Include = { asyncSolve: function(callback) { return Cube._asyncSolve(this, callback); } }; for (key in Extend) { value = Extend[key]; Cube[key] = value; } for (key in Include) { value = Include[key]; Cube.prototype[key] = value; } }).call(this);
mit
crestonbunch/godata
count_parser.go
234
package godata import ( "strconv" ) func ParseCountString(count string) (*GoDataCountQuery, error) { i, err := strconv.ParseBool(count) if err != nil { return nil, err } result := GoDataCountQuery(i) return &result, nil }
mit
davidezordan/MixedRealitySamples
Oculus Demo/Assets/Oculus/Platform/Scripts/MicrophoneInputNative.cs
1355
//This file is deprecated. Use the high level voip system instead: // https://developer.oculus.com/documentation/platform/latest/concepts/dg-cc-voip/ #if OVR_PLATFORM_USE_MICROPHONE using UnityEngine; using System; using System.Collections.Generic; namespace Oculus.Platform { public class MicrophoneInputNative : IMicrophone { IntPtr mic; int tempBufferSize = 960 * 10; float[] tempBuffer; private Dictionary<int, float[]> micSampleBuffers; public MicrophoneInputNative() { mic = CAPI.ovr_Microphone_Create(); CAPI.ovr_Microphone_Start(mic); tempBuffer = new float[tempBufferSize]; micSampleBuffers = new Dictionary<int, float[]>(); } public float[] Update() { ulong readSize = (ulong)CAPI.ovr_Microphone_ReadData(mic, tempBuffer, (UIntPtr)tempBufferSize); if (readSize > 0) { float[] samples; if (!micSampleBuffers.TryGetValue((int)readSize, out samples)) { samples = new float[readSize]; micSampleBuffers[(int)readSize] = samples; } Array.Copy(tempBuffer, samples, (int)readSize); return samples; } return null; } public void Start() { } public void Stop() { CAPI.ovr_Microphone_Stop(mic); CAPI.ovr_Microphone_Destroy(mic); } } } #endif
mit
yogeshsaroya/new-cdnjs
ajax/libs/tinymce/3.5.8/plugins/xhtmlxtras/js/acronym.min.js
128
version https://git-lfs.github.com/spec/v1 oid sha256:fb0c7bfaa3bc37b821fcb6a7307d169622894bafa5f508e9dc524e2108185848 size 281
mit
maxim-kuzmin/Makc2016
Makc2016.Modules.AspNetIdentity/Operations/Account/ModuleAspNetIdentityOperationAccountHasBeenVerified.cs
1112
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin // Author: Maxim Kuzmin using Makc2016.Core.Execution.Operations.Async; using Makc2016.Modules.AspNetIdentity.Managers; using System; using System.Threading.Tasks; namespace Makc2016.Modules.AspNetIdentity.Operations.Account { public class ModuleAspNetIdentityOperationAccountHasBeenVerified : CoreExecutionOperationAsyncWithInputAndOutputData < ModuleAspNetIdentityManagerSignIn, bool > { #region Constructors /// <summary> /// Конструктор. /// </summary> /// <param name="executableFunction">Выполняемая функция.</param> public ModuleAspNetIdentityOperationAccountHasBeenVerified( Func<ModuleAspNetIdentityManagerSignIn, Task<bool>> executableFunction ) : base( executableFunction, null, null, null, null ) { } #endregion Constructors } }
mit
DusanKasan/Knapsack
tests/scenarios/CallableFuctionNamesTest.php
587
<?php namespace DusanKasan\Knapsack\Tests\Scenarios; use DusanKasan\Knapsack\Collection; use PHPUnit_Framework_TestCase; class CallableFunctionNamesTest extends PHPUnit_Framework_TestCase { /** * Example that it's possible to use callable function names as arguments. */ public function testIt() { $result = Collection::from([2, 1]) ->concat([3, 4]) ->sort('\DusanKasan\Knapsack\compare') ->values() ->toArray(); $expected = [1, 2, 3, 4]; $this->assertEquals($expected, $result); } }
mit
Lemma1/MAC-POSTS
src/3rdparty/g3log/time.cpp
2970
/** ========================================================================== * 2012 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include "g3log/time.hpp" #include <sstream> #include <string> #include <chrono> #include <cassert> #include <iomanip> namespace g3 { namespace internal { // This mimics the original "std::put_time(const std::tm* tmb, const charT* fmt)" // This is needed since latest version (at time of writing) of gcc4.7 does not implement this library function yet. // return value is SIMPLIFIED to only return a std::string std::string put_time(const struct tm *tmb, const char *c_time_format) { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) std::ostringstream oss; oss.fill('0'); // BOGUS hack done for VS2012: C++11 non-conformant since it SHOULD take a "const struct tm* " oss << std::put_time(const_cast<struct tm *> (tmb), c_time_format); return oss.str(); #else // LINUX const size_t size = 1024; char buffer[size]; // IMPORTANT: check now and then for when gcc will implement std::put_time. // ... also ... This is way more buffer space then we need auto success = std::strftime(buffer, size, c_time_format, tmb); if (0 == success) { assert((0 != success) && "strftime fails with illegal formatting"); return c_time_format; } return buffer; #endif } } // internal } // g3 namespace g3 { std::time_t systemtime_now() { system_time_point system_now = std::chrono::system_clock::now(); return std::chrono::system_clock::to_time_t(system_now); } tm localtime(const std::time_t &time) { struct tm tm_snapshot; #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) && !defined(__GNUC__)) localtime_s(&tm_snapshot, &time); // windsows #else localtime_r(&time, &tm_snapshot); // POSIX #endif return tm_snapshot; } /// returns a std::string with content of time_t as localtime formatted by input format string /// * format string must conform to std::put_time /// This is similar to std::put_time(std::localtime(std::time_t*), time_format.c_str()); std::string localtime_formatted(const std::time_t &time_snapshot, const std::string &time_format) { std::tm t = localtime(time_snapshot); // could be const, but cannot due to VS2012 is non conformant for C++11's std::put_time (see above) return g3::internal::put_time(&t, time_format.c_str()); // format example: //"%Y/%m/%d %H:%M:%S"); } } // g3
mit
Tonodus/GlowSponge
src/main/java/net/glowstone/data/type/GlowProfession.java
459
package net.glowstone.data.type; import net.glowstone.GlowCatalogType; import org.spongepowered.api.data.type.Profession; import org.spongepowered.api.text.translation.Translation; public class GlowProfession extends GlowCatalogType implements Profession { public GlowProfession(String id, String name, int numericalId) { super(id, name, numericalId); } @Override public Translation getTranslation() { return null; } }
mit
AsrOneSdk/azure-sdk-for-net
sdk/avs/Microsoft.Azure.Management.Avs/src/Generated/IAuthorizationsOperations.cs
10369
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Avs { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// AuthorizationsOperations operations. /// </summary> public partial interface IAuthorizationsOperations { /// <summary> /// List ExpressRoute Circuit Authorizations in a private cloud /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// Name of the private cloud /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ExpressRouteAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string privateCloudName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an ExpressRoute Circuit Authorization by name in a private /// cloud /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// Name of the private cloud /// </param> /// <param name='authorizationName'> /// Name of the ExpressRoute Circuit Authorization in the private cloud /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ExpressRouteAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string privateCloudName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update an ExpressRoute Circuit Authorization in a private /// cloud /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// The name of the private cloud. /// </param> /// <param name='authorizationName'> /// Name of the ExpressRoute Circuit Authorization in the private cloud /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ExpressRouteAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string privateCloudName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an ExpressRoute Circuit Authorization in a private cloud /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// Name of the private cloud /// </param> /// <param name='authorizationName'> /// Name of the ExpressRoute Circuit Authorization in the private cloud /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string privateCloudName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update an ExpressRoute Circuit Authorization in a private /// cloud /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// The name of the private cloud. /// </param> /// <param name='authorizationName'> /// Name of the ExpressRoute Circuit Authorization in the private cloud /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ExpressRouteAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string privateCloudName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an ExpressRoute Circuit Authorization in a private cloud /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// Name of the private cloud /// </param> /// <param name='authorizationName'> /// Name of the ExpressRoute Circuit Authorization in the private cloud /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string privateCloudName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List ExpressRoute Circuit Authorizations in a private cloud /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ExpressRouteAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
mit
McJty/XNet
src/main/java/mcjty/xnet/apiimpl/items/ItemChannelSettings.java
23279
package mcjty.xnet.apiimpl.items; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import mcjty.lib.varia.WorldTools; import mcjty.xnet.XNet; import mcjty.xnet.api.channels.IChannelSettings; import mcjty.xnet.api.channels.IConnectorSettings; import mcjty.xnet.api.channels.IControllerContext; import mcjty.xnet.api.gui.IEditorGui; import mcjty.xnet.api.gui.IndicatorIcon; import mcjty.xnet.api.helper.DefaultChannelSettings; import mcjty.xnet.apiimpl.EnumStringTranslators; import mcjty.xnet.api.keys.ConsumerId; import mcjty.xnet.api.keys.SidedConsumer; import mcjty.xnet.compat.RFToolsSupport; import mcjty.xnet.config.ConfigSetup; import mcjty.xnet.setup.ModSetup; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.wrapper.InvWrapper; import net.minecraftforge.items.wrapper.SidedInvWrapper; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.function.Predicate; public class ItemChannelSettings extends DefaultChannelSettings implements IChannelSettings { public static final ResourceLocation iconGuiElements = new ResourceLocation(XNet.MODID, "textures/gui/guielements.png"); public static final String TAG_MODE = "mode"; // Cache data private Map<SidedConsumer, ItemConnectorSettings> itemExtractors = null; private List<Pair<SidedConsumer, ItemConnectorSettings>> itemConsumers = null; public enum ChannelMode { PRIORITY, ROUNDROBIN } private ChannelMode channelMode = ChannelMode.PRIORITY; private int delay = 0; private int roundRobinOffset = 0; private Map<ConsumerId, Integer> extractIndices = new HashMap<>(); public ChannelMode getChannelMode() { return channelMode; } @Override public int getColors() { return 0; } @Override public JsonObject writeToJson() { JsonObject object = new JsonObject(); object.add("mode", new JsonPrimitive(channelMode.name())); return object; } @Override public void readFromJson(JsonObject data) { channelMode = EnumStringTranslators.getItemChannelMode(data.get("mode").getAsString()); } @Override public void readFromNBT(NBTTagCompound tag) { channelMode = ChannelMode.values()[tag.getByte("mode")]; delay = tag.getInteger("delay"); roundRobinOffset = tag.getInteger("offset"); int[] cons = tag.getIntArray("extidx"); for (int idx = 0 ; idx < cons.length ; idx += 2) { extractIndices.put(new ConsumerId(cons[idx]), cons[idx+1]); } } @Override public void writeToNBT(NBTTagCompound tag) { tag.setByte("mode", (byte) channelMode.ordinal()); tag.setInteger("delay", delay); tag.setInteger("offset", roundRobinOffset); if (!extractIndices.isEmpty()) { int[] cons = new int[extractIndices.size() * 2]; int idx = 0; for (Map.Entry<ConsumerId, Integer> entry : extractIndices.entrySet()) { cons[idx++] = entry.getKey().getId(); cons[idx++] = entry.getValue(); } tag.setIntArray("extidx", cons); } } private int getExtractIndex(ConsumerId consumer) { return extractIndices.getOrDefault(consumer, 0); } private void rememberExtractIndex(ConsumerId consumer, int index) { extractIndices.put(consumer, index); } private static class MInteger { private int i; public MInteger(int i) { this.i = i; } // This can return an index out of bounds! public int get() { return i; } // Safe get that is always in bounds public int getSafe(int bounds) { return bounds <= 0 ? i : (i % bounds); } public void set(int i) { this.i = i; } public void inc() { i++; } } private static Random random = new Random(); @Override public void tick(int channel, IControllerContext context) { delay--; if (delay <= 0) { delay = 200*6; // Multiply of the different speeds we have } if (delay % 5 != 0) { return; } int d = delay/5; updateCache(channel, context); World world = context.getControllerWorld(); for (Map.Entry<SidedConsumer, ItemConnectorSettings> entry : itemExtractors.entrySet()) { ItemConnectorSettings settings = entry.getValue(); if (d % settings.getSpeed() != 0) { continue; } ConsumerId consumerId = entry.getKey().getConsumerId(); BlockPos extractorPos = context.findConsumerPosition(consumerId); if (extractorPos != null) { EnumFacing side = entry.getKey().getSide(); BlockPos pos = extractorPos.offset(side); if (!WorldTools.chunkLoaded(world, pos)) { continue; } if (checkRedstone(world, settings, extractorPos)) { continue; } if (!context.matchColor(settings.getColorsMask())) { continue; } TileEntity te = world.getTileEntity(pos); if (ModSetup.rftools && RFToolsSupport.isStorageScanner(te)) { RFToolsSupport.tickStorageScanner(context, settings, te, this); } else { IItemHandler handler = getItemHandlerAt(te, settings.getFacing()); if (handler != null) { int idx = getStartExtractIndex(settings, consumerId, handler); idx = tickItemHandler(context, settings, handler, idx); if (handler.getSlots() > 0) { rememberExtractIndex(consumerId, (idx + 1) % handler.getSlots()); } } } } } } private int getStartExtractIndex(ItemConnectorSettings settings, ConsumerId consumerId, IItemHandler handler) { switch (settings.getExtractMode()) { case FIRST: return 0; case RND: { if (handler.getSlots() <= 0) { return 0; } // Try 5 times to find a non empty slot for (int i = 0 ; i < 5 ; i++) { int idx = random.nextInt(handler.getSlots()); if (!handler.getStackInSlot(idx).isEmpty()) { return idx; } } // Otherwise use a more complicated algorithm List<Integer> slots = new ArrayList<>(); for (int i = 0 ; i < handler.getSlots() ; i++) { if (!handler.getStackInSlot(i).isEmpty()) { slots.add(i); } } if (slots.isEmpty()) { return 0; } return slots.get(random.nextInt(slots.size())); } case ORDER: return getExtractIndex(consumerId); } return 0; } private int tickItemHandler(IControllerContext context, ItemConnectorSettings settings, IItemHandler handler, int startIdx) { Predicate<ItemStack> extractMatcher = settings.getMatcher(); Integer count = settings.getCount(); int amount = 0; if (count != null) { amount = countItems(handler, extractMatcher); if (amount < count) { return startIdx; } } MInteger index = new MInteger(startIdx); while (true) { ItemStack stack = fetchItem(handler, true, extractMatcher, settings.getStackMode(), settings.getExtractAmount(), 64, index, startIdx); if (!stack.isEmpty()) { // Now that we have a stack we first reduce the amount of the stack if we want to keep a certain // number of items int toextract = stack.getCount(); if (count != null) { int canextract = amount-count; if (canextract <= 0) { index.inc(); continue; } if (canextract < toextract) { toextract = canextract; stack = stack.copy(); stack.setCount(toextract); } } List<Pair<SidedConsumer, ItemConnectorSettings>> inserted = new ArrayList<>(); int remaining = insertStackSimulate(inserted, context, stack); if (!inserted.isEmpty()) { if (context.checkAndConsumeRF(ConfigSetup.controllerOperationRFT.get())) { insertStackReal(context, inserted, fetchItem(handler, false, extractMatcher, settings.getStackMode(), settings.getExtractAmount(), toextract-remaining, index, startIdx)); } break; } else { index.inc(); } } else { break; } } return index.getSafe(handler.getSlots()); } // Returns what could not be inserted public int insertStackSimulate(@Nonnull List<Pair<SidedConsumer, ItemConnectorSettings>> inserted, @Nonnull IControllerContext context, @Nonnull ItemStack stack) { World world = context.getControllerWorld(); if (channelMode == ChannelMode.PRIORITY) { roundRobinOffset = 0; // Always start at 0 } int total = stack.getCount(); for (int j = 0 ; j < itemConsumers.size() ; j++) { int i = (j + roundRobinOffset) % itemConsumers.size(); Pair<SidedConsumer, ItemConnectorSettings> entry = itemConsumers.get(i); ItemConnectorSettings settings = entry.getValue(); if (settings.getMatcher().test(stack)) { BlockPos consumerPos = context.findConsumerPosition(entry.getKey().getConsumerId()); if (consumerPos != null) { if (!WorldTools.chunkLoaded(world, consumerPos)) { continue; } if (checkRedstone(world, settings, consumerPos)) { continue; } if (!context.matchColor(settings.getColorsMask())) { continue; } EnumFacing side = entry.getKey().getSide(); BlockPos pos = consumerPos.offset(side); TileEntity te = world.getTileEntity(pos); int actuallyinserted; int toinsert = total; ItemStack remaining; Integer count = settings.getCount(); if (ModSetup.rftools && RFToolsSupport.isStorageScanner(te)) { if (count != null) { int amount = RFToolsSupport.countItems(te, settings.getMatcher(), count); int caninsert = count - amount; if (caninsert <= 0) { continue; } toinsert = Math.min(toinsert, caninsert); stack = stack.copy(); if (toinsert <= 0) { stack.setCount(0); } else { stack.setCount(toinsert); } } remaining = RFToolsSupport.insertItem(te, stack, true); } else { IItemHandler handler = getItemHandlerAt(te, settings.getFacing()); if (handler != null) { if (count != null) { int amount = countItems(handler, settings.getMatcher()); int caninsert = count - amount; if (caninsert <= 0) { continue; } toinsert = Math.min(toinsert, caninsert); stack = stack.copy(); if (toinsert <= 0) { stack.setCount(0); } else { stack.setCount(toinsert); } } remaining = ItemHandlerHelper.insertItem(handler, stack, true); } else { continue; } } actuallyinserted = toinsert - remaining.getCount(); if (count == null) { // If we are not using a count then we restore 'stack' here as that is what // we actually have to keep inserting until it is empty. If we are using a count // then we don't do this as we don't want to risk stack getting null (on 1.10.2) // from the insertItem() and then not being able to set stacksize a few lines // above this stack = remaining; } if (actuallyinserted > 0) { inserted.add(entry); total -= actuallyinserted; if (total <= 0) { return 0; } } } } } return total; } public void insertStackReal(@Nonnull IControllerContext context, @Nonnull List<Pair<SidedConsumer, ItemConnectorSettings>> inserted, @Nonnull ItemStack stack) { int total = stack.getCount(); for (Pair<SidedConsumer, ItemConnectorSettings> entry : inserted) { BlockPos consumerPosition = context.findConsumerPosition(entry.getKey().getConsumerId()); EnumFacing side = entry.getKey().getSide(); ItemConnectorSettings settings = entry.getValue(); BlockPos pos = consumerPosition.offset(side); TileEntity te = context.getControllerWorld().getTileEntity(pos); if (ModSetup.rftools && RFToolsSupport.isStorageScanner(te)) { int toinsert = total; Integer count = settings.getCount(); if (count != null) { int amount = RFToolsSupport.countItems(te, settings.getMatcher(), count); int caninsert = count - amount; if (caninsert <= 0) { continue; } toinsert = Math.min(toinsert, caninsert); stack = stack.copy(); if (toinsert <= 0) { stack.setCount(0); } else { stack.setCount(toinsert); } } ItemStack remaining = RFToolsSupport.insertItem(te, stack, false); int actuallyinserted = toinsert - remaining.getCount(); if (count == null) { // If we are not using a count then we restore 'stack' here as that is what // we actually have to keep inserting until it is empty. If we are using a count // then we don't do this as we don't want to risk stack getting null (on 1.10.2) // from the insertItem() and then not being able to set stacksize a few lines // above this stack = remaining; } if (actuallyinserted > 0) { roundRobinOffset = (roundRobinOffset + 1) % itemConsumers.size(); total -= actuallyinserted; if (total <= 0) { return; } } } else { IItemHandler handler = getItemHandlerAt(te, settings.getFacing()); int toinsert = total; Integer count = settings.getCount(); if (count != null) { int amount = countItems(handler, settings.getMatcher()); int caninsert = count - amount; if (caninsert <= 0) { continue; } toinsert = Math.min(toinsert, caninsert); stack = stack.copy(); if (toinsert <= 0) { stack.setCount(0); } else { stack.setCount(toinsert); } } ItemStack remaining = ItemHandlerHelper.insertItem(handler, stack, false); int actuallyinserted = toinsert - remaining.getCount(); if (count == null) { // If we are not using a count then we restore 'stack' here as that is what // we actually have to keep inserting until it is empty. If we are using a count // then we don't do this as we don't want to risk stack getting null (on 1.10.2) // from the insertItem() and then not being able to set stacksize a few lines // above this stack = remaining; } if (actuallyinserted > 0) { roundRobinOffset = (roundRobinOffset + 1) % itemConsumers.size(); total -= actuallyinserted; if (total <= 0) { return; } } } } } private int countItems(IItemHandler handler, Predicate<ItemStack> matcher) { int cnt = 0; for (int i = 0 ; i < handler.getSlots() ; i++) { ItemStack s = handler.getStackInSlot(i); if (!s.isEmpty()) { if (matcher.test(s)) { cnt += s.getCount(); } } } return cnt; } private ItemStack fetchItem(IItemHandler handler, boolean simulate, Predicate<ItemStack> matcher, ItemConnectorSettings.StackMode stackMode, int extractAmount, int maxamount, MInteger index, int startIdx) { if (handler.getSlots() <= 0) { return ItemStack.EMPTY; } for (int i = index.get(); i < handler.getSlots()+startIdx ; i++) { int j = i % handler.getSlots(); ItemStack stack = handler.getStackInSlot(j); if (!stack.isEmpty()) { int s = 0; switch (stackMode) { case SINGLE: s = 1; break; case STACK: s = stack.getMaxStackSize(); break; case COUNT: s = extractAmount; break; } s = Math.min(s, maxamount); stack = handler.extractItem(j, s, simulate); if (!stack.isEmpty() && matcher.test(stack)) { index.set(i); return stack; } } } return ItemStack.EMPTY; } private void updateCache(int channel, IControllerContext context) { if (itemExtractors == null) { itemExtractors = new HashMap<>(); itemConsumers = new ArrayList<>(); Map<SidedConsumer, IConnectorSettings> connectors = context.getConnectors(channel); for (Map.Entry<SidedConsumer, IConnectorSettings> entry : connectors.entrySet()) { ItemConnectorSettings con = (ItemConnectorSettings) entry.getValue(); if (con.getItemMode() == ItemConnectorSettings.ItemMode.EXT) { itemExtractors.put(entry.getKey(), con); } else { itemConsumers.add(Pair.of(entry.getKey(), con)); } } connectors = context.getRoutedConnectors(channel); for (Map.Entry<SidedConsumer, IConnectorSettings> entry : connectors.entrySet()) { ItemConnectorSettings con = (ItemConnectorSettings) entry.getValue(); if (con.getItemMode() == ItemConnectorSettings.ItemMode.INS) { itemConsumers.add(Pair.of(entry.getKey(), con)); } } itemConsumers.sort((o1, o2) -> o2.getRight().getPriority().compareTo(o1.getRight().getPriority())); } } @Override public void cleanCache() { itemExtractors = null; itemConsumers = null; } @Override public boolean isEnabled(String tag) { return true; } @Nullable @Override public IndicatorIcon getIndicatorIcon() { return new IndicatorIcon(iconGuiElements, 0, 80, 11, 10); } @Nullable @Override public String getIndicator() { return null; } @Override public void createGui(IEditorGui gui) { gui.nl().choices(TAG_MODE, "Item distribution mode", channelMode, ChannelMode.values()); } @Override public void update(Map<String, Object> data) { channelMode = ChannelMode.valueOf(((String)data.get(TAG_MODE)).toUpperCase()); roundRobinOffset = 0; } @Nullable public static IItemHandler getItemHandlerAt(@Nullable TileEntity te, EnumFacing intSide) { if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, intSide)) { IItemHandler handler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, intSide); if (handler != null) { return handler; } } else if (te instanceof ISidedInventory) { // Support for old inventory ISidedInventory sidedInventory = (ISidedInventory) te; return new SidedInvWrapper(sidedInventory, intSide); } else if (te instanceof IInventory) { // Support for old inventory IInventory inventory = (IInventory) te; return new InvWrapper(inventory); } return null; } }
mit
fanyingming/car-pooling-site
src/com/project/dao/UserDao.java
5589
package com.project.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.project.javabean.User; import com.project.util.DBPoolUtil; public class UserDao { public boolean addUser(User u) throws Exception { Connection conn = DBPoolUtil.getConnection(); String sql = "insert into tb_user(user_name,user_pass,user_phone,user_mail) values (?,?,?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, u.getUser_name()); pstmt.setString(2, u.getUser_pass()); pstmt.setString(3, u.getUser_phone()); pstmt.setString(4, u.getUser_mail()); pstmt.executeUpdate(); DBPoolUtil.closeConnection(conn); return true; } public boolean isExist(User u) throws Exception { boolean flag = false; Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user where user_name='" + u.getUser_name() + "' and user_pass='" + u.getUser_pass() + "'"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); if (result.next()) flag = true; DBPoolUtil.closeConnection(conn); return flag; } public boolean deleteUserByUid(int user_id) throws Exception { Connection conn = DBPoolUtil.getConnection(); String sql = "delete from tb_user where user_id=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, user_id); pstmt.executeUpdate(); DBPoolUtil.closeConnection(conn); return true; } public boolean modifyUser(User u) throws Exception { Connection conn = DBPoolUtil.getConnection(); String sql = "update tb_user set user_name=?,user_pass=? ,user_phone=?, user_mail=? where user_id=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, u.getUser_name()); pstmt.setString(2, u.getUser_pass()); pstmt.setString(3, u.getUser_phone()); pstmt.setString(4, u.getUser_mail()); pstmt.setInt(5, u.getUser_id()); pstmt.executeUpdate(); DBPoolUtil.closeConnection(conn); return true; } public List<User> listAllUsers() throws Exception { List<User> users = new ArrayList<User>(); Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); while (result.next()) { User u = new User(); u.setUser_id(result.getInt("user_id")); u.setUser_name(result.getString("user_name")); u.setUser_pass(result.getString("user_pass")); u.setUser_phone(result.getString("user_phone")); u.setUser_mail(result.getString("user_mail")); users.add(u); } DBPoolUtil.closeConnection(conn); return users; } public User getUserByUserId(int user_id) throws Exception { User u = new User(); Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user where user_id=" + user_id; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); if (result.next()) { u.setUser_id(user_id); u.setUser_name(result.getString("user_name")); u.setUser_pass(result.getString("user_pass")); u.setUser_phone(result.getString("user_phone")); u.setUser_mail(result.getString("user_mail")); } DBPoolUtil.closeConnection(conn); return u; } public int getUserIdByUserName(String user_name) throws SQLException { int value = 0; Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user where user_name='" + user_name + "'"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); if (result.next()) { value = result.getInt("user_id"); } DBPoolUtil.closeConnection(conn); return value; } public String getUserNameByUserId(int user_id) throws Exception { String str = null; Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user where user_id='" + user_id + "'"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); if (result.next()) { str = result.getString("user_name"); } DBPoolUtil.closeConnection(conn); return str; } public int getUserTotalNum() throws Exception { int user_num = 0; Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user "; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); if (result.next()) { result.last(); user_num = result.getRow(); } else { user_num = 0; } DBPoolUtil.closeConnection(conn); return user_num; } public List<User> listAllUserOrderByUserId(int begin, int offset) throws Exception{ List<User> users = new ArrayList<User>(); Connection conn = DBPoolUtil.getConnection(); String sql = "select * from tb_user order by user_id desc limit " + begin + "," + offset; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet result = pstmt.executeQuery(sql); while (result.next()) { User u = new User(); u.setUser_id(result.getInt("user_id")); u.setUser_name(result.getString("user_name")); u.setUser_pass(result.getString("user_pass")); u.setUser_phone(result.getString("user_phone")); u.setUser_mail(result.getString("user_mail")); users.add(u); } DBPoolUtil.closeConnection(conn); return users; } }
mit
jeremiebernard/suivi_alternants
src/AppBundle/Forms/Types/CourseManagerType.php
985
<?php /** * Created by PhpStorm. * User: lp * Date: 06/04/2017 * Time: 17:29 */ namespace AppBundle\Forms\Types; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints\Regex; class CourseManagerType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('phoneNumber', TextType::class, array( 'label' => "Numéro de téléphone", 'required' => false, 'constraints' => array(new Regex( array( 'pattern' => "/^((0|\\+33)[0-9]{9})?$/", 'message' => 'Le numéro de téléphone doit être de format 0xxxxxxxxx ou +33xxxxxxxxx',) )) )); } public function getParent(){ return UserType::class; } }
mit
reneolivo/laptop-friendly
src/lib/decorators/index.js
276
export {default as Component} from './component'; export {default as State} from './state'; export {default as Service} from './service'; export {default as Inject} from './inject'; export {default as Attribute} from './attribute'; export {default as Filter} from './filter';
mit
hugomelo/ralsp
src/cake/app/plugins/burocrata/webroot/js/burocrata.js
59940
/** * * Copyright 2010-2012, Preface Design LTDA (http://www.preface.com.br") * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2010-2011, Preface Design LTDA (http://www.preface.com.br) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) * @link https://github.com/prefacedesign/jodeljodel Jodel Jodel public repository */ var E_NOT_JSON = 1; // Not a JSON response var E_JSON = 2; // JSON tells me the error var E_NOT_AUTH = 3; // Server sended a 403 (Not Authorized) code document.observe('dom:loaded', function(ev){ Element.addMethods({ getForm: function(element) { if (!(element = $(element))) return; if (!BuroCR) return; if (!(id = element.readAttribute('buro:form'))) return; return BuroCR.get('frm'+id); } }) }) /** * A instance of a Hash-like class, without overwriting of values, to keep * a list of instace objects used to keep all created classes * during the script. * * @access public * @todo An garbage colletor to free all not instanciated objects */ var BuroCR = new (Class.create(Hash, { set: function($super, id, obj) { if (this.get(id)) return false; return $super(id, obj); } }))(); /** * Abstract class that implements the behaviour of callbacks * with the methods `addCallbacks` and `trigger` * It works like Events * * @access protected */ var BuroCallbackable = Class.create({ addCallbacks: function(callbacks) { if (!Object.isHash(this.callbacks)) this.callbacks = $H({}); callbacks = $H(callbacks); if (callbacks.size()) callbacks.each(this.mergeCallback.bind(this)); return this; }, removeCallback: function(name, _function) { if (Object.isUndefined(name)) { this.callbacks.keys().each(function(key) { this.callbacks.unset(key); }.bind(this)); } else { var callbacks = this.callbacks.get(name); if (Object.isFunction(_function) && (index = callbacks.indexOf(_function)) != -1) callbacks.splice(index,1); else if (Object.isUndefined(_function)) callbacks = []; this.callbacks.set(name, callbacks); } return this; }, mergeCallback: function(pair) { var name = pair.key, _function = pair.value; var callback = this.callbacks.get(name); if (!Object.isArray(callback)) callback = []; callback.push(_function); this.callbacks.set(name, callback); }, isRegistred: function(callback) { return Object.isArray(this.callbacks.get(callback)); }, trigger: function() { if (Object.isUndefined(this.callbacks)) this.callbacks = $H({}); var name = arguments[0]; if (!this.isRegistred(name)) return false; var i,args = new Array(); for(i = 1; i < arguments.length; i++) args.push(arguments[i]); try { this.callbacks.get(name).invoke('apply', this, args); } catch(e) { if (debug && console && console.error) console.error(e); } return true; } }); /** * Adds all javascript functionality to the form. * * Callbacks: * - `onStart` function (form){} * - `onComplete` function (form, response){} * - `onFailure` function (form, response){} * - `onError` function (code, error){} * - `onSave` function (form, response, json, saved){} * - `onReject` function (form, response, json, saved){} * - `onSuccess` function (form, response, json){} * * @access public */ var BuroForm = Class.create(BuroCallbackable, { initialize: function() { this.params = $H({}); this.submitCancelled = false; var n_args = arguments.length; if (n_args > 0) this.url = arguments[0]; if (n_args > 1) { this.id_base = arguments[1]; this.form = $('frm' + this.id_base); if (!this.form) return; this.form.lock = this.lockForm.bind(this); this.form.unlock = this.unlockForm.bind(this); this.form.observe('keypress', this.keyPress.bind(this)); BuroCR.set(this.form.id, this); this.submit = $('sbmt' + this.id_base); if (this.submit) this.submit.observe('click', this.submits.bind(this)); this.cancel = $('cncl' + this.id_base); if (this.cancel) this.cancel.observe('click', this.cancels.bind(this)); } if (n_args > 2) { this.addCallbacks(arguments[3]); } if (n_args > 3) { this.addParameters(arguments[4]); } (function(){ this.lastSavedData = this.serialize(); }).bind(this).defer(1); }, reset: function() { this.inputs.each(this.resetInput.bind(this)); this.trigger('onReset', this.form); return this; }, resetInput: function(input) { switch (input.nodeName.toLowerCase()) { case 'textarea': input.value = input.innerHTML; break; case 'input': switch (input.type) { case 'text': case 'file': case 'password': input.value = input.readAttribute('value'); break; case 'radio': case 'checkbox': input.checked = input.readAttribute('checked'); break; } break; case 'select': $A(input.options).each(function(option) { option.selected = option.readAttribute('selected'); }); break; } }, addParameters: function(params, pattern) { if (Object.isString(params) || Object.isArray(params)) { throw new Error('Form.addParameters method accepts only objects or Hashes.'); return; } params = $H(params); if (pattern) { params.each(function(pattern, pair) { this.set(pair.key, pair.value.interpolate(pattern)); }.bind(params, pattern)); } this.params = this.params.merge(params); return this; }, lockForm: function() { this.inputs.each(Form.Element.disable); return this; }, unlockForm: function() { this.inputs.each(Form.Element.enable); return this; }, keyPress: function(ev){ var element = ev.findElement().nodeName.toLowerCase(); var key = ev.keyCode; if (ev.ctrlKey && key == Event.KEY_RETURN && element == 'input' && confirm('Deseja enviar os dados do formulário?')) { ev.stop(); this.submits(); } }, submits: function(ev) { if (this.ajax && !this.ajax.done()) { return this; } this.submitCancelled = false; this.updateLastSavedData(); this.trigger('onStart', this.form); if (this.submitCancelled == true) { this.trigger('onCancel', this.form); return this; } this.ajax = new BuroAjax( this.url, {parameters: this.lastSavedData}, { onError: function(code, error) { this.trigger('onError', code, error); }.bind(this), onComplete: function (response) { this.trigger('onComplete', this.form, response); }.bind(this), onFailure: function (response) { this.trigger('onFailure', this.form, response); // Page not found }.bind(this), onSuccess: function (response, json) { this.json = json; if (!Object.isUndefined(this.json.saved)) { if (json.saved) this.trigger('onSave', this.form, response, this.json, this.json.saved); else this.trigger('onReject', this.form, response, this.json, this.json.saved); } this.trigger('onSuccess', this.form, response, this.json); }.bind(this) } ); return this; }, cancels: function(ev) { ev.stop(); this.trigger('onCancel', this.form); return this; }, purge: function() { BuroCR.unset(this.id_base); this.form.stopObserving('keypress'); if (this.submit) this.submit.stopObserving('click'); if (this.cancel) this.cancel.stopObserving('click'); if (this.form.up('body')) this.form.remove(); this.removeCallback(); this.cancel = this.submit = this.form = null; }, updateLastSavedData: function() { this.lastSavedData = this.serialize(); }, serialize: function() { this.inputs = $$('[buro\\:form="'+this.id_base+'"]'); var data = Form.serializeElements(this.inputs, {hash:true}); data = $H(data).merge(this.params); return data; }, changed: function() { return this.lastSavedData.toQueryString() != this.serialize().toQueryString(); }, cancelSubmit: function() { this.submitCancelled = true; return this; } }); // Callbacks graph: // // start // ____|___ // |http ok?| // / \ // / \ // failure success // | ____|______ // | |data saved?| // | /\ // \ save reject // \ | / // \ | / // complete /** * Extends the default Autocomplete built in Scriptaculous. * * Callbacks: * - `onStart` function (input){} * - `onComplete` function (input, response){} * - `onFailure` function (input, response){} * - `onError` function (code, error){} * - `onSuccess` function (input, response, json){} * - `onSelect` function (input, response, json){} * * @access public */ var BuroAutocomplete = Class.create(BuroCallbackable, { initialize: function(url, id_base, options) { BuroCR.set(id_base, this); var id_of_text_field = 'input'+id_base, id_of_div_to_populate = 'div'+id_base; options.updateElement = this.alternateUpdateElement.bind(this); options.onHide = this.onHide.bind(this); Ajax.Autocompleter.addMethods({ markPrevious: function() { if (this.index > 0) this.index--; else this.index = this.entryCount-1; if (this.getEntry(this.index).cumulativeOffset().top < document.viewport.getScrollOffsets().top) this.getEntry(this.index).scrollIntoView(true); }, markNext: function() { if (this.index < this.entryCount-1) this.index++; else this.index = 0; if (this.getEntry(this.index).cumulativeOffset().top+this.getEntry(this.index).getHeight() > document.viewport.getScrollOffsets().top+document.viewport.getHeight()) this.getEntry(this.index).scrollIntoView(false); } }); this.autocompleter = new Ajax.Autocompleter(id_of_text_field, id_of_div_to_populate, url, options); this.autocompleter.options.onComplete = this.onComplete.bind(this); this.autocompleter.options.onFailure = this.onFailure.bind(this); this.autocompleter.options.onSuccess = this.onSuccess.bind(this); this.autocompleter.options.onCreate = this.onCreate.bind(this); this.onShow = this.autocompleter.options.onShow; this.autocompleter.options.onShow = this.onShowTrap.bind(this); this.input = this.autocompleter.element; this.pair = {}; while(tmp = this.autocompleter.update.next('.message')) this.autocompleter.update.insert(tmp); }, onHide: function(element, update) { new Effect.Fade(update,{duration:0.15}); this.trigger('onHide'); }, onShowTrap: function(element, update) { this.autocomplete.update.setOpacity(1); this.onShow(element, update); this.trigger('onShow'); }, onSuccess: function(response) { if (response && response.responseJSON) this.trigger('onSuccess', this.input, response, response.responseJSON); }, onFailure: function(response) { this.trigger('onFailure', this.input, response); }, onCreate: function() { if (!this.autocompleter.update.visible()) { this.autocompleter.update.show().setLoading(); this.autocompleter.update.select('div.message').each(Element.hide); } this.trigger('onStart', this.input); }, onComplete: function(response) { if (!response.getAllHeaders()) this.trigger('onFailure', this.form, response); // No server response if (!response.responseJSON) { this.trigger('onError', E_NOT_JSON); return; } this.json = response.responseJSON; if (this.json.error != false) { this.trigger('onError', E_JSON, this.json.error); return; } if (Object.isArray(this.json.content)) this.json.content = {}; this.foundContent = $H(this.json.content); var ac = this.autocompleter; ac.update.unsetLoading(); if (!ac.update.down('ul')) ac.update.insert({top: new Element('ul')}); ac.update.down('ul').replace(this.createChoices()); if (!ac.changed && ac.hasFocus) { Element.cleanWhitespace(ac.update); Element.cleanWhitespace(ac.update.down()); if (ac.update.firstChild && ac.update.down().childNodes) { ac.entryCount = ac.update.down('ul').childNodes.length; for (var i = 0; i < ac.entryCount; i++) { var entry = ac.getEntry(i); entry.autocompleteIndex = i; ac.addObservers(entry); } } else { ac.entryCount = 0; } ac.stopIndicator(); ac.index = 0; if (ac.entryCount==1 && ac.options.autoSelect) { ac.selectEntry(); ac.hide(); } else { ac.render(); } } ac.update.setOpacity(1); if (ac.entryCount != 1) ac.update.down('.nothing_found').hide(); else ac.update.down('.nothing_found').show(); this.trigger('onUpdate', this.input, response); }, createChoices: function() { var i, ul = new Element('ul'); var keys = this.foundContent.keys(); for(i = 0; i < keys.length; i++) ul.insert(new Element('li').update(this.foundContent.get(keys[i]))); ul.insert(new Element('li').hide()); return ul; }, alternateUpdateElement: function(selectedElement) { var keys = this.foundContent.keys(); if (!keys.length) return false; this.pair.id = keys[this.autocompleter.index]; this.pair.value = this.foundContent.get(this.pair.id); this.trigger('onSelect', this.input, this.pair, selectedElement); } }); /** * Extends the default Ajax.Request built in Prototype. * * It is possible to create a ajax dump for each request, just letting the debug * config from cake != 0 and setting window.ajax_dump = true (on JS console) * Also, if an request didnt return ajax and it debug != 0, it asks if you want a dump. * * Callbacks: * - `onStart` function (){} * - `onComplete` function (response){} * - `onFailure` function (response){} * - `onError` function (code, error, json){} * - `onSuccess` function (response, json){} * * @access public */ var BuroAjax = Class.create(BuroCallbackable, { initialize: function(url, options, callbacks) { this.addCallbacks(callbacks); this.url = url; this.fulldebug = debug != 0 && !Object.isUndefined(window.ajax_dump) && window.ajax_dump == true; this.ajax_options = {}; this.ajax_options.parameters = options.parameters; this.ajax_options.onComplete = this.requestOnComplete.bind(this); this.ajax_options.onSuccess = this.requestOnSuccess.bind(this); this.ajax_options.onFailure = this.requestOnFailure.bind(this); this.trigger('onStart'); this.request = new Ajax.Request(this.url, this.ajax_options); }, done: function() { return this.request._complete; }, requestOnComplete: function (re) { this.trigger('onComplete', re); if (this.fulldebug) this.dumpResquest(re); }, requestOnSuccess: function(re) { var json = false; if (re.responseJSON) json = re.responseJSON; if (!re.getAllHeaders()) { this.trigger('onFailure', re); // No server response } else if (!json) { this.trigger('onError', E_NOT_JSON); if (debug != 0 && !this.fulldebug) this.dumpResquest(re); } else if (json.error != false) { this.trigger('onError', E_JSON, json.error, json); } else { this.trigger('onSuccess', re, json); } }, requestOnFailure: function(re) { switch (re.status) { case 403: // Not Authorized if (this.isRegistred('onError')) { this.trigger('onError', E_NOT_AUTH); break; } default: this.trigger('onFailure', re); // Page not found } }, dumpResquest: function(re) { if (!confirm('This last request didn\'t return a valid JSON.\nDo you want to create a dump of this request?\n\nNote: to close the created dump, just double click on it.')) return; var div = new Element('div', {className: 'dump_ajax'}) .insert(new Element('div', {className: 'dump_config'}) .insert('<h1>Call config</h1>') .insert(new Element('div', {className: 'dump_content'}) .insert(new Element('pre') .insert('URL: '+this.url+'<br />') .insert(Object.toJSON(this.ajax_options)) ) ) ) .insert(new Element('div', {className: 'dump_code'}) .insert('<h1>Response status</h1>') .insert(new Element('div', {className: 'dump_content'}) .insert('HTTP status: '+re.status+' ('+re.statusText+')') ) ) .insert(new Element('div', {className: 'dump_headers'}) .insert('<h1>Response headers</h1>') .insert(new Element('div', {className: 'dump_content'}) .insert(new Element('pre').update(re.getAllHeaders())) ) ) .insert(new Element('div', {className: 'dump_content_code'}) .insert('<h1>Response complete code</h1>') .insert(new Element('div', {className: 'dump_content'}) .insert(new Element('pre').update(re.responseText.unfilterJSON().escapeHTML())) ) ) .insert(new Element('div', {className: 'dump_code'}) .insert('<h1>Response content</h1>') .insert(new Element('div', {className: 'dump_content'}) .insert(re.responseText/* .replace(/\{"\w+":.*\}/, '') */) ) ) ; div.observe('dblclick', function(ev){ev.findElement('div.dump_ajax').remove(); ev.stop();}); document.body.insert({bottom: div}); Effect.ScrollTo(div); } }); /** * How it works: on load, if passed true on update_on_load, it will try to update the * display div and hide the autocomplete input. Else, it will hide the autocomplete * input. * * Callbacks: * - `onInitilize` function (response){} * - `onComplete` function (response){} * - `onFailure` function (response){} * - `onError` function (code, error){} * - `onSuccess` function (response, json){} * * @access public */ var BuroBelongsTo = Class.create(BuroCallbackable, { baseFxDuration: 0.3, initialize: function(id_base, autocompleter_id_base, update_on_load, callbacks) { this.form = false; this.id_base = id_base; BuroCR.set(this.id_base, this); this.autocomplete = BuroCR.get(autocompleter_id_base); this.addCallbacks(callbacks); this.input = $('hii'+id_base); this.divBase = $('div'+id_base); this.update = $('update'+id_base); this.error = $('error'+id_base); this.actions = this.update.next('.actions'); this.actions.select('a').each(this.observeControls.bind(this)); this.observeControls(this.autocomplete.autocompleter.update.down('.action a')); if (this.input.value.empty()) { this.reset(false).setActions(''); } else { if (!update_on_load) this.setActions('edit reset').hideAutocomplete(); else this.showPreview(); } this.queue = {position:'end', scope: this.id_base}; }, reset: function(animate) { if (!this.input.value.blank()) this.backup_id = this.input.value; this.input.value = this.autocomplete.input.value = ''; this.autocomplete.input.show(); this.autocomplete.input.removeAttribute('disabled'); if (!this.input.value.blank()) this.setActions('undo_reset'); if (!animate) { this.update.hide(); } else { this.update.setStyle({height: (this.update.getHeight()-this.autocomplete.input.getHeight())+'px'}); new Effect.BlindUp(this.update, {duration: this.baseFxDuration, queue: this.queue}); } this.error.show(); return this; }, observeControls: function(element) { if (Object.isElement(element) || Object.isElement(element = $(element))) element.observe('click', this.controlClick.bindAsEventListener(this, element)); return this; }, controlClick: function(ev, element) { ev.stop(); this.setActions(''); var action = element.readAttribute('buro:action'); switch (action) { case 'new': this.update.setLoading(); this.trigger('onAction', action); break; case 'edit': this.update.setLoading(); this.trigger('onAction', action, this.input.value); break; case 'reset': this.reset(true); break; case 'undo_reset': this.input.value = this.backup_id; this.hideAutocomplete().showPreview(); this.error.show(); break; } }, actionSuccess: function(json) { if (this.form) this.form.purge(); this.form = false; var iHeight = this.update.show().unsetLoading().getHeight(), fHeight = this.update.update(json.content).getHeight(); //disable the autocomplete field this.autocomplete.input.disable(); //find the field with the same name of the autocompleter, //to populate it with autocomplete content var name, input; if (json.action == 'new') { name = 'data'+this.autocomplete.input.name.substr(22); if (input = this.update.down('input[name="'+name+'"]')) input.value = this.autocomplete.input.value; } this.update.setStyle({height: iHeight+'px', overflow: 'hidden'}); new Effect.Morph(this.update, { duration: this.baseFxDuration, queue: this.queue, style: {height: fHeight+'px'}, afterFinish: function(action, fx) { this.update.setStyle({height: '', overflow: ''}); this.observeForm(); this.setActions(''); if (action == 'preview') this.setActions('edit reset').hideAutocomplete(); if (action == 'preview' || action == 'new') this.error.hide(); }.bind(this, json.action) }); }, actionError: function(json) { this.trigger('onError'); }, observeForm: function() { var form_id = false, div_form = this.update.down('.buro_form'); if (Object.isElement(div_form)) if (form_id = div_form.readAttribute('id')) this.form = BuroCR.get(form_id).addCallbacks({ onStart: function(form){form.setLoading().lock();}, onCancel: this.cancel.bind(this), onSave: this.saved.bind(this), onReject: this.reject.bind(this) }); }, showPreview: function() { this.update.update().show().setLoading(); this.trigger('onAction', 'preview', this.input.value); }, saved: function(form, response, json, saved) { this.form.form.unsetLoading().unlock(); this.autocomplete.input.value = ''; this.input.value = saved; this.showPreview(); }, reject: function(form, response, json, saved) { this.form.form.unsetLoading().purge(); this.update.update(json.content); this.observeForm.bind(this).delay(0.1); }, cancel: function() { var content = this.update.innerHTML, iHeight = this.update.show().getHeight(), fHeight = this.update.update().setLoading().getHeight(); this.update.unsetLoading().update(content).setStyle({height: iHeight+'px', overflow: 'hidden'}); new Effect.Morph(this.update, { duration: this.baseFxDuration, queue: this.queue, style: {height: fHeight+'px'}, afterFinish: function(fx) { if (!this.input.value.blank()) this.showPreview(); else this.reset(); }.bind(this) }); }, ACUpdated: function() { var new_item = this.autocomplete.autocompleter.update.down('.action'); if (new_item) new_item.show(); }, ACSelected: function(pair) { this.hideAutocomplete(); this.input.value = pair.id; this.showPreview(); }, setActions: function(filter) { var links = this.actions.select('a'), filter = function(filter, link) { return $w(filter).indexOf(link.readAttribute('buro:action')) != -1; }.curry(filter); links.invoke('hide').findAll(filter).invoke('show'); return this; }, showAutocomplete: function() {this.autocomplete.input.show(); return this;}, hideAutocomplete: function() {this.autocomplete.input.hide(); return this;} }); /** * The main class for a list of items. It handles all ajax calls * * ***How it works:*** * * - This class receives the templates for an item and for an menu. * - Also it receives all already saved contents and renders it on initialize using the item template. * - This class keeps updated two arrays (one for the items objects `BuroListOfItemsItem` and other * for the menu objects `BuroListOfItemsMenu`) * - Each item created has a callback called `buro:controlClick` (actions up, down, duplicate...) that * is mapped here to method BuroListOfItems.routeAction(item, action, id) that triggers its own * `onAction` callback that is coded on BuroBurocrataHelper::_orderedItensManyChildren method * - The `onAction` callback performs an ajax call witch, when is complete, calls * BuroListOfItems.actionError(json) or BuroListOfItems.actionSuccess(json) depending on response * - The BuroListOfItems.actionSuccess(json) method do on user interface what the controllers and * models did on backstage. * - Each menu object created has a callback named `buro:newItem` that is mapped here to * BuroListOfItems.newItem() method that opens a form right below the menu div * - When a form is opened, this class searches for it and observes its main callbacks (like `onError`, * `onCancel` and `onSave`) to make possible do the necessary changes after the submit. * * * @access public * @param string id_base The master ID used to find one specific instance of this class and elements on HTML * @param object parameters A list of parameters to be sent with all requests. * @param object content A object with 3 properties: texts (object), templates (object), contents (array) */ var BuroListOfItems = Class.create(BuroCallbackable, { baseFxDuration: 0.3, //in seconds initialize: function(id_base, parameters, content) { this.templates = content.templates || {menu: '', item: ''}; this.contents = content.contents || []; this.texts = content.texts || {}; this.parameters = parameters || {}; this.url = content.url; this.menus = []; this.items = []; this.id_base = id_base; BuroCR.set(this.id_base, this); this.divCont = $('div'+id_base); this.divCont.insert(this.divForm = new Element('div', {id: 'divform'+id_base}).hide()); this.addNewMenu(); this.contents.each(this.addNewItem.bind(this)); this.editing = false; this.queue = {position:'end', scope: this.id_base}; }, addNewMenu: function(order) { var div, prevMenu = false; if (Object.isUndefined(order) || order > this.menus.length) order = this.menus.length; if (this.menus.length > order) prevMenu = this.menus[order]; this.menus.each(function(order, menu) { if (Number(menu.order) >= order) menu.setOrder(Number(menu.order)+1); }.curry(order)); div = new Element('div').insert(this.templates.menu.interpolate({order:order})).down(); if (prevMenu) prevMenu.div.insert({before:div}); else this.divCont.insert(div); this.menus.push(this.createMenu(div)); this.reorderMenuList(); return this; }, createMenu: function(div) { return new BuroListOfItemsMenu(div).addCallbacks({'buro:newItem': this.newItem.bind(this)}); }, removeMenu: function(div) { var order = Number(div.readAttribute('buro:order')); this.menus.splice(order, 1); div.remove(); this.menus.each(function(order, menu) { if (menu.order >= order) menu.setOrder(Number(menu.order)-1); }.curry(order)); return this; }, reorderMenuList: function() { return this.menus = this.menus.sortBy(function(menu) { return Number(menu.order); }); }, addNewItem: function(data, order, animate) { var item,content, div; if ((!data.title || data.title.blank()) && this.texts.title) data.title = this.texts.title; content = this.templates.item.interpolate(data), div = new Element('div').insert(content).down(); this.addNewMenu(order); if (this.menus[order]) this.menus[order].div.insert({after: div}); item = new BuroListOfItemsItem(div, this).addCallbacks({'buro:controlClick': this.routeAction.bind(this)}) this.items.push(item); this.updateSiblings(item); if (animate) new Effect.BlindDown(div, { queue: this.queue, duration: this.baseFxDuration }); return this; }, removeItem: function(item) { this.items.splice(this.items.indexOf(item), 1); item.div.unsetLoading(); new Effect.BlindUp(item.div, { queue: this.queue, duration: this.baseFxDuration, afterFinish: function(item, eff) { var prev = this.getItem(item.getPrev()), next = this.getItem(item.getNext()); item.div.remove(); if (prev) prev.checkSiblings(); if (next) next.checkSiblings(); }.bind(this, item) }); return this; }, updateSiblings: function(item) { var prev = this.getItem(item.getPrev()), next = this.getItem(item.getNext()); if (prev) prev.checkSiblings(); if (next) next.checkSiblings(); }, newItem: function(menuObj, contentType) { this.currentContentType = contentType; if (this.placesForm(menuObj)) this.trigger('onAction', 'edit', '', contentType); }, placesForm: function(obj) { if (this.editing !== false) return false; obj.div.insert({after: this.divForm}).hide().unsetLoading(); this.divForm.show().setLoading(); this.editing = obj; this.menus.each(function(menu){ menu.disable(); }); return true; }, openForm: function(content) { var iHeight = this.editing.id ? this.editing.div.getHeight() : this.divForm.getHeight(), fHeight = this.divForm.update(content).setStyle({height:''}).getHeight(); this.divForm.unsetLoading().setStyle({overflow:'hidden', height: iHeight+'px'}); new Effect.Morph(this.divForm, { queue: this.queue, duration: this.baseFxDuration, style: {height: fHeight+'px'}, afterFinish: function () { this.divForm.setStyle({overflow: '', height:''}).scrollVisible(); this.injectControlOnForm(); }.bind(this) }); }, closeForm: function() { var fHeight = this.editing.id ? this.editing.div.getHeight() : 0; this.divForm.unsetLoading().setStyle({overflow: 'hidden'}); new Effect.Morph(this.divForm, { queue: this.queue, duration: this.baseFxDuration, style: {height: fHeight+'px'}, afterFinish: function() { if (this.editing) this.editing.div.show(); this.editing = false; this.menus.each(function(menu){ menu.close().enable(); }); this.divForm.update().hide().setStyle({overflow: ''}); this.trigger('onFormClose'); }.bind(this) }); }, getOpenedForm: function() { var form_id = this.divForm.down('.buro_form') && this.divForm.down('.buro_form').readAttribute('id'); return BuroCR.get(form_id); }, injectControlOnForm: function() { var OpenedForm = this.getOpenedForm(); if (OpenedForm) { OpenedForm.url = this.url; OpenedForm.addParameters(this.parameters.request); OpenedForm.addParameters(this.parameters.buroAction); OpenedForm.addParameters(this.parameters.fkBounding); if (this.currentContentType && this.parameters.contentType); OpenedForm.addParameters(this.parameters.contentType, {content_type: this.currentContentType}); // If it doens't exists (creating) if (this.editing.order && this.parameters.orderField) OpenedForm.addParameters(this.parameters.orderField, {order: Number(this.editing.order)+1}); // If it already exists (editing) if (this.editing.id) OpenedForm.addParameters(this.parameters.contentId, {id: this.editing.id}); OpenedForm.addCallbacks({ onStart: function(form) { form.lock(); this.divForm.down().setLoading(); }.bind(this), onComplete: function(form) { form.unlock(); }, onCancel: this.formCanceled.bind(this), onSave: this.formSaved.bind(this), onError: this.formError.bind(this), onReject: this.formRejected.bind(this) }); this.trigger('onShowForm', OpenedForm); } }, formSaved: function(form, response, json) { var id = this.editing.id || json.saved; if (id) this.trigger('onAction', 'afterEdit', id); }, formCanceled: function() { this.closeForm(); }, formRejected: function(form, response, json) { this.divForm.down().unsetLoading(); this.openForm(json.content); }, formError: function(code, error) { if (this.texts.error) alert(this.texts.error); else if (debug) { if (code == E_JSON) alert(error); } }, routeAction: function(item, action, id) { var prev, next; if (!action || (!Object.isUndefined(this.texts.confirm[action]) && !confirm(this.texts.confirm[action]))) return; item.div.setLoading(); if (action == 'up' && (prev = item.getPrev())) this.getItem(prev).div.setLoading(); if (action == 'down' && (next = item.getNext())) this.getItem(next).div.setLoading(); this.trigger('onAction', action, id); }, actionError: function(json) { this.items.each(function(item){ item.div.unsetLoading(); }); if (this.editing) this.closeForm(); this.trigger('onError', json); }, actionSuccess: function(json) { var item, prev, next; switch (json.action) { case 'down': if (!json.id || !(item = this.getItem(json.id)) || !(next = this.getItem(item.getNext()))) break; item.div.swapWith(next.div.unsetLoading()).unsetLoading(); item.checkSiblings(); next.checkSiblings(); break; case 'up': if (!json.id || !(item = this.getItem(json.id)) || !(prev = this.getItem(item.getPrev()))) break; item.div.swapWith(prev.div.unsetLoading()).unsetLoading(); item.checkSiblings(); prev.checkSiblings(); break; case 'delete': if (!json.id || !(item = this.getItem(json.id))) break; this.removeMenu(item.div.next('.ordered_list_menu')); this.removeItem(item); break; case 'duplicate': if (!json.id || !json.old_id || !(item = this.getItem(json.old_id))) break; item.div.unsetLoading(); this.addNewItem(json, json.order, true); break; case 'save': case 'edit': if (json.id && (item = this.getItem(json.id))) { this.divForm.setStyle({height: item.div.getHeight()+'px'}); this.placesForm(item); } if (this.editing == false) break; this.openForm(json.content); break; case 'afterEdit': if (this.divForm.down()) this.divForm.down().unsetLoading(); if (this.editing.id == json.id) { // Finished editing an item that already exists this.editing.content.update(json.content); } else if (!Object.isUndefined(this.editing.order)) { // Finished editing a new item this.addNewItem({content: json.content, id: json.id, title: json.title}, this.editing.order); } this.closeForm(); break; } }, getItem: function(id) { if (Object.isElement(id)) id = id.readAttribute('buro:id'); var result = this.items.findAll(function(id, item) {return item.id == id}.curry(id)); if (result.length) return result[0]; return false; } }); /** * Automatic ordering version of BuroListOfItems. * All specific methods and behaviors are implemented here. * * @access public */ var BuroListOfItemsAutomatic = Class.create(BuroListOfItems, { addNewItem: function($super, data, order, animate, reference) { $super(data, order, animate); var item = this.items.last(); reference = reference || this.menus[1].div; if (this.editing) reference = this.editing.div; item.disableOrderControl(); if (reference == this.menus[1].div) reference.insert({before: item.div}); else reference.insert({after: item.div}); this.checkLast(); return this; }, addNewMenu: function($super, order) { if (this.menus.length < 2) $super(this.menus.length); return this; }, removeMenu: function($super, div) { if (this.items.length == 1) $super(div); return this; }, actionSuccess: function($super, json) { switch (json.action) { case 'duplicate': if (!json.id || !json.old_id || !(item = this.getItem(json.old_id))) break; item.div.unsetLoading(); this.addNewItem(json, null, true, item.div); this.getItem(json.id).div.setLoading(); this.trigger.bind(this,'onAction', 'afterEdit', json.id).delay(this.baseFxDuration); break; case 'afterEdit': $super(json); this.getItem(json.id).div.unsetLoading(); if (Object.isArray(json.id_order)) { var index = json.id_order.map(Number).indexOf(Number(json.id)); if (this.items.length > 1) { if (index == 0) this.putItem(json.id_order[index], 'before', json.id_order[index+1], true); else this.putItem(json.id_order[index], 'after', json.id_order[index-1], true); } } break; default: $super(json); } }, putItem: function(id, on, other_id, animate) { var item = this.getItem(id), other = this.getItem(other_id); if (item && item.div && other && other.div) { if (on == 'after' && other.getNext() == item.div || on == 'before' && item.getNext() == other.div) return; item.div.unsetLoading(); other.div.unsetLoading(); var div, insert, insertion = $H({}); if (!animate) { insertion.set(on, item.div); other.div.insert(insertion.toObject()); } else { insertion.set(on, div = new Element('div')); other.div.insert(insertion.toObject()); new Effect.Morph(div, { style: {height: item.div.getHeight()+'px'}, queue: this.queue, delay: this.baseFxDuration, duration: this.baseFxDuration, afterFinish: function(item, div, fx) { item.div .swapWith(div) .setStyle({ position: 'relative', top: (div.cumulativeOffset().top-item.div.cumulativeOffset().top)+'px' }); }.curry(item, div) }); new Effect.Morph(item.div, { style: {top: '0px'}, queue: this.queue, duration: this.baseFxDuration, afterFinish: function(item, div, fx) { item.div.setStyle({position:'', top: ''}); this.checkLast(); }.bind(this, item, div) }); new Effect.Morph(div, { style: {height: '0px'}, queue: this.queue, duration: this.baseFxDuration, afterFinish: function(fx) { fx.element.remove.bind(fx.element).defer(); } }); } } }, checkLast: function() { var last = this.divCont.down('div.ordered_list_item.last_item'), items = this.divCont.select('div.ordered_list_item'); if (last) last.removeClassName('last_item'); if (items.length) items.last().addClassName('last_item'); }, updateSiblings: function() { this.checkLast(); } }); /** * Class for the menu of a list of items. It triggers the `buro:newItem` callback * when the creation of a new item is requested. If it has a list of contents, it triggers * when the link of that content is clicked. If not (just one item), it triggers when the * 'expand menu' link is clicked. * * ### Callbacks: * - `buro:newItem` callback receive itself and the 'type' of content (when there is a list) * * @access public * @param element div The div reference of menu container * @todo order? */ var BuroListOfItemsMenu = Class.create(BuroCallbackable, { initialize: function(div) { this.div = $(div); this.order = this.div.readAttribute('buro:order'); this.plus_button = this.div.down('button.ordered_list_menu_add'); this.plus_button.observe('click', this.plusClick.bind(this)); this.menu = this.div.down('div.ordered_list_menu_list'); this.links = this.menu.select('a.ordered_list_menu_link'); this.links.each(function(lnk){lnk.observe('click', this.lnkClick.bind(this))}.bind(this)); this.close_link = this.div.down('.ordered_list_menu_close>a'); this.close_link.observe('click', function(ev){ ev.stop(); this.close();}.bind(this)); this.border = this.div.down('.border'); this.enable().close(); }, plusClick: function(ev) { ev.stop(); if (this.links.length > 1) this.open(); else if (this.links.length == 1) this.trigger('buro:newItem', this, this.getType(this.links[0])); }, lnkClick: function(ev) { ev.stop(); var lnk = ev.findElement('a'); if (lnk) this.trigger('buro:newItem', this, this.getType(lnk)); }, getType: function(lnk) { return lnk.readAttribute('buro:content_type'); }, open: function() { this.close_link.up().show(); this.plus_button.hide(); this.border.hide(); new Effect.SlideDown(this.menu, {duration: 0.15}); return this; }, close: function(ev) { this.close_link.up().hide(); this.plus_button.show(); this.border.show(); if (ev) new Effect.SlideUp(this.menu, {duration: 0.15}); else this.menu.hide(); return this; }, setOrder: function(order) { if (Object.isNumber(order)) this.div.writeAttribute('buro:order', this.order = order); return this; }, hide: function() { this.div.hide(); return this; }, show: function() { this.div.show(); return this; }, disable: function() { Form.Element.disable(this.plus_button); return this; }, enable: function() { Form.Element.enable(this.plus_button); return this; } }); /** * Represents one item on list of items. It handles events on controls like (move up, move down, edit, etc) * It triggers a callback (`buro:controlClick`) every time a control is activeted and is passed what type of * callback was triggered (up, down, edit ... ). * It doesn't handles any kind of ajax requests by itself. * * ### Callbacks * - `buro:controlClick` function(object, action) - It receive the object that triggered and an string describing the action * * @access public * @param object list The object for the parent list * @param element div The div containing the item */ var BuroListOfItemsItem = Class.create(BuroCallbackable, { initialize: function (div, parent) { this.div = $(div); this.linksEnabled = true; this.id = this.div.readAttribute('buro:id'); this.content = this.div.down('div.ordered_list_content'); this.controls = this.div.down('.ordered_list_controls'); this.controls.childElements().each(this.observeControls.bind(this)); this.checkSiblings(); parent.addCallbacks({ 'onFormClose': this.enableLinks.bind(this), 'onShowForm': this.disableLinks.bind(this) }); }, enableLinks: function() { this.linksEnabled = true; this.controls.setOpacity(1); this.controls.childElements().invoke('removeClassName', 'disabled'); }, disableLinks: function() { this.linksEnabled = false; this.controls.setOpacity(0.5); this.controls.childElements().invoke('addClassName', 'disabled'); }, observeControls: function(element) { element.observe('click', this.controlClick.bindAsEventListener(this, element)); return this; }, controlClick: function(ev, element) { ev.stop(); if (!this.linksEnabled) return; var action = element.readAttribute('buro:action'); this.trigger('buro:controlClick', this, action, this.id); }, checkSiblings: function() { this.controls.childElements().each(Form.Element.enable); if (!Object.isElement(this.getPrev())) Form.Element.disable(this.controls.down('.ordered_list_up')); if (!Object.isElement(this.getNext())) Form.Element.disable(this.controls.down('.ordered_list_down')); return this; }, getNext: function() { return this.div.next('div.ordered_list_item'); }, getPrev: function() { return this.div.previous('div.ordered_list_item'); }, disableOrderControl: function() { this.controls.down('.ordered_list_up').hide(); this.controls.down('.ordered_list_down').hide(); return this; } }); /** * * * Callbacks: * - `onInitilize` function (response){} * - `onComplete` function (response){} * - `onFailure` function (response){} * - `onError` function (code, error){} * - `onSuccess` function (response, json){} * * @access public */ var BuroEditableList = Class.create(BuroCallbackable, { baseFxDuration: 0.3, initialize: function(id_base, autocompleter_id_base, content, callbacks) { this.id_base = id_base; this.itemsList = $H({}); this.form = false; Object.extend(this,content); BuroCR.set(this.id_base, this); this.update = $('update'+id_base); this.items = $('items'+id_base); this.autocomplete = BuroCR.get(autocompleter_id_base); this.observeControls(this.autocomplete.autocompleter.update.down('.action a')); this.addCallbacks(callbacks); if (this.contents) this.contents.each(this.addNewItem.bind(this)); this.queue = {position:'end', scope: this.id_base}; }, observeControls: function(element) { if (Object.isElement(element) || Object.isElement(element = $(element))) element.observe('click', this.controlClick.bindAsEventListener(this, element)); return this; }, observeForm: function() { var form_id = false, div_form = this.update.down('.buro_form'); if (Object.isElement(div_form)) if (form_id = div_form.readAttribute('id')) this.form = BuroCR.get(form_id).addCallbacks({ onStart: function(form){form.setLoading().lock();}, onCancel: this.formCancel.bind(this), onSave: this.formSaved.bind(this), onReject: function(form, re, json) { form.unsetLoading().unlock(); this.update.update(json.content); this.observeForm.bind(this).defer(); }.bind(this), }); }, formCancel: function() { var content = this.update.innerHTML, iHeight = this.update.show().getHeight(), fHeight = this.update.update().setLoading().getHeight(); this.update.unsetLoading().update(content).setStyle({height: iHeight+'px', overflow: 'hidden'}); new Effect.Morph(this.update, { duration: this.baseFxDuration, queue: this.queue, style: {height: '0px'} }); }, formSaved: function(form, response, json, saved) { this.form.form.unsetLoading().unlock(); new Effect.SlideUp(this.update, { duration: this.baseFxDuration, queue: this.queue, afterFinish: function() { if (this.form) { this.form.purge(); this.form = false; } }.bind(this) }); this.trigger('onAction', 'add', saved); this.items.setLoading(); }, controlClick: function(ev, element) { ev.stop(); if (this.form) this.form.purge(); this.form = false; var action = element.readAttribute('buro:action'); switch (action) { case 'new': this.update.update().setLoading(); this.trigger('onAction', action); break; case 'edit': case 'preview': this.update.update().setLoading(); this.trigger('onAction', action, element.up('div').readAttribute('buro:id')); break; case 'unlink': if (confirm(this.texts.confirm_unlink)) this.removeItem(element.up('div').readAttribute('buro:id'), true); break; } }, addNewItem: function(data) { this.removeItem(data.id); var input = new Element('div').insert(this.templates.input.interpolate(data)).down(), item = new Element('div').insert(this.templates.item.interpolate($H(data).merge(this.texts).toObject())).down(); this.itemsList.set(data.id, {input: input, item:item}); this.items.insert(input).insert(item); item.down('.controls').select('a').each(this.observeControls.bind(this)); }, removeItem: function(id, animate) { var obj = this.itemsList.get(id); if (obj) { this.itemsList.unset(obj.input.value); obj.input.remove(); if (animate) new Effect.Fade(obj.item, { duration: this.baseFxDuration, afterFinish: function(eff) { window.setTimeout(Element.remove.curry(eff.element), 1000); } }); else Element.remove(obj.item); } }, actionError: function(json) { this.trigger('onError'); }, actionSuccess: function(json) { if (this.form) this.form.purge(); this.form = false; switch (json.action) { case 'add': this.addNewItem(json); this.items.unsetLoading(); break; case 'preview': case 'edit': default: var iHeight = this.update.show().unsetLoading().getHeight(), fHeight = this.update.update(json.content).getHeight(); this.update.setStyle({height: iHeight+'px', overflow: 'hidden'}); new Effect.Morph(this.update, { duration: this.baseFxDuration, queue: this.queue, style: {height: fHeight+'px'}, afterFinish: function(fx){ this.update.setStyle({height: '', overflow: ''}); this.observeForm(); }.bind(this) }); break; } }, ACSelected: function(pair) { this.autocomplete.input.value = ''; if (this.itemsList.get(pair.id)) return; this.trigger('onAction', 'add', pair.id); this.items.setLoading(); }, ACUpdated: function() { var new_item = this.autocomplete.autocompleter.update.down('.action'); if (new_item) new_item.show(); } }); /** * * * Callbacks: * - `onStart` function (input){} * - `onComplete` function (input){} * - `onFailure` function (input){} * - `onError` function (code, error){} * - `onSuccess` function (input, json){} * * @access public */ var BuroUpload = Class.create(BuroCallbackable, { initialize: function(id_base, url, errors, parameters) { if (Prototype.Browser.IE) { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 ); } this._submitted = false; this.uploading = false; this.id_base = id_base; this.url = url; this.errors = errors; this.parameters = $H(parameters); BuroCR.set(this.id_base, this); this.iframe = new Element('iframe', { name: 'if'+this.id_base, id: 'if'+this.id_base, src: 'javascript:false;', width: '900', height: '900' }); this.iframe.observe('load', this.complete.bind(this)); this.form = new Element('form', { action: this.url, target: this.iframe.name, method: 'post' }); var upload_enctype = 'multipart/form-data'; if (Prototype.Browser.IE && rv == 7) this.form.writeAttribute({encoding: upload_enctype}); else this.form.writeAttribute({enctype: upload_enctype}); this.div_container = new Element('div') .setStyle({height: '1px', width: '1px', position: 'absolute', left: '-100px', overflow: 'hidden'}) .insert(this.iframe) .insert(this.form); document.body.appendChild(this.div_container); if (!document.loaded) document.observe('dom:loaded', this.startObserve.bindAsEventListener(this, true)); else this.startObserve(true); }, startObserve: function(ev, first) { if (ev === true) first = true; this.master_input = $('mi'+this.id_base); this.hidden_input = $('hi'+this.id_base); this.div_hidden = $('div'+this.id_base); this.master_input.hide(); if (!first || this.hidden_input.value.blank()) { this.tmp_input = this.master_input.clone().show(); this.tmp_input.observe('change', this.submit.bind(this)); this.master_input.insert({after: this.tmp_input}); } }, submit: function() { if (this.tmp_input.value.empty()) return; this.trigger('onStart', this.tmp_input); this.div_hidden.select('input[type=hidden]').each(function(input) { this.form.insert(input.clone()); }.bind(this)); this.parameters.each(function(pair) { this.form.insert(new Element('input', {name: pair.key, value: pair.value})); }.bind(this)); this.div_hidden.up().removeClassName('error'); this.div_hidden.up().select('.error-message').invoke('remove'); this.div_hidden.setLoading(); this.form.insert(this.tmp_input).submit(); this._submitted = true; this.uploading = true; }, complete: function() { if (!this._submitted) return; this.uploading = false; this.div_hidden.unsetLoading(); var d, i = this.iframe; if (i.contentDocument) { d = i.contentDocument; } else if (i.contentWindow) { d = i.contentWindow.document; } else { d = window.frames[this.iframe.name].document; } var response = null; if (d.body.innerHTML.isJSON()) { response = this.responseJSON = d.body.innerHTML.evalJSON(); if (this.responseJSON.error != false) this.trigger('onError', E_JSON, response.error, response); else this.trigger('onSuccess', this.tmp_input, this.responseJSON); if (this.responseJSON.saved != false) this.saved(); else this.rejected(); } else { response = d.body.innerHTML; this.responseJSON = false; this.trigger('onError', E_NOT_JSON); } this.trigger('onComplete', this.tmp_input, response); }, again: function(reset_id) { if (!this._submitted && this.tmp_input) this.tmp_input.remove(); if (reset_id == true) this.hidden_input.value = ''; this._submitted = false; this.uploading = false; this.form.update(); this.startObserve(); this.trigger('onRestart'); }, saved: function() { this.hidden_input.value = this.responseJSON.saved; this.trigger('onSave', this.tmp_input, this.responseJSON, this.responseJSON.saved); }, rejected: function() { this.hidden_input.value = ''; if (this.responseJSON.validationErrors && this.errors) { if (this.errors[$H(this.responseJSON.validationErrors).values()[0]]) this.responseJSON.error = this.errors[$H(this.responseJSON.validationErrors).values()[0]]; else this.responseJSON.error = $H(this.responseJSON.validationErrors).values()[0]; } this.div_hidden.up().addClassName('error'); this.div_hidden.up().insert(new Element('div', {className:'error-message'}).update(this.responseJSON.error)); this.trigger('onReject', this.tmp_input, this.responseJSON, this.responseJSON.saved); this.again(); } }); /** * * * @access public */ var BuroTextile = Class.create(BuroCallbackable, { initialize: function(id_base) { BuroCR.set(id_base, this); this.selection = {start: false, end: false}; this.with_focus = false; this.id_base = id_base; this.input = $('npt'+this.id_base); this.links = this.input.up('.textarea_container').up().select('a.buro_textile'); this.links.invoke('observe', 'click', this.routeAction.bind(this)); this.input.observe('keyup', this.getSelection.bind(this)); this.input.observe('mouseup', this.getSelection.bind(this)); this.input.observe('focus', this.focus.bind(this)); this.input.observe('blur', this.blur.bind(this)); }, routeAction: function (ev) { ev.stop(); var action = ev.findElement('a').readAttribute('buro:action'); switch (action) { case 'bold': this.insertToken('*'); break; case 'italic': this.insertToken('_'); break; case 'superscript': this.insertToken('^'); break; case 'subscript': this.insertToken('~'); break; case 'link': $('itlink'+this.id_base).value = ''; $('iulink'+this.id_base).value = ''; var selection = this.getSelection(this.input); if (selection.start != selection.end) $('itlink'+this.id_base).value = this.input.value.substring(selection.start, selection.end); case 'image': case 'file': case 'title': showPopup(action+this.id_base); break; } }, focus: function(ev) { this.with_focus = true; }, blur: function(ev) { this.with_focus = false; }, insertFile: function(fileJson) { if (fileJson.saved) this.insertLink(fileJson.filename, null, fileJson.dlurl); }, insertImage: function(fileJson) { if (fileJson.saved) this.insert('!'+fileJson.url+'!'); }, insertLink: function(text, title, url) { if (text.blank() || url.blank()) return; if (!url.startsWith('/') && !url.match(/^\w+:\/\//i)) url = 'http://' + url; url = encodeURI(url); this.insert('"'+text+'":'+url+' '); }, insertTitle: function(type, title) { if (title.blank()) return; var selection = this.getSelection(this.input); var header = type + '. ' + title + '\n\n'; var char_before = '\n'; if (selection.start != 0) { char_before = this.input.value.substr(selection.start-1, 1); header = '\n' + header; } if (char_before != '\n' && char_before != '\r') header = '\n' + header; this.insert(header); }, insertToken: function(token) { var selection = this.getSelection(this.input); var textBefore = this.input.value.substring(0, selection.start); var selectedText = this.input.value.substring(selection.start, selection.end); var textAfter = this.input.value.substring(selection.end, this.input.value.length); if (!selectedText.blank()) selectedText = selectedText.replace(/(^[\s\n\t\r]*)([^\t\n\r]*[^\s\t\n\r])([\s\b\t\r]*$)/gim, '$1'+token+'$2'+token+'$3'); this.insert(selectedText); }, insert: function(text) { var scrollTmp = this.input.scrollTop; var selection = this.getSelection(this.input); var textBefore = this.input.value.substring(0, selection.start); var textAfter = this.input.value.substring(selection.end); this.input.value = textBefore+text+textAfter; this.setSelection(this.input, selection.start, selection.start+text.length); this.input.scrollTop = scrollTmp; }, getSelection: function() { if (!this.with_focus) { if (this.selection.start !== false && this.selection.end !== false) return this.selection; else return {start:this.input.value.length, end:this.input.value.length}; } var start, end; if (document.selection) //IE { selected_text = document.selection.createRange().text; start = this.input.value.indexOf(selected_text); if (start != -1) end = start + selected_text.length; } else if (typeof this.input.selectionStart != 'undefined') //FF { start = this.input.selectionStart; end = this.input.selectionEnd; } return this.selection = {start:start, end:end}; }, setSelection: function(input, start, end) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(start,end); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end); range.select(); } this.getSelection(); } }); /** * Create a input that comes with a color palette. * * @access public * @param string id_base */ var CP; var BuroColorPicker = Class.create(BuroCallbackable, { initialize: function(id_base) { if (!(this.input = $('inp'+id_base))) return; if (!CP) CP = new ColorPicker(); BuroCR.set(id_base, this); this.input.observe('focus', this.openCP.bind(this)); this.input.observe('keydown', this.keydown.bind(this)); this.input.observe('keyup', this.keyup.bind(this)); this.sample = $('samp'+id_base); if (!this.input.value.blank()) this.updateSample(); this.observeForm(); }, observeForm: function() { var form = BuroCR.get('frm'+this.input.readAttribute('buro:form')); if (!form) { window.setTimeout(this.observeForm.bind(this), 200); return; } form.addCallbacks({ onReset: this.updateSample.bind(this) }); }, openCP: function(ev) { CP.open(this.input); CP.callbacks.change = this.change.bind(this); if (!this.input.value.blank()) CP.setHex(this.input.value); }, closeCP: function() { CP.close(); return this; }, change: function(color) { this.input.value = color.toHEX(); this.updateSample(); }, keydown: function(ev) { var code = ev.keyCode || ev.witch; if (code == Event.KEY_TAB) this.closeCP(); }, keyup: function(ev) { CP.setHex(this.input.value); this.updateSample(); }, updateSample: function() { this.sample.setStyle({ backgroundColor: this.input.value }); return this; }, setColor: function(color) { this.input.value = color; this.updateSample().closeCP(); return this; } }); /** * Handles the dynamic textarea actions * * @access public */ var BuroDynamicTextarea = Class.create({ initialize: function(id) { this.input = $(id); this.span = this.input.previous().down('span'); this.input .observe('focus', this.focus.bind(this)) .observe('blur', this.blur.bind(this)); if (Prototype.Browser.IE) this.input.attachEvent('onpropertychange', this.update.bind(this)); else this.input.observe('input', this.update.bind(this)); this.update(); this.observeForm(); }, observeForm: function() { var form = BuroCR.get('frm'+this.input.readAttribute('buro:form')); if (!form) { window.setTimeout(this.observeForm.bind(this), 200); return; } form.addCallbacks({ onReset: this.update.bind(this) }); }, update: function(ev) { if (this.span) { if (Prototype.Browser.IE) this.span.innerText = this.input.value; else this.span.textContent = this.input.value; } }, focus: function(ev){this.input.up().addClassName('focus')}, blur: function(ev){this.input.up().removeClassName('focus')} });
mit
greatwolf/cryptofu
arbitrate.lua
3687
local tablex = require 'pl.tablex' local isempty = function (t) return not next (t) end local compute_arb = function (orderbook1, orderbook2) --[[ arbitration algorithm orderbook 1 orderbook 2 buy sell 0.02018989 0.00015972 0.02016002 1.47555059 0.02016001 6.35601551 0.02015999 3.94617200 0.02014996 8.32493600 0.02014992 66.04248947 0.02014990 39.63971162 ->> 39.02813755 ->> 21.45727557 ->> 13.62995628 0.02040001 0.61086245 x 0.02040000 17.57086198 x 0.02020000 7.82731929 x 0.02010000 57.32231791 0.01985023 3.07442252 while sell_pos.price < buy_pos.price last_sellprice = sell_pos.price last_buyprice = buy_pos.price if sell_pos.amount < buy_pos.amount accum += sell_pos.amount buy_pos.amount -= sell_pos.amount sell_pos++ else accum += buy_pos.amount sell_pos.amount -= buy_pos.amount buy_pos++ buy/sell amount +0.61086245 +17.57086198 +7.82731929 final output: buy 26.00904372 @0.02014990 sell 26.00904372 @0.02020000 --]] local ask_amounts = tablex.icopy ({}, orderbook2.asks.amount) local bid_amounts = tablex.icopy ({}, orderbook1.bids.amount) local sells, buys = orderbook2.asks.price, orderbook1.bids.price local ask_index, bid_index = 1, 1 local r = { buy = orderbook2, sell = orderbook1, } while sells[ask_index] and buys[bid_index] and sells[ask_index] < buys[bid_index] do table.insert (r, { buyprice = sells[ask_index], sellprice = buys[bid_index] }) r[#r].amount = math.min (ask_amounts[ask_index], bid_amounts[bid_index]) ask_amounts[ask_index] = ask_amounts[ask_index] - r[#r].amount bid_amounts[bid_index] = bid_amounts[bid_index] - r[#r].amount if bid_amounts[bid_index] == 0 then bid_index = bid_index + 1 end if ask_amounts[ask_index] == 0 then ask_index = ask_index + 1 end end return #r > 0 and r end local arbitrate = function (orderbook1, orderbook2) if not isempty (orderbook1.bids.price) and not isempty (orderbook2.asks.price) and orderbook2.asks.price[1] < orderbook1.bids.price[1] then return compute_arb (orderbook1, orderbook2) end if not isempty (orderbook2.bids.price) and not isempty (orderbook1.asks.price) and orderbook1.asks.price[1] < orderbook2.bids.price[1] then return compute_arb (orderbook2, orderbook1) end return false end local makearb = function (apiname1, apiname2, market1, market2, arbhandler_callback) local log = require 'tools.logger' (apiname1 .. "<->" .. apiname2 .. " " .. market1 .. "/" .. market2) local api1 = require ("exchange." .. apiname1) local api2 = require ("exchange." .. apiname2) local main = function () local o1, o2 while true do local noerr, errmsg = pcall (function () o1 = api1:orderbook (market1, market2) o2 = api2:orderbook (market1, market2) local res = arbitrate (o1, o2) if res then res.buy = res.buy == o1 and apiname1 or apiname2 res.sell = res.sell == o2 and apiname2 or apiname1 arbhandler_callback { res, [apiname1] = api1, [apiname2] = api2, log = log} end end) log._if (not noerr, errmsg) if not noerr and errmsg:match "wantread" then break end coroutine.yield () end end return { main = main, interval = 4 } end return { arbitrate = arbitrate, makearb = makearb }
mit
Killiancorbel/Timvelo
src/TV/CoreBundle/Repository/ResultRepository.php
239
<?php namespace TV\CoreBundle\Repository; /** * ResultRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ResultRepository extends \Doctrine\ORM\EntityRepository { }
mit
acolin/sailsify
lib/sailsify/version.rb
40
module Sailsify VERSION = "0.0.2" end
mit
tinkerspy/Automaton
src/Atm_encoder.hpp
1063
#pragma once #include <Automaton.h> class Atm_encoder : public Machine { public: enum { IDLE, UP, DOWN }; // STATES enum { EVT_UP, EVT_DOWN, ELSE }; // EVENTS Atm_encoder( void ) : Machine(){}; Atm_encoder& begin( int pin1, int pin2, int divider = 1 ); Atm_encoder& trace( Stream& stream ); Atm_encoder& onChange( Machine& machine, int event = 0 ); Atm_encoder& onChange( atm_cb_push_t callback, int idx = 0 ); Atm_encoder& onChange( bool status, Machine& machine, int event = 0 ); Atm_encoder& onChange( bool status, atm_cb_push_t callback, int idx = 0 ); int state( void ); Atm_encoder& range( int min, int max, bool wrap = false ); Atm_encoder& set( int value ); private: enum { LP_IDLE, ENT_UP, ENT_DOWN }; // ACTIONS short pin1, pin2; const static char enc_states[]; uint8_t enc_bits; int8_t enc_counter; int8_t enc_direction; int divider; int value, min, max; bool wrap, range_invert; atm_connector onup, ondown; bool count( int direction ); int event( int id ); void action( int id ); };
mit
junwang1216/btgk-edms
edms-support/src/test/java/groovy/util/RandomCreditCardNumberGenerator.java
5274
package groovy.util; import java.util.List; import java.util.Stack; import java.util.Vector; /** * Created by zhaotao on 2016/4/1. */ public class RandomCreditCardNumberGenerator { public static final String[] VISA_PREFIX_LIST = new String[]{"4539", "4556", "4916", "4532", "4929", "40240071", "4485", "4716", "4" }; public static final String[] MASTERCARD_PREFIX_LIST = new String[]{"51", "52", "53", "54", "55"}; public static final String[] AMEX_PREFIX_LIST = new String[]{"34", "37"}; public static final String[] DISCOVER_PREFIX_LIST = new String[]{"6011"}; public static final String[] DINERS_PREFIX_LIST = new String[]{"300", "301", "302", "303", "36", "38"}; public static final String[] ENROUTE_PREFIX_LIST = new String[]{"2014", "2149"}; public static final String[] JCB_PREFIX_LIST = new String[]{"35"}; public static final String[] VOYAGER_PREFIX_LIST = new String[]{"8699"}; static String strrev(String str) { if (str == null) return ""; String revstr = ""; for (int i = str.length() - 1; i >= 0; i--) { revstr += str.charAt(i); } return revstr; } /* * 'prefix' is the start of the CC number as a string, any number of digits. * 'length' is the length of the CC number to generate. Typically 13 or 16 */ static String completed_number(String prefix, int length) { String ccnumber = prefix; // generate digits while (ccnumber.length() < (length - 1)) { ccnumber += new Double(Math.floor(Math.random() * 10)).intValue(); } // reverse number and convert to int String reversedCCnumberString = strrev(ccnumber); List<Integer> reversedCCnumberList = new Vector<Integer>(); for (int i = 0; i < reversedCCnumberString.length(); i++) { reversedCCnumberList.add(new Integer(String .valueOf(reversedCCnumberString.charAt(i)))); } // calculate sum int sum = 0; int pos = 0; Integer[] reversedCCnumber = reversedCCnumberList .toArray(new Integer[reversedCCnumberList.size()]); while (pos < length - 1) { int odd = reversedCCnumber[pos] * 2; if (odd > 9) { odd -= 9; } sum += odd; if (pos != (length - 2)) { sum += reversedCCnumber[pos + 1]; } pos += 2; } // calculate check digit int checkdigit = new Double( ((Math.floor(sum / 10) + 1) * 10 - sum) % 10).intValue(); ccnumber += checkdigit; return ccnumber; } public static String[] credit_card_number(String[] prefixList, int length, int howMany) { Stack<String> result = new Stack<String>(); for (int i = 0; i < howMany; i++) { int randomArrayIndex = (int) Math.floor(Math.random() * prefixList.length); String ccnumber = prefixList[randomArrayIndex]; result.push(completed_number(ccnumber, length)); } return result.toArray(new String[result.size()]); } public static String[] generateMasterCardNumbers(int howMany) { return credit_card_number(MASTERCARD_PREFIX_LIST, 16, howMany); } public static String generateMasterCardNumber() { return credit_card_number(MASTERCARD_PREFIX_LIST, 16, 1)[0]; } public static boolean isValidCreditCardNumber(String creditCardNumber) { boolean isValid = false; try { String reversedNumber = new StringBuffer(creditCardNumber) .reverse().toString(); int mod10Count = 0; for (int i = 0; i < reversedNumber.length(); i++) { int augend = Integer.parseInt(String.valueOf(reversedNumber .charAt(i))); if (((i + 1) % 2) == 0) { String productString = String.valueOf(augend * 2); augend = 0; for (int j = 0; j < productString.length(); j++) { augend += Integer.parseInt(String.valueOf(productString .charAt(j))); } } mod10Count += augend; } if ((mod10Count % 10) == 0) { isValid = true; } } catch (NumberFormatException e) { } return isValid; } public static void main(String[] args) { int howMany = 0; try { howMany = Integer.parseInt(args[0]); } catch (Exception e) { System.err .println("Usage error. You need to supply a numeric argument (ex: 500000)"); } String[] creditcardnumbers = generateMasterCardNumbers(howMany); for (int i = 0; i < creditcardnumbers.length; i++) { System.out.println(creditcardnumbers[i] + ":" + (isValidCreditCardNumber(creditcardnumbers[i]) ? "valid" : "invalid")); } } }
mit
kwotsin/TensorFlow-ENet
preprocessing.py
1295
import tensorflow as tf def preprocess(image, annotation=None, height=360, width=480): ''' Performs preprocessing for one set of image and annotation for feeding into network. NO scaling of any sort will be done as per original paper. INPUTS: - image (Tensor): the image input 3D Tensor of shape [height, width, 3] - annotation (Tensor): the annotation input 3D Tensor of shape [height, width, 1] - height (int): the output height to reshape the image and annotation into - width (int): the output width to reshape the image and annotation into OUTPUTS: - preprocessed_image(Tensor): the reshaped image tensor - preprocessed_annotation(Tensor): the reshaped annotation tensor ''' #Convert the image and annotation dtypes to tf.float32 if needed if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) # image = tf.cast(image, tf.float32) image = tf.image.resize_image_with_crop_or_pad(image, height, width) image.set_shape(shape=(height, width, 3)) if not annotation == None: annotation = tf.image.resize_image_with_crop_or_pad(annotation, height, width) annotation.set_shape(shape=(height, width, 1)) return image, annotation return image
mit
torstenheinrich/lej-order-php
src/LejOrder/IdentityAccess/Domain/Model/Enablement.php
77
<?php namespace LejOrder\IdentityAccess\Domain\Model; class Enablement { }
mit
bbender/spark-js-sdk
packages/node_modules/@webex/plugin-phone/src/bool-to-status.js
624
/*! * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file. */ /** * Helper for converting booleans into an sdp-style direction string * @param {Boolean} sending * @param {Boolean} receiving * @private * @returns {String} */ export default function boolToStatus(sending, receiving) { if (sending && receiving) { return 'sendrecv'; } if (sending && !receiving) { return 'sendonly'; } if (!sending && receiving) { return 'recvonly'; } if (!sending && !receiving) { return 'inactive'; } throw new Error('If you see this error, your JavaScript engine has a major flaw'); }
mit
Darrow87/phase-0
week-5/group-research-methods/methods_spec.rb
1044
require_relative "my_solution" # PERSON 4: DELETE MATCHING DATA describe 'PERSON 4: my_array_deletion_method!' do let(:i_want_pets) { ["I", "want", 3, "pets", "but", "only", "have", 2 ] } it "deletes all words that contain an 'a'" do expect(my_array_deletion_method!(i_want_pets, "a")).to eq ["I", 3, "pets", "but", "only", 2 ] end it "operates destructively" do expect(my_array_deletion_method!(i_want_pets, "o").object_id).to eq(i_want_pets.object_id) end end describe 'PERSON 4: my_hash_deletion_method!' do let(:my_family_pets_ages) {{"Evi" => 6, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0, "Ditto" => 3}} it "deletes an animal based on name" do expect(my_hash_deletion_method!(my_family_pets_ages, "George")).to eq({"Evi" => 6, "Hoobie" => 3, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0, "Ditto" => 3}) end it "operates destructively" do expect(my_hash_deletion_method!(my_family_pets_ages, "George").object_id).to eq(my_family_pets_ages.object_id) end end
mit
fernandoPalaciosGit/PARTNERS
William/algoritmos/Vectorimpar17.java
387
package algoritmos�os_algoritmos; public class Vectorimpar17 { public static void main(String[] args) { int[] numeros; numeros = new int[100]; int num =1; for (int i = 0; i <numeros.length; i++) { numeros[i]= num ; num++; } for(int i=numeros.length-1; i>=0; i--){ if((numeros[i]%2)!=0) System.out.print(numeros[i]+" "); } } }
mit
karim/adila
database/src/main/java/adila/db/gt2ds5830m_gt2ds5830m.java
233
// This file is automatically generated. package adila.db; /* * Samsung Galaxy Ace * * DEVICE: GT-S5830M * MODEL: GT-S5830M */ final class gt2ds5830m_gt2ds5830m { public static final String DATA = "Samsung|Galaxy Ace|"; }
mit
thefex/Xamarin.FileExplorer
Xamarin.iOS.FileExplorer/Xamarin.iOS.FileExplorer/CustomViews/CollectionViewHeader.cs
2235
using System; using System.IO; using CoreGraphics; using Foundation; using UIKit; using Xamarin.iOS.FileExplorer.ViewModels; namespace Xamarin.iOS.FileExplorer.CustomViews { public sealed class CollectionViewHeader : UICollectionReusableView { private UISegmentedControl segmentedControl; private readonly Action<SortMode> sortModeChangeAction = sortMode => { }; public CollectionViewHeader() { Initialize(); } public CollectionViewHeader(NSCoder coder) : base(coder) { Initialize(); } public CollectionViewHeader(CGRect frame) : base(frame) { Initialize(); } public CollectionViewHeader(IntPtr ptr) : base(ptr) { Initialize(); } private void Initialize() { segmentedControl = new UISegmentedControl(new object[] {"Name", "Date"}); segmentedControl.SizeToFit(); segmentedControl.Frame = new CGRect(segmentedControl.Frame.X, segmentedControl.Frame.Y, 160, segmentedControl.Bounds.Size.Height); segmentedControl.AutoresizingMask = UIViewAutoresizing.None; segmentedControl.ValueChanged += (sender, args) => { sortModeChangeAction(sortMode); }; AddSubview(segmentedControl); sortMode = SortMode.Name; } private SortMode sortMode { get { switch (segmentedControl.SelectedSegment) { case 0: return SortMode.Name; case 1: return SortMode.Date; default: throw new InvalidDataException(); } } set { switch (value) { case SortMode.Name: segmentedControl.SelectedSegment = 0; break; case SortMode.Date: segmentedControl.SelectedSegment = 1; break; } } } } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/lodash-compat/3.5.0/lodash.js
131
version https://git-lfs.github.com/spec/v1 oid sha256:5cce0c9efb8fc8416adbaea7125effa8f8f8c6c7a3c672c011f07f096b87f482 size 397251
mit
mstane/algorithms-in-java
src/main/java/org/sm/jdsa/tree/AvlNode.java
320
package org.sm.jdsa.tree; public class AvlNode<E> { E element; AvlNode<E> left; AvlNode<E> right; int height; AvlNode(E e) { this(e, null, null, 0); } AvlNode(E e, AvlNode<E> left, AvlNode<E> right, int height) { this.element = e; this.left = left; this.right = right; this.height = height; } }
mit
h2non/bimg
version.go
98
package bimg // Version represents the current package semantic version. const Version = "1.1.6"
mit
wefine/reactjs-guide
react-redux-basic/src/component/User.js
697
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const User = ({name}) => { return ( <div> <div className="row"> <div className="col-xs-12"> <h1>The User Page</h1> </div> </div> <div className="row"> <div className="col-xs-12"> <p>User Name: {name}</p> </div> </div> </div> ); }; User.propTypes = { name: PropTypes.string }; const mapStateToProps = (state) => { return { name: state.user.name } }; export default connect(mapStateToProps)(User);
mit