language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
8,180
2.53125
3
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode-public-domain", "JSON", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-4-Clause", "Python-2.0", "LGPL-2.1-or-later" ]
permissive
//[ Lambda /////////////////////////////////////////////////////////////////////////////// // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This example builds a simple but functional lambda library using Proto. #include <iostream> #include <algorithm> #include <boost/mpl/int.hpp> #include <boost/mpl/min_max.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/next_prior.hpp> #include <boost/fusion/tuple.hpp> #include <boost/typeof/typeof.hpp> #include <boost/typeof/std/ostream.hpp> #include <boost/typeof/std/iostream.hpp> #include <boost/proto/core.hpp> #include <boost/proto/context.hpp> #include <boost/proto/transform.hpp> namespace mpl = boost::mpl; namespace proto = boost::proto; namespace fusion = boost::fusion; using proto::_; // Forward declaration of the lambda expression wrapper template<typename T> struct lambda; struct lambda_domain : proto::domain<proto::pod_generator<lambda> > {}; template<typename I> struct placeholder { typedef I arity; }; template<typename T> struct placeholder_arity { typedef typename T::arity type; }; // The lambda grammar, with the transforms for calculating the max arity struct lambda_arity : proto::or_< proto::when< proto::terminal< placeholder<_> > , mpl::next<placeholder_arity<proto::_value> >() > , proto::when< proto::terminal<_> , mpl::int_<0>() > , proto::when< proto::nary_expr<_, proto::vararg<_> > , proto::fold<_, mpl::int_<0>(), mpl::max<lambda_arity, proto::_state>()> > > {}; // The lambda context is the same as the default context // with the addition of special handling for lambda placeholders template<typename Tuple> struct lambda_context : proto::callable_context<lambda_context<Tuple> const> { lambda_context(Tuple const &args) : args_(args) {} template<typename Sig> struct result; template<typename This, typename I> struct result<This(proto::tag::terminal, placeholder<I> const &)> : fusion::result_of::at<Tuple, I> {}; template<typename I> typename fusion::result_of::at<Tuple, I>::type operator ()(proto::tag::terminal, placeholder<I> const &) const { return fusion::at<I>(this->args_); } Tuple args_; }; // The lambda<> expression wrapper makes expressions polymorphic // function objects template<typename T> struct lambda { BOOST_PROTO_BASIC_EXTENDS(T, lambda<T>, lambda_domain) BOOST_PROTO_EXTENDS_ASSIGN() BOOST_PROTO_EXTENDS_SUBSCRIPT() // Calculate the arity of this lambda expression static int const arity = boost::result_of<lambda_arity(T)>::type::value; template<typename Sig> struct result; // Define nested result<> specializations to calculate the return // type of this lambda expression. But be careful not to evaluate // the return type of the nullary function unless we have a nullary // lambda! template<typename This> struct result<This()> : mpl::eval_if_c< 0 == arity , proto::result_of::eval<T const, lambda_context<fusion::tuple<> > > , mpl::identity<void> > {}; template<typename This, typename A0> struct result<This(A0)> : proto::result_of::eval<T const, lambda_context<fusion::tuple<A0> > > {}; template<typename This, typename A0, typename A1> struct result<This(A0, A1)> : proto::result_of::eval<T const, lambda_context<fusion::tuple<A0, A1> > > {}; // Define our operator () that evaluates the lambda expression. typename result<lambda()>::type operator ()() const { fusion::tuple<> args; lambda_context<fusion::tuple<> > ctx(args); return proto::eval(*this, ctx); } template<typename A0> typename result<lambda(A0 const &)>::type operator ()(A0 const &a0) const { fusion::tuple<A0 const &> args(a0); lambda_context<fusion::tuple<A0 const &> > ctx(args); return proto::eval(*this, ctx); } template<typename A0, typename A1> typename result<lambda(A0 const &, A1 const &)>::type operator ()(A0 const &a0, A1 const &a1) const { fusion::tuple<A0 const &, A1 const &> args(a0, a1); lambda_context<fusion::tuple<A0 const &, A1 const &> > ctx(args); return proto::eval(*this, ctx); } }; // Define some lambda placeholders lambda<proto::terminal<placeholder<mpl::int_<0> > >::type> const _1 = {{}}; lambda<proto::terminal<placeholder<mpl::int_<1> > >::type> const _2 = {{}}; template<typename T> lambda<typename proto::terminal<T>::type> const val(T const &t) { lambda<typename proto::terminal<T>::type> that = {{t}}; return that; } template<typename T> lambda<typename proto::terminal<T &>::type> const var(T &t) { lambda<typename proto::terminal<T &>::type> that = {{t}}; return that; } template<typename T> struct construct_helper { typedef T result_type; // for TR1 result_of T operator()() const { return T(); } // Generate BOOST_PROTO_MAX_ARITY overloads of the // following function call operator. #define BOOST_PROTO_LOCAL_MACRO(N, typename_A, A_const_ref, A_const_ref_a, a)\ template<typename_A(N)> \ T operator()(A_const_ref_a(N)) const \ { return T(a(N)); } #define BOOST_PROTO_LOCAL_a BOOST_PROTO_a #include BOOST_PROTO_LOCAL_ITERATE() }; // Generate BOOST_PROTO_MAX_ARITY-1 overloads of the // following construct() function template. #define M0(N, typename_A, A_const_ref, A_const_ref_a, ref_a) \ template<typename T, typename_A(N)> \ typename proto::result_of::make_expr< \ proto::tag::function \ , lambda_domain \ , construct_helper<T> \ , A_const_ref(N) \ >::type const \ construct(A_const_ref_a(N)) \ { \ return proto::make_expr< \ proto::tag::function \ , lambda_domain \ >( \ construct_helper<T>() \ , ref_a(N) \ ); \ } BOOST_PROTO_REPEAT_FROM_TO(1, BOOST_PROTO_MAX_ARITY, M0) #undef M0 struct S { S() {} S(int i, char c) { std::cout << "S(" << i << "," << c << ")\n"; } }; int main() { // Create some lambda objects and immediately // invoke them by applying their operator(): int i = ( (_1 + 2) / 4 )(42); std::cout << i << std::endl; // prints 11 int j = ( (-(_1 + 2)) / 4 )(42); std::cout << j << std::endl; // prints -11 double d = ( (4 - _2) * 3 )(42, 3.14); std::cout << d << std::endl; // prints 2.58 // check non-const ref terminals (std::cout << _1 << " -- " << _2 << '\n')(42, "Life, the Universe and Everything!"); // prints "42 -- Life, the Universe and Everything!" // "Nullary" lambdas work too int k = (val(1) + val(2))(); std::cout << k << std::endl; // prints 3 // check array indexing for kicks int integers[5] = {0}; (var(integers)[2] = 2)(); (var(integers)[_1] = _1)(3); std::cout << integers[2] << std::endl; // prints 2 std::cout << integers[3] << std::endl; // prints 3 // Now use a lambda with an STL algorithm! int rgi[4] = {1,2,3,4}; char rgc[4] = {'a','b','c','d'}; S rgs[4]; std::transform(rgi, rgi+4, rgc, rgs, construct<S>(_1, _2)); return 0; } //]
Ruby
UTF-8
546
3.03125
3
[]
no_license
require 'minitest/autorun' class QuickSortTest < Minitest::Test def test_simple assert_equal [1,2,3,4,5], quick_sort([2,3,4,5,1]) end def test_repeated_numbers assert_equal [1,1,1,2,2,3], quick_sort([2,2,3,1,1,1]) end def test_negative_numbers assert_equal [-1,2,3,4,5], quick_sort([5,3,2,-1,4]) end def test_sorting_twice list = [5,4,3,2,1] assert_equal [1,2,3,4,5], quick_sort(list) assert_equal [1,2,3,4,5], quick_sort(list) end def test_empty_list assert_equal [], quick_sort([]) end end
C#
UTF-8
7,056
2.59375
3
[ "MIT" ]
permissive
using System.IO; using System.Windows; using Microsoft.Win32; using System.Diagnostics; namespace DragonInjector_Firmware_Tool { public partial class MainWindow : Window { string uf2File; string uf2ShortFile; readonly string defaultUF2File = Directory.GetCurrentDirectory() + "\\defaultpayload.uf2"; readonly string bootloader = Directory.GetCurrentDirectory() + "\\defaultbootloader.uf2"; public MainWindow() { InitializeComponent(); DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { if (d.VolumeLabel == "DRAGONBOOT") { DriveBox.Items.Add(d.Name); OutputBox.Content += "\n\\:Found drive: " + (d.Name).Replace(":\\",""); OutputBox.ScrollToBottom(); } } DriveBox.SelectedIndex = 0; } private void DriveButton_Click(object sender, RoutedEventArgs e) { OutputBox.Content += "\n...Scanning"; int selectedIndex = DriveBox.SelectedIndex; DriveBox.Items.Clear(); DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { if (d.VolumeLabel == "DRAGONBOOT") { DriveBox.Items.Add(d.Name); OutputBox.Content += "\n\\:Found drive: " + (d.Name).Replace(":\\", ""); OutputBox.ScrollToBottom(); } } DriveBox.SelectedIndex = selectedIndex; } private void CloseButton_Click(object sender, RoutedEventArgs e) { Window.Close(); } private void CheckUpdateButton_Click(object sender, RoutedEventArgs e) { OutputBox.Content += "\n...Checking for updates"; OutputBox.ScrollToBottom(); LatestBootloaderVersionLabel.Text = "v1.1"; LatestFirmwareVersionLabel.Text = "DRAGONBOOT v1.3"; } private void FlashButton_Click(object sender, RoutedEventArgs e) { string dest = DriveBox.SelectedItem.ToString() + "\\flash.uf2"; if (uf2File != null) { OutputBox.Content += "\n\\:Copying " + uf2ShortFile + " to " + DriveBox.SelectedItem.ToString().Replace(":\\", ""); OutputBox.ScrollToBottom(); File.Copy(uf2File, dest, true); } else { OutputBox.Content += "\n\\:Copying default payload to " + DriveBox.SelectedItem.ToString().Replace(":\\", ""); OutputBox.ScrollToBottom(); File.Copy(defaultUF2File, dest, true); } } private void FlashAllButton_Click(object sender, RoutedEventArgs e) { if (uf2File != null) { foreach (var item in DriveBox.Items) { string dest = item.ToString() + "\\flash.uf2"; OutputBox.Content += "\n\\:Copying " + uf2ShortFile + " to " + item.ToString().Replace(":\\", ""); OutputBox.ScrollToBottom(); File.Copy(uf2File, dest, true); } } else { foreach (var item in DriveBox.Items) { string dest = item.ToString() + "\\flash.uf2"; OutputBox.Content += "\n\\:Copying default payload to " + item.ToString().Replace(":\\", ""); OutputBox.ScrollToBottom(); File.Copy(defaultUF2File, dest, true); } } } private void BootloaderButton_Click(object sender, RoutedEventArgs e) { string dest = DriveBox.SelectedItem.ToString() + "\\flash.uf2"; OutputBox.Content += "\n\\:Updating bootloader on " + DriveBox.SelectedItem.ToString().Replace(":\\", ""); OutputBox.ScrollToBottom(); File.Copy(bootloader, dest, true); } private void BootloaderAllButton_Click(object sender, RoutedEventArgs e) { foreach (var item in DriveBox.Items) { string dest = item.ToString() + "\\flash.uf2"; OutputBox.Content += "\n\\:Updating bootloader on " + (item.ToString()).Replace(":\\", ""); OutputBox.ScrollToBottom(); File.Copy(bootloader, dest, true); } } private void Drag_Click(object sender, RoutedEventArgs e) { Window.DragMove(); } private void PayloadTextBox_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); { openFileDialog.Filter = "UF2 (*.uf2)|*.uf2"; if (openFileDialog.ShowDialog() == true) { string filePath = openFileDialog.FileName; uf2ShortFile = (Path.GetFileName(filePath)).ToString(); uf2File = Path.GetFullPath(filePath).ToString(); PayloadTextBox.Text = uf2ShortFile; OutputBox.Content += "\nGot payload: " + (Path.GetFileName(filePath)).ToString(); OutputBox.ScrollToBottom(); } } } private void DriveBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { try { string selectedItem = (DriveBox.SelectedItem).ToString(); StreamReader infoUF2 = new System.IO.StreamReader(selectedItem + "INFO_UF2.TXT"); string infoUF2Line = infoUF2.ReadLine(); if (infoUF2Line.Contains("DragonInjector UF2 Bootloader")) { BootloaderVersionLabel.Text = (infoUF2Line.Replace("DragonInjector UF2 Bootloader ", "")); } else { BootloaderVersionLabel.Text = "Custom"; } } catch { } } private void PayloadButton_Click(object sender, RoutedEventArgs e) { PayloadTextBox.Clear(); OutputBox.Content += "\n...Using default payload"; OutputBox.ScrollToBottom(); } private void LogoButton_Click(object sender, RoutedEventArgs e) { Process.Start("https://www.dragoninjector.com"); } } } /* TODO: Really need to fix and add try/catch, especially where drive scan happens Check if default files exist first Add customization options = show boot logo, show path only, no visual feedback Figure out how to pull firmware version Add "pressed" states to buttons Make check for updates actually, you know, check for updates Possibly add more verbose output */
PHP
UTF-8
1,919
2.53125
3
[]
no_license
<?php declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20180516074344 extends AbstractMigration { public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE series (id VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, description LONGTEXT DEFAULT NULL, first_date DATETIME NOT NULL, last_date DATETIME NOT NULL, create_date DATETIME NOT NULL, mod_date DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE Series_pages (series_id VARCHAR(255) NOT NULL, page_id VARCHAR(255) NOT NULL, INDEX IDX_70B3265B514956FD (series_id), INDEX IDX_70B3265BC4663E4 (page_id), PRIMARY KEY(series_id, page_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE Series_pages ADD CONSTRAINT FK_70B3265B514956FD FOREIGN KEY (series_id) REFERENCES series (id)'); $this->addSql('ALTER TABLE Series_pages ADD CONSTRAINT FK_70B3265BC4663E4 FOREIGN KEY (page_id) REFERENCES page (id)'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE Series_pages DROP FOREIGN KEY FK_70B3265B514956FD'); $this->addSql('DROP TABLE series'); $this->addSql('DROP TABLE Series_pages'); } }
Java
UTF-8
730
2.8125
3
[]
no_license
package autre; import java.util.Scanner; public class Autre { public final static Scanner lire_clavier = new Scanner(System.in); final static String alphabet_grec[] = { "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi", "rho", "sigma", "tau", "upsilon", "phi", "khi", "psi", "omega" }; public static int nombre_aleatoire_borne(int minimum, int maximum) { int randomNum = minimum + (int) (Math.random() * maximum); return randomNum; } public static String recuperer_alphabet_grec(int index) { return alphabet_grec[index]; } public static void clearScreen() { System.out.print("\033[H\033[2J"); System.out.flush(); } }
JavaScript
UTF-8
1,864
3.03125
3
[]
no_license
'use strict' let CacheClientFactory = require('./CacheClientFactory'); class Cache { /** * * @param {String} host Host IP address * @param {Integer} port Port used by the cache server * @param {String} vendor 'redis' or 'memcached' */ constructor(host, port, vendor) { this.client = new CacheClientFactory(host, port, vendor); } /** * Gets a value by key * @param {String} key A cache key * @return {Promise} A promise containing the value or an error */ get(key) { return this.client.get(key); } /** * Creates a Key and adds a value to it * @param {String} key * @param {Promise} val A promise containing an OK message or en error */ set(key, val) { return this.client.set(key, val); } /** * Gets a hash as a JSON object * @param {String} key * @return {Promise} A promise containing a JSON object or an error */ getHash(key) { return this.client.getHash(key); } /** * Stores a JSON Object as a Hash * @param {String} key * @param {JSON} object to be stored * @return {Promise} Promise containing an OK message or an error */ setHash(key, object) { return this.client.setHash(key, object); } /** * Deletes a value by key * @param {String} key * @return {Promise} Promise containing an OK message or an error */ delete(key) { return this.client.delete(key); } /** * Gets a value by key. If it doesn't exist, executes the callback * in order to fetch and set the value * @param {String} key key to get or fetch * @param {Function} callback A callback that fetches the value to be set * @return {Promise} Promise containing the get or fetched value */ getOrFetch(key, callback){ return this.client.getOrFetch(key, callback); } } module.exports = Cache;
JavaScript
UTF-8
1,546
2.5625
3
[]
no_license
module.exports = function (RED) { const BS = require('node-beacon-scanner'); const scanner = new BS(); let setStatus = (node, scanning, error) => { node.status({ fill: scanning ? "blue" : error ? "red" : "grey", shape: scanning ? "dot" : "ring", text: scanning ? "scanning" : error ? "error" : "stopped" }); node.scanning = scanning; }; let start = (node, scanner) => { if (node.scanning) return; scanner.startScan().then(() => { setStatus(node, true) node.log('Scanner started'); }).catch((error) => { setStatus(node, false, error); node.error('Error starting scanner', { payload: {}, error: error }); }); }; let stop = (node, scanner) => { if (!node.scanning) return; scanner.stopScan(); setStatus(node, false) node.log('Scanner stopped'); } function BeaconScanner(config) { RED.nodes.createNode(this, config); let node = this; // Initial status setStatus(node, false); // Read input node.on("input", function (msg) { if (msg.payload === true || msg.payload === 1 || msg.payload === "on") { start(node, scanner); } else { stop(node, scanner); } }); // Send message when receive an advertisement scanner.onadvertisement = (data) => { msg = {}; msg.topic = node.topic; msg.payload = JSON.stringify(data); node.send(msg); node.trace('Sending message payload', msg.payload); }; // Stop scanning on close node.on("close", function () { stop(node, scanner); }); } RED.nodes.registerType("BeaconScanner", BeaconScanner); }
Markdown
UTF-8
732
2.84375
3
[]
no_license
# MVP 1. Users * User registration with validations * Login page for users with validations * User authentication that persists throughout session * Guest User (for demonstration) * Login/Logout functionality * Profile/Profile photo that appears in top right when logged in 2. Upload/Remove Files and Folders * Utilizes Amazon S3 to store and retrieve data * Only allows certain file types to be uploaded * Flags items as "deleted" in database which will move their location to "Deleted files" 3. Drag and Drop * Ability to drag a file or folder into a target location to upload data 4. Move File and Folder Locations * Ability to move files or folders into a different folder locations
C
UTF-8
68,993
3.21875
3
[ "MIT" ]
permissive
#include "gfops.h" #ifdef SLOW //-------------------------------------------------------------------------- // GF(2^8) multiplication modulo x^8 + x^4 + x^3 + x + 1 in constant time //-------------------------------------------------------------------------- uint8_t gfmult( uint8_t h, uint8_t v ){ uint8_t z = 0 ; uint8_t i = 0 ; uint8_t mask = 0; for( i=0 ; i<8 ; i++ ){ mask = -( (h>>i) & 1 ); //check every bit of h and create a mask of 0xff or 0x00 depending on if the bit is 1 or 0 respectively. z = z ^(mask & v); //according to the mask, either a 0 or the other [shifted] [reduced] operand is added to the result mask = -( (v>>7) & 1 ); //create a mask based on the degree of the other operand v<<=1; //shift v one position v^= mask & 0x1b; //if the degree of the other operand is more than 7, reduce it modulo 0x1b } return z ; } //-------------------------------------------------------------------------- // GF(2^8) squaring modulo x^8 + x^4 + x^3 + x + 1 in constant time //-------------------------------------------------------------------------- uint8_t gfsqr( uint8_t a ){ return (a & 0x01)^((a&0x02)<<1)^((a&0x04)<<2)^((a&0x08)<<3)^(-((a&0x10)>>4)&0x1b)^(-((a&0x20)>>5)&0x6c)^(-((a&0x40)>>6)&0xab)^(-((a&0x80)>>7)&0x9a) ; } #elif FAST //-------------------------------------------------------------------------- // GF(2^8) multiplication modulo x^8 + x^4 + x^3 + x + 1 in constant time, // uses precomputed 8KB LUT, requires 2 look-ups and 1 field addition //-------------------------------------------------------------------------- static const uint8_t lLUT[16][256] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,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e, 0x01, 0x54, 0x5b, 0x4a, 0x45, 0x68, 0x67, 0x76, 0x79, 0xdc, 0xd3, 0xc2, 0xcd, 0xe0, 0xef, 0xfe, 0xf1, 0xa4, 0xab, 0xba, 0xb5, 0x98, 0x97, 0x86, 0x89, 0xd7, 0xd8, 0xc9, 0xc6, 0xeb, 0xe4, 0xf5, 0xfa, 0xaf, 0xa0, 0xb1, 0xbe, 0x93, 0x9c, 0x8d, 0x82, 0x27, 0x28, 0x39, 0x36, 0x1b, 0x14, 0x05, 0x0a, 0x5f, 0x50, 0x41, 0x4e, 0x63, 0x6c, 0x7d, 0x72} }; // end of lLUT static const uint8_t hLUT[16][256] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x1b, 0x0b, 0x3b, 0x2b, 0x5b, 0x4b, 0x7b, 0x6b, 0x9b, 0x8b, 0xbb, 0xab, 0xdb, 0xcb, 0xfb, 0xeb, 0x36, 0x26, 0x16, 0x06, 0x76, 0x66, 0x56, 0x46, 0xb6, 0xa6, 0x96, 0x86, 0xf6, 0xe6, 0xd6, 0xc6, 0x2d, 0x3d, 0x0d, 0x1d, 0x6d, 0x7d, 0x4d, 0x5d, 0xad, 0xbd, 0x8d, 0x9d, 0xed, 0xfd, 0xcd, 0xdd, 0x6c, 0x7c, 0x4c, 0x5c, 0x2c, 0x3c, 0x0c, 0x1c, 0xec, 0xfc, 0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 0x1f, 0xf9, 0x09, 0x02, 0xf2, 0xd5, 0x25, 0x2e, 0xde, 0x38, 0xc8, 0xc3, 0x33, 0xf6, 0x06, 0x0d, 0xfd, 0x1b, 0xeb, 0xe0, 0x10, 0x37, 0xc7, 0xcc, 0x3c, 0xda, 0x2a, 0x21, 0xd1, 0x6f, 0x9f, 0x94, 0x64, 0x82, 0x72, 0x79, 0x89, 0xae, 0x5e, 0x55, 0xa5, 0x43, 0xb3, 0xb8, 0x48, 0xdf, 0x2f, 0x24, 0xd4, 0x32, 0xc2, 0xc9, 0x39, 0x1e, 0xee, 0xe5, 0x15, 0xf3, 0x03, 0x08, 0xf8, 0x46, 0xb6, 0xbd, 0x4d, 0xab, 0x5b, 0x50, 0xa0, 0x87, 0x77, 0x7c, 0x8c, 0x6a, 0x9a, 0x91, 0x61} }; // end of hLUT //uint8_t gfmult( uint8_t a, uint8_t b ){ // return gfadd( hLUT[a>>4][b] , lLUT[a&0x0f][b] ) ; //} // A macro saves the function call overhead #define gfmult(a,b) gfadd( hLUT[(a)>>4][(b)] , lLUT[(a)&0x0f][(b)] ) //------------------------------------------------------------------------------ // GF(2^8) squaring modulo x^8 + x^4 + x^3 + x + 1 in constant time, // uses precomputed LUT //------------------------------------------------------------------------------ uint8_t sqrLUT[256] = { 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, 0x1b, 0x1a, 0x1f, 0x1e, 0x0b, 0x0a, 0x0f, 0x0e, 0x5b, 0x5a, 0x5f, 0x5e, 0x4b, 0x4a, 0x4f, 0x4e, 0x6c, 0x6d, 0x68, 0x69, 0x7c, 0x7d, 0x78, 0x79, 0x2c, 0x2d, 0x28, 0x29, 0x3c, 0x3d, 0x38, 0x39, 0x77, 0x76, 0x73, 0x72, 0x67, 0x66, 0x63, 0x62, 0x37, 0x36, 0x33, 0x32, 0x27, 0x26, 0x23, 0x22, 0xab, 0xaa, 0xaf,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, 0x07, 0x02, 0x03, 0x16, 0x17, 0x12, 0x13}; #define gfsqr(a) sqrLUT[(a)] #elif EXPLOG //------------------------------------------------------------------------------ // GF(2^8) Exp table, the generator is 0x03 //------------------------------------------------------------------------------ uint8_t expt[256] = { 0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35, 0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa, 0xe5, 0x34, 0x5c, 0xe4, 0x37, 0x59, 0xeb, 0x26, 0x6a, 0xbe, 0xd9, 0x70, 0x90, 0xab, 0xe6, 0x31, 0x53, 0xf5, 0x04, 0x0c, 0x14, 0x3c, 0x44, 0xcc, 0x4f, 0xd1, 0x68, 0xb8, 0xd3, 0x6e, 0xb2, 0xcd, 0x4c, 0xd4, 0x67, 0xa9, 0xe0, 0x3b, 0x4d, 0xd7, 0x62, 0xa6, 0xf1, 0x08, 0x18, 0x28, 0x78, 0x88, 0x83, 0x9e, 0xb9, 0xd0, 0x6b, 0xbd, 0xdc, 0x7f, 0x81, 0x98, 0xb3, 0xce, 0x49, 0xdb, 0x76, 0x9a, 0xb5, 0xc4, 0x57, 0xf9, 0x10, 0x30, 0x50, 0xf0, 0x0b, 0x1d, 0x27, 0x69, 0xbb, 0xd6, 0x61, 0xa3, 0xfe, 0x19, 0x2b, 0x7d, 0x87, 0x92, 0xad, 0xec, 0x2f, 0x71, 0x93, 0xae, 0xe9, 0x20, 0x60, 0xa0, 0xfb, 0x16, 0x3a, 0x4e, 0xd2, 0x6d, 0xb7, 0xc2, 0x5d, 0xe7, 0x32, 0x56, 0xfa, 0x15, 0x3f, 0x41, 0xc3, 0x5e, 0xe2, 0x3d, 0x47, 0xc9, 0x40, 0xc0, 0x5b, 0xed, 0x2c, 0x74, 0x9c, 0xbf, 0xda, 0x75, 0x9f, 0xba, 0xd5, 0x64, 0xac, 0xef, 0x2a, 0x7e, 0x82, 0x9d, 0xbc, 0xdf, 0x7a, 0x8e, 0x89, 0x80, 0x9b, 0xb6, 0xc1, 0x58, 0xe8, 0x23, 0x65, 0xaf, 0xea, 0x25, 0x6f, 0xb1, 0xc8, 0x43, 0xc5, 0x54, 0xfc, 0x1f, 0x21, 0x63, 0xa5, 0xf4, 0x07, 0x09, 0x1b, 0x2d, 0x77, 0x99, 0xb0, 0xcb, 0x46, 0xca, 0x45, 0xcf, 0x4a, 0xde, 0x79, 0x8b, 0x86, 0x91, 0xa8, 0xe3, 0x3e, 0x42, 0xc6, 0x51, 0xf3, 0x0e, 0x12, 0x36, 0x5a, 0xee, 0x29, 0x7b, 0x8d, 0x8c, 0x8f, 0x8a, 0x85, 0x94, 0xa7, 0xf2, 0x0d, 0x17, 0x39, 0x4b, 0xdd, 0x7c, 0x84, 0x97, 0xa2, 0xfd, 0x1c, 0x24, 0x6c, 0xb4, 0xc7, 0x52, 0xf6, 0x01 }; //------------------------------------------------------------------------------ // GF(2^8) Log table, , the generator is 0x03 //------------------------------------------------------------------------------ uint8_t logt[256] = { 0x00, 0xff, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03, 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1, 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78, 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e, 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38, 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10, 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba, 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57, 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07 }; //-------------------------------------------------------------------------- // Exp-Log GF(2^8) multiplication modulo x^8 + x^4 + x^3 + x + 1 in constant time //-------------------------------------------------------------------------- uint8_t gfmult( uint8_t h, uint8_t v ){ uint16_t tmp; uint8_t out, nonzero ; nonzero = h ; nonzero |= nonzero >> 4 ; nonzero |= nonzero >> 2 ; nonzero |= nonzero >> 1 ; nonzero &= 0x01 ; out = -nonzero ; nonzero = v ; nonzero |= nonzero >> 4 ; nonzero |= nonzero >> 2 ; nonzero |= nonzero >> 1 ; nonzero &= 0x01 ; out = -nonzero & out ; //For an 8-bit architecture, check the carry flag tmp = logt[h] + logt[v] ; //tmp mod (2^n)-1 tmp = tmp + (tmp>>8) ; tmp = tmp & 0xff ; return ( out & expt[(uint8_t)tmp] ) ; } //-------------------------------------------------------------------------- // GF(2^8) squaring modulo x^8 + x^4 + x^3 + x + 1 in constant time //-------------------------------------------------------------------------- // uint8_t gfsqr( uint8_t a ){ // return (a & 0x01)^((a&0x02)<<1)^((a&0x04)<<2)^((a&0x08)<<3)^(-((a&0x10)>>4)&0x1b)^(-((a&0x20)>>5)&0x6c)^(-((a&0x40)>>6)&0xab)^(-((a&0x80)>>7)&0x9a) ; // } //------------------------------------------------------------------------------ // GF(2^8) squaring modulo x^8 + x^4 + x^3 + x + 1 in constant time, // uses precomputed LUT //------------------------------------------------------------------------------ uint8_t sqrLUT[256] = { 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, 0x1b, 0x1a, 0x1f, 0x1e, 0x0b, 0x0a, 0x0f, 0x0e, 0x5b, 0x5a, 0x5f, 0x5e, 0x4b, 0x4a, 0x4f, 0x4e, 0x6c, 0x6d, 0x68, 0x69, 0x7c, 0x7d, 0x78, 0x79, 0x2c, 0x2d, 0x28, 0x29, 0x3c, 0x3d, 0x38, 0x39, 0x77, 0x76, 0x73, 0x72, 0x67, 0x66, 0x63, 0x62, 0x37, 0x36, 0x33, 0x32, 0x27, 0x26, 0x23, 0x22, 0xab, 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x29 ,0x2f ,0x2d ,0x23 ,0x21 ,0x27 ,0x25 ,0x5b ,0x59 ,0x5f ,0x5d ,0x53 ,0x51 ,0x57 ,0x55 ,0x4b ,0x49 ,0x4f ,0x4d ,0x43 ,0x41 ,0x47 ,0x45 ,0x7b ,0x79 ,0x7f ,0x7d ,0x73 ,0x71 ,0x77 ,0x75 ,0x6b ,0x69 ,0x6f ,0x6d ,0x63 ,0x61 ,0x67 ,0x65 ,0x9b ,0x99 ,0x9f ,0x9d ,0x93 ,0x91 ,0x97 ,0x95 ,0x8b ,0x89 ,0x8f ,0x8d ,0x83 ,0x81 ,0x87 ,0x85 ,0xbb ,0xb9 ,0xbf ,0xbd ,0xb3 ,0xb1 ,0xb7 ,0xb5 ,0xab ,0xa9 ,0xaf ,0xad ,0xa3 ,0xa1 ,0xa7 ,0xa5 ,0xdb ,0xd9 ,0xdf ,0xdd ,0xd3 ,0xd1 ,0xd7 ,0xd5 ,0xcb ,0xc9 ,0xcf ,0xcd ,0xc3 ,0xc1 ,0xc7 ,0xc5 ,0xfb ,0xf9 ,0xff ,0xfd ,0xf3 ,0xf1 ,0xf7 ,0xf5 ,0xeb ,0xe9 ,0xef ,0xed ,0xe3 ,0xe1 ,0xe7 ,0xe5 } ; //-------------------------------------------------------------------------- // GF(2^8) multiplication modulo x^8 + x^4 + x^3 + x + 1 in constant time //-------------------------------------------------------------------------- uint8_t gfmult( uint8_t h, uint8_t v ){ uint8_t z = 0 ; uint8_t i ; uint8_t mask ; for( i=0 ; i<8 ; i++ ){ mask = -((h>>i)&1); z = z ^(mask & v); v=secondOp[v] ; } return z ; } //-------------------------------------------------------------------------- // GF(2^8) squaring modulo x^8 + x^4 + x^3 + x + 1 in constant time, // uses precomputed LUT //-------------------------------------------------------------------------- uint8_t sqrLUT[256] = { 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, 0x1b, 0x1a, 0x1f, 0x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70, 0x75, 0x74, 0x61, 0x60, 0x65, 0x64, 0x2a, 0x2b, 0x2e, 0x2f, 0x3a, 0x3b, 0x3e, 0x3f, 0x6a, 0x6b, 0x6e, 0x6f, 0x7a, 0x7b, 0x7e, 0x7f, 0x5d, 0x5c, 0x59, 0x58, 0x4d, 0x4c, 0x49, 0x48, 0x1d, 0x1c, 0x19, 0x18, 0x0d, 0x0c, 0x09, 0x08, 0x46, 0x47, 0x42, 0x43, 0x56, 0x57, 0x52, 0x53, 0x06, 0x07, 0x02, 0x03, 0x16, 0x17, 0x12, 0x13}; #define gfsqr(a) sqrLUT[(a)] #endif // GF multiplication //------------------------------------------------------------------------------ // GF(2^8) times 2 multiplication modulo x^8 + x^4 + x^3 + x + 1 in const time //------------------------------------------------------------------------------ uint8_t gftimes2( uint8_t v ){ uint8_t mask; mask = -( (v>>7) & 1 ); v<<=1; v^= mask & 0x1b; return v ; } //------------------------------------------------------------------------------ // GF(2^8) exponentiation modulo x^8 + x^4 + x^3 + x + 1 //------------------------------------------------------------------------------ uint8_t gfexp ( uint8_t base , uint8_t exp ){ uint8_t i,res ; res = 0x01 ; //Call multiplication as many times as needed, max 255 for( i=0 ; i<exp ; i++) { res = gfmult( base, res ) ; } return res ; } //------------------------------------------------------------------------------ // GF(2^8) matrix*vector multiplication modulo x^8 + x^4 + x^3 + x + 1 //------------------------------------------------------------------------------ void gfmvmul( uint8_t mat[N][N] , uint8_t vec[N], uint8_t res[N] ){ uint8_t i,k, sum ; sum = 0 ; for( i=0 ; i<N ; i++ ){ for( k=0 ; k<N ; k++){ sum = gfadd( sum , gfmult( mat[i][k], vec[k] )) ; } res[i] = sum ; sum = 0 ; } }
Python
UTF-8
753
4
4
[ "MIT" ]
permissive
"""https://www.hackerrank.com/challenges/recursive-digit-sum/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=recursion-backtracking We define super digit of an integer using the following rules: Given an integer, we need to find the super digit of the integer. If has only digit, then its super digit is . Otherwise, the super digit of is equal to the super digit of the sum of the digits of . """ def superDigit(n, k): first = sum([int(d)*k for d in n]) first = str(first) def r(n): if len(n) == 1: return n n = sum([int(d) for d in n]) return r(str(n)) return r(first) n = '148' k = 3 print(f'testing with n: {n}, k: {k}, ans: {superDigit(n,k)}')
Java
UTF-8
318
1.953125
2
[]
no_license
package org.fkit.service; import java.util.List; import org.fkit.domain.Cart; public interface CartService { List<Cart> getAll(); Cart findCart(int book_id); Cart saveCart(int book_id); Cart addCart(int book_id); Cart reduceCart(int book_id); Cart removeCart(int book_id); void clearCart(); }
Shell
UTF-8
1,686
2.75
3
[]
no_license
ACI_RESOURCE_GROUP=sonaraci LOCATION=southeastasia ACI_STORAGE_ACCOUNT=sonaraci ACI_FILE_SHARE=sonarqube ACI_SQL_SERVER=sonarqubeaci ACI_SQL_USERNAME=sonar ACI_SQL_PASSWORD='Warhorse!23' az group create -n $ACI_RESOURCE_GROUP --location $LOCATION # Create the storage account for fileshare az storage account create \ --name $ACI_STORAGE_ACCOUNT \ --resource-group $ACI_RESOURCE_GROUP \ --location $LOCATION \ --sku Standard_LRS # Create the file share for sonar az storage share create --name sonarqubeconf --account-name $ACI_STORAGE_ACCOUNT az storage share create --name sonarqubedata --account-name $ACI_STORAGE_ACCOUNT az storage share create --name sonarqubelogs --account-name $ACI_STORAGE_ACCOUNT az storage share create --name sonarqubeextensions --account-name $ACI_STORAGE_ACCOUNT # Deploy sql db az sql server create \ --resource-group $ACI_RESOURCE_GROUP \ --name $ACI_SQL_SERVER \ --location $LOCATION \ --admin-user $ACI_SQL_USERNAME \ --admin-password $ACI_SQL_PASSWORD az sql db create \ --name sonar \ --resource-group $ACI_RESOURCE_GROUP \ --server $ACI_SQL_SERVER \ --service-objective S0 \ --collation SQL_Latin1_General_CP1_CS_AS az sql server firewall-rule create \ --name allAzureIPs \ --server $ACI_SQL_SERVER \ --resource-group $ACI_RESOURCE_GROUP \ --start-ip-address 0.0.0.0 \ --end-ip-address 0.0.0.0 #Deploy arm template for Sonarqube az group deployment create --name sonarqube --resource-group $ACI_RESOURCE_GROUP \ --template-file dockeraci.json \ --parameters storageAccountName=$ACI_STORAGE_ACCOUNT sqlServerName=$ACI_SQL_SERVER sqlPassword=$ACI_SQL_PASSWORD
Markdown
UTF-8
39,970
3.375
3
[]
no_license
# 背包问题 [markmap](assets\markmap11.html) 背包问题力扣题目大纲如下: <img src="assets/image-20210513101228972.png" alt="image-20210513101228972" style="zoom:50%;" /> 关于这⼏种常⻅的背包,其关系如下: <img src="assets/image-20210513101109665.png" alt="image-20210513101109665" style="zoom:44%;" /> ## 01 背包 有N件物品和⼀个最多能被重量为W 的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。每件物品只能⽤⼀次,求解将哪些物品装⼊背包⾥物品价值总和最⼤。 ### 回溯法 #### 二叉树单个节点是否选取的回溯方式 每⼀件物品其实只有两个状态,取或者不取,所以可以使⽤回溯法搜索出所有的情况,那么时间复杂度就是O(2^n),这⾥的n表示物品数量。 时间复杂度太高,每层回溯中都存在冗余,不推荐。 <img src="assets/image-20210712152907103.png" alt="image-20210712152907103" style="zoom:50%;" /> - ```c++ /* 函数意义:在物品重量小于w的情形下,在数组中[0-i]下标的范围中选物品,能获得的最大收益; 参数:alreadyWeight 不包括i下标之前的范围中选取物品的重量 */ public static int process1(int[] weight, int[] values, int i, int alreadyWeight, int bag) { if (alreadyWeight > bag) { return Integer.MIN_VALUE; } if (i == -1) { return 0; } //不取当前物品 int num1 = process1(weight, values, i - 1, alreadyWeight, bag); //取当前物品 int num2 = values[i] + process1(weight, values, i - 1, alreadyWeight + weight[i], bag) /* 显示回溯 //取当前物品 alreadyWeight += weight[i]; int num2 = values[i] + process1(weight, values, i - 1,alreadyWeight , bag); alreadyWeight -= weight[i]; */ return Math.max(num1,num2); } process1(weight,values,weight.size()-1,0,bag); ``` #### 二叉树集合中选取元素的回溯方式 时间复杂度O(n!) - ```c++ class Solution { private: int maxValue = 0; int maxWeight = 0; int curValue = 0; int curWeight = 0; vector<int> result; vector<int> path; //回溯解决在子集中递归查找子集的问题 /* 递归三部曲: 1、函数意义:在idx为开始下标的集合中选择题目要求的元素,并加入集合; 2、参数:idx起始下标 3、返回值:void */ void backtracking(vector<int> &weight, vector<int> &value, int w, int idx) { if (curValue > maxValue) { maxValue = curValue; result = path; } //单层逻辑 子集范围 for (int i = idx; i < weight.size(); i++) { //递归终止条件 if (curWeight + weight[i] > w) continue; path.push_back(value[i]); curValue += value[i]; curWeight += weight[i]; backtracking(weight, value, w, idx + 1); path.pop_back(); curValue -= value[i]; curWeight -= weight[i]; } } public: vector<int> package(vector<int> &weight, vector<int> &value, int w) { backtracking(weight, value, w, 0); return result; } }; ``` ### ⼆维dp数组 * 要点 **`dp[i][j]`表示从下标为[0-i]的物品⾥任意取,放进容量为j的背包,价值总和最⼤是多少。** `dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])` **二维dp数组先遍历物品还是先遍历背包都是可以的,且第二层for循环是从小到大遍历。** 在下面的讲解中,我举一个例子: 背包最大重量为4。 物品 重量 价值 物品0 1 15 物品1 3 20 物品2 4 30 问背包能背的物品最大价值是多少? - 动规五部曲分析⼀波。 1. 确定dp数组(dp table)以及下标的含义 **使⽤⼆维数组,即`dp[i][j]`表示从下标为[0-i]的物品⾥任意取,放进容量为j的背包,价值总和最⼤是多少。** <img src="assets/1619754400600.png" alt="1619754400600" style="zoom: 50%;" /> 要时刻记着这个dp数组的含义,下⾯的⼀些步骤都围绕这dp数组的含义进⾏的,如果哪⾥看懵了,就来回顾⼀下i代表什么,j⼜代表什么。 2. 确定递推公式 那么可以有两个⽅向推出来`dp[i][j]` - `由dp[i - 1][j]`推出,即背包容量为j,⾥⾯不放物品i的最⼤价值,此时`dp[i][j]`就是`dp[i - 1][j]` - 由`dp[i - 1][j - weight[i]]`推出,`dp[i - 1][j - weight[i]]` 为背包容量为j - weight[i]的时候不放物品i的最⼤价值,那么`dp[i - 1][j - weight[i]] + value[i]` (物品i的价值),就是背包放物品i得到的最⼤价值 **`所以递归公式: dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);`** 3. dp数组如何初始化 关于初始化,⼀定要和dp数组的定义吻合,否则到递推公式的时候就会越来越乱。 ⾸先从`dp[i][j]`的定义触发,如果背包容量j为0的话,即`dp[i][0]`,⽆论是选取哪些物品,背包价值总和⼀定为0。 在看其他情况。状态转移⽅程 `dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);` 可以看出i 是由 i-1 推导出来,那么i为0的时候就⼀定要初始化。 `dp[0][j]`,即:i为0,从编号0的物品选择物品存放的时候,各个容量的背包所能存放的最⼤价值。 ```c++ // 初始化 for (int j = weight[0]; j <= bagWeight; j++) { dp[0][j] = value[0]; } ``` 此时dp数组初始化情况如图所示: <img src="assets/image-20210705202755655.png" alt="image-20210705202755655" style="zoom:50%;" /> 4. 确定遍历顺序 **二维dp数组先遍历物品还是先遍历背包都是可以的,且第二层for循环是从小到大遍历。** 那么我先给出先遍历物品,然后遍历背包重量的代码。 ```c++ // weight数组的大小 就是物品个数 for(int i = 1; i < weight.size(); i++) { // 遍历物品 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; // 这个是为了展现dp数组里元素的变化 else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } ``` 先遍历背包,再遍历物品,也是可以的!(注意我这里使用的二维dp数组) 例如这样: ```c // weight数组的大小 就是物品个数 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 for(int i = 1; i < weight.size(); i++) { // 遍历物品 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } ``` 为什么也是可以的呢? **要理解递归的本质和递推的方向**。 `dp[i-1][j]`和`dp[i - 1][j - weight[i]]` 都在`dp[i][j]`的左上角方向(包括正左和正上两个方向)。虽然两个for循环遍历的次序不同,但是`dp[i][j]`所需要的数据就是左上角,根本不影响`dp[i][j]`公式的推导! 但先遍历物品再遍历背包这个顺序更好理解。 5. 举例推导dp数组 来看一下对应的dp数组的数值,最终结果就是`dp[2][4]`。 <img src="assets/image-20210705203937275.png" alt="image-20210705203937275" style="zoom:50%;" /> 6. 完整代码如下: ```c++ void test_2_wei_bag_problem1() { vector<int> weight = {1, 3, 4}; vector<int> value = {15, 20, 30}; int bagWeight = 4; // 二维数组 vector<vector<int>> dp(weight.size() + 1, vector<int>(bagWeight + 1, 0)); // 初始化 for (int j = weight[0]; j <= bagWeight; j++) { dp[0][j] = value[0]; } // weight数组的大小 就是物品个数 for(int i = 1; i < weight.size(); i++) { // 遍历物品 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } cout << dp[weight.size() - 1][bagWeight] << endl; } ``` ### 滚动数组 --- * 要点 **dp[j]表示:容量为j的背包,所背的物品价值可以最大为dp[j]。** `dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);` **一维dp数组01背包只能先遍历物品再遍历背包容量,且第二层for循环是从大到小遍历。** --- 在使用二维数组的时候,递推公式:`dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);` 其实可以发现如果把dp[i - 1]那一层拷贝到dp[i]上,表达式完全可以是:`dp[i][j] = max(dp[i][j], dp[i][j - weight[i]] + value[i]);` 于其把dp[i - 1]这一层拷贝到dp[i]上,不如只用一个一维数组了,只用dp[j](一维数组,也可以理解是一个滚动数组) 动态规划五部曲: 1.确定dp数组(dp table)以及下标的含义 在一维dp数组中,dp[j]表示:容量为j的背包,所背的物品价值可以最大为dp[j]。 2.dp数组如何初始化 那么我假设物品价值都是大于0的,所以dp数组初始化的时候,都初始为0就可以了。 3.确定递推公式 ```php dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); ``` 4.确定遍历顺序 **一维dp数组01背包只能先遍历物品再遍历背包容量,且第二层for循环是从大到小遍历。** **倒叙遍历是为了保证物品i只被放入一次!**。但如果一旦正序遍历了,那么物品0就会被重复加入多次 **再来看看两个嵌套for循环的顺序,代码中是先遍历物品嵌套遍历背包容量,那可不可以先遍历背包容量嵌套遍历物品呢?** 不可以! 因为一维dp的写法,背包容量一定是要倒序遍历(原因上面已经讲了),**如果遍历背包容量放在上一层,那么每个dp[j]就只会放入一个物品,即:背包里只放入了一个物品。** **所以一维dp数组的背包在遍历顺序上和二维其实是有很大差异的!**,这一点大家一定要注意。 5.举例推导dp数组 来看一下对应的dp数组的数值,最终结果就是`dp[2][4]`。 <img src="assets/image-20210705203937275.png" alt="image-20210705203937275" style="zoom:50%;" /> 6.完整代码如下: ```c++ // 初始化 vector<int> dp(bagWeight + 1, 0); for(int i = 0; i < weight.size(); i++) { // 遍历物品 for(int j = bagWeight; j >= weight[i]; j--) { // 倒序遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } } ``` ## 完全背包 有N件物品和一个最多能背重量为W的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。每件物品都有无限个(也就是可以放入背包多次),求解将哪些物品装入背包里物品价值总和最大。 **完全背包和01背包问题唯一不同的地方就是,每种物品有无限件**。 ```c++ // 先遍历物品,再遍历背包 for(int i = 0; i < weight.size(); i++) { // 遍历物品 for(int j = weight[i]; j < bagWeight ; j++) { // 从小到大去遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } } ``` **纯完全背包的一维dp数组实现,先遍历物品还是先遍历背包都是可以的,且第二层for循环是从小到大遍历。** 因为dp[j] 是根据 下标j之前所对应的dp[j]计算出来的。 只要保证下标j之前的dp[j]都是经过计算的就可以了。 ```c++ // 先遍历背包,再遍历物品 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 for(int i = 0; i < weight.size(); i++) { // 遍历物品 if (j - weight[i] >= 0) dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } cout << endl; } ``` ## 多重背包 有N种物品和一个容量为V 的背包。第i种物品最多有Mi件可用,每件耗费的空间是Ci ,价值是Wi 。求解将哪些物品装入背包可使这些物品的耗费的空间 总和不超过背包容量,且价值总和最大。 每件物品最多有Mi件可用,把Mi件摊开,其实就是一个01背包问题了。 ```c for (int i = 0; i < nums.size(); i++) { while (nums[i] > 1) { // nums[i]保留到1,把其他物品都展开 weight.push_back(weight[i]); value.push_back(value[i]); nums[i]--; } } for (int i = 0; i < weight.size(); i++) { // 遍历物品 for (int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } } ``` ## # 应用 ## 能否装满背包 ->(or最多装多少/最大价值)(即01背包) **dp[j]表示 背包总容量是j,总和最大为dp[i]**。 `dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])` #### 474.一和零 给你一个二进制字符串数组 strs 和两个整数 m 和 n 。 请你找出并返回 strs 的最大子集的大小,该子集中 最多 有 m 个 0 和 n 个 1 。 示例 1: 输入:strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3 输出:4 解释:最多有 5 个 0 和 3 个 1 的最大子集是 {"10","0001","1","0"} ,因此答案是 4 。 其他满足题意但较小的子集包括 {"0001","1"} 和 {"10","1","0"} 。{"111001"} 不满足题意,因为它含 4 个 1 ,大于 n 的值 3 。 * 01背包的二维背包 **本题中strs 数组里的元素就是物品,每个物品都是一个!而m 和 n相当于是一个背包,两个维度的背包**。 `dp[i][j]`:最多有i个0和j个1的strs的最大子集的大小为`dp[i][j]`。 递推公式:`dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1)`; 对比一下就会发现,字符串的zeroNum和oneNum相当于物品的重量(weight[i]),字符串本身的个数相当于物品的价值(value[i])。 **这就是一个典型的01背包!** 只不过物品的重量有了两个维度而已。 ```c++ int findMaxForm(vector<string>& strs, int m, int n) { vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0)); // 默认初始化0 for (string str : strs) { // 遍历物品 int oneNum = 0, zeroNum = 0; for (char c : str) { if (c == '0') zeroNum++; else oneNum++; } for (int i = m; i >= zeroNum; i--) { // 遍历背包容量且从后向前遍历! for (int j = n; j >= oneNum; j--) { dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1); } } } return dp[m][n]; } ``` #### 416. 分割等和子集 给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 注意: 每个数组中的元素不会超过 100 ,数组的大小不会超过 200 示例 1: 输入: [1, 5, 11, 5] 输出: true 解释: 数组可以分割成 [1, 5, 5] 和 [11]. 示例 2: 输入: [1, 2, 3, 5] 输出: false 解释: 数组不能分割成两个元素和相等的子集. --- 解法一、回溯法:组合问题:n个数中求和为target的集合,时间复杂度较高。 解法二、01背包。那么只要找到集合里能够出现 sum / 2 的子集总和,就算是可以分割成两个相同元素和子集了。 **dp[j]表示 背包总容量是j,子集总和最大为dp[i]**。 01背包相对于本题,主要要理解,题目中物品是nums[i],重量是nums[i]i,价值也是nums[i],背包体积是sum/2。 最后判断dp[target]==target,说明集合中的元素正好可以凑成总和target。 ```c class Solution { public: bool canPartition(vector<int>& nums) { int sum = 0; // dp[i]中的i表示背包内总和 // 题目中说:每个数组中的元素不会超过 100,数组的大小不会超过 200 // 总和不会大于20000,背包最大只需要其中一半,所以10001大小就可以了 vector<int> dp(10001, 0); for (int i = 0; i < nums.size(); i++) { sum += nums[i]; } if (sum % 2 == 1) return false; int target = sum / 2; // 开始 01背包 for(int i = 0; i < nums.size(); i++) { for(int j = target; j >= nums[i]; j--) { // 每一个元素一定是不可重复放入,所以从大到小遍历 dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]); } } // 集合中的元素正好可以凑成总和target if (dp[target] == target) return true; return false; } }; ``` * 相似题目 * 698.划分为k个相等的子集 给定一个整数数组 `nums` 和一个正整数 `k`,找出是否有可能把这个数组分成 `k` 个非空子集,其总和都相等。 思路: ```java for(int i=1;i<=k;i++){ if(dp[sum/k*i] != sum/k*i) return false; } ``` * 473.火柴拼正方形 #### 1049. 最后一块石头的重量 II 有一堆石头,每块石头的重量都是正整数。 每一回合,从中选出任意两块石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: 如果 x == y,那么两块石头都会被完全粉碎; 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。 最后,最多只会剩下一块石头。返回此石头最小的可能重量。如果没有石头剩下,就返回 0。 --- 本题其实就是尽量让石头分成重量相同的两堆,相撞之后剩下的石头最小,**这样就化解成01背包问题了**。**dp[j]表示容量为j的背包,最多可以背dp[j]这么重的石头**。 最后dp[target]里是容量为target的背包所能背的最大重量。那么分成两堆石头,一堆石头的总重量是dp[target],另一堆就是sum - dp[target]。**在计算target的时候,target = sum / 2 因为是向下取整,所以sum - dp[target] 一定是大于等于dp[target]的**。 那么相撞之后剩下的最小石头重量就是 (sum - dp[target]) - dp[target]。 ```c class Solution { public: int lastStoneWeightII(vector<int>& stones) { vector<int> dp(15001, 0); int sum = 0; for (int i = 0; i < stones.size(); i++) sum += stones[i]; int target = sum / 2; for (int i = 0; i < stones.size(); i++) { // 遍历物品 for (int j = target; j >= stones[i]; j--) { // 遍历背包 dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]); } } return sum - dp[target] - dp[target]; } }; ``` 本题其实和416. 分割等和子集几乎是一样的,只是最后对dp[target]的处理方式不同。 416. 分割等和子集相当于是求背包是否正好装满,而本题是求背包最多能装多少。 ## 背包组合/排列问题 **dp[j] 表示:填满容量为j的包,有dp[j]种方法.** `dp[j] += dp[j - nums[i]]` **如果求组合数就是外层for循环遍历物品,内层for遍历背包**。(可以保证物品5在物品1之后出现) **如果求排列数就是外层for遍历背包,内层for循环遍历物品**。(结果会出现{1,5}和{5,1}) ### 背包组合问题 #### [494. 目标和](https://leetcode-cn.com/problems/target-sum/) 给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。返回可以使最终数组和为目标数 S 的所有添加符号的方法数。 示例: 输入:nums: [1, 1, 1, 1, 1], S: 3 输出:5 解释: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 一共有5种方法让最终目标和为3。 --- * 01背包组合问题 **既然为target,那么就一定有 left组合 - right组合 = target。**left + right等于sum, left = (target + sum)/2 。问题转换为在集合中找和为 (target + sum)/2的组合。 <font color=red>**回溯:组合问题:n个数中求和为target的集合。如果仅仅是求个数的话,就可以用dp,但[回溯算法:39. 组合总和](https://mp.weixin.qq.com/s/FLg8G6EjVcxBjwCbzpACPw)要求的是把所有组合列出来,还是要使用回溯法爆搜的。**<font> **此时问题就转化为,装满容量为x背包,有几种方法**。 1. 确定dp数组以及下标的含义 **dp[j] 表示:填满容量为j的包,有dp[j]种方法.** 2. 确定递推公式 有哪些来源可以推出dp[j]呢? 不考虑nums[i]的情况下,填满容量为j - nums[i]的背包,有dp[j - nums[i]]种方法。 那么凑成dp[j](考虑nums[i]的组合总和)就有dp[j - nums[i]] (不考虑nums[i]的组合总和)种方法。 那么需要把 这些方法累加起来就可以了,dp[j] += dp[j - nums[i]] `dp[j] += dp[j - nums[i]]`**这个公式在后面在讲解背包解决排列组合问题的时候还会用到!** 3. dp数组如何初始化 从递归公式可以看出,在初始化的时候dp[0] 一定要初始化为1,因为dp[0]是在公式中一切递推结果的起源,如果dp[0]是0的话,递归结果将都是0。 4. 确定遍历顺序 对于01背包问题一维dp的遍历,nums放在外循环,target在内循环,且内循环倒序。 5. 举例推导dp数组 ```c++ class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { int sum = 0; for (int i = 0; i < nums.size(); i++) sum += nums[i]; if (S > sum) return 0; // 此时没有方案 if ((S + sum) % 2 == 1) return 0; // 此时没有方案 int bagSize = (S + sum) / 2; vector<int> dp(bagSize + 1, 0); dp[0] = 1; for (int i = 0; i < nums.size(); i++) { for (int j = bagSize; j >= nums[i]; j--) { dp[j] += dp[j - nums[i]]; } } return dp[bagSize]; } }; ``` **方法二、回溯** 回溯算法可以解决这个问题,时间复杂度为 `O(2^N)`,`N` 为 `nums` 的大小。这个复杂度怎么算的?回忆前文 [学习数据结构和算法的框架思维](),发现这个回溯算法就是个二叉树的遍历问题: ```c void backtrack(int[] nums, int i, int rest) { if (i == nums.length) { return; } backtrack(nums, i + 1, rest - nums[i]); backtrack(nums, i + 1, rest + nums[i]); } ``` **树的高度就是 `nums` 的长度嘛**,所以说时间复杂度就是这棵二叉树的节点数,为 `O(2^N)`,其实是非常低效的。 #### 518. 零钱兑换 II 给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。 示例 1: 输入: amount = 5, coins = [1, 2, 5] 输出: 4 解释: 有四种方式可以凑成总金额: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 示例 2: 输入: amount = 3, coins = [2] 输出: 0 解释: 只用面额2的硬币不能凑成总金额3。 示例 3: 输入: amount = 10, coins = [10] 输出: 1 --- - 完全背包的组合问题:先遍历物品再遍历背包 dp[j]:凑成总金额j的货币组合数为dp[j], dp[j] (考虑coins[i]的组合总和) 就是所有的dp[j - coins[i]](不考虑coins[i])相加。 所以递推公式:dp[j] += dp[j - coins[i]]; 首先dp[0]一定要为1,dp[0] = 1是 递归公式的基础。**从dp[i]的含义上来讲就是,凑成总金额0的货币组合数为1。** ```c class Solution { public: int change(int amount, vector<int>& coins) { vector<int> dp(amount + 1, 0); dp[0] = 1; for (int i = 0; i < coins.size(); i++) { // 遍历物品 for (int j = coins[i]; j <= amount; j++) { // 遍历背包 dp[j] += dp[j - coins[i]]; } } return dp[amount]; } }; ``` 假设:coins[0] = 1,coins[1] = 5。 那么就是先把1加入计算,然后再把5加入计算,得到的方法数量只有{1, 5}这种情况。而不会出现{5, 1}的情况,因为nums遍历放在外层,5只能出现在1后面! **所以这种遍历顺序中dp[j]里计算的是组合数!** 如果把两个for交换顺序,代码如下: ```c for (int j = 0; j <= amount; j++) { // 遍历背包容量 for (int i = 0; i < coins.size(); i++) { // 遍历物品 if (j - coins[i] >= 0) dp[j] += dp[j - coins[i]]; } } ``` 背包容量的每一个值,都是经过 1 和 5 的计算,包含了{1, 5} 和 {5, 1}两种情况。 **此时dp[j]里算出来的就是排列数!** **如果求组合数就是外层for循环遍历物品,内层for遍历背包**。 **如果求排列数就是外层for遍历背包,内层for循环遍历物品**。 ### 背包排列问题 #### 377. 组合总和 Ⅳ 给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。 示例: nums = [1, 2, 3] target = 4 所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) 请注意,顺序不同的序列被视作不同的组合。 因此输出为 7。 --- - 完全背包的排列问题:先遍历背包再遍历物品 - **dp[i]: 凑成目标正整数为i的排列个数为dp[i]** ```c class Solution { public: int combinationSum4(vector<int>& nums, int target) { vector<int> dp(target + 1, 0); dp[0] = 1; for (int i = 0; i <= target; i++) { // 遍历背包 for (int j = 0; j < nums.size(); j++) { // 遍历物品 if (i - nums[j] >= 0 && dp[i] < INT_MAX - dp[i - nums[j]]) { dp[i] += dp[i - nums[j]]; } } } return dp[target]; } }; ``` C++测试用例有超过两个树相加超过int的数据,所以需要在if里加上dp[i] < INT_MAX - dp[i - num]。 #### 70. 爬楼梯进阶版 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数。 示例 1: 输入: 2 输出: 2 解释: 有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶 **一步一个台阶,两个台阶,三个台阶,.......,直到 m个台阶。问有多少种不同的方法可以爬到楼顶呢?** - 完全背包的排列问题 ```c class Solution { public: int climbStairs(int n) { vector<int> dp(n + 1, 0); dp[0] = 1; for (int i = 1; i <= n; i++) { // 遍历背包 for (int j = 1; j <= m; j++) { // 遍历物品 if (i - j >= 0) dp[i] += dp[i - j]; } } return dp[n]; } }; ``` m=2时就可以AC[ 70.爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/) ## 装满背包所需的最少物品个数 **dp[j]:凑足重量总和为j所需物品的最少个数为dp[j]**。 `dp[j] = min(dp[j - coins[i]] + 1, dp[j]);` 如果求最小数,那么两层for循环的先后顺序就无所谓了 ### 322. 零钱兑换 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 你可以认为每种硬币的数量是无限的。 示例 1: 输入:coins = [1, 2, 5], amount = 11 输出:3 解释:11 = 5 + 5 + 1 示例 2: 输入:coins = [2], amount = 3 输出:-1 --- * 完全背包的最少物品个数问题 递归五部曲: 1.确定dp数组以及下标的含义 **dp[j]:凑足总额为j所需钱币的最少个数为dp[j]**。 2.确定递推公式 递推公式:`dp[j] = min(dp[j - coins[i]] + 1, dp[j]);` 3.dp数组如何初始化 首先凑足总金额为0所需钱币的个数一定是0,那么dp[0] = 0; dp[j]必须初始化为一个最大的数,即`vector<int> dp(amount + 1, INT_MAX);` 4.确定遍历顺序 本题求钱币最小个数,**那么钱币有顺序和没有顺序都可以,都不影响钱币的最小个数。所以本题的两个for循环的关系是:外层for循环遍历物品,内层for遍历背包或者外层for遍历背包,内层for循环遍历物品都是可以的!(当dp定义为所需钱币的最少个数时,硬币是组合数还是排列数都无所谓!for循环次序不影响dp值,只有dp[j]定义为总额为j的排列/组合个数时循环次序才影响dp值)** 5.举例推导dp数组 ```c class Solution { public: int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount + 1, INT_MAX); dp[0] = 0; for (int i = 0; i < coins.size(); i++) { // 遍历物品 for (int j = coins[i]; j <= amount; j++) { // 遍历背包 if (dp[j - coins[i]] != INT_MAX) { // 如果dp[j - coins[i]]是初始值则跳过 dp[j] = min(dp[j - coins[i]] + 1, dp[j]); } } } if (dp[amount] == INT_MAX) return -1; return dp[amount]; } }; ``` 对于遍历方式遍历背包放在外循环,遍历物品放在内循环也是可以的,我就直接给出代码了 ```c // 版本二 class Solution { public: int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount + 1, INT_MAX); dp[0] = 0; for (int i = 1; i <= amount; i++) { // 遍历背包 for (int j = 0; j < coins.size(); j++) { // 遍历物品 if (i - coins[j] >= 0 && dp[i - coins[j]] != INT_MAX ) { dp[i] = min(dp[i - coins[j]] + 1, dp[i]); } } } if (dp[amount] == INT_MAX) return -1; return dp[amount]; } }; ``` ### 279.完全平方数 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。 示例 1: 输入:n = 12 输出:3 解释:12 = 4 + 4 + 4 --- * 完全背包的最少物品个数问题,和322.零钱兑换一模一样。 **dp[j]:凑足完全平方和为j的最少个数为dp[j]**。 - ```c class Solution { public: int numSquares(int n) { vector<int> dp(n + 1, INT_MAX); dp[0] = 0; for (int i = 1; i * i <= n; i++) { // 遍历物品 for (int j = i*i; j <= n; j++) { // 遍历背包 if (dp[j - i * i] != INT_MAX) { dp[j] = min(dp[j - i * i] + 1, dp[j]); } } } return dp[n]; } }; ``` ## dp值true/false ### 139.单词拆分 给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。 说明: 拆分时可以重复使用字典中的单词。 你可以假设字典中没有重复的单词。 示例 1: 输入: s = "leetcode", wordDict = ["leet", "code"] 输出: true 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。 示例 2: 输入: s = "applepenapple", wordDict = ["apple", "pen"] 输出: true 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。 注意你可以重复使用字典中的单词。 示例 3: 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 输出: false --- 解法一、回溯问题中的分割问题。[回溯算法:分割回文串](https://mp.weixin.qq.com/s/Pb1epUTbU8fHIht-g_MS5Q):是枚举分割后的所有子串,判断是否回文。本题是枚举分割所有字符串,判断是否在字典里出现过。 时间复杂度:O(2^n),因为每一个单词都有两个状态,切割和不切割 ```c class Solution { private: bool backtracking (const string& s, const unordered_set<string>& wordSet, int startIndex) { if (startIndex >= s.size()) { return true; } for (int i = startIndex; i < s.size(); i++) { string word = s.substr(startIndex, i - startIndex + 1); if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, i + 1)) { return true; } } return false; } public: bool wordBreak(string s, vector<string>& wordDict) { unordered_set<string> wordSet(wordDict.begin(), wordDict.end()); return backtracking(s, wordSet, 0); } }; ``` 使用memory数组保存每次计算的以startIndex起始的计算结果,如果memory[startIndex]里已经被赋值了,直接用memory[startIndex]的结果。 C++代码如下: ```c class Solution { private: bool backtracking (const string& s,const unordered_set<string>& wordSet,vector<int>& memory,int startIndex) { if (startIndex >= s.size()) { return true; } // 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果 if (memory[startIndex] != -1) return memory[startIndex]; for (int i = startIndex; i < s.size(); i++) { string word = s.substr(startIndex, i - startIndex + 1); if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) { memory[startIndex] = 1; // 记录以startIndex开始的子串是可以被拆分的 return true; } } memory[startIndex] = 0; // 记录以startIndex开始的子串是不可以被拆分的 return false; } public: bool wordBreak(string s, vector<string>& wordDict) { unordered_set<string> wordSet(wordDict.begin(), wordDict.end()); vector<int> memory(s.size(), -1); // -1 表示初始化状态 return backtracking(s, wordSet, memory, 0); } }; ``` 这个时间复杂度其实也是:O(2^n)。只不过对于上面那个超时测试用例优化效果特别明显。 解法二、完全背包排列问题 **单词就是物品,字符串s就是背包,单词能否组成字符串s,就是问物品能不能把背包装满。** 拆分时可以重复使用字典中的单词,说明就是一个完全背包! 1. 确定dp数组以及下标的含义 **dp[i] : 长度为i的s[0:i-1]子串能否拆分为一个或多个在字典中出现的单词,dp[i]为true,表示可以拆分**。 2. 确定递推公式 所以**递推公式是 if([j, i-1] 这个区间的子串出现在字典里 && dp[j]是true) 那么 dp[i] = true。** 3. dp数组如何初始化 dp[0]就是递归的根基,dp[0]一定要为true。下标非0的dp[i]初始化为false,只要没有被覆盖说明都是不可拆分为一个或多个在字典中出现的单词。 4. 确定遍历顺序 本题最终要求的是是否都出现过,所以先遍历物品还是先遍历背包都可以。 但本题还有特殊性,因为是要求子串,最好是遍历背包放在外循环,将遍历物品放在内循环。 如果要是外层for循环遍历物品,内层for遍历背包,就需要把所有的子串都预先放在一个容器里。(如果不理解的话,可以自己尝试这么写一写就理解了) 所以最终我选择的遍历顺序为:遍历背包放在外循环,将遍历物品放在内循环。内循环从前到后。 5. 举例推导dp[i] 以输入: s = "leetcode", wordDict = ["leet", "code"]为例,dp状态如图: <img src="assets/image-20210707100051992.png" alt="image-20210707100051992" style="zoom: 33%;" /> <img src="assets/image-20210707100537445.png" alt="image-20210707100537445" style="zoom:33%;" /> <img src="assets/image-20210707101415852.png" alt="image-20210707101415852" style="zoom:55%;" /> $\color{red}{红色字}$ <u>下划线文本</u> ```c class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { unordered_set<string> wordSet(wordDict.begin(), wordDict.end()); vector<bool> dp(s.size() + 1, false); dp[0] = true; for (int i = 1; i <= s.size(); i++) { // 遍历背包 for (int j = 0; j < i; j++) { // 遍历物品 string word = s.substr(j, i - j); //substr(起始位置,截取的个数) if (wordSet.find(word) != wordSet.end() && dp[j]) { dp[i] = true; } } } return dp[s.size()]; } }; -----i = 1----- j = 0,word = l -----i = 2----- j = 0,word = le j = 1,word = e -----i = 3----- j = 0,word = lee j = 1,word = ee j = 2,word = e -----i = 4----- j = 0,word = leet j = 1,word = eet j = 2,word = et j = 3,word = t -----i = 5----- j = 0,word = leetc j = 1,word = eetc j = 2,word = etc j = 3,word = tc j = 4,word = c -----i = 6----- j = 0,word = leetco j = 1,word = eetco j = 2,word = etco j = 3,word = tco j = 4,word = co j = 5,word = o -----i = 7----- j = 0,word = leetcod j = 1,word = eetcod j = 2,word = etcod j = 3,word = tcod j = 4,word = cod j = 5,word = od j = 6,word = d -----i = 8----- j = 0,word = leetcode j = 1,word = eetcode j = 2,word = etcode j = 3,word = tcode j = 4,word = code j = 5,word = ode j = 6,word = de j = 7,word = e ``` ## 【背包总结】 ### 递推公式 1)能否装满背包 ->(or最多装多少/最大价值)(即01背包) **dp[j]表示 背包总容量是j,总和最大为dp[i]**。 `dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])` 2)背包组合/排列问题 **dp[j] 表示:填满容量为j的包,有dp[j]种方法.** `dp[j] += dp[j - nums[i]]` 3)装满背包所需的最少物品个数 **dp[j]:凑足重量总和为j所需物品的最少个数为dp[j]**。 `dp[j] = min(dp[j - coins[i]] + 1, dp[j]);` ### 遍历顺序 #### 01背包 二维dp数组01背包先遍历物品还是先遍历背包都是可以的,且第二层for循环是从小到大遍历。 一维dp数组01背包只能先遍历物品再遍历背包容量,且第二层for循环是从大到小遍历。 **一维dp数组的背包在遍历顺序上和二维dp数组实现的01背包其实是有很大差异的,大家需要注意!** #### 完全背包 先遍历物品还是先遍历背包都是可以的,且第二层for循环是从小到大遍历。 但是仅仅是纯完全背包的遍历顺序是这样的,题目稍有变化,两个for循环的先后顺序就不一样了。 如果求组合数就是外层for循环遍历物品,内层for遍历背包。 如果求排列数就是外层for遍历背包,内层for循环遍历物品。 相关题目如下: 求组合数:动态规划:518.零钱兑换II 求排列数:动态规划:377. 组合总和 Ⅳ、动态规划:70. 爬楼梯进阶版(完全背包) 如果求最小数,那么两层for循环的先后顺序就无所谓了,相关题目如下: 求最小数:动态规划:322. 零钱兑换、动态规划:279.完全平方数
Java
UTF-8
36,623
1.835938
2
[]
no_license
package com.vukapesa.cleandeal; import anywheresoftware.b4a.B4AMenuItem; import android.app.Activity; import android.os.Bundle; import anywheresoftware.b4a.BA; import anywheresoftware.b4a.BALayout; import anywheresoftware.b4a.B4AActivity; import anywheresoftware.b4a.ObjectWrapper; import anywheresoftware.b4a.objects.ActivityWrapper; import java.lang.reflect.InvocationTargetException; import anywheresoftware.b4a.B4AUncaughtException; import anywheresoftware.b4a.debug.*; import java.lang.ref.WeakReference; public class reviews extends Activity implements B4AActivity{ public static reviews mostCurrent; static boolean afterFirstLayout; static boolean isFirst = true; private static boolean processGlobalsRun = false; BALayout layout; public static BA processBA; BA activityBA; ActivityWrapper _activity; java.util.ArrayList<B4AMenuItem> menuItems; public static final boolean fullScreen = false; public static final boolean includeTitle = true; public static WeakReference<Activity> previousOne; public static boolean dontPause; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mostCurrent = this; if (processBA == null) { processBA = new BA(this.getApplicationContext(), null, null, "com.vukapesa.cleandeal", "com.vukapesa.cleandeal.reviews"); processBA.loadHtSubs(this.getClass()); float deviceScale = getApplicationContext().getResources().getDisplayMetrics().density; BALayout.setDeviceScale(deviceScale); } else if (previousOne != null) { Activity p = previousOne.get(); if (p != null && p != this) { BA.LogInfo("Killing previous instance (reviews)."); p.finish(); } } processBA.setActivityPaused(true); processBA.runHook("oncreate", this, null); if (!includeTitle) { this.getWindow().requestFeature(android.view.Window.FEATURE_NO_TITLE); } if (fullScreen) { getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN, android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN); } processBA.sharedProcessBA.activityBA = null; layout = new BALayout(this); setContentView(layout); afterFirstLayout = false; WaitForLayout wl = new WaitForLayout(); if (anywheresoftware.b4a.objects.ServiceHelper.StarterHelper.startFromActivity(this, processBA, wl, false)) BA.handler.postDelayed(wl, 5); } static class WaitForLayout implements Runnable { public void run() { if (afterFirstLayout) return; if (mostCurrent == null) return; if (mostCurrent.layout.getWidth() == 0) { BA.handler.postDelayed(this, 5); return; } mostCurrent.layout.getLayoutParams().height = mostCurrent.layout.getHeight(); mostCurrent.layout.getLayoutParams().width = mostCurrent.layout.getWidth(); afterFirstLayout = true; mostCurrent.afterFirstLayout(); } } private void afterFirstLayout() { if (this != mostCurrent) return; activityBA = new BA(this, layout, processBA, "com.vukapesa.cleandeal", "com.vukapesa.cleandeal.reviews"); processBA.sharedProcessBA.activityBA = new java.lang.ref.WeakReference<BA>(activityBA); anywheresoftware.b4a.objects.ViewWrapper.lastId = 0; _activity = new ActivityWrapper(activityBA, "activity"); anywheresoftware.b4a.Msgbox.isDismissing = false; if (BA.isShellModeRuntimeCheck(processBA)) { if (isFirst) processBA.raiseEvent2(null, true, "SHELL", false); processBA.raiseEvent2(null, true, "CREATE", true, "com.vukapesa.cleandeal.reviews", processBA, activityBA, _activity, anywheresoftware.b4a.keywords.Common.Density, mostCurrent); _activity.reinitializeForShell(activityBA, "activity"); } initializeProcessGlobals(); initializeGlobals(); BA.LogInfo("** Activity (reviews) Create, isFirst = " + isFirst + " **"); processBA.raiseEvent2(null, true, "activity_create", false, isFirst); isFirst = false; if (this != mostCurrent) return; processBA.setActivityPaused(false); BA.LogInfo("** Activity (reviews) Resume **"); processBA.raiseEvent(null, "activity_resume"); if (android.os.Build.VERSION.SDK_INT >= 11) { try { android.app.Activity.class.getMethod("invalidateOptionsMenu").invoke(this,(Object[]) null); } catch (Exception e) { e.printStackTrace(); } } } public void addMenuItem(B4AMenuItem item) { if (menuItems == null) menuItems = new java.util.ArrayList<B4AMenuItem>(); menuItems.add(item); } @Override public boolean onCreateOptionsMenu(android.view.Menu menu) { super.onCreateOptionsMenu(menu); try { if (processBA.subExists("activity_actionbarhomeclick")) { Class.forName("android.app.ActionBar").getMethod("setHomeButtonEnabled", boolean.class).invoke( getClass().getMethod("getActionBar").invoke(this), true); } } catch (Exception e) { e.printStackTrace(); } if (processBA.runHook("oncreateoptionsmenu", this, new Object[] {menu})) return true; if (menuItems == null) return false; for (B4AMenuItem bmi : menuItems) { android.view.MenuItem mi = menu.add(bmi.title); if (bmi.drawable != null) mi.setIcon(bmi.drawable); if (android.os.Build.VERSION.SDK_INT >= 11) { try { if (bmi.addToBar) { android.view.MenuItem.class.getMethod("setShowAsAction", int.class).invoke(mi, 1); } } catch (Exception e) { e.printStackTrace(); } } mi.setOnMenuItemClickListener(new B4AMenuItemsClickListener(bmi.eventName.toLowerCase(BA.cul))); } return true; } @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { if (item.getItemId() == 16908332) { processBA.raiseEvent(null, "activity_actionbarhomeclick"); return true; } else return super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(android.view.Menu menu) { super.onPrepareOptionsMenu(menu); processBA.runHook("onprepareoptionsmenu", this, new Object[] {menu}); return true; } protected void onStart() { super.onStart(); processBA.runHook("onstart", this, null); } protected void onStop() { super.onStop(); processBA.runHook("onstop", this, null); } public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (processBA.subExists("activity_windowfocuschanged")) processBA.raiseEvent2(null, true, "activity_windowfocuschanged", false, hasFocus); } private class B4AMenuItemsClickListener implements android.view.MenuItem.OnMenuItemClickListener { private final String eventName; public B4AMenuItemsClickListener(String eventName) { this.eventName = eventName; } public boolean onMenuItemClick(android.view.MenuItem item) { processBA.raiseEventFromUI(item.getTitle(), eventName + "_click"); return true; } } public static Class<?> getObject() { return reviews.class; } private Boolean onKeySubExist = null; private Boolean onKeyUpSubExist = null; @Override public boolean onKeyDown(int keyCode, android.view.KeyEvent event) { if (processBA.runHook("onkeydown", this, new Object[] {keyCode, event})) return true; if (onKeySubExist == null) onKeySubExist = processBA.subExists("activity_keypress"); if (onKeySubExist) { if (keyCode == anywheresoftware.b4a.keywords.constants.KeyCodes.KEYCODE_BACK && android.os.Build.VERSION.SDK_INT >= 18) { HandleKeyDelayed hk = new HandleKeyDelayed(); hk.kc = keyCode; BA.handler.post(hk); return true; } else { boolean res = new HandleKeyDelayed().runDirectly(keyCode); if (res) return true; } } return super.onKeyDown(keyCode, event); } private class HandleKeyDelayed implements Runnable { int kc; public void run() { runDirectly(kc); } public boolean runDirectly(int keyCode) { Boolean res = (Boolean)processBA.raiseEvent2(_activity, false, "activity_keypress", false, keyCode); if (res == null || res == true) { return true; } else if (keyCode == anywheresoftware.b4a.keywords.constants.KeyCodes.KEYCODE_BACK) { finish(); return true; } return false; } } @Override public boolean onKeyUp(int keyCode, android.view.KeyEvent event) { if (processBA.runHook("onkeyup", this, new Object[] {keyCode, event})) return true; if (onKeyUpSubExist == null) onKeyUpSubExist = processBA.subExists("activity_keyup"); if (onKeyUpSubExist) { Boolean res = (Boolean)processBA.raiseEvent2(_activity, false, "activity_keyup", false, keyCode); if (res == null || res == true) return true; } return super.onKeyUp(keyCode, event); } @Override public void onNewIntent(android.content.Intent intent) { super.onNewIntent(intent); this.setIntent(intent); processBA.runHook("onnewintent", this, new Object[] {intent}); } @Override public void onPause() { super.onPause(); if (_activity == null) return; if (this != mostCurrent) return; anywheresoftware.b4a.Msgbox.dismiss(true); if (!dontPause) BA.LogInfo("** Activity (reviews) Pause, UserClosed = " + activityBA.activity.isFinishing() + " **"); else BA.LogInfo("** Activity (reviews) Pause event (activity is not paused). **"); if (mostCurrent != null) processBA.raiseEvent2(_activity, true, "activity_pause", false, activityBA.activity.isFinishing()); if (!dontPause) { processBA.setActivityPaused(true); mostCurrent = null; } if (!activityBA.activity.isFinishing()) previousOne = new WeakReference<Activity>(this); anywheresoftware.b4a.Msgbox.isDismissing = false; processBA.runHook("onpause", this, null); } @Override public void onDestroy() { super.onDestroy(); previousOne = null; processBA.runHook("ondestroy", this, null); } @Override public void onResume() { super.onResume(); mostCurrent = this; anywheresoftware.b4a.Msgbox.isDismissing = false; if (activityBA != null) { //will be null during activity create (which waits for AfterLayout). ResumeMessage rm = new ResumeMessage(mostCurrent); BA.handler.post(rm); } processBA.runHook("onresume", this, null); } private static class ResumeMessage implements Runnable { private final WeakReference<Activity> activity; public ResumeMessage(Activity activity) { this.activity = new WeakReference<Activity>(activity); } public void run() { reviews mc = mostCurrent; if (mc == null || mc != activity.get()) return; processBA.setActivityPaused(false); BA.LogInfo("** Activity (reviews) Resume **"); if (mc != mostCurrent) return; processBA.raiseEvent(mc._activity, "activity_resume", (Object[])null); } } @Override protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) { processBA.onActivityResult(requestCode, resultCode, data); processBA.runHook("onactivityresult", this, new Object[] {requestCode, resultCode}); } private static void initializeGlobals() { processBA.raiseEvent2(null, true, "globals", false, (Object[])null); } public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { for (int i = 0;i < permissions.length;i++) { Object[] o = new Object[] {permissions[i], grantResults[i] == 0}; processBA.raiseEventFromDifferentThread(null,null, 0, "activity_permissionresult", true, o); } } public anywheresoftware.b4a.keywords.Common __c = null; public static int _btn = 0; public anywheresoftware.b4a.objects.PanelWrapper _panel1 = null; public anywheresoftware.b4a.objects.LabelWrapper _labelrevname = null; public anywheresoftware.b4a.objects.LabelWrapper _labeldetname = null; public anywheresoftware.b4a.objects.LabelWrapper _labelreview = null; public anywheresoftware.b4a.objects.LabelWrapper _labeldetails = null; public anywheresoftware.b4a.objects.LabelWrapper _labeldesc = null; public anywheresoftware.b4a.objects.ButtonWrapper _btnreapply = null; public anywheresoftware.b4a.objects.ButtonWrapper _btnclaim = null; public anywheresoftware.b4a.samples.httputils2.httputils2service _httputils2service = null; public com.vukapesa.cleandeal.main _main = null; public com.vukapesa.cleandeal.acccreate2 _acccreate2 = null; public com.vukapesa.cleandeal.acclogins _acclogins = null; public com.vukapesa.cleandeal.applicationconfirm _applicationconfirm = null; public com.vukapesa.cleandeal.apply _apply = null; public com.vukapesa.cleandeal.claimsavings _claimsavings = null; public com.vukapesa.cleandeal.detailsoverview _detailsoverview = null; public com.vukapesa.cleandeal.directory _directory = null; public com.vukapesa.cleandeal.educlevel _educlevel = null; public com.vukapesa.cleandeal.inuka _inuka = null; public com.vukapesa.cleandeal.login _login = null; public com.vukapesa.cleandeal.starter _starter = null; public com.vukapesa.cleandeal.acccreate _acccreate = null; public com.vukapesa.cleandeal.acclogin _acclogin = null; public com.vukapesa.cleandeal.inukaloan _inukaloan = null; public com.vukapesa.cleandeal.membership _membership = null; public com.vukapesa.cleandeal.membershipselection _membershipselection = null; public com.vukapesa.cleandeal.nextofkin _nextofkin = null; public com.vukapesa.cleandeal.occupation _occupation = null; public com.vukapesa.cleandeal.processingtill _processingtill = null; public com.vukapesa.cleandeal.reward _reward = null; public com.vukapesa.cleandeal.saveconfirmpage _saveconfirmpage = null; public com.vukapesa.cleandeal.savingspage _savingspage = null; public com.vukapesa.cleandeal.tillsavings _tillsavings = null; public static void initializeProcessGlobals() { try { Class.forName(BA.applicationContext.getPackageName() + ".main").getMethod("initializeProcessGlobals").invoke(null, null); } catch (Exception e) { throw new RuntimeException(e); } } public static String _activity_create(boolean _firsttime) throws Exception{ anywheresoftware.b4a.objects.drawable.ColorDrawable _page = null; anywheresoftware.b4a.objects.collections.List _lists = null; String _pass = ""; String _phon = ""; String _names = ""; String _amount = ""; String _period = ""; String _repay = ""; String _intrests = ""; String _amounts = ""; String _interest = ""; String _periods = ""; //BA.debugLineNum = 28;BA.debugLine="Sub Activity_Create(FirstTime As Boolean)"; //BA.debugLineNum = 30;BA.debugLine="Activity.LoadLayout(\"ReviewsPage\")"; mostCurrent._activity.LoadLayout("ReviewsPage",mostCurrent.activityBA); //BA.debugLineNum = 31;BA.debugLine="Dim page As ColorDrawable"; _page = new anywheresoftware.b4a.objects.drawable.ColorDrawable(); //BA.debugLineNum = 32;BA.debugLine="page.Initialize(Inuka.pages,0)"; _page.Initialize(mostCurrent._inuka._pages /*int*/ ,(int) (0)); //BA.debugLineNum = 33;BA.debugLine="Panel1.Background=page"; mostCurrent._panel1.setBackground((android.graphics.drawable.Drawable)(_page.getObject())); //BA.debugLineNum = 43;BA.debugLine="LabelRevName.Text=\"Loan Status:\""; mostCurrent._labelrevname.setText(BA.ObjectToCharSequence("Loan Status:")); //BA.debugLineNum = 44;BA.debugLine="LabelRevName.TextSize=16"; mostCurrent._labelrevname.setTextSize((float) (16)); //BA.debugLineNum = 45;BA.debugLine="LabelRevName.TextColor=Colors.Black"; mostCurrent._labelrevname.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); //BA.debugLineNum = 47;BA.debugLine="LabelDetName.Text=\"Amount applied:\""; mostCurrent._labeldetname.setText(BA.ObjectToCharSequence("Amount applied:")); //BA.debugLineNum = 48;BA.debugLine="LabelDetName.TextSize=16"; mostCurrent._labeldetname.setTextSize((float) (16)); //BA.debugLineNum = 49;BA.debugLine="LabelDetName.TextColor=Colors.Black"; mostCurrent._labeldetname.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); //BA.debugLineNum = 51;BA.debugLine="BtnReapply.Text=\"Reapply\""; mostCurrent._btnreapply.setText(BA.ObjectToCharSequence("Reapply")); //BA.debugLineNum = 52;BA.debugLine="BtnReapply.TextSize=15"; mostCurrent._btnreapply.setTextSize((float) (15)); //BA.debugLineNum = 53;BA.debugLine="BtnReapply.TextColor=Colors.Black"; mostCurrent._btnreapply.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); //BA.debugLineNum = 55;BA.debugLine="BtnClaim.Text=\"Claim Savings\""; mostCurrent._btnclaim.setText(BA.ObjectToCharSequence("Claim Savings")); //BA.debugLineNum = 56;BA.debugLine="BtnClaim.TextSize=15"; mostCurrent._btnclaim.setTextSize((float) (15)); //BA.debugLineNum = 57;BA.debugLine="BtnClaim.TextColor=Colors.Black"; mostCurrent._btnclaim.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); //BA.debugLineNum = 59;BA.debugLine="Dim lists As List"; _lists = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 60;BA.debugLine="lists.Initialize"; _lists.Initialize(); //BA.debugLineNum = 61;BA.debugLine="Dim pass,phon As String"; _pass = ""; _phon = ""; //BA.debugLineNum = 62;BA.debugLine="If File.Exists(File.DirInternal,\"data2.dat\")Then"; if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data2.dat")) { //BA.debugLineNum = 63;BA.debugLine="lists=File.ReadList(File.DirInternal,\"data2.dat\")"; _lists = anywheresoftware.b4a.keywords.Common.File.ReadList(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data2.dat"); //BA.debugLineNum = 64;BA.debugLine="pass=lists.Get(0)"; _pass = BA.ObjectToString(_lists.Get((int) (0))); //BA.debugLineNum = 65;BA.debugLine="phon=lists.Get(1)"; _phon = BA.ObjectToString(_lists.Get((int) (1))); //BA.debugLineNum = 67;BA.debugLine="LabelReview.Text=$\"Interrupted!\"$"; mostCurrent._labelreview.setText(BA.ObjectToCharSequence(("Interrupted!"))); //BA.debugLineNum = 68;BA.debugLine="LabelReview.Color=Colors.Green"; mostCurrent._labelreview.setColor(anywheresoftware.b4a.keywords.Common.Colors.Green); //BA.debugLineNum = 69;BA.debugLine="LabelReview.TextSize=14"; mostCurrent._labelreview.setTextSize((float) (14)); //BA.debugLineNum = 70;BA.debugLine="LabelReview.TextColor=Colors.Red"; mostCurrent._labelreview.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Red); //BA.debugLineNum = 73;BA.debugLine="LabelDetails.Text=$\"Not Found!\"$"; mostCurrent._labeldetails.setText(BA.ObjectToCharSequence(("Not Found!"))); //BA.debugLineNum = 74;BA.debugLine="LabelDetails.Color=Colors.Green"; mostCurrent._labeldetails.setColor(anywheresoftware.b4a.keywords.Common.Colors.Green); //BA.debugLineNum = 75;BA.debugLine="LabelDetails.TextSize=14"; mostCurrent._labeldetails.setTextSize((float) (14)); //BA.debugLineNum = 76;BA.debugLine="LabelDetails.TextColor=Colors.Red"; mostCurrent._labeldetails.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Red); //BA.debugLineNum = 79;BA.debugLine="LabelDesc.Text=$\"Your loan application was inter"; mostCurrent._labeldesc.setText(BA.ObjectToCharSequence(("Your loan application was interrupted!"))); //BA.debugLineNum = 80;BA.debugLine="LabelDesc.TextSize=14"; mostCurrent._labeldesc.setTextSize((float) (14)); //BA.debugLineNum = 81;BA.debugLine="LabelDesc.TextColor=Colors.Red"; mostCurrent._labeldesc.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Red); }else { //BA.debugLineNum = 83;BA.debugLine="Dim lists As List"; _lists = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 84;BA.debugLine="lists.Initialize"; _lists.Initialize(); //BA.debugLineNum = 85;BA.debugLine="Dim names,phon,amount,period As String"; _names = ""; _phon = ""; _amount = ""; _period = ""; //BA.debugLineNum = 86;BA.debugLine="If File.Exists(File.DirInternal,\"data1.dat\")Then"; if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data1.dat")) { //BA.debugLineNum = 87;BA.debugLine="lists=File.ReadList(File.DirInternal,\"data1.dat"; _lists = anywheresoftware.b4a.keywords.Common.File.ReadList(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data1.dat"); //BA.debugLineNum = 88;BA.debugLine="names=lists.Get(0)"; _names = BA.ObjectToString(_lists.Get((int) (0))); //BA.debugLineNum = 89;BA.debugLine="phon=lists.Get(1)"; _phon = BA.ObjectToString(_lists.Get((int) (1))); //BA.debugLineNum = 90;BA.debugLine="amount=lists.Get(2)"; _amount = BA.ObjectToString(_lists.Get((int) (2))); //BA.debugLineNum = 91;BA.debugLine="period=lists.Get(3)"; _period = BA.ObjectToString(_lists.Get((int) (3))); //BA.debugLineNum = 93;BA.debugLine="Dim repay,intrests As String"; _repay = ""; _intrests = ""; //BA.debugLineNum = 94;BA.debugLine="Dim amounts As String=amount"; _amounts = _amount; //BA.debugLineNum = 95;BA.debugLine="Dim interest As String=0.025"; _interest = BA.NumberToString(0.025); //BA.debugLineNum = 96;BA.debugLine="Dim periods As String=period"; _periods = _period; //BA.debugLineNum = 97;BA.debugLine="repay=(periods*interest*amount)"; _repay = BA.NumberToString(((double)(Double.parseDouble(_periods))*(double)(Double.parseDouble(_interest))*(double)(Double.parseDouble(_amount)))); //BA.debugLineNum = 98;BA.debugLine="intrests=(repay-amounts)"; _intrests = BA.NumberToString(((double)(Double.parseDouble(_repay))-(double)(Double.parseDouble(_amounts)))); //BA.debugLineNum = 100;BA.debugLine="LabelReview.Text=$\"In Review\"$"; mostCurrent._labelreview.setText(BA.ObjectToCharSequence(("In Review"))); //BA.debugLineNum = 101;BA.debugLine="LabelReview.Color=Colors.Green"; mostCurrent._labelreview.setColor(anywheresoftware.b4a.keywords.Common.Colors.Green); //BA.debugLineNum = 102;BA.debugLine="LabelReview.TextSize=14"; mostCurrent._labelreview.setTextSize((float) (14)); //BA.debugLineNum = 103;BA.debugLine="LabelReview.TextColor=Colors.Black"; mostCurrent._labelreview.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); //BA.debugLineNum = 106;BA.debugLine="LabelDetails.Text=$\"Ksh.\"$&amount&$\" due in \"$&"; mostCurrent._labeldetails.setText(BA.ObjectToCharSequence(("Ksh.")+_amount+(" due in ")+_period+(" months."))); //BA.debugLineNum = 107;BA.debugLine="LabelDetails.Color=Colors.Green"; mostCurrent._labeldetails.setColor(anywheresoftware.b4a.keywords.Common.Colors.Green); //BA.debugLineNum = 108;BA.debugLine="LabelDetails.TextSize=14"; mostCurrent._labeldetails.setTextSize((float) (14)); //BA.debugLineNum = 109;BA.debugLine="LabelDetails.TextColor=Colors.Black"; mostCurrent._labeldetails.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); //BA.debugLineNum = 112;BA.debugLine="LabelDesc.Text=$\"Dear \"$&names&$\" your loan req"; mostCurrent._labeldesc.setText(BA.ObjectToCharSequence(("Dear ")+_names+(" your loan request is in review and will be processed as soon as possible.\n"+"Sorry for any inconviniences caused."))); //BA.debugLineNum = 114;BA.debugLine="LabelDesc.TextSize=14"; mostCurrent._labeldesc.setTextSize((float) (14)); //BA.debugLineNum = 115;BA.debugLine="LabelDesc.TextColor=Colors.Black"; mostCurrent._labeldesc.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Black); }else { //BA.debugLineNum = 118;BA.debugLine="LabelReview.Color=Colors.White"; mostCurrent._labelreview.setColor(anywheresoftware.b4a.keywords.Common.Colors.White); //BA.debugLineNum = 119;BA.debugLine="LabelReview.TextSize=14"; mostCurrent._labelreview.setTextSize((float) (14)); //BA.debugLineNum = 120;BA.debugLine="LabelReview.TextColor=Colors.Red"; mostCurrent._labelreview.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Red); //BA.debugLineNum = 121;BA.debugLine="LabelReview.Text=$\"Not applied\"$"; mostCurrent._labelreview.setText(BA.ObjectToCharSequence(("Not applied"))); //BA.debugLineNum = 123;BA.debugLine="LabelDesc.Color=Colors.White"; mostCurrent._labeldesc.setColor(anywheresoftware.b4a.keywords.Common.Colors.White); //BA.debugLineNum = 124;BA.debugLine="LabelDesc.Text=$\"\"$&names&$\"You have not applie"; mostCurrent._labeldesc.setText(BA.ObjectToCharSequence(("")+_names+("You have not applied for any loan! Apply and get the loan instantly"))); //BA.debugLineNum = 125;BA.debugLine="LabelDesc.TextSize=17"; mostCurrent._labeldesc.setTextSize((float) (17)); //BA.debugLineNum = 126;BA.debugLine="LabelDesc.TextColor=Colors.Red"; mostCurrent._labeldesc.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Red); //BA.debugLineNum = 128;BA.debugLine="LabelDetails.Text=$\"Not applied\"$"; mostCurrent._labeldetails.setText(BA.ObjectToCharSequence(("Not applied"))); //BA.debugLineNum = 129;BA.debugLine="LabelDetails.Color=Colors.White"; mostCurrent._labeldetails.setColor(anywheresoftware.b4a.keywords.Common.Colors.White); //BA.debugLineNum = 130;BA.debugLine="LabelDetails.TextSize=14"; mostCurrent._labeldetails.setTextSize((float) (14)); //BA.debugLineNum = 131;BA.debugLine="LabelDetails.TextColor=Colors.Red"; mostCurrent._labeldetails.setTextColor(anywheresoftware.b4a.keywords.Common.Colors.Red); }; }; //BA.debugLineNum = 140;BA.debugLine="End Sub"; return ""; } public static String _activity_pause(boolean _userclosed) throws Exception{ //BA.debugLineNum = 146;BA.debugLine="Sub Activity_Pause (UserClosed As Boolean)"; //BA.debugLineNum = 148;BA.debugLine="End Sub"; return ""; } public static String _activity_resume() throws Exception{ //BA.debugLineNum = 142;BA.debugLine="Sub Activity_Resume"; //BA.debugLineNum = 144;BA.debugLine="End Sub"; return ""; } public static void _btnclaim_click() throws Exception{ ResumableSub_BtnClaim_Click rsub = new ResumableSub_BtnClaim_Click(null); rsub.resume(processBA, null); } public static class ResumableSub_BtnClaim_Click extends BA.ResumableSub { public ResumableSub_BtnClaim_Click(com.vukapesa.cleandeal.reviews parent) { this.parent = parent; } com.vukapesa.cleandeal.reviews parent; anywheresoftware.b4a.objects.collections.List _lists = null; String _pass = ""; String _phon = ""; @Override public void resume(BA ba, Object[] result) throws Exception{ while (true) { switch (state) { case -1: return; case 0: //C this.state = 1; //BA.debugLineNum = 191;BA.debugLine="Dim lists As List"; _lists = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 192;BA.debugLine="lists.Initialize"; _lists.Initialize(); //BA.debugLineNum = 193;BA.debugLine="Dim pass,phon As String"; _pass = ""; _phon = ""; //BA.debugLineNum = 194;BA.debugLine="If File.Exists(File.DirInternal,\"data2.dat\")Then"; if (true) break; case 1: //if this.state = 12; if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data2.dat")) { this.state = 3; }else { this.state = 5; }if (true) break; case 3: //C this.state = 12; //BA.debugLineNum = 195;BA.debugLine="ProgressDialogShow(\"Checking savings.....\")"; anywheresoftware.b4a.keywords.Common.ProgressDialogShow(mostCurrent.activityBA,BA.ObjectToCharSequence("Checking savings.....")); //BA.debugLineNum = 196;BA.debugLine="Sleep(4000)"; anywheresoftware.b4a.keywords.Common.Sleep(mostCurrent.activityBA,this,(int) (4000)); this.state = 13; return; case 13: //C this.state = 12; ; //BA.debugLineNum = 197;BA.debugLine="ProgressDialogHide"; anywheresoftware.b4a.keywords.Common.ProgressDialogHide(); //BA.debugLineNum = 198;BA.debugLine="MsgboxAsync(\"You have already claimed\",\"Dear use"; anywheresoftware.b4a.keywords.Common.MsgboxAsync(BA.ObjectToCharSequence("You have already claimed"),BA.ObjectToCharSequence("Dear user"),processBA); if (true) break; case 5: //C this.state = 6; //BA.debugLineNum = 200;BA.debugLine="Dim lists As List"; _lists = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 201;BA.debugLine="lists.Initialize"; _lists.Initialize(); //BA.debugLineNum = 202;BA.debugLine="If File.Exists(File.DirInternal,\"data1.dat\")Then"; if (true) break; case 6: //if this.state = 11; if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data1.dat")) { this.state = 8; }else { this.state = 10; }if (true) break; case 8: //C this.state = 11; //BA.debugLineNum = 203;BA.debugLine="ProgressDialogShow(\"Checking savings.....\")"; anywheresoftware.b4a.keywords.Common.ProgressDialogShow(mostCurrent.activityBA,BA.ObjectToCharSequence("Checking savings.....")); //BA.debugLineNum = 204;BA.debugLine="Sleep(4000)"; anywheresoftware.b4a.keywords.Common.Sleep(mostCurrent.activityBA,this,(int) (4000)); this.state = 14; return; case 14: //C this.state = 11; ; //BA.debugLineNum = 205;BA.debugLine="ProgressDialogHide"; anywheresoftware.b4a.keywords.Common.ProgressDialogHide(); //BA.debugLineNum = 209;BA.debugLine="StartActivity(ClaimSavings)"; anywheresoftware.b4a.keywords.Common.StartActivity(processBA,(Object)(parent.mostCurrent._claimsavings.getObject())); if (true) break; case 10: //C this.state = 11; //BA.debugLineNum = 212;BA.debugLine="ProgressDialogShow(\"Checking savings.....\")"; anywheresoftware.b4a.keywords.Common.ProgressDialogShow(mostCurrent.activityBA,BA.ObjectToCharSequence("Checking savings.....")); //BA.debugLineNum = 213;BA.debugLine="Sleep(4000)"; anywheresoftware.b4a.keywords.Common.Sleep(mostCurrent.activityBA,this,(int) (4000)); this.state = 15; return; case 15: //C this.state = 11; ; //BA.debugLineNum = 214;BA.debugLine="ProgressDialogHide"; anywheresoftware.b4a.keywords.Common.ProgressDialogHide(); //BA.debugLineNum = 215;BA.debugLine="MsgboxAsync(\"You have no savings yet\",\"Dear user"; anywheresoftware.b4a.keywords.Common.MsgboxAsync(BA.ObjectToCharSequence("You have no savings yet"),BA.ObjectToCharSequence("Dear user"),processBA); if (true) break; case 11: //C this.state = 12; ; if (true) break; case 12: //C this.state = -1; ; //BA.debugLineNum = 218;BA.debugLine="End Sub"; if (true) break; } } } } public static void _btnreapply_click() throws Exception{ ResumableSub_BtnReapply_Click rsub = new ResumableSub_BtnReapply_Click(null); rsub.resume(processBA, null); } public static class ResumableSub_BtnReapply_Click extends BA.ResumableSub { public ResumableSub_BtnReapply_Click(com.vukapesa.cleandeal.reviews parent) { this.parent = parent; } com.vukapesa.cleandeal.reviews parent; anywheresoftware.b4a.objects.collections.List _lists = null; String _pass = ""; String _phon = ""; @Override public void resume(BA ba, Object[] result) throws Exception{ while (true) { switch (state) { case -1: return; case 0: //C this.state = 1; //BA.debugLineNum = 151;BA.debugLine="Dim lists As List"; _lists = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 152;BA.debugLine="lists.Initialize"; _lists.Initialize(); //BA.debugLineNum = 153;BA.debugLine="Dim pass,phon As String"; _pass = ""; _phon = ""; //BA.debugLineNum = 154;BA.debugLine="If File.Exists(File.DirInternal,\"data2.dat\")Then"; if (true) break; case 1: //if this.state = 12; if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data2.dat")) { this.state = 3; }else { this.state = 5; }if (true) break; case 3: //C this.state = 12; //BA.debugLineNum = 155;BA.debugLine="ProgressDialogShow(\"Validating loan reapplicatio"; anywheresoftware.b4a.keywords.Common.ProgressDialogShow(mostCurrent.activityBA,BA.ObjectToCharSequence("Validating loan reapplication.....")); //BA.debugLineNum = 156;BA.debugLine="Sleep(4000)"; anywheresoftware.b4a.keywords.Common.Sleep(mostCurrent.activityBA,this,(int) (4000)); this.state = 13; return; case 13: //C this.state = 12; ; //BA.debugLineNum = 157;BA.debugLine="ProgressDialogHide"; anywheresoftware.b4a.keywords.Common.ProgressDialogHide(); //BA.debugLineNum = 158;BA.debugLine="MsgboxAsync(\"Your savings refund is already in p"; anywheresoftware.b4a.keywords.Common.MsgboxAsync(BA.ObjectToCharSequence("Your savings refund is already in process"),BA.ObjectToCharSequence("Dear user"),processBA); if (true) break; case 5: //C this.state = 6; //BA.debugLineNum = 160;BA.debugLine="Dim lists As List"; _lists = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 161;BA.debugLine="lists.Initialize"; _lists.Initialize(); //BA.debugLineNum = 162;BA.debugLine="If File.Exists(File.DirInternal,\"data1.dat\")Then"; if (true) break; case 6: //if this.state = 11; if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data1.dat")) { this.state = 8; }else { this.state = 10; }if (true) break; case 8: //C this.state = 11; //BA.debugLineNum = 163;BA.debugLine="ProgressDialogShow(\"Validating loan reapplication"; anywheresoftware.b4a.keywords.Common.ProgressDialogShow(mostCurrent.activityBA,BA.ObjectToCharSequence("Validating loan reapplication.....")); //BA.debugLineNum = 164;BA.debugLine="Sleep(4000)"; anywheresoftware.b4a.keywords.Common.Sleep(mostCurrent.activityBA,this,(int) (4000)); this.state = 14; return; case 14: //C this.state = 11; ; //BA.debugLineNum = 165;BA.debugLine="ProgressDialogHide"; anywheresoftware.b4a.keywords.Common.ProgressDialogHide(); //BA.debugLineNum = 169;BA.debugLine="StartActivity(SaveConfirmPage)"; anywheresoftware.b4a.keywords.Common.StartActivity(processBA,(Object)(parent.mostCurrent._saveconfirmpage.getObject())); if (true) break; case 10: //C this.state = 11; //BA.debugLineNum = 172;BA.debugLine="ProgressDialogShow(\"Checking savings.....\")"; anywheresoftware.b4a.keywords.Common.ProgressDialogShow(mostCurrent.activityBA,BA.ObjectToCharSequence("Checking savings.....")); //BA.debugLineNum = 173;BA.debugLine="Sleep(4000)"; anywheresoftware.b4a.keywords.Common.Sleep(mostCurrent.activityBA,this,(int) (4000)); this.state = 15; return; case 15: //C this.state = 11; ; //BA.debugLineNum = 174;BA.debugLine="ProgressDialogHide"; anywheresoftware.b4a.keywords.Common.ProgressDialogHide(); //BA.debugLineNum = 175;BA.debugLine="MsgboxAsync(\"You have not applied\",\"Dear user\")"; anywheresoftware.b4a.keywords.Common.MsgboxAsync(BA.ObjectToCharSequence("You have not applied"),BA.ObjectToCharSequence("Dear user"),processBA); if (true) break; case 11: //C this.state = 12; ; if (true) break; case 12: //C this.state = -1; ; //BA.debugLineNum = 188;BA.debugLine="End Sub"; if (true) break; } } } } public static String _globals() throws Exception{ //BA.debugLineNum = 12;BA.debugLine="Sub Globals"; //BA.debugLineNum = 16;BA.debugLine="Private Panel1 As Panel"; mostCurrent._panel1 = new anywheresoftware.b4a.objects.PanelWrapper(); //BA.debugLineNum = 17;BA.debugLine="Private LabelRevName As Label"; mostCurrent._labelrevname = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 18;BA.debugLine="Private LabelDetName As Label"; mostCurrent._labeldetname = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 19;BA.debugLine="Private LabelReview As Label"; mostCurrent._labelreview = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 20;BA.debugLine="Private LabelDetails As Label"; mostCurrent._labeldetails = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 21;BA.debugLine="Private LabelDesc As Label"; mostCurrent._labeldesc = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 22;BA.debugLine="Private BtnReapply As Button"; mostCurrent._btnreapply = new anywheresoftware.b4a.objects.ButtonWrapper(); //BA.debugLineNum = 24;BA.debugLine="Private BtnClaim As Button"; mostCurrent._btnclaim = new anywheresoftware.b4a.objects.ButtonWrapper(); //BA.debugLineNum = 26;BA.debugLine="End Sub"; return ""; } public static String _process_globals() throws Exception{ //BA.debugLineNum = 6;BA.debugLine="Sub Process_Globals"; //BA.debugLineNum = 9;BA.debugLine="Dim btn As Int = Colors.ARGB(182,223,255,255)"; _btn = anywheresoftware.b4a.keywords.Common.Colors.ARGB((int) (182),(int) (223),(int) (255),(int) (255)); //BA.debugLineNum = 10;BA.debugLine="End Sub"; return ""; } }
C++
UTF-8
2,057
2.84375
3
[]
no_license
#include "colors.h" #include "function.h" bool loadLuaFile(lua_State *L, const char *fileName) { if (luaL_loadfile(L, fileName) || lua_pcall(L, 0, 0, 0)) { printf( "ERROR. Cannot load Lua file '%s': '%s'\n", fileName, lua_tostring(L, -1)); lua_pop(L, 1); return false; } return true; } void readWidthHeight(lua_State *L, int *width, int *height) { // Width. lua_getglobal(L, "width"); if (!lua_isnumber(L, -1)) { printf("readWidthHeight. 'width' should be a number\n"); } else { *width = (int)lua_tonumber(L, -1); } lua_pop(L, 1); // Height. lua_getglobal(L, "height"); if (!lua_isnumber(L, -1)) { printf("readWidthHeight. 'height' should be a number\n"); } else { *height = (int)lua_tonumber(L, -1); } lua_pop(L, 1); } int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s /path/to/cfg.lua\n", argv[0]); return 1; } const char *fileName = argv[1]; // Create lua state. lua_State *L = luaL_newstate(); luaL_openlibs(L); // Register mylib. luaopen_mylib(L); setupPredefinedColors(L); if (loadLuaFile(L, fileName)) { // Read width and height. int width = 0; int height = 0; readWidthHeight(L, &width, &height); printf("main. width: '%d' height: '%d'\n", width, height); // Read background color. unsigned char r = 0; unsigned char g = 0; unsigned char b = 0; readColor(L, "background", &r, &g, &b); printf("main. background: '%d, %d, %d'\n", r, g, b); readColor(L, "foreground", &r, &g, &b); printf("main. foreground: '%d, %d, %d'\n", r, g, b); // Execute function. double x = 20; double y = 3; double f = functionF(L, x, y); printf("main. '%f' = functionF(%f, %f)\n", f, x, y); } // Close lua state. lua_close(L); return 0; }
Go
UTF-8
2,539
2.53125
3
[ "MIT" ]
permissive
package main import ( "io" "strings" "github.com/jessevdk/go-flags" "github.com/mmktomato/go-twmedia/svc/extcmd" "github.com/mmktomato/go-twmedia/svc/image" "github.com/mmktomato/go-twmedia/svc/tw" "github.com/mmktomato/go-twmedia/svc/video" "github.com/mmktomato/go-twmedia/util" ) var httpClient util.HttpClient var logger *util.TinyLogger var tweetService tw.TweetService var videoService video.VideoService type Opts struct { Headers map[string]string `short:"H" long:"header" description:"HTTP header"` // same as curl's one. VerboseLog []bool `short:"v" long:"verbose" description:"verbose log"` } func initServices(opts *Opts) { httpClient = util.HttpClient{opts.Headers} logger = util.NewTinyLogger(0 < len(opts.VerboseLog)) extcmdService := extcmd.NewExternalCmdServiceImpl(logger) imageService := image.NewImageServiceImpl(logger) videoService = video.NewVideoServiceImpl(extcmdService, &httpClient, logger) tweetService = tw.NewTweetServiceImpl(imageService, logger) } func onTweetFetched(tweetUrl string, r io.Reader) error { tweet, err := tweetService.ParseTweet(tweetUrl, r) if err != nil { return err } // TODO: move to svc/image for url, filename := range tweet.ImageUrls { err := httpClient.Fetch(url, func(r io.Reader) error { return util.Save(filename, r) }) if err == nil { logger.Writeln(filename) } else { logger.Writef("%s : %v\n", url, err) } } // TODO: move to svc/video if tweet.VideoUrl != "" { err := httpClient.Fetch(tweet.VideoUrl, func(r io.Reader) error { trackInfo, err := videoService.ParseVideo(tweet.TweetId, r) if err != nil { return err } logger.Verbosef("track info: %v\n", trackInfo) return videoService.SavePlaylist(trackInfo) }) if err != nil { return err } } return nil } func getOptions() ([]string, *Opts, error) { opts := Opts{} parser := flags.NewParser(&opts, flags.IgnoreUnknown) args, err := parser.Parse() if err != nil { return []string{}, nil, err } for k, v := range opts.Headers { opts.Headers[k] = strings.TrimSpace(v) } return args, &opts, nil } func main() { args, opts, err := getOptions() if err != nil { panic(err) } initServices(opts) for _, v := range args { if strings.HasPrefix(v, "-") { // unknown option continue } logger.Verbosef("Try: %s\n", v) opts.Headers["Referer"] = v err := httpClient.Fetch(v, func(r io.Reader) error { return onTweetFetched(v, r) }) if err != nil { logger.Writef("%s : %v\n", v, err) } } }
JavaScript
UTF-8
1,748
3.125
3
[]
no_license
var _newElement = document.getElementById("newElement"); var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } // Add a "checked" symbol when clicking on a list item var list = document.querySelector('#myUL'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value = ""; var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); li.appendChild(span); for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } } //Accordian var acc = document.getElementsByClassName("accordion"); var j; for (j = 0; j < acc.length; j++) { acc[j].addEventListener("click", function() { this.classList.toggle("active"); var panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; } }); } _newElement.onclick = newElement;
C#
UTF-8
4,094
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using InterXLib.Display; namespace InterXLib.XGUI.Rendering { class BorderedRenderer : ARenderer { private Rectangle m_UL, m_UR, m_LL, m_LR; private Rectangle m_T, m_R, m_B, m_L; private Rectangle m_BG; public int BorderWidth { get; protected set; } public BorderedRenderer(Texture2D texture, Rectangle source, int borderWidth) : base(texture) { BorderWidth = borderWidth; m_UL = new Rectangle(source.Left, source.Top, BorderWidth, BorderWidth); m_UR = new Rectangle(source.Right - BorderWidth, source.Top, BorderWidth, BorderWidth); m_LL = new Rectangle(source.Left, source.Bottom - BorderWidth, BorderWidth, BorderWidth); m_LR = new Rectangle(source.Right - BorderWidth, source.Bottom - BorderWidth, BorderWidth, BorderWidth); m_T = new Rectangle(source.Left + BorderWidth, source.Top, source.Width - 2 * BorderWidth, BorderWidth); m_R = new Rectangle(source.Right - BorderWidth, source.Top + BorderWidth, BorderWidth, source.Height - 2 * BorderWidth); m_B = new Rectangle(source.Left + BorderWidth, source.Bottom - BorderWidth, source.Width - 2 * BorderWidth, BorderWidth); m_L = new Rectangle(source.Left, source.Top + BorderWidth, BorderWidth, source.Height - 2 * BorderWidth); m_BG = new Rectangle(source.Left + BorderWidth, source.Top + BorderWidth, source.Width - 2 * BorderWidth, source.Height - 2 * BorderWidth); } public override Rectangle BuildChildArea(Point area) { return new Rectangle(BorderWidth, BorderWidth, area.X - 2 * BorderWidth, area.Y - 2 * BorderWidth); } public override void Render(YSpriteBatch batch, Rectangle area, Color? color = null) { Color Color = (color == null) ? Color.White : color.Value; // ##### Draw Background ##### // Rectangle drawArea = new Rectangle( area.Left + BorderWidth, area.Top + BorderWidth, area.Width - (2 * BorderWidth), area.Height - (2 * BorderWidth)); batch.GUIDrawSprite(Texture, drawArea, m_BG, Color); // ##### Draw Corners ##### // drawArea.Width = BorderWidth; drawArea.Height = BorderWidth; //Top Left drawArea.X = area.Left; drawArea.Y = area.Top; batch.GUIDrawSprite(Texture, drawArea, m_UL, Color); //Top Right drawArea.X = area.Right - BorderWidth; drawArea.Y = area.Top; batch.GUIDrawSprite(Texture, drawArea, m_UR, Color); //Bottom Right drawArea.X = area.Right - BorderWidth; drawArea.Y = area.Bottom - BorderWidth; batch.GUIDrawSprite(Texture, drawArea, m_LR, Color); //Bottom Left drawArea.X = area.Left; drawArea.Y = area.Bottom - BorderWidth; batch.GUIDrawSprite(Texture, drawArea, m_LL, Color); // ##### Draw Edges ##### // //Top Edge drawArea.X = area.Left + BorderWidth; drawArea.Y = area.Top; drawArea.Width = area.Width - (2 * BorderWidth); batch.GUIDrawSprite(Texture, drawArea, m_T, Color); //Bottom Edge drawArea.Y = area.Bottom - BorderWidth; batch.GUIDrawSprite(Texture, drawArea, m_B, Color); //Left Edge drawArea.X = area.Left; drawArea.Y = area.Top + BorderWidth; drawArea.Width = BorderWidth; drawArea.Height = area.Height - (2 * BorderWidth); batch.GUIDrawSprite(Texture, drawArea, m_L, Color); //Right Edge drawArea.X = area.Right - BorderWidth; batch.GUIDrawSprite(Texture, drawArea, m_R, Color); } } }
Java
UTF-8
821
3.109375
3
[]
no_license
import java.util.Scanner; public class Zombie { public static void main(String[] args) { int numberOfStudents = 29; double avgGPA = 3.78; String name = ""; String job = ""; String alone = ""; boolean gameOver = false; //or true int age = 0; // Create a Scanner object Scanner input = new Scanner (System.in); //Make the user answer 3 question pertaining to the start of zombie game //What is your name? System.out.println("What is your name?"); name = input.next(); //Starting profession System.out.println("What is your job?"); job = input.next(); //Are you alone? System.out.println("Are you alone?"); alone = input.next(); } }
C++
UTF-8
9,440
2.875
3
[ "Apache-2.0" ]
permissive
/** * Author: Mark Larkin * * Copyright (c) 2007 Des Higgins, Julie Thompson and Toby Gibson. * * @author Mark Larkin, Conway Institute, UCD. mark.larkin@ucd.ie * * Changes: * * 2007-12-03, Andreas Wilm (UCD): replaced gets with fgets, and * got rid of some compiler warning * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <iostream> #include <algorithm> #include "Utility.h" #include "general/userparams.h" namespace clustalw { /** constructor */ Utility::Utility() { quiet=false; } /** * Removes trailing blanks from a string */ void Utility::rTrim(string *str) { string::reverse_iterator rit = str->rbegin(); while(rit != str->rend() && isspace(*rit)) { str->erase((++rit).base()); } } /** * Removes trailing blanks from a string * @param str String to remove trailing blanks from. * @return Pointer to the processed string */ char * Utility::rTrim(char *str) { register int p; p = strlen(str) - 1; while (isspace(str[p])) { p--; } str[p + 1] = EOS; return str; } /** * Replace blanks in a string with underscores. Also replaces , ; : ( or ) with _. * @param str String to process. * @return Pointer to the processed string */ char * Utility::blankToUnderscore(char *str) { int i, p; p = strlen(str) - 1; for (i = 0; i <= p; i++) if ((str[i] == ' ') || (str[i] == ';') || (str[i] == ',') || (str[i] == '(') || (str[i] == ')') || (str[i] == ':')) { str[i] = '_'; } return str; } /** * Replace blanks in a string with underscores. Also replaces , ; : ( or ) with _. * @param str String to process. * @return Pointer to the processed string */ string Utility::blankToUnderscore(string str) { int i, p; p = str.size() - 1; for (i = 0; i <= p; i++) if ((str[i] == ' ') || (str[i] == ';') || (str[i] == ',') || (str[i] == '(') || (str[i] == ')') || (str[i] == ':')) { str[i] = '_'; } return str; } /** * * @param instr * @return */ char Utility::getChoice(string instr) { cout << instr << ": "; cout.flush(); char choice; cin.get(choice); // We only want one character, so we ignore the rest. if(choice != '\n') { cin.ignore(150, '\n'); } cin.clear(); if(isalpha(choice) || isNumeric(choice)) { return choice; } else if(choice == '\n') { return '\n'; } else { return ' '; } } bool Utility::isNumeric(char ch) { if(ch >= '0' && ch <= '9') { return true; } return false; } /** * * @param instr * @param outstr */ void Utility::getStr(string instr, string& outstr) { cout << instr << ": "; cout.flush(); string temp; getline(cin, temp, '\n'); outstr = temp; cin.clear(); } /** * * @param instr * @param minx * @param maxx * @param def * @return */ double Utility::getReal(const char *instr, double minx, double maxx, double def) { int status; float ret; char line[MAXLINE]; while (true) { fprintf(stdout, "%s (%.1f-%.1f) [%.1f]: ", instr, minx, maxx, def); //gets(line); fgets(line, MAXLINE, stdin); status = sscanf(line, "%f", &ret); if (status == EOF) { return def; } if (ret > maxx) { fprintf(stderr, "ERROR: Max. value=%.1f\n\n", maxx); continue; } if (ret < minx) { fprintf(stderr, "ERROR: Min. value=%.1f\n\n", minx); continue; } break; } return (double)ret; } /** * * @param instr * @param minx * @param maxx * @param def * @return */ int Utility::getInt(const char *instr, int minx, int maxx, int def) { int ret, status; char line[MAXLINE]; while (true) { fprintf(stdout, "%s (%d..%d) [%d]: ", instr, minx, maxx, def); //gets(line); fgets(line, MAXLINE, stdin); status = sscanf(line, "%d", &ret); if (status == EOF) { return def; } if (ret > maxx) { fprintf(stderr, "ERROR: Max. value=%d\n\n", maxx); continue; } if (ret < minx) { fprintf(stderr, "ERROR: Min. value=%d\n\n", minx); continue; } break; } return ret; } /** * * @param line * @param code * @return */ bool Utility::lineType(char *line, const char *code) { // AW: introduced sanity check int n; if (strlen(line)<strlen(code)) n=strlen(line); else n=strlen(code); return (strncmp(line, code, strlen(code)) == 0); } /** * * @param line * @return */ bool Utility::blankLine(char *line) { int i; for (i = 0; line[i] != '\n' && line[i] != EOS; i++) { if (isdigit(line[i]) || isspace(line[i]) || (line[i] == '*') || (line[i] == ':') || (line[i] == '.')) ; else { return false; } } return true; } /** * * @param str * @param path */ void Utility::getPath(string str, string *path) { int i; string _temp; _temp = str; for (i = _temp.length() - 1; i > - 1; --i) { if (str[i] == DIRDELIM) { i = - 1; break; } if (str[i] == '.') { break; } } if (i < 0) { _temp += "."; } else { _temp = _temp.substr(0, i + 1); } *path = _temp; } /** * * @param title * @param prompt * @return * * */ char Utility::promptForYesNo(char *title, const char *prompt) { cout << "\n" << title << "\n"; string promptMessage = string(prompt) + "(y/n) ? [y]"; string answer; getStr(promptMessage, answer); if(!answer.empty()) { if ((answer[0] != 'n') && (answer[0] != 'N')) { return ('y'); } } return ('n'); } /** * * @param title * @param prompt * @return * */ char Utility::promptForYesNo(const char *title, const char *prompt) { cout << "\n" << title << "\n"; string promptMessage = string(prompt) + "(y/n) ? [y]"; string answer; getStr(promptMessage, answer); if(!answer.empty()) { if ((answer[0] != 'n') && (answer[0] != 'N')) { return ('y'); } } return ('n'); } /** * * @param msg */ void Utility::error( char *msg,...) { va_list ap; va_start(ap, msg); fprintf(stderr, "\n\nERROR: "); vfprintf(stderr, msg, ap); fprintf(stderr, "\n\n"); va_end(ap); } /** * * @param msg */ void Utility::warning( char *msg,...) { va_list ap; va_start(ap, msg); fprintf(stderr, "\n\nWARNING: "); vfprintf(stderr, msg, ap); fprintf(stderr, "\n\n"); va_end(ap); } /** * * @param msg */ void Utility::error( const char *msg,...) { va_list ap; va_start(ap, msg); fprintf(stderr, "\n\nERROR: "); vfprintf(stderr, msg, ap); fprintf(stderr, "\n\n"); va_end(ap); } /** * * @param msg */ void Utility::warning( const char *msg,...) { va_list ap; va_start(ap, msg); fprintf(stderr, "\n\nWARNING: "); vfprintf(stderr, msg, ap); fprintf(stderr, "\n\n"); va_end(ap); } /** * * @param msg */ void Utility::info( char *msg,...) { va_list ap; va_start(ap, msg); if(! quiet) { fprintf(stdout, "\n"); vfprintf(stdout, msg, ap); va_end(ap); } } /** * * @param msg */ void Utility::info(const char *msg,...) { va_list ap; if(! quiet) { va_start(ap, msg); fprintf(stdout, "\n"); vfprintf(stdout, msg, ap); va_end(ap); } } /** * */ void Utility::myname( char *myname) { strcpy(myname, "clustalw\0"); } /** * Change: * Mark 25-1-2007. I made this change to get around the problem of having to keep track * of output indexes in the alignment stage. This function returns the next unique id. */ unsigned long Utility::getUniqueSequenceIdentifier() { static unsigned long nextSequenceIdentifier = MinIdentifier; return nextSequenceIdentifier++; } void Utility::setInfoLabelPtr(QLabel* ptrToLabelObj) { // Dont do anything. This is here to allow the function to be added to QTUtility. // Polymorphism wont work with different functions in the classes. } double Utility::average(std::vector<double>& v) { double tmp = 0.0; std::vector<double>::iterator i; if (v.size() == 0) return 0.0; for (i=v.begin(); i != v.end(); i++) tmp += *i; return (tmp / v.size()); } double Utility::stdDev(std::vector<double>& v) { std::vector<double>::iterator i; double tmp = 0.0; double avg = average(v); if (v.size() == 0) return 0.0; for(i=v.begin(); i != v.end(); ++i) tmp += (*i - avg) * (*i - avg); return sqrt(tmp / v.size()); } double Utility::median(std::vector<double> v) { // From Moo & Koenig, "Accelerated C++: typedef vector<double>::size_type vec_sz; vec_sz size = v.size(); if (v.size() == 0) return 0.0; std::sort(v.begin(), v.end()); vec_sz mid = size/2; return size % 2 == 0 ? (v[mid] + v[mid-1]) / 2 : v[mid]; } }
Markdown
UTF-8
6,787
3.21875
3
[]
no_license
## 仿微信「跳一跳」- 1. 简单实现 微信的跳一跳大家应该都玩过吧,玩法很简单,但是各种细节做的很不错。据了解它是使用 three.js 实现的,那么不用 WebGL,使用简单的 2D canvas 能否实现这样的效果呢?我们试试看。 > 部分素材来自网上资源,仅供学习使用,如有问题请与我联系。 ### 1. 初始化项目 我们选用 [Tiny.js](http://tinyjs.net) 这款高效而强劲的 HTML5 2D 游戏引擎来实现整个游戏,那么项目初始化使用 tinyjs-cli 即可,参考文档:http://tinyjs.net/guide/start.html 执行 `tiny init`,选择「标准版」,按照自己的情况填写项目内容,会自动生成项目的初始化脚本。然后 `npm install` 来安装依赖,执行 `npm start` 来启动开发服务器,一个完整的 demo 就跑起来了。 ### 2. 渲染一个小蚂蚁 第一步,将蚂蚁的图片放到 `res/images` 目录中,然后在 resources.js 中导出一下。 ```js const antPng = 'res/images/ant.png'; export { antPng, }; ``` 第二步,开始写代码喽。 在 StartLayer.js 的 constructor 中,创建一个小蚂蚁。 ```js // 使用图片生成一个 sprite const ant = Tiny.Sprite.fromImage(Tiny.resources.antPng); // canvas 默认旋转中心是在左上角,这样定位起来比较麻烦,所以这里将蚂蚁的脚底作为定位中心 ant.setPivot(ant.width / 2, ant.height); // 先随便定个位置吧 ant.setPosition(100, 300); // 加到 container 中来渲染 this.addChild(ant); ``` > 使用初始化生成的项目架构,图片在执行这里的业务代码前已经加载好了,因此不用担心图片加载问题,直接用来生成 sprite 就好。 看看效果: ![](https://gw.alipayobjects.com/zos/rmsportal/becwawYwTmsILlBfQlza.png) ### 3. 给蚂蚁加个小盒子 跟上面一样,使用盒子的图片生成一个 sprite,然后渲染出来。 ```js const box = Tiny.Sprite.fromImage(Tiny.resources.boxPng); box.setPivot(box.width / 2, box.height); // 位置得调整一下,使得蚂蚁能够正好站在盒子上 box.setPosition(100, 400); // 如果使用 addChild,会发现盒子将蚂蚁盖起来了,所以使用 addChildAt 来将盒子放到蚂蚁下面 this.addChildAt(box, 0); ``` 看看效果: ![](https://gw.alipayobjects.com/zos/rmsportal/pzicRPmYXEazTfrLvoqk.png) ### 4. 让蚂蚁跳起来 我们要实现的效果是,当鼠标按下然后松开时,蚂蚁向右方跳一下。 首先,要响应鼠标事件。移动端跟桌面浏览器的响应事件有些差别,因此要兼容一下。 ```js const canvas = Tiny.app.view; const supportTouch = 'ontouchstart' in window; canvas.addEventListener(supportTouch ? 'touchstart' : 'mousedown', () => { // 鼠标按下了 }); canvas.addEventListener(supportTouch ? 'touchend' : 'mouseup', () => { // 鼠标抬起来了 }); ``` 下一步要实现蚂蚁跳跃了。我们设计的跳跃动作是:蚂蚁要翻个跟头,同时向右移动距离 deltaX。我们使用 Tiny.TWEEN.Tween 来实现这个动作。 ```js jump(deltaX, onComplete) { const maxHeight = 200; // 跳的最高点 const ant = this.ant; // 上面创建的蚂蚁实例 const originX = ant.position.x; const originY = ant.position.y; const tween = new Tiny.TWEEN.Tween({ // 起始值 rotation: 0, x: originX, y: originY, }).to({ // 结束值 rotation: 360, // 旋转 1 周 x: originX + deltaX, // 向右移动 deltaX y: [originY - maxHeight, originY], // 设置 2 个关键帧,一个是最高点,一个是最终点。效果就是蚂蚁跳起来然后落下 }, 1000).onUpdate(function() { // 设置位置 ant.setPosition(this.x, this.y); // 需要将角度转换为弧度,然后设置旋转 ant.setRotation(Tiny.deg2radian(this.rotation)); }).onComplete(function () { // 动画结束的回调 onComplete(); }); // 动画开始 tween.start(); } ``` 鼠标按下时,我们期望蚂蚁能有个动作来响应这个操作,所以加了一个压缩的动画来模拟,因为比较简单,直接使用 Action 来实现。 ```js compress() { // 动画 持续 1000ms,y 轴缩放到 0.7 this.ant.runAction(Tiny.ScaleTo(1000, { scaleY: 0.7, })); } ``` 如果鼠标还没有按 0.7s 就松开了,这时候应该马上终止动画,然后恢复蚂蚁大小。 ```js compressRestore() { this.ant.removeActions(); // 移除动画 this.ant.runAction(Tiny.ScaleTo(500, Tiny.scale(1))); } ``` 看看蚂蚁跳跃的效果: ![](https://gw.alipayobjects.com/zos/rmsportal/RQRdFTMeBpHWJJKMoIwq.gif) ### 5. 再来一个小盒子 用上面同样的方法,在原来位置向右 deltaX 的位置再绘制一个小盒子。但是这次我们想加一个从上面掉下来的动画,直接使用 `Tiny.MoveBy` 即可,为了使落地动画更加生动,可以使用 `action.setEasing` 增加一个回弹效果。 ```js dropBox() { var box = Tiny.Sprite.fromImage(Tiny.resources.boxPng); box.setPivot(box.width / 2, box.height); box.name = 'box'; const deltaY = 100; // 从 deltaY 开始掉落 const x = this.currentBox.x + this.deltaX; const y = this.currentBox.y - deltaY; box.setPosition(x, y); // 设置初始位置 // 下落动画 const action = Tiny.MoveBy(500, { y: deltaY, }); action.setEasing(Tiny.TWEEN.Easing.Bounce.Out); // 盒子落地有个弹性效果 box.runAction(action); this.addChildAt(box, 0); return box; } ``` ### 6. 屏幕滚动 蚂蚁跳到了下一个盒子,因此整个屏幕也要进行滚动,使得下一个盒子成为屏幕中心。要实现这个效果,只要为整个 container 加个动画即可。下面代码中的 this 指的就是 container。 ```js sceneMove() { this.runAction(Tiny.MoveBy(500, { x: -this.deltaX, })); } ``` ### 7. 通过用户行为来控制上面的动作 ```js canvas.addEventListener(supportTouch ? 'touchstart' : 'mousedown', () => { // 蚂蚁被压效果 this.compress(); }); canvas.addEventListener(supportTouch ? 'touchend' : 'mouseup', () => { // 蚂蚁恢复被压效果 this.compressRestore(); // 跳的过程中就不能再跳了 if (this.isJumping) return; this.isJumping = true; this.jump(this.deltaX, () => { // 跳完后 this.isJumping = false; this.currentBox = this.targetBox; // 移动屏幕 this.sceneMove(); // 再来一个盒子 this.targetBox = this.dropBox(); }); }); ``` 整体效果: ![](https://gw.alipayobjects.com/zos/rmsportal/sbPxdVwfiIevxnpdZunm.gif) ### 8. 总结 这样就实现了一个最简单的「跳一跳」的原型,当然动画还有些粗糙,后面我们慢慢来优化,源码可见: https://github.com/stonelee/jump/tree/feat-1
C#
UTF-8
2,535
2.515625
3
[]
no_license
using System.Data; namespace ECM7.Migrator.Framework.Tools { public static class TransformationProviderHiLoExtensions { /// <summary> /// Название служебной таблицы HiLo /// </summary> public const string HI_LO_TABLE_NAME = "hibernate_unique_key"; public const string KEY_FIELD_NAME = "entity_key"; public const string VALUE_FIELD_NAME = "next_hi_value"; /// <summary> /// Добавление служебной таблицы HiLo /// </summary> /// <param name="database">Провайдер БД</param> public static void CreateHiLoTable(this ITransformationProvider database) { database.AddTable(HI_LO_TABLE_NAME, new Column(KEY_FIELD_NAME, DbType.AnsiString.WithSize(200), ColumnProperty.NotNull | ColumnProperty.PrimaryKey), new Column(VALUE_FIELD_NAME, DbType.Int64, ColumnProperty.NotNull, 1) ); } /// <summary> /// Удаление служебной таблицы HiLo /// </summary> /// <param name="database">Провайдер БД</param> public static void RemoveHiLoTable(this ITransformationProvider database) { database.RemoveTable(HI_LO_TABLE_NAME); } /// <summary> /// Добавление записи в служебную таблицу HiLo /// </summary> /// <param name="database">Провайдер БД</param> /// <param name="table">Название добавляемой таблицы</param> public static void AddHiLoTableRecord(this ITransformationProvider database, string table) { AddHiLoTableRecord(database, table, 0); } /// <summary> /// Добавление записи в служебную таблицу HiLo /// </summary> /// <param name="database">Провайдер БД</param> /// <param name="table">Название добавляемой таблицы</param> /// <param name="initialHiValue">Текущее старшее значение идентификатора</param> public static void AddHiLoTableRecord(this ITransformationProvider database, string table, int initialHiValue) { Require.IsNotNullOrEmpty(table, "Не задано название таблицы для генерациии ID алгоритмом HiLo"); Require.That(database.TableExists(HI_LO_TABLE_NAME), "Отсутствует служебная таблица HiLo"); database.Insert(HI_LO_TABLE_NAME, new[] { KEY_FIELD_NAME, VALUE_FIELD_NAME }, new[] { table, initialHiValue.ToString() }); } } }
Ruby
UTF-8
722
2.546875
3
[]
no_license
require 'rails_helper' describe Astronaut, type: :model do describe 'Validations' do it { should validate_presence_of :name } it { should validate_presence_of :age } it { should validate_presence_of :job } end describe 'Relationships' do it { should have_many :astronaut_missions} it { should have_many :missions} end describe "class methods" do it ".get_average_age" do astronaut_1 = Astronaut.create(name: "Scott", age: 30, job: "astronaut") astronaut_2 = Astronaut.create(name: "Tim", age: 29, job: "super astronaut") astronaut_3 = Astronaut.create(name: "Oldie", age: 100, job: "astronaut") expect(Astronaut.get_average_age).to eq(53) end end end
Java
UTF-8
1,182
2.28125
2
[]
no_license
package com.flycode.jasonfit.adapter.viewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.flycode.jasonfit.R; import org.zakariya.stickyheaders.SectioningAdapter; import butterknife.BindView; import butterknife.ButterKnife; /** * Created - Schumakher on 3/9/17. */ public class WorkoutHeaderViewHolder extends SectioningAdapter.HeaderViewHolder { @BindView(R.id.workout_header_title) TextView titleTextView; public static WorkoutHeaderViewHolder initialize (ViewGroup parent) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_workout, parent, false); return new WorkoutHeaderViewHolder(view); } private WorkoutHeaderViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public void setupHeader(int sectionIndex) { if (sectionIndex == 0) { titleTextView.setText("Reccomended for today"); } else if (sectionIndex == 1) { titleTextView.setText("All other workouts"); } } }
JavaScript
UTF-8
2,087
3.796875
4
[]
no_license
function changeVocals (str) { var holder = ''; for(var i = 0; i < str.length; i++){ if(str[i] === 'a'){ holder += 'b'; } else if(str[i] === 'i'){ holder += 'j'; } else if(str[i] === 'u'){ holder += 'v'; } else if(str[i] === 'e'){ holder += 'f'; } else if(str[i] === 'o'){ holder += 'p'; } else if(str[i] === 'A'){ holder += 'B'; } else if(str[i] === 'I'){ holder += 'J'; }else if(str[i] === 'U'){ holder += 'V'; }else if(str[i] === 'E'){ holder += 'F'; }else if(str[i] === 'O'){ holder += 'P'; }else{ holder += str[i]; } } return holder; } function reverseWord (str) { var terbalik = ''; for(var j = str.length - 1; j >= 0 ; j--){ terbalik += str[j]; } return terbalik; } function setLowerUpperCase (str) { var ukuranHuruf = ''; for(var k = 0; k < str.length; k++){ if(str[k] !== str[k].toLowerCase()){ ukuranHuruf += str[k].toLowerCase(); } else{ ukuranHuruf += str[k].toUpperCase(); } } return ukuranHuruf; } function removeSpaces (str) { var removedSpaces = ''; for(var l = 0; l < str.length; l++){ if(str[l] !== ' '){ removedSpaces += str[l]; } } return removedSpaces; } function passwordGenerator (name) { if(name.length < 5){ return 'Minimal karakter yang diinputkan adalah 5 karakter'; } var ubah = changeVocals(name); var balik = reverseWord(ubah); var huruf = setLowerUpperCase(balik); var spasi = removeSpaces(huruf); return spasi; } console.log(passwordGenerator('Sergei Dragunov')); // 'VPNVGBRdJFGRFs' console.log(passwordGenerator('Dimitri Wahyudiputra')); // 'BRTVPJDVYHBwJRTJMJd' console.log(passwordGenerator('Alexei')); // 'JFXFLb' console.log(passwordGenerator('Alex')); // 'Minimal karakter yang diinputkan adalah 5 karakter'
Java
UTF-8
2,086
2.140625
2
[]
no_license
package com.dmg.fish.business.handler.room; import java.io.UnsupportedEncodingException; import com.dmg.fish.business.config.dic.FishRoomDic; import com.dmg.fish.business.logic.FishMsgMgr; import com.dmg.fish.business.model.room.Seat; import com.dmg.gameconfigserverapi.fish.dto.FishRoomDTO; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.dmg.common.starter.rocketmq.annotation.RocketMQMessageListener; import com.dmg.common.starter.rocketmq.core.listener.RocketMQListener; import com.dmg.fish.business.logic.FishMgr; import lombok.extern.slf4j.Slf4j; @Slf4j @Component @RocketMQMessageListener(consumerGroup = "MAINTAIN_CONSUMER", topic = "MAINTAIN", tags = "MAINTAIN", messageModel = MessageModel.BROADCASTING) public class MaintainListener implements RocketMQListener { @Value("${game-id}") private String gameId; @Autowired private FishMgr fishMgr; @Autowired private FishMsgMgr fishMsgMgr; @Override public void onMessage(MessageExt msg) { String data = null; try { data = new String(msg.getBody(), "utf-8"); } catch (UnsupportedEncodingException e) { log.error("消息解析异常{}", e); return; } if (StringUtils.isBlank(data)) { log.info("接收到的消息为空,不做任何处理"); return; } log.warn("==>收到停服消息"); if (StringUtils.equals(this.gameId, data)) { fishMgr.stopService(); for (Seat seat : this.fishMgr.getPlayerSeats().values()) { if (seat.robot) { continue; } long playerId = seat.playerId; this.fishMsgMgr.sendStopServerExitMsg(playerId); } } } }
Java
UTF-8
1,062
2.34375
2
[]
no_license
package fr.soe.a3s.dao; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class EncryptionProvider { private static final byte[] secreteKey = new byte[] { 0x01, 0x72, 0x43, 0x3E, 0x1C, 0x7A, 0x55, 0, 0x01, 0x72, 0x43, 0x3E, 0x1C, 0x7A, 0x55, 0x4F }; public static Cipher getEncryptionCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Cipher cipher = Cipher.getInstance("AES"); SecretKey key = new SecretKeySpec(secreteKey, "AES"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher; } public static Cipher getDecryptionCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Cipher cipher = Cipher.getInstance("AES"); SecretKey key = new SecretKeySpec(secreteKey, "AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher; } }
TypeScript
UTF-8
1,324
2.875
3
[]
no_license
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from "@angular/forms"; @Component({ selector: 'fb-fibonacci', templateUrl: './fibonacci.component.html', styleUrls: ['./fibonacci.component.css'] }) export class FibonacciComponent implements OnInit { answer:string=''; inputNumber:number=0; constructor() { } ngOnInit(): void { } onKeyPress(event: any) { const regexpNumber = /[0-9\+\]/; let inputCharacter = String.fromCharCode(event.charCode); if (event.keyCode != 8 && !regexpNumber.test(inputCharacter)) { event.preventDefault(); } } getFromSequence() { let fibonacciIndex = this.getfibonacciIndex(this.inputNumber); this.answer = `Index is : ` +fibonacciIndex.toString(); } getfibonacciIndex(value: number): number { if (value <= 1) return value; let firstNumber= 0, secondNumber = 1, nextNumber = 1; let result = 1; while (nextNumber < value) { nextNumber = firstNumber + secondNumber; // res keeps track of number of generated fibonacci number result++; firstNumber = secondNumber; secondNumber = nextNumber; } return result; } }
Java
UTF-8
1,268
2.40625
2
[]
no_license
package com.sam_chordas.android.stockhawk.service; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by PriyamSaikia on 25-05-2016. */ public class Parser { public Parser() { } public ArrayList<HistoryStockBean> getHistoryData(String response) { ArrayList<HistoryStockBean> arrayList = null; try { arrayList = new ArrayList<HistoryStockBean>(); JSONObject mainObj = new JSONObject(response); JSONObject queryObj = mainObj.getJSONObject("query"); JSONObject resultsObj = queryObj.getJSONObject("results"); JSONArray quoteArray = resultsObj.getJSONArray("quote"); for (int i = 0; i < quoteArray.length(); i++) { JSONObject itemObj = quoteArray.getJSONObject(i); HistoryStockBean historyStockBean = new HistoryStockBean(); historyStockBean.setDate(itemObj.getString("Date")); historyStockBean.setAdjusted_close(itemObj.getString("Adj_Close")); arrayList.add(historyStockBean); } } catch (JSONException e) { e.printStackTrace(); } return arrayList; } }
Python
UTF-8
1,153
2.96875
3
[]
no_license
import keras from keras.datasets import fashion_mnist from keras.models import load_model from keras import backend as K # Data dimensions. Images are 28x28 pixels, and the number of classes is 10. image_rows, image_columns = 28, 28 number_of_classes = 10 # Load test dataset from Fashion MNIST and prepare it. _, (x_test, y_test) = fashion_mnist.load_data() y_test = keras.utils.to_categorical(y_test, number_of_classes) if K.image_data_format() == 'channel_first': x_test = x_test.reshape(x_test.shape[0], 1, image_rows, image_columns) input_shape = (1, image_rows, image_columns) else: x_test = x_test.reshape(x_test.shape[0], image_rows, image_columns, 1) input_shape = (image_rows, image_columns, 1) # Normalize data ranges. x_test = x_test.astype('float32') / 255 # Load saved model and evaluate it using the test dataset. try: model = load_model('model.h5') print('Evaluating model on test dataset...') score = model.evaluate(x_test, y_test, verbose = 0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) except OSError: print('Cannot find model.h5! Re-run training to generate it.')
Markdown
UTF-8
4,022
2.671875
3
[]
no_license
--- description: "Steps to Prepare Quick Smoked salmon sandwich" title: "Steps to Prepare Quick Smoked salmon sandwich" slug: 1725-steps-to-prepare-quick-smoked-salmon-sandwich date: 2020-07-27T05:32:40.875Z image: https://img-global.cpcdn.com/recipes/d6e1790785ca6333/751x532cq70/smoked-salmon-sandwich-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/d6e1790785ca6333/751x532cq70/smoked-salmon-sandwich-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/d6e1790785ca6333/751x532cq70/smoked-salmon-sandwich-recipe-main-photo.jpg author: Gene Dunn ratingvalue: 4.6 reviewcount: 7691 recipeingredient: - " Soft cheese" - " Wild rocket" - " Chopped red onion" - " Olives" - "slices Smoked salmon" - " Bread" recipeinstructions: - "Toast 2 slices of bread" - "Spread cheese on both slices" - "Put layer of wild rocket, onions, olives and finally salmon slices." - "Add more rocket then cover with the other toast slice." categories: - Recipe tags: - smoked - salmon - sandwich katakunci: smoked salmon sandwich nutrition: 270 calories recipecuisine: American preptime: "PT13M" cooktime: "PT40M" recipeyield: "4" recipecategory: Dessert --- ![Smoked salmon sandwich](https://img-global.cpcdn.com/recipes/d6e1790785ca6333/751x532cq70/smoked-salmon-sandwich-recipe-main-photo.jpg) Hello everybody, I hope you are having an incredible day today. Today, we're going to make a special dish, smoked salmon sandwich. It is one of my favorites food recipes. This time, I will make it a little bit unique. This will be really delicious. Smoked salmon sandwich is one of the most favored of current trending meals in the world. It is simple, it's fast, it tastes yummy. It's appreciated by millions daily. They're nice and they look wonderful. Smoked salmon sandwich is something that I have loved my whole life. Our Delicious Sandwich Recipe Has A Bit Of Everything. A Freezer Full of Omaha Steaks Means Peace of Mind for Your Family. For the herb butter, combine all the butter ingredients in a mixer fitted with a paddle attachment. Beat until mixed, but do not whip. To begin with this recipe, we must first prepare a few components. You can have smoked salmon sandwich using 6 ingredients and 4 steps. Here is how you can achieve it. <!--inarticleads1--> ##### The ingredients needed to make Smoked salmon sandwich: 1. Take Soft cheese 1. Take Wild rocket 1. Get Chopped red onion 1. Get Olives 1. Take slices Smoked salmon 1. Get Bread This version of the classic salmon tea sandwich uses a cream cheese with dill along with some red onion to brighten up the sandwich. Part of the fun of tea sandwiches is the fancy way they are presented. Smoked salmon sandwich makes for the perfect epic lunch sandwich. Packed full of veggies such as arugula, alfalfa, avocado and cucumber this one of the best sandwiches of all time. <!--inarticleads2--> ##### Steps to make Smoked salmon sandwich: 1. Toast 2 slices of bread 1. Spread cheese on both slices 1. Put layer of wild rocket, onions, olives and finally salmon slices. 1. Add more rocket then cover with the other toast slice. Smoked salmon sandwich makes for the perfect epic lunch sandwich. Packed full of veggies such as arugula, alfalfa, avocado and cucumber this one of the best sandwiches of all time. Mix freshly roasted salmon with smoked salmon for a delicious filling that&amp;rsquo;s not overpowering. Get the recipe for Smoked Salmon Salad Sandwich. Smoked Salmon Sandwiches with Dill Cream Cheese are an elegant gourmet choice for summer picnics and outings or when it&#39;s just too hot to turn on the stove to cook dinner. So that's going to wrap it up for this exceptional food smoked salmon sandwich recipe. Thank you very much for your time. I am confident that you can make this at home. There's gonna be more interesting food at home recipes coming up. Remember to bookmark this page on your browser, and share it to your loved ones, friends and colleague. Thanks again for reading. Go on get cooking!
Java
UTF-8
584
2.03125
2
[]
no_license
package interview_questions; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Sample5 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.google.com/"); WebElement name= driver.findElement(By.name("q")); name.sendKeys("Oracle"); driver.findElements(By.xpath("")); } }
Java
UTF-8
3,453
2.21875
2
[]
no_license
package com.example.rex.homework3_2; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.AnimationUtils; import android.view.animation.RotateAnimation; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.TextView; public class MainActivity extends ActionBarActivity { private TextView txtWord; private Button startBtn, stopBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); } public void findViews() { txtWord = (TextView) findViewById(R.id.txtWord); startBtn = (Button) findViewById(R.id.startBtn); stopBtn = (Button) findViewById(R.id.stopBtn); getAnimationSet(); } private AnimationSet getAnimationSet(){ TranslateAnimation translateAnimation = getTranslateAnimation(); RotateAnimation rotateAnimation=getRotateAnimation(); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(translateAnimation); animationSet.addAnimation(rotateAnimation); return animationSet; } public void onStartClick(View view) { txtWord.startAnimation(getTranslateAnimation()); txtWord.startAnimation(getRotateAnimation()); Animation anim= AnimationUtils.loadAnimation(MainActivity.this,R.anim.anim); txtWord.startAnimation(anim); } public void onStopClick(View view){ txtWord.clearAnimation(); } private TranslateAnimation getTranslateAnimation() { View parentView = (View) txtWord.getParent(); // 球移動的距離 float distance = parentView.getWidth() - 100; TranslateAnimation translateAnimation = new TranslateAnimation(100,distance,100,1000); translateAnimation.setDuration(1000); translateAnimation.setRepeatMode(Animation.RESTART); translateAnimation.setRepeatCount(Animation.INFINITE); return translateAnimation; } private RotateAnimation getRotateAnimation() { RotateAnimation rotateAnimation = new RotateAnimation( 0,360, Animation.RELATIVE_TO_SELF,1f, Animation.RELATIVE_TO_SELF,1f); rotateAnimation.setDuration(300); rotateAnimation.setRepeatMode(Animation.RESTART); rotateAnimation.setRepeatCount(Animation.INFINITE); return rotateAnimation; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
PHP
UTF-8
2,872
2.96875
3
[]
no_license
<?php declare(strict_types=1); namespace app\services\Payment; use app\exceptions\ApiException; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; /** * Class JsonApiMtsPaymentSystem * @package app\services\Payment */ class JsonApiMtsPaymentSystem implements PaymentInterface { /** * @var Client */ private $client; /** * JsonApiMtsPaymentSystem constructor. * @param array $config */ public function __construct(array $config) { $this->client = new Client($config); // У меня Yii тут нет, я сделал просто. В твоем случае просто public проперти и все } /** * @param PaymentRequestDto $paymentRequestDto * @return PaymentResponseDto * @throws ApiException */ public function bill(PaymentRequestDto $paymentRequestDto): PaymentResponseDto { // DTO позволяет тебе называть атрибуты так, как принято в проекте. // Именно здесь происходит маппинг названий внешнего сервиса и внутренних. Это методология DDD, детка $response = $this->sendRequest([ 'msisdn' => $paymentRequestDto->clientId, 'money' => $paymentRequestDto->cost, 'description' => $paymentRequestDto->category, 'olololoIAmMTS' => $paymentRequestDto->description, ]); // Если скажешь Guzzle, что ждешь json на выходе, то $response->getBody()->getContents() это будет уже результат json decode return new PaymentResponseDto($response->getStatusCode(), $response->getBody()->getContents()); } /** * @param array $data * @return ResponseInterface * @throws ApiException */ private function sendRequest(array $data): ResponseInterface { try { // @todo Ну ясен красен, урлы в конфиге, хост в клиент прописывается в конструкторе. Это так, пример return $this->client->request('POST', 'https://api.mts.ru/bill', [ 'auth' => ['user', 'pass'], 'body' => $data, ]); } catch (GuzzleException $exception) { // Тут оборачиваешь GuzzleException в ApiException, чтобы снаружи потребитель ничего не знал про Guzzle // Кто знает, может ты его на другую либу заменишь или на Curl или завтра скажут, что SOap используйте throw new ApiException($exception->getMessage()); } } }
C
UTF-8
4,544
3
3
[]
no_license
/* * COPYRIGHT NOTICE * Copyright (C) 2015, Jhuster, All Rights Reserved * Author: Jhuster(lujun.hust@gmail.com) * * https://github.com/Jhuster/TLV * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. */ #include <stdio.h> #include <string.h> #include "tlv.h" #define TLV_TYPE_OBJECTS 0xff #define TLV_TYPE_USERNAME 0x01 #define TLV_TYPE_PASSWORD 0x02 #define TLV_TYPE_SEX 0x03 #define TLV_TYPE_AGE 0x04 #define TLV_TYPE_SNO 0x05 #define TLV_TYPE_SCORE 0x06 #define LOG(format,...) printf(format,##__VA_ARGS__) typedef struct _file_header_t { char startcode[4]; int content_length; } file_header_t; typedef struct _student_t { char username[20]; char sex; int age; long long sno; float score; } student_t; static int test_write_tlv() { const char *filepath = "student.txt"; FILE *wp = fopen(filepath,"wb"); if(wp == NULL) { LOG("failed to open %s\n",filepath); return -1; } student_t student; strcpy(student.username,"jhuster"); student.sex = 1; student.age = 28; student.sno = 1234567890; student.score = 98.55; tlv_t *object = tlv_create(); tlv_put_char(object,TLV_TYPE_SEX,&student.sex); tlv_put_string(object,TLV_TYPE_USERNAME,student.username); tlv_put_int(object,TLV_TYPE_AGE,&student.age); tlv_put_longlong(object,TLV_TYPE_SNO,&student.sno); tlv_put_float(object,TLV_TYPE_SCORE,&student.score); if(tlv_serialize(object) != 0) { LOG("failed to serialize object !\n"); fclose(wp); return -1; } tlv_t *objects = tlv_create(); tlv_put_object(objects,TLV_TYPE_OBJECTS,object); if(tlv_serialize(objects) != 0) { LOG("failed to serialize objects !\n"); fclose(wp); return -1; } file_header_t header; header.startcode[0] = 0x0A; header.startcode[1] = 0x0B; header.startcode[2] = 0x0C; header.startcode[3] = 0x0D; header.content_length = tlv_get_size(objects); if(fwrite(&header,sizeof(header),1,wp) != 1) { LOG("failed to write file_header_t !\n"); fclose(wp); return -1; } if(fwrite(tlv_get_buffer(objects),tlv_get_size(objects),1,wp) != 1) { LOG("failed to write objects !\n"); fclose(wp); return -1; } fclose(wp); tlv_destroy(object); tlv_destroy(objects); LOG("Write student success !\n"); return 0; } static int test_read_tlv() { const char *filepath = "student.txt"; FILE *rp = fopen(filepath,"rb"); if(rp == NULL) { LOG("failed to open %s\n",filepath); return -1; } file_header_t header; if(fread(&header,sizeof(header),1,rp) != 1) { LOG("failed to read file_header_t !\n"); fclose(rp); return -1; } if(header.startcode[0] != 0x0A || header.startcode[1] != 0x0B || header.startcode[2] != 0x0C || header.startcode[3] != 0x0D) { LOG("invalid file_header_t !\n"); fclose(rp); return -1; } unsigned char *buffer = (unsigned char*)malloc(header.content_length*sizeof(char)); if(fread(buffer,header.content_length,1,rp) != 1) { LOG("failed to read student !\n"); fclose(rp); return -1; } tlv_t* objects = tlv_parse(buffer,header.content_length); if(objects == NULL) { LOG("failed to do parse !\n"); fclose(rp); return -1; } free(buffer); fclose(rp); tlv_t* object = NULL; if(tlv_get_object(objects,TLV_TYPE_OBJECTS,&object) != 0) { LOG("failed get_object !\n"); return -1; } student_t student; int usernameLen = 20; tlv_get_char(object,TLV_TYPE_SEX,&student.sex); tlv_get_string(object,TLV_TYPE_USERNAME,student.username,&usernameLen); tlv_get_int(object,TLV_TYPE_AGE,&student.age); tlv_get_longlong(object,TLV_TYPE_SNO,&student.sno); tlv_get_float(object,TLV_TYPE_SCORE,&student.score); LOG("Read student success, sex = %d, username = %s, age = %d, sno = %lld, score = %0.2f \n", student.sex,student.username,student.age,student.sno,student.score); tlv_destroy(object); tlv_destroy(objects); return 0; } int main(int argc, char const *argv[]) { if(test_write_tlv() == 0 && test_read_tlv() == 0) { LOG("All tests passed !\n"); } return 0; }
C#
UTF-8
2,625
3.28125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _106_Classwork8; namespace _106_Quiz7 { public static class ShapeType //靜態類別, 不能被實體化 (new) { public enum Geo //使用 enum 增加程式的可讀性 { UNKNOWN = -1, BALL = 0, CUBE, CYLINDER, PYRAMID }; public enum Material //使用 enum 增加程式的可讀性 { UNKNOWN = -1, Al = 0, Fe, Pb }; } abstract class Shape3D //抽象類別, 不能被實體化 (new) { protected static int _amount; //被繼承的欄位 (資料成員)需宣告為 protected //protected double _density; //被繼承的欄位 (資料成員)需宣告為 protected, _material 與 _density 有相關性 故取消 protected ShapeType.Geo _geoType; protected ShapeType.Material _materialType; //_material 與 _density 有相關性 public Shape3D() { _materialType = ShapeType.Material.UNKNOWN; _amount++; } public Shape3D(ShapeType.Material mType) { _materialType = mType; _amount++; } public static int Amount //要給其他類別取用, 故宣告為 public { get { return _amount; } } public ShapeType.Material MaterialType //要給其他類別取用, 故宣告為 public { get { return _materialType; } } public ShapeType.Geo GeoType //要給其他類別取用, 故宣告為 public { get { return _geoType; } } public abstract double Volume(); //抽象函式, 子類別需進行 override public double Weight() //開放給其他類別使用, 故宣告成 public { return Density() * Volume(); } public double Density() //根據 Material Type 計算 density { return MaterialTable.Density(_materialType); } public abstract string ShapeProperty(); //抽象函式, 子類別需進行 override protected string Property() //只讓子類別呼叫, 故宣告 protected, 抽出子類別重複的程式碼進行重構 { string str=""; str += string.Format("{0,8:F2}", Density()); str += '\t'; str += string.Format("{0,8:F2}", Volume()); str += '\t'; str += string.Format("{0,8:F2}", Weight()); return str; } } }
JavaScript
UTF-8
323
2.90625
3
[]
no_license
module.exports.reversePlusOne = function(array) { var resArray = array.reverse(); resArray.unshift(1); return resArray; }; module.exports.plusesEverywhere = function(array) { var resArray = array.join("+"); return resArray; }; module.exports.arrayQuantityPlusOne = function(array) { return array.length + 1; }
Python
UTF-8
657
3.8125
4
[]
no_license
# 기본적으로 N제곱의 효율성 but 거의 정렬되있는 상태의 경우 최선은 N의 효율성을 가진다. array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8] for i in range(1, len(array)): for j in range(i, 0, -1): # 현재위치부터 첫번째 위치까지 돌면서 넣을 위치 찾아서 정렬 if array[j] < array[j-1]: # 만약 다음항이 전항보다 크다면 print(array[j], "<", array[j-1]) print("스왑!", array[j], array[j-1], array[j-1], array[j]) array[j], array[j-1] = array[j-1], array[j] else: break print("array for문 끝", array) print(array)
Java
UTF-8
2,642
2.453125
2
[]
no_license
package com.kuanguang.huiyun.http; import android.content.Context; import android.os.Handler; import android.os.Message; import okhttp3.Call; import okhttp3.Response; /** * ================================================ * 作 者:廖子尧 * 版 本:1.0 * 创建日期:2016/1/14 * 描 述:默认将返回的数据解析成需要的Bean,可以是 BaseBean,String,List,Map * 修订历史: * - * - * - * - * -我的注释都已经写的不能再多了,不要再来问我怎么获取数据对象,怎么解析集合数据了,你只要会 gson ,就会解析 * - * -如果你对这里的代码原理不清楚,可以看这里的详细原理说明:https://github.com/jeasonlzy/okhttp-OkGo/blob/master/README_JSONCALLBACK.md * -如果你对这里的代码原理不清楚,可以看这里的详细原理说明:https://github.com/jeasonlzy/okhttp-OkGo/blob/master/README_JSONCALLBACK.md * -如果你对这里的代码原理不清楚,可以看这里的详细原理说明:https://github.com/jeasonlzy/okhttp-OkGo/blob/master/README_JSONCALLBACK.md * - * - * - * ================================================ */ public class OkgoCallback extends JsonCallback { private Context mContext; private ResponseCallback callback; Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case -1://失败 try { callback.onResponseFailure(msg.obj.toString()); } catch (Exception e) { e.printStackTrace(); } break; case 0://成功 try { callback.onResponseSucess(msg.obj.toString()); } catch (Exception e) { e.printStackTrace(); } break; } } }; public OkgoCallback(Context mContext, ResponseCallback callback) { this.mContext = mContext; this.callback = callback; } @Override public void onSuccess(String s, Call call, Response response) { Message msg = Message.obtain(); msg.what = 0; msg.obj = s; mHandler.sendMessage(msg); } @Override public void onError(Call call, Response response, Exception e) { // super.onError(call, response, e); Message msg = Message.obtain(); msg.what = -1; msg.obj = e.getMessage(); mHandler.sendMessage(msg); } }
Markdown
UTF-8
3,280
2.9375
3
[]
no_license
--- title: Crypto - Steroid Stream description: 2021 | PBCTF | Crypto --- ## 题目 I found a weird stream cipher scheme. Can you break this? [CTFtime.org / pbctf 2021 / Steroid Stream](https://ctftime.org/task/17579) ## 解题思路 - [Alkaloid Stream](alkaloid_stream.md) 进阶版,除了 `fake` 数组的产生方式有所差异,其他部分都是一样的 ```py fake = [0] * ln for i in range(ln - ln // 3): arr = list(range(i + 1, ln)) random.shuffle(arr) for j in arr[:ln // 3]: # 在 [i + 1, ln) 中随机选取 ln // 3 个 key 异或 fake[i] ^= key[j] ``` - 对于 `fake` 数组中下标为 $[ln - ln // 3, ln)$ 的元素值均为 $0$ - 异或等同于 $GF(2)$ 中的加法,可以把 `fake` 数组中的值看作是已知 `keys` 的线性组合,而 `keys` 数组中的值相互间线性无关,从而可以区分 `fake` 和 `keys` - 使用已知 `keys` 构建一个以 `keys` 为行的 $GF(2)$ 矩阵,假设 `keys` 的数量为 $k$,那么有 $k$ 行相互独立,矩阵的秩(rank)为 $k$。添加值 $v$ 到 $k + 1$ 行,如果 $v$ 是 `keys` 的线性组合,那么矩阵的秩仍为 $k$,否则是 $k + 1$ ```py def gf2_rank(rows): """ Find rank of a matrix over GF2. The rows of the matrix are given as nonnegative integers, thought of as bit-strings. This function modifies the input list. Use gf2_rank(rows.copy()) instead of gf2_rank(rows) to avoid modifying rows. """ rank = 0 while rows: pivot_row = rows.pop() if pivot_row: rank += 1 lsb = pivot_row & -pivot_row for index, row in enumerate(rows): if row & lsb: rows[index] = row ^ pivot_row return rank def is_linear_combination(keys, test): rows = keys.copy() rows.append(test) return len(rows) > gf2_rank(rows) keys, remain = [], [] for p in public: if 0 in p: keys.append(p[0] + p[1]) else: remain.append(p) while remain: cur_remain = [] for p in remain: if is_linear_combination(keys, p[0]): keys.append(p[1]) elif is_linear_combination(keys, p[1]): keys.append(p[0]) else: cur_remain.append(p) remain = cur_remain keystream = recover_keystream(keys, public) print(bits_to_bytes(xor(enc, keystream))) # b'pbctf{I_hope_you_enjoyed_this_challenge_now_how_about_playing_Metroid_Dread?}' ``` ## 参考资料 - [另一种世界观——有限域](https://www.bilibili.com/read/cv2922069) - [GF(2) - Wikipedia](https://en.wikipedia.org/wiki/GF(2)) - [Linear combination - Wikipedia](https://en.wikipedia.org/wiki/Linear_combination) - [Rank (linear algebra) - Wikipedia](https://en.wikipedia.org/wiki/Rank_(linear_algebra)) - [Fast computation of matrix rank over GF(2)](https://stackoverflow.com/questions/56856378/fast-computation-of-matrix-rank-over-gf2) ### 拓展阅读 <!-- 如果能懂的话... --> - [[Tutorial] Matroid intersection in simple words - Codeforces](https://codeforces.com/blog/entry/69287)
Go
UTF-8
244
3.34375
3
[ "MIT" ]
permissive
package sorting func InsertionSort(s []int) []int { c := make([]int, len(s)) copy(c, s) l := len(s) for i := 1; i < l; i++ { j := i temp := c[i] for j > 0 && (c[j-1] > temp) { c[j] = c[j-1] j-- } c[j] = temp } return c }
PHP
UTF-8
4,273
2.75
3
[]
no_license
<?php declare(strict_types=1); namespace OCA\GPodderSync\Core\EpisodeAction; use DateTimeZone; use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use OCA\GPodderSync\Db\EpisodeAction\EpisodeActionEntity; use OCA\GPodderSync\Db\EpisodeAction\EpisodeActionRepository; use OCA\GPodderSync\Db\EpisodeAction\EpisodeActionWriter; use OCP\DB\Exception; class EpisodeActionSaver { private EpisodeActionRepository $episodeActionRepository; private EpisodeActionWriter $episodeActionWriter; private EpisodeActionReader $episodeActionReader; const DATETIME_FORMAT = 'Y-m-d\TH:i:s'; public function __construct( EpisodeActionRepository $episodeActionRepository, EpisodeActionWriter $episodeActionWriter, EpisodeActionReader $episodeActionReader ) { $this->episodeActionRepository = $episodeActionRepository; $this->episodeActionWriter = $episodeActionWriter; $this->episodeActionReader = $episodeActionReader; } /** * @param array $episodeActionsArray * * @return EpisodeActionEntity[] */ public function saveEpisodeActions($episodeActionsArray, string $userId): array { $episodeActions = $this->episodeActionReader->fromArray($episodeActionsArray); $episodeActionEntities = []; foreach ($episodeActions as $episodeAction) { $episodeActionEntity = $this->hydrateEpisodeActionEntity($episodeAction, $userId); try { $episodeActionEntities[] = $this->episodeActionWriter->save($episodeActionEntity); } catch (UniqueConstraintViolationException $uniqueConstraintViolationException) { $episodeActionEntities[] = $this->updateEpisodeAction($episodeActionEntity, $userId); } catch (Exception $exception) { if ($exception->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { $episodeActionEntities[] = $this->updateEpisodeAction($episodeActionEntity, $userId); } } } return $episodeActionEntities; } private function convertTimestampToUnixEpoch(string $timestamp): string { return \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp) ->format("U"); } private function updateEpisodeAction( EpisodeActionEntity $episodeActionEntity, string $userId ): EpisodeActionEntity { $identifier = $episodeActionEntity->getGuid() ?? $episodeActionEntity->getEpisode(); $episodeActionToUpdate = $this->episodeActionRepository->findByEpisodeIdentifier( $identifier, $userId ); if ($episodeActionToUpdate === null && $episodeActionEntity->getGuid() !== null) { $episodeActionToUpdate = $this->getOldEpisodeActionByEpisodeUrl($episodeActionEntity->getEpisode(), $userId); } $episodeActionEntity->setId($episodeActionToUpdate->getId()); $this->ensureGuidDoesNotGetNulledWithOldData($episodeActionToUpdate, $episodeActionEntity); return $this->episodeActionWriter->update($episodeActionEntity); } private function getOldEpisodeActionByEpisodeUrl(string $episodeUrl, string $userId): ?EpisodeAction { return $this->episodeActionRepository->findByEpisodeIdentifier( $episodeUrl, $userId ); } private function ensureGuidDoesNotGetNulledWithOldData(EpisodeAction $episodeActionToUpdate, EpisodeActionEntity $episodeActionEntity): void { $existingGuid = $episodeActionToUpdate->getGuid(); if ($existingGuid !== null && $episodeActionEntity->getGuid() == null) { $episodeActionEntity->setGuid($existingGuid); } } private function hydrateEpisodeActionEntity(EpisodeAction $episodeAction, string $userId): EpisodeActionEntity { $episodeActionEntity = new EpisodeActionEntity(); $episodeActionEntity->setPodcast($episodeAction->getPodcast()); $episodeActionEntity->setEpisode($episodeAction->getEpisode()); $episodeActionEntity->setGuid($episodeAction->getGuid()); $episodeActionEntity->setAction($episodeAction->getAction()); $episodeActionEntity->setPosition($episodeAction->getPosition()); $episodeActionEntity->setStarted($episodeAction->getStarted()); $episodeActionEntity->setTotal($episodeAction->getTotal()); $episodeActionEntity->setTimestampEpoch($this->convertTimestampToUnixEpoch($episodeAction->getTimestamp())); $episodeActionEntity->setUserId($userId); return $episodeActionEntity; } }
C++
UTF-8
1,200
2.65625
3
[ "Zlib" ]
permissive
// Project: libv.math, File: src/libv/noise/white.cpp // hpp #include <libv/noise/white.hpp> // libv #include <libv/utility/random/uniform_distribution.hpp> // std #include <random> namespace libv { // ------------------------------------------------------------------------------------------------- //std::vector<double> noise_white_2D(uint64_t seed, uint32_t X, uint32_t Y) { // std::mt19937_64 rng(seed); // auto dist = libv::make_uniform_distribution_inclusive(0.0, 1.0); // // std::vector<double> result; // result.resize(X * Y); // // for (uint32_t y = 0; y < Y; y++) // for (uint32_t x = 0; x < X; x++) // result[y * Y + x] = dist(rng); // // return result; //} std::vector<libv::vec3uc> noise_white_2D_3uc(uint64_t seed, uint32_t X, uint32_t Y) { std::mt19937_64 rng(seed); auto dist = libv::make_uniform_distribution_inclusive(uint8_t(0), uint8_t(255)); std::vector<libv::vec3uc> result; result.resize(X * Y); for (uint32_t i = 0; i < X * Y; i++) { result[i].x = dist(rng); result[i].y = dist(rng); result[i].z = dist(rng); } return result; } // ------------------------------------------------------------------------------------------------- } // namespace libv
Markdown
UTF-8
13,578
2.890625
3
[]
no_license
# capacitacion-problema1 # Ejercicio 1 Capacitación: Git, bash y docker Integrantes: - Rafael Montoya - Daniela Tizón - Claudia Valdivieso --- 1. ¿Qué importancia tiene los tags en un proyecto? - Para el versionamiento de mi código :D 2. ¿Cuál es la diferencia entre un tag normal y un tag anotado en git? - En que en el tag anotado puedes poner un mensaje 👍 3. ¿Cómo se sube todos los tags de git que hay en mi local? - Con el comando `git push --tags` 4. ¿Es necesario loguearse cada vez que subo una imagen a dockerhub? - No. 5. ¿Qué es y para qué sirve docker? - Docker es una plataforma Open Source para desarrollar, implementar y ejecutar aplicaciones dentro de contenedores. - Sirve para empaquetar ambientes de desarrollo. --- 6. ¿Cuál es la diferencia entre docker y VirtualBox? - Docker me permite crear contenedores para tus app trabajando desde el kernel <3 y VirtualBOx crea una maquina virtual con hardware designado para cada app :/ 7. ¿Es necesario depender de una imagen de docker base al crear una imagen nueva? - Nope, porque se puede crear desde scratch 8. ¿Porqué debo anteponer el nombre de usuario en una imagen docker nueva? - Para identificar al propietario del dockerhub 9. ¿Que pasa si creo una imagen sin especificar una versión o tag, con qué versión se crea? - Se le agrega el tag latest happy :whale: --- ¿Porqué es necesario crear un contenedor con esta bandera -it ? ¿Qué pasa si no le pongo -it? - `-i` es para que los comandos que ingresemos en nuestra terminal se ejecuten en la terminal de docker. - `-t` es para que podamos ver los logs de la terminal de docker. ¿Para qué sirve ejecutar el comando bash al ejecutar una imagen? - Para poder ejecutar comandos en el contenedor. ¿Cuál es la diferencia entre docker ps y docker ps -a? - `docker ps` muestra todos los contenedores que están corriendo. - `docker ps -a` muestra todos los contenedores. COMANDO PARA EJECUTAR EL CONTENEDOR ``` docker run -it --rm dtizonportilla/orbis-training-docker:0.2.0 bash ``` --- 1. ¿Cuál es la diferencia entre una imagen y un contenedor? - Una imagen es como una plantilla y el contenedor es la instancia de esa plantilla. 2. ¿Cómo listo las imágenes que hay en mi computadora? - Con el comando `docker images` 3. ¿Cómo salgo de un contenedor de docker? - Con `Ctrl-C` 4. ¿Se elimina el contenedor al salir de ella? - Si le pones los flags `--rm` sí se eliminar, pero sino no. 5. ¿Cómo elimino un contenedor? - Con el comando `docker rm <NAME O CONTAINER ID>` 6. ¿Para qué es necesario el flag `-i`, `-t`, `--rm`? - `-i` es para que los comandos que ingresemos en nuestra terminal se ejecuten en la terminal de docker. - `-t` es para que podamos ver los logs de la terminal de docker. - `--rm` es para eliminar el contenedor apenas se sale de él. --- 7. ¿Cómo verifico que el archivo creado se encuentra en la imagen? - Con los siguientes comandos: ``` docker run -it --rm dtizonportilla/orbis-training-docker:0.2.0 bash # cd app # ls ``` 8. ¿Cómo se comenta una linea de código en Dockerfile? - Se comenta agregando un hash `#` al inicio de la línea. 1. ¿Qué es NGINX? - Un servidor web. 2. ¿Cómo expongo puertos en docker? - Se expone con `EXPOSE` en el Dockerfile. 3. ¿Cómo especifico los puertos al levantar un contenedor (docker run)? - Con `-p <puerto local>:<puerto expuesto en el contenedor>` 4. ¿Cómo hago 'forward' al levantar un contenedor (docker run)? - Con `-p` --- # PARTE 7 - ¿Qué pasa si no especifico el directorio de trabajo? El comando se ejecuta en el directorio raíz del container. 1. ¿Es necesario especificar el `workdir` en docker?, ¿Porqué? Si es que no se quiere ejecutar los comandos el el directorio raíz, sí. 2. ¿Que hacen los siguientes comandos? -`docker ps` Muestra todos los contenedores que estan levantados. -`docker pull` Descarga la imagen o un repositorio de un registro. Especificar la imagen debe. -`docker push` Sube una imagen a un respositorio. -`docker rm` Borra un contenedor especificado. -`docker rmi` Borra la imagen especificada. -`docker run` Levanta un contenedor, basado en una imagen. -`docker tag` Crea un tag a la imagen. --- -`docker search` Busca imágenes en docker hub. -`docker login` Permite loguearse a docker hub. -`docker exec` Permite ejecutar comandos en un contenedor que ya está levantado. -`docker build` Construye la imagen. -`docker inspect` Muestra información sobre el contenedor especificado. -`docker network` Permite administrar la red. Conectar, desconectar, crear, inspeccionar, listar... --- # PARTE 8 1. ¿Qué es bash? ¿Qué significa? - Es un programa informático, cuya función consiste en interpretar órdenes, y un lenguaje de consola. 2. ¿Cómo ejecuto un archivo bash? - . < archivo > / bash < archivo > 3. ¿Qué pasa si no especifico en un `.sh`, la linea `#!/bin/bash`? - Es una convención de Unix. Si no está, el archivo SOLO se ejecuta con bash / zsh o cualquiera sea tu shell. 4. ¿Se puede cambiar el modo bash (`/bin/bash`) a otro tipo de ejecución? - Sí! Lee arriba. --- 5. ¿Cómo se envía variables de entorno por Docker CLI y docker-compose? Docker CLI: ``` -e NAME='Harry Potter' ``` docker-compose: ``` service: environment: - DEBUG=1 ``` --- # PARTE 9 1. Qué sucede si le quito el @ al target resources del Makefile? - Se ejecuta y se imprime el comando 2. ¿Para qué sirve el archivo `Makefile`? Para ejecutar archivos, o comandos. 3. ¿Qué es un `target` en `Makefile`? - Generalmente es un archivo generado por un programa. También puede ser un comando para ejecutar ua tarea. # PARTE 10 1. ¿Qué significa el comando -d? - Especifica un directorio 2. ¿Porqué la sentencia comienza con @? - Oculta la instrucción ejecutada 3. ¿Para qué sirve el comando mkdir? - Para crear una carpeta 4. Explicar lo que hace la función `mkdir_deploy_dir` - Si no existe el directorio, entonces crear la carpeta # PARTE 10 1. ¿Para qué sirve el uso de \? - Para el salto de línea 2. ¿Para qué sirve el uso de &&? - Es un comando lógico que se ejecuta cuando el comando anterior se ejecutó con éxito 3. ¿Qué función cumple usar los argumentos -rf? - Para realizar una eliminación recursiva forzada 4. Explicar lo que hace la función `git_init` (linea por linea) - Primero se ubica en el directorio gh-pages, luego elimina el `.git` y después inicializa git # PARTE 10 1. ¿Para qué sirve el uso de eval? - Para ejecutar un comando almacenado en un a variable 2. ¿Para qué sirve el uso de shell? - Para interpretar comando en el Makefile 3. ¿Para qué sirve el uso de git log --pretty=format:"%an"? - git log: enlista la historia de commits - pretty=format te permite especificar lo que quieres que te muestre , %an se refiere a AuthorName 4. ¿Cuál es la diferencia en usar git config y git config --global? - Con global puedo configurar de manera global, no tengo que volver a configurarlo en cada repositorio. - El global modifica el archivo .gitconfig de l usuario de mi máquina, el otro crea el archivo config dentro de la carpeta .git del repositorio. 5. Explicar lo que hace la función `git_config` (línea por línea) - Crea las variables de `GIT_USER_NAME` y `GIT_USER_EMAIL`. Luego entra al directorio especificado y configura el nombre y usuario de git con las variables guardadas. # PARTE 10 1. ¿Para qué sirve el uso de awk? - AWK es un lenguaje de programación diseñado para procesar datos basados en texto. 2. ¿Para qué sirve el uso de sed? - sed permite modificar el contenido de un fichero en base a un fichero de comandos. 3. Explicar lo que hace la función `git_add_remote_repository` - 1era linea: Guarda en una variable el nombre del repositorio remoto del push - 2da linea: Busca una cadena y reemplaza el valor que está buscando por otro valor. Es como un replace.- Luego entra a la carpeta especificada y agrega como origen del repositorio la variable guardada. # PARTE 11 1. Explicar lo que hace la función `create_branch_gh_pages` - Entra al directorio especificado, y luego está creando y cambiando a la rama especificada. # PARTE 12 1. Explicar lo que hace la función `copy_files_to_deploy` - Esta función lo que hace es copiar archivos de un directorio a otro directorio. # PARTE 13 1. Explicar lo que hace la función `git_add` - Entra al directorio especificado, agrega los cambios al staging area y verifica el estado de los archivos aplicando el `git status`. # PARTE 14 1. Explicar lo que hace la función `create_commit` (línea por línea) - Primero obtiene el mensaje del último commit, luego se ubica en otrop directorio y finalmente hace un commit con el mensaje definido. # PARTE 15 1. Explicar lo que hace la función `git_push` (línea por línea) - Primero entra al directorio y luego sube el último commit de manera forzada a la rama. # PARTE 16 1. Explicar lo que hace la función `clean_workspace` - Borra el directorio de manera recursiva y forzada. # PARTE 17 1. ¿Para qué sirve el uso de ifeq? - Significa `if equal`. Es una condicional que permite comparar un resultado. 2. ¿Para qué sirve el uso de strip? - Compara 2 cadenas, no teniendo en cuenta espacios en blanco, sino solo el contenido. 3. Explicar lo que hace la función `show_deploy_url` (línea por línea) - Primero, guarda en una variable la ruta del repositorio remoto donde se suben los cambios. - Busca que esa variable contenga `git@`. Si existe, guarda la cadena en la nueva variable, y sino guarda la variable vacía. - Luego, evalúa si esta última variable es igual a "vacío" usando `strip`. Si es verdadero, significa que el repositorio fue creado con protocolo HTTPS, de lo contrario, con SSH. Dependiendo de como fue creado, usa un ternario para extraer el nombre de usuario y guardarlo en una variable. - Luego, hace lo mismo para guardar el nombre del repositorio. - Por último, imprime la url donde será publicado el proyecto. # PARTE 18 1. `$(call mkdir_deploy_dir)` - La función pregunta si existe el directorio de deploy y sino existe lo crea. 2. `$(call git_init)` - La función inicializa el proyecto git dentro del directorio creado 3. `$(call git_config)` - La función configura email y nombre de usuario de git del nuevo proyecto creado 4. `$(call git_add_remote_repository)` - La función agrega un repositorio remoto al repositorio git creado del nuevo directorio. 5. `$(call create_branch_gh_pages)` - La función crea una nueva rama basándose en la rama actual. 6. `$(call copy_files_to_deploy)` - La función copia los archivos de un directorio a nuevo. 7. `$(call git_add)` - La función agrega nuevos archivos al directorio y luego los muestra con `git status` 8. `$(call create_commit)` - La función obtiene el mensaje del último commit y crea un nuevo commit con este mismo mensaje en el nuevo directorio con los cambios agregados. 9. `$(call git_push)` - La función sube los últimos cambios en el nuevo directorio 10. `$(call clean_workspace)` - La función elimina el directorio y su contenido 11. `$(call show_deploy_url)` - La función muestra la URL del proyecto donde se realizo el último deploy # SECCION 12 --> Ejercicio Makefile, Jenkins, Cloudformation TAREA 3: 1. Explicar lo que hace la función `get_user_name` - Guarda en 2 variables: el nombre del repositorio remoto del proyecto actual y el nombre del usuario de dicho repositorio remoto. TAREA 4: 1. ¿Qué significa el argumento s3? 2. ¿Qué significa el argumento --delete? 3. ¿Qué significa el argumento --acl? 4. ¿Qué significa el argumento --region? 5. ¿Para qué sirve el comando aws? 6. Explicar lo que hace la función `deploy_bucket` # Parte 11 --> Jenkins ## 1. Instalación de jenkins con docker 1. ¿Que sucede si no volumeo el docker.sock? - Si no se volumea el docker.sock, no nos permite ejecutar comandos de docker dentro de un contenedor. - (Normalmente, los comandos los ejecutamos fuera del contenedor. Pero en este caso estamos usando docker dentro de uno) 2. ¿Para que sirve el volumen var/jenkins_home? - Es el espacio donde se va a reflejar el workspace del jenkins 3. ¿Puedo cambiar de puerto? - Sí, puedo cambiar el puerto que representa mi host, pero no el de docker (host:docker) 4. ¿Que pasa si no utlizo el usuario root? - No voy a tener permiso para elmininar/crear carpetas. 5. ¿Còmo instalo make en una imagen? - `apk add --update make` ## 1.1 Workspace 1. ¿Se puede crear un volúmen desde otro volúmen en docker? ¿Porqué? - No. Porque no puedo asignar un volumen a un espacio que ya ha sido asignado a otro volumen. 2. ¿Para que sirve el comando docker create -v <dir> --name <container> <image>? - Para crear un contenedor que ocupa un espacio en el disco, sin ejecutarlo. 3. ¿Qué hace el comando docker cp ./ <container>:<dir>? - Copia de un directorio (en este caso todo) al directorio de otro container. 4. ¿Cómo creo una network usando docker run? - `docker network create <network_name>` - `docker run -it --net=<network_name> -v $PWD/app:/app alpine:3.6 /bin/sh` 5. ¿Cómo conecto una network a un container? usando docker run - `docker run -it --net=<network_name> -v $PWD/app:/app alpine:3.6 /bin/sh` 6. ¿Qué hace docker run -it --rm --volumes-from <container> -w <dir> <image> <command>? - Crea y ejecuta un contenedor y lo volumea a partir de otro contenedor Y especifica el directorio de trabajo, especifica la image, ejecuta algún comando y luego muere.
Java
UTF-8
1,336
2.171875
2
[]
no_license
package com.cards.payment.service; import com.cards.payment.client.CardClient; import com.cards.payment.dto.GetCardInfoResponse; import com.cards.payment.entity.Payment; import com.cards.payment.exception.CardIsNotActiveException; import com.cards.payment.exception.CardNotFoundException; import com.cards.payment.exception.PaymentNotFoundException; import com.cards.payment.repository.PaymentRepository; import feign.FeignException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PaymentService { @Autowired PaymentRepository paymentRepository; @Autowired CardClient cardClient; public Iterable<Payment> findAll() { return paymentRepository.findAll(); } public Payment getById(Long id) throws PaymentNotFoundException { return paymentRepository.findById(id).orElseThrow(PaymentNotFoundException::new); } public Iterable<Payment> findByCardId(Long cardId) { return paymentRepository.findByCardId(cardId); } public Payment create(Payment payment) throws CardNotFoundException, CardIsNotActiveException { GetCardInfoResponse card = cardClient.getInfoById(payment.getCardId()); if (!card.getActive()) { throw new CardIsNotActiveException(); } return paymentRepository.save(payment); } }
PHP
UTF-8
1,235
2.59375
3
[ "MIT" ]
permissive
<?php namespace YaoiTests\PHPUnit\Sql; use Yaoi; class InsertTest extends \YaoiTests\PHPUnit\Sql\TestBase { public function testSingleRow() { $statement = Yaoi\Database::getInstance('test_mysqli')->statement(); $statement->insert('table') ->valuesRow(array('a' => 1, 'b' => 2)) ->valuesRow(array('b' => 3, 'c' => 4)); //var_dump($u); $this->assertSame('INSERT INTO table (`a`, `b`, `c`) VALUES (1, 2, DEFAULT), (DEFAULT, 3, 4)', (string)$statement); } public function testMultipleRows() { $i = Yaoi\Database::getInstance('test_mysqli')->insert('table2')->valuesRows(array( array('a' => 1, 'b' => 2), array('b' => 3, 'c' => 4), array('a' => 5, 'c' => 7) )); $this->assertSame('INSERT INTO table2 (`a`, `b`, `c`) VALUES (1, 2, DEFAULT), (DEFAULT, 3, 4), (5, DEFAULT, 7)', (string)$i); } public function testEmpty() { $this->assertSame('INSERT INTO table', (string)Yaoi\Database::getInstance('test_mysqli')->insert('table')); $this->assertSame('INSERT INTO table', (string)Yaoi\Database::getInstance('test_mysqli')->insert('table')->valuesRows(array())); } }
C#
UTF-8
1,492
2.71875
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using AutoMapper; using Competitions.Models; using Tennis.Mappers; using Tennis.ViewModels.Competitions; namespace Tennis.WebApp.Mappers { /// <summary> /// This represents the mapper entity between <see cref="TeamAddViewModel"/> and <see cref="TeamModel"/>. /// </summary> public class TeamAddViewModelToTeamModelMapper : BaseMapper { /// <summary> /// Configures the mapping information between source and destination. /// </summary> /// <param name="config"><see cref="IMapperConfigurationExpression"/> instance.</param> protected override void ConfigureMap(IMapperConfigurationExpression config) { config.CreateMap<TeamAddViewModel, TeamModel>() .ForMember(d => d.TeamPlayers, o => o.MapFrom(s => GetTeamPlayers(s))) ; } private static List<TeamPlayerModel> GetTeamPlayers(TeamAddViewModel model) { var tps = model.PlayerIds .Select( (playerId, i) => new TeamPlayerModel() { Order = model.PlayerOrders[i], PlayerId = playerId, }) .ToList(); return tps; } } }
TypeScript
UTF-8
730
3
3
[]
no_license
export interface iPostion { title: string, salary: number, expPerClick: number, btnText: string, altText: string requirements: { int?: number, dex?: number, char?: number, perc?: number, karma?: number, creativity?: number, } } export default class Position { title: string; requirements: object; salary: number; expPerClick: number; btnText: string; altText: string; level: number; constructor({title, salary, expPerClick, btnText, altText, requirements}: iPostion) { this.title = title; this.requirements = requirements; this.salary = salary; this.expPerClick = expPerClick; this.btnText = btnText; this.altText = altText; this.level = 0 } }
C++
UTF-8
3,987
2.6875
3
[]
no_license
#ifdef _WIN32 #define UVA_API_EXPORT __declspec(dllexport) #else #define __cdecl #define UVA_API_EXPORT #endif #include "u10150.h" #include <iostream> #include <iomanip> #include <map> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <numeric> #include <limits> #include <queue> #include <list> extern "C" { UVA_API_EXPORT void __cdecl invoke(); } void __cdecl invoke() { U10150 instance; instance(); } namespace { class solution { std::map<size_t, std::list<std::string>> dictionary_; std::string a_; std::string b_; size_t a_idx_; size_t b_idx_; std::vector<int64_t> path_; std::vector<std::string> doublets_; bool have_solution_; public: solution() : dictionary_(), a_(), b_(), a_idx_(), b_idx_(), path_(), doublets_(), have_solution_(false) {} friend std::istream& operator >>(std::istream& in, solution& sol); friend std::ostream& operator <<(std::ostream& out, const solution& sol); bool operator () (std::istream& in); private: void print_path(std::ostream& out, size_t start, size_t end) const; bool is_doublets(size_t u, size_t v); }; std::istream& operator >> (std::istream& in, solution& sol) { std::string word; while (std::getline(in, word) && !word.empty()) { sol.dictionary_[word.length()].push_back(word); } return in; } std::ostream& operator << (std::ostream& out, const solution& sol) { if (sol.have_solution_) { sol.print_path(out, sol.a_idx_, sol.b_idx_); } else { out << "No solution." << std::endl; } return out; } void solution::print_path(std::ostream& out, size_t start, size_t end) const { if (start != end) { print_path(out, start, path_[end]); } out << doublets_[end] << std::endl; } bool solution::operator ()(std::istream& in) { have_solution_ = false; in >> a_ >> b_; if (a_.length() == b_.length()) { doublets_.assign(dictionary_[a_.length()].begin(), dictionary_[a_.length()].end()); a_idx_ = std::find(doublets_.begin(), doublets_.end(), a_) - doublets_.begin(); b_idx_ = std::find(doublets_.begin(), doublets_.end(), b_) - doublets_.begin(); if (a_idx_ < doublets_.size() && b_idx_ < doublets_.size()) { path_.clear(); path_.reserve(doublets_.size()); std::generate_n(std::back_inserter(path_), doublets_.size(), []() { return -1; }); path_[a_idx_] = a_idx_; std::queue<size_t> path_q; path_q.push(a_idx_); while (path_q.size() && path_q.front() != b_idx_) { size_t u = path_q.front(); path_q.pop(); for (size_t v = 0; v < doublets_.size(); v++) { if (u != v && path_[v] < 0 && is_doublets(u, v)) { path_[v] = u; path_q.push(v); } } } have_solution_ = path_[b_idx_] != -1; } } return (bool)in; } bool solution::is_doublets(size_t u, size_t v) { size_t diff (0); for (auto itu = doublets_[u].begin(), itv = doublets_[v].begin(); diff < 2 && itu != doublets_[u].end(); ++itu, ++itv) { diff += (*itu) != (*itv); } return diff == 1; } } void U10150::operator()() const { solution sol; std::cin >> sol; while (sol(std::cin)) { std::cout << sol << std::endl; } }
Markdown
UTF-8
10,750
2.859375
3
[ "BSD-2-Clause" ]
permissive
--- title: 'CFD Notebooks: Learning OpenFOAM for HPC' tags: - Python - CFD - OpenFOAM - numerical methods - finite differences authors: - name: Ajay B. Harish orcid: 0000-0001-5234-7047 affiliation: "1, 2" - name: Sanjay Govindjee orcid: 0000-0003-0711-3633 affiliation: "1, 2" - name: Frank McKenna affiliation: 2 affiliations: - name: Department of Civil and Environmental Engineering, University of California, Berkeley, CA (USA) index: 1 - name: NHERI SimCenter, University of California, Berkeley, CA (USA) index: 2 date: 25 Dec 2020 bibliography: paper.bib --- # Summary The **CFD Notebooks** is a set of Jupyter notebooks aimed at senior undergraduate and early graduate students interested in learning OpenFOAM. It allows the learner to get started with the open-source CFD tool OpenFOAM and run it on Designsafe. It provides a foundation for all aspects of OpenFOAM, from running cases to programming. Hence, it is helpful to both new users and existing users wishing to broaden their basic knowledge. The learners are exposed to running exercises and simulating OpenFOAM cases using an HPC computing platform, accessed directly through the Jupyter notebook. The Jupyter notebooks consist of video tutorials, DIY examples, and general reading materials. This learning tool is platform-independent and leverages the power of HPC. At present, CFD Notebooks are hosted and uses Designsafe's supercomputing infrastructure at the Texas Advanced Computing Center, particularly the Stampede2 and Frontera clusters. The notebooks are broken up into various editions, each with four lessons: Beginner / Intermediate / Expert / Professional. At present, only the beginner edition is available. The beginner edition of the notebook includes four lessons: * Lesson 1 (Introduction to OpenFOAM and Designsafe): Introduces the learner to the basic structure of OpenFOAM and Designsafe cyberinfrastructure. * Lesson 2 (Different solvers in OpenFOAM and which to use?): Helps learners identify different types of solvers (laminar vs. turbulent; steady-state vs. transient). * Lesson 3 (Boundary conditions in OpenFOAM): While the number of boundary conditions is several, the lesson introduces the learner to the primary boundary conditions and their meaning. * Lesson 4 (Meshing in OpenFOAM (blockMesh)): The lesson introduces the learner to blockMesh utility basics in OpenFOAM. Additionally, CFD-Notebooks are accompanied by an extensive theoretical [documentation](https://nheri-simcenter.github.io/CFD-Notebooks/) and [user forum](http://simcenter-messageboard.designsafe-ci.org/smf/index.php?board=11.0) to provide hands-on support. ## Learning objectives Upon completion of this beginner series, one should have the ability to: - Modify the files and file directories of OpenFOAM - Modify and setup boundary conditions - Mesh using blockMesh utilities - Run OpenFOAM jobs on supercomputing cluster Stampede2 - Be exposed to Agave API and Jupyter notebooks - Visualize OpenFOAM results using Paraview # Statement of need There are several tutorials available on Youtube, particularly concerning the usage of OpenFOAM for CFD. The CFD Notebooks are not an alternative to these video tutorials but as complementary to the conventional classroom and online Computational Fluid Dynamics (CFD) courses like ''CFD Python: the 12 steps to Navier-Stokes equations'' [@Barba2019]; and computational fluid mechanics textbooks [@moukalled2015]. The most attractive aspect of the CFD Notebooks is its interface with HPC facilities that are often unavailable with other tutorials and tools. Today, OpenFOAM is one of the widely used open-source tools for CFD modeling and simulation and in this regard. While the documentation is comprehensive, most often forums like [CFD Online](https://www.cfd-online.com/) and [Quora](https://www.quora.com) are widely used to get personalized help and support. However, CFD Notebooks emphasizes a structured module to help students learn OpenFOAM in a coherent and orderly fashion despite the several tutorials available. The support includes hands-on help through the [user forum](http://simcenter-messageboard.designsafe-ci.org/smf/index.php?board=11.0). The module contains multiple sections as beginner/intermediate/expert, and thus, it caters to all categories of learners. At present, only the beginner section is published and only caters to beginner users. However, as an open-source educational tool, this provides a foundation and structure to solicit contributions for newer updated modules from the community, alongside our development. Most importantly, OpenFOAM simulations are often prohibitively expensive to perform on a user’s local computer. However, it is hard for many student users to access HPC facilities, particularly command-line access (CLI) that provides complete flexibility to use OpenFOAM. CFD Notebooks are seamlessly integrated to facilitate the learners to perform the computations remotely on the Teas Advanced Computing Center (TACC) supercomputing facility. The CFD Notebooks users have access to the Stampede and Frontera clusters of the TACC through a Designsafe account. Today, Stampede and Frontera are among the top 20 supercomputers in the world. The access to the [Texas Advanced Computing Center (TACC)](https://www.tacc.utexas.edu) is made available to the user through [NHERI DesignSafe](https://www.designsafe-ci.org), the cyberinfrastructure provider for the distributed NSF funded Natural Hazards in Engineering Research Infrastructure (NHERI) facility. Designsafe automatically provides 50GB of storage and 2000 node hours for all registered users. The above provided compute time is roughly equivalent to using a single processor core for one year. However, researchers and teachers in US institutions can request higher allocations. They can be allocated up to 100,000 node-hours and 100TB and 1TB, respectively, contingent on a positive review of their needs. The additional allocation is also possible for non-US researchers through a collaborative project with a US-based PI. Additionally, Designsafe allows easy access to data through cloud storage (Box / Dropbox / Google drive), making it easy to copy case directories and results to and from the HPC facility. CFD Notebooks helps learners of OpenFOAM to leverage this access to HPC resources. Fluid mechanics form a part of the core curriculum for both mechanical and aerospace engineers. However, civil engineering students have much less exposure to fluid mechanics and particularly CFD. However, CFD is a critical aspect of several areas related to civil and geotechnical engineering, like modeling water/wind/fire borne natural hazards. This module addresses this need for easier access to fluid mechanics tools and HPC for civil engineering students, particularly those interested in natural hazards engineering. The developed module is funded through the NSF NHERI to ensure that this is a stepping stone to use CFD-based research tools like [Hydro-UQ](https://simcenter.designsafe-ci.org/research-tools/hydro-uq/), [WE-UQ](https://simcenter.designsafe-ci.org/research-tools/we-uq/). # Functionality and usage THE CFD Notebooks are a series of Jupyter notebooks that include video tutorials, DIY examples, and exercises. Furthermore, sample problems are also available on the [documentation](https://nheri-simcenter.github.io/CFD-Notebooks/) site. Four primary aspects facilitate the learner to access and use OpenFOAM on DesignSafe, starting with login and authentication. Designsafe account acts as authentication to access the HPC resources at TACC and is achieved through an Agave API client. ```python from agavepy.agave import Agave ag = Agave.restore() ag.profiles.get() ``` Once authenticated, the learners can access all the apps and software available for public users on TACC. TACC classifies software (or `apps`) as `public` and `private`. `private` refers to the custom `apps` created by users and can be accessed only if permitted by the user who has created it. In contrast, `public` refers to those that are accessible to all users. The learners can access the list of `apps` and choose a particular version of OpenFOAM of interest. Such easy access reduces the requirement to install OpenFOAM on the local computer and ensures access to the same version every time. Access to a particular version of the OpenFOAM app is achieved through the Agave API client's usage. ```python ag.apps.list() app = ag.apps.get(appId = 'openfoam-7.0u3') app.parameters ``` Once the OpenFOAM version of interest is loaded, the job parameters are provided in a JSON format, as shown below. The TACC HPC system uses this data to automatically generate a runtime script to run, and facilitate the job. ```python jobdetails = { "name": "OpenFOAM-Demo", #Name of job "appId": "openfoam-7.0u3", #OpenFOAM version to be used "maxRunTime": "00:02:00", #Clock time to run the job "nodeCount": 1, #Number of nodes "processorsPerNode": 1, #Number of processors (Max 64 per node) "archive": True, #To add results to archive folder "archiveSystem": "designsafe.storage.default", "parameters": { "mesh": "On", #Use blockMesh or snappyHexMesh? "decomp": "Off", #Use parallelization? "solver": "simpleFoam" #Solver to be used? }, "inputs": { "inputDirectory": "agave://designsafe.storage.published// \ PRJ-2915/examples/pitzDaily" #Where are the care directories located? } } job = ag.jobs.submit(body=jobdetails) ``` The OpenFOAM simulation can be monitored both on the [Designsafe-ci](https://www.designsafe-ci.org/) dashboard or through the CFD Jupyter Notebook using the status commands. The status command lets the user determine if a job is `QUEUED`, `ACCEPTED`, `RUNNING` or `COMPLETED`. ```python from agavepy.async import AgaveAsyncResponse asrp = AgaveAsyncResponse(ag,job) asrp.status ``` # Recent Uses The CFD Notebooks are planned to be used in the upcoming 2021 HydroUQ tool-training program for researchers in Natural Hazards. # Acknowledgements The SimCenter was financially supported by the National Science Foundation under Grant CMMI-1612843. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the National Science Foundation. We would like to acknowledge (1) the contributions and collaboration with many faculty, post-doctoral researchers, students and staff who have contributed to the SimCenter’s work, and (2) the support and close collaboration with DesignSafe, which facilitates access to high-performance computing and information technologies for SimCenter tools. # References
Java
UTF-8
3,015
2.046875
2
[]
no_license
package com.rebolt.ark.popularmoviesone.content; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.provider.BaseColumns; /** * Created by AkhilRaja on 15/12/16. */ public class MovieContract { static final String CONTENT_AUTHORITY = "com.rebolt.ark.popularmoviesone"; private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); static final String PATH_MOVIE = "movie"; static final String PATH_FAVOURITE = "favourite"; public static final class Movie { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_MOVIE).build(); static final String TABLE_NAME = "movie"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_VOTE = "vote_count"; public static final String COLUMN_POSTER = "poster_path"; public static final String COLUMN_BACKDROP = "backdrop_path"; public static final String COLUMN_OVERVIEW = "overview"; public static final String COLUMN_DATE = "date"; public static final String COLUMN_TYPE = "type"; static final String DATABASE_CREATE = "create table " + TABLE_NAME + "(" + COLUMN_ID + " integer primary key, " + COLUMN_TITLE + " text not null, " + COLUMN_VOTE + " integer not null," + COLUMN_POSTER + " text not null," + COLUMN_BACKDROP + " text not null," + COLUMN_OVERVIEW + " text not null," + COLUMN_DATE + " text not null," + COLUMN_TYPE + " integer not null " + ");"; } public static final class Favourite { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVOURITE).build(); static final String TABLE_NAME = "favourite"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_VOTE = "vote_count"; public static final String COLUMN_POSTER = "poster_path"; public static final String COLUMN_BACKDROP = "backdrop_path"; public static final String COLUMN_OVERVIEW = "overview"; static final String DATABASE_CREATE = "create table " + TABLE_NAME + "(" + COLUMN_ID + " integer primary key, " + COLUMN_TITLE + " text not null, " + COLUMN_VOTE + " integer not null," + COLUMN_POSTER + " text not null," + COLUMN_BACKDROP + " text not null," + COLUMN_OVERVIEW + " text not null" + ");"; } }
C++
UTF-8
1,426
2.859375
3
[]
no_license
// // Created by ita on 14/09/17. // #ifndef BLOODBOND_CHARACTER_H #define BLOODBOND_CHARACTER_H #include <SFML/Graphics/RenderWindow.hpp> #include "Weapon.h" #include "Medicine.h" #include "Window.h" class Character { public: Character(const Character& original); explicit Character(int h, int x=0, int y=0, Weapon* w= nullptr): hp(h),posX(x),posY(y), weapon(w){} virtual ~Character()= default; virtual void move()=0; virtual void attack(Character& enemy)=0; virtual void Render(Window& l_window)=0; int getHp(){ return hp; } void heal(int value){ Character::hp+=value; } void hit(int value){ Character::hp-=value; } float getPosX(){ return posX; } float getPosY(){ return posY; } sf::Vector2f getPosition(){ return sf::Vector2f(posX,posY); } Weapon* getWeapon(){ return weapon; } void setWeapon(Weapon* weapon){ Character::weapon=weapon; } Character& operator =(const Character& right); Character& copier(const Character& original); sf::Vector2f getCollisionArea(){ return collisionArea; } void screenBound(); protected: sf::Texture texture; sf::Sprite sprite; sf::Vector2f collisionArea; int hp; float frame; float posX, posY; Weapon* weapon; int walk; }; #endif //BLOODBOND_CHARACTER_H
Java
UTF-8
2,345
1.921875
2
[]
no_license
package com.qinjiangbo.gen.model; import java.io.Serializable; public class RegsatDateCenterDet extends RegsatDateCenterDetKey implements Serializable { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column regsat_date_center_det.cent_code * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ private String centCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column regsat_date_center_det.status * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ private Integer status; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table regsat_date_center_det * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column regsat_date_center_det.cent_code * * @return the value of regsat_date_center_det.cent_code * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ public String getCentCode() { return centCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column regsat_date_center_det.cent_code * * @param centCode the value for regsat_date_center_det.cent_code * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ public void setCentCode(String centCode) { this.centCode = centCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column regsat_date_center_det.status * * @return the value of regsat_date_center_det.status * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ public Integer getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column regsat_date_center_det.status * * @param status the value for regsat_date_center_det.status * * @mbggenerated Tue Jun 21 00:00:04 CST 2016 */ public void setStatus(Integer status) { this.status = status; } }
Shell
UTF-8
1,441
3.296875
3
[]
no_license
#!/bin/bash #set -x FIRST_REALLOC=1379128 BLOCK_TIME=2.625 SUPER_BLOCK_CYCLE=16616 HALVING_INTERVAL=210240 FIRST_REWARD_BLOCK=1261441 HALVING_REDUCTION_AMOUNT="1/14" STARTING_BLOCK_REWARD=1.44236248 REALLOC_AMOUNT=(513 526 533 540 546 552 557 562 567 572 577 582 585 588 591 594 597 599 600) current_block=$(dash-cli getblockcount) blocks_per_year=$(printf '%.0f' $(echo "scale=4;60/$BLOCK_TIME*24*365.25"|bc)) last_block_of_the_year=$((current_block+blocks_per_year)) enabled_mns=$(dash-cli masternode count|jq -r .enabled) # General idea compute the reward for every n blocks and accumulate it. # where n is the number of enabled MNs. reward=0 for((block=current_block; block<last_block_of_the_year; block+=enabled_mns));do # Find which halving period we are on blocks_since_halving=$((block-FIRST_REWARD_BLOCK)) halving_period=$((blocks_since_halving/HALVING_INTERVAL)) # Find which realloc period we are on. blocks_since_realloc=$((block-FIRST_REALLOC)) # We start counting our periods from zero, each realloc period lasts for 3 super blocks. period=$((blocks_since_realloc/(SUPER_BLOCK_CYCLE*3))) if ((period>18));then period=18 fi # Combined bc statement. reward=$(echo "scale=8;base_reward=$STARTING_BLOCK_REWARD * (1 - $HALVING_REDUCTION_AMOUNT)^$halving_period;new_reward=base_reward / 500 * ${REALLOC_AMOUNT[$period]};$reward+new_reward"|bc -l) done roi=$(echo "scale=6;$reward/10"|bc) echo "ROI = ${roi}%"
C#
UTF-8
208
2.59375
3
[]
no_license
using System; class Welcome { static void Main() { Console.WriteLine("Please enter your name:"); Console.ReadLine(); Console.WriteLine("Welcome aboard, captain."); } }
Markdown
UTF-8
887
2.859375
3
[]
no_license
## 项目说明 该项目是对 `chatterbot` 的一些使用和试验,**不成熟项目,不可用于线上环境**。 ## 外部依赖 pip依赖:见 `requirements.txt` ## 功能 ### 基于脚本的chatterbot #### 脚本 `main.py` #### 运行 ```bash python3 ./main.py ``` ### 基于Django的chatterbot 项目位于 `django_app/` ,下面的操作都是在这个目录中进行的。 #### 准备 ##### 安装Django ```bash pip install django ``` ##### 同步数据库 ```bash python manage.py migrate ``` ##### 创建超级用户 ```bash python manage.py createsuperuser ``` ##### 训练chatterbot ```bash python manage.py train ``` ##### 运行server ```bash python manage.py runserver ``` web服务器默认监听5000端口,访问[http://127.0.0.0.1:5000](http://127.0.0.0.1:5000)就能访问页面了 ## Python 2/3 兼容性说明 只能保证对python3的兼容性
JavaScript
UTF-8
2,359
3.015625
3
[]
no_license
'use strict' /** * route 模块,存放管理path值一定时的method和callback的关系数组 */ const debug = require('debug')('express:router:route') const Layer = require('./layer') let methods = require('http').METHODS const flatten = require('array-flatten').flatten const slice = Array.prototype.slice const toString = Object.prototype.toString; module.exports = Route /** * 采用设计模式中的工厂模式实现 */ function Route(path) { this.path = path this.stack = [] //method fun对应数组,Layer实例 this.methods = {} } /** * 对同一path对应的methods进行注册,存放入stack中 */ methods.forEach((method) => { method = method.toLowerCase() Route.prototype[method] = function () { let handles = flatten(slice.call(arguments)) for (let i = 0; i < handles.length; i++) { let handle = handles[i] if (typeof handle !== 'function') { // 如果handle不是function,则对外抛出异常 let msg = `Route.${method}() requires a callback function but not a ${type}` throw new Error(msg) } debug('%s %o', method, this.path) let layer = new Layer('/', {}, handle) // 注册method和handle的关系 layer.method = method this.methods[method] = true this .stack .push(layer) } return this } }) /** * 遍历stack数组,并处理函数 */ Route.prototype.dispatch = function dispatch(req, res, done) { let idx = 0 let stack = this.stack if (stack.length === 0) { return done() // 函数出来完成之后,将执行入口交给母函数管理,此处的done为router handle中的next } let method = req .method .toLowerCase() req.route = this next() function next(err) { let layer = stack[idx++] if (!layer) { // 当循环完成,调回router handle中的next return done(err) } if (layer.method && layer.method !== method) { // 不符合要求,继续调用next进行遍历 return next(err) } // 3:新增 加入错误处理 if (err) { layer.handle_error(err, req, res, next) } else { layer.handle_request(req, res, next) } } } /** * 判断当前route实例是否有注册method方法 */ Route.prototype._handles_method = function _handles_method(method) { return Boolean(this.methods[method.toLowerCase()]) }
PHP
UTF-8
9,163
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\API; use App\Http\Requests\API\CreateFeatureTypeAPIRequest; use App\Http\Requests\API\UpdateFeatureTypeAPIRequest; use App\Models\FeatureType; use App\Repositories\FeatureTypeRepository; use Illuminate\Http\Request; use App\Http\Controllers\AppBaseController; use Response; /** * Class FeatureTypeController * @package App\Http\Controllers\API */ class FeatureTypeAPIController extends AppBaseController { /** @var FeatureTypeRepository */ private $featureTypeRepository; public function __construct(FeatureTypeRepository $featureTypeRepo) { $this->featureTypeRepository = $featureTypeRepo; } /** * @param Request $request * @return Response * * @OA\Get( * path="/featureTypes", * summary="getFeatureTypeList", * tags={"FeatureType"}, * description="Get all FeatureTypes", * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * type="array", * @OA\Items(ref="#/definitions/FeatureType") * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function index(Request $request) { $featureTypes = $this->featureTypeRepository->all( $request->except(['skip', 'limit']), $request->get('skip'), $request->get('limit') ) ->sortBy('id')->values(); // or sortByDesc // ->orderBy not working on this object type // sortBy changes the output schema by making key value pairs for rows instead of only values so "->values()" needs to be added return $this->sendResponse($featureTypes->toArray(), 'Feature Types retrieved successfully'); // return $this->sendResponse($featureTypes->toArray(), 'Feature Types retrieved successfully'); } /** * @param Request $request * @return Response * * @OA\Post( * path="/featureTypes", * summary="createFeatureType", * tags={"FeatureType"}, * description="Create FeatureType", * @OA\RequestBody( * required=true, * @OA\MediaType( * mediaType="application/x-www-form-urlencoded", * @OA\Schema( * type="object", * required={""}, * @OA\Property( * property="name", * description="desc", * type="string" * ) * ) * ) * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * ref="#/definitions/FeatureType" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function store(CreateFeatureTypeAPIRequest $request) { $input = $request->all(); $featureType = $this->featureTypeRepository->create($input); return $this->sendResponse($featureType->toArray(), 'Feature Type saved successfully'); } /** * @param int $id * @return Response * * @OA\Get( * path="/featureTypes/{id}", * summary="getFeatureTypeItem", * tags={"FeatureType"}, * description="Get FeatureType", * @OA\Parameter( * name="id", * description="id of FeatureType", * @OA\Schema( * type="integer" * ), * required=true, * in="path" * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * ref="#/definitions/FeatureType" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function show($id) { /** @var FeatureType $featureType */ $featureType = $this->featureTypeRepository->find($id); if (empty($featureType)) { return $this->sendError('Feature Type not found'); } return $this->sendResponse($featureType->toArray(), 'Feature Type retrieved successfully'); } /** * @param int $id * @param Request $request * @return Response * * @OA\Put( * path="/featureTypes/{id}", * summary="updateFeatureType", * tags={"FeatureType"}, * description="Update FeatureType", * @OA\Parameter( * name="id", * description="id of FeatureType", * @OA\Schema( * type="integer" * ), * required=true, * in="path" * ), * @OA\RequestBody( * required=true, * @OA\MediaType( * mediaType="application/x-www-form-urlencoded", * @OA\Schema( * type="object", * required={""}, * @OA\Property( * property="name", * description="desc", * type="string" * ) * ) * ) * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * ref="#/definitions/FeatureType" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function update($id, UpdateFeatureTypeAPIRequest $request) { $input = $request->all(); /** @var FeatureType $featureType */ $featureType = $this->featureTypeRepository->find($id); if (empty($featureType)) { return $this->sendError('Feature Type not found'); } $featureType = $this->featureTypeRepository->update($input, $id); return $this->sendResponse($featureType->toArray(), 'FeatureType updated successfully'); } /** * @param int $id * @return Response * * @OA\Delete( * path="/featureTypes/{id}", * summary="deleteFeatureType", * tags={"FeatureType"}, * description="Delete FeatureType", * @OA\Parameter( * name="id", * description="id of FeatureType", * @OA\Schema( * type="integer" * ), * required=true, * in="path" * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * type="string" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function destroy($id) { /** @var FeatureType $featureType */ $featureType = $this->featureTypeRepository->find($id); if (empty($featureType)) { return $this->sendError('Feature Type not found'); } $featureType->delete(); return $this->sendSuccess('Feature Type deleted successfully'); } }
Java
UTF-8
1,274
2.828125
3
[]
no_license
package core.Kits; import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; public class KitLockManager { private static HashMap<UUID, Boolean> canEquip = new HashMap<UUID, Boolean>(); private static ArrayList<UUID> singleEquipees = new ArrayList<UUID>(); private static ArrayList<UUID> burnedEquipees = new ArrayList<UUID>(); public static boolean canEquip(UUID playerUUID) { if (canEquip.get(playerUUID) == null || canEquip.get(playerUUID) == false) return false; return true; } public static boolean isEquipped(UUID playerUUID) { return burnedEquipees.contains(playerUUID); } public static boolean justEquipped(UUID playerUUID) { if (singleEquipees.contains(playerUUID)) { singleEquipees.remove(playerUUID); canEquip.put(playerUUID, false); burnedEquipees.add(playerUUID); return true; } return false; } public static void setCanEquip(boolean infinite, UUID playerUUID) { KitLockManager.canEquip.put(playerUUID, true); burnedEquipees.remove(playerUUID); if (!infinite) singleEquipees.add(playerUUID); } public static void setCanNotEquip(UUID playerUUID) { burnedEquipees.remove(playerUUID); KitLockManager.canEquip.put(playerUUID, false); singleEquipees.remove(playerUUID); } }
JavaScript
UTF-8
1,790
2.765625
3
[]
no_license
const Product = require("../models/Products"); const { isValidObjectId } = require("mongoose"); // create a new product exports.createProduct = async (req, res, next) => { const newProduct = new Product(req.body); try { const product = await newProduct.save(); res.status(201).json({ message: "Product Saved Successfully", product, }); } catch (error) { console.log(error); next(); } }; // get all products exports.getProducts = async (req, res, next) => { try { // consultar base de datos const products = await Product.find(); res.status(200).json(products); } catch (error) { console.log(err); next(); } }; // get a product exports.getProduct = async (req, res, next) => { try { const validObject = isValidObjectId(req.params.id); if (!validObject) { return res.status(422).json({ message: "The id is not valid" }); } const product = await Product.findById(req.params.id); res.json(product); } catch (error) { console.log(error); next(); } }; // updated a product exports.updateProduct = async (req, res, next ) => { try { const productUpdated = await Product.findByIdAndUpdate( req.params.id, req.body, { new: true} ); res.status(200).json({ message: "Successfully updated", productUpdated }) } catch (error) { console.log(error); next(); } } // delete a product exports.deleteProduct = async (req, res, next) => { try { const deleteProduct = await Product.findByIdAndDelete(req.params.id); res.status(200).json({ message: "product deleted"}) } catch (error) { console.log(error); next(); } }
Python
UTF-8
1,421
3.09375
3
[]
no_license
from graficos import grafico_boxplot path_in = "experimentos/experimento_1_memoria/memoria_{0}_{1}_{2}.txt" path_in_sin_truco = "experimentos/experimento_1_memoria/memoria_sintruco_{0}_{1}_{2}.txt" label = "{0} con valor k={1} de PCA" rango = [1] + list(range(5, 20, 5)) modo = ["big", "red"] PCAS = ["PCA", "PCA_pesos"] def leer_memoria_usada(path): res = [] with open(path) as f: d = f.readlines() for i in d: res.append(float(i[:-1])/(1024*1024)) return res # Grafico entre PCA y PCA_pesos (ambos usando truco) para verios k de PCA #for m in modo: # for k in rango: # datos = [] # labels = [] # for p in PCAS: # archivo_in = path_in.format(m, p, k) # datos.append(leer_memoria_usada(archivo_in)) # labels.append(label.format(p, k)) # grafico_boxplot(datos, labels) for m in modo: archivo_in = path_in.format(m, "PCA", 1) archivo_in_sin_truco = path_in_sin_truco.format(m, "PCA", 1) datos = [leer_memoria_usada(archivo_in), leer_memoria_usada(archivo_in_sin_truco)] labels = ["PCA + kNN, usando el truco", "PCA + kNN, sin usar el truco"] if m == "big": titulo = "Memoria utilizada según método para las imágenes originales" else: titulo = "Memoria utilizada según método para las imágenes reducidas" grafico_boxplot(datos, labels, titulo, "Método","Memoria(Mb)")
JavaScript
UTF-8
124
2.6875
3
[]
no_license
function circleOfNumbers(n, firstNumber) { return n / 2 + firstNumber >= n ? firstNumber - n / 2 : n / 2 + firstNumber; }
Java
UTF-8
608
1.820313
2
[]
no_license
package br.com.eventoadmin.mb; import java.io.Serializable; import com.xpert.core.crud.AbstractBaseBean; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import br.com.eventoadmin.bo.SedeBO; import br.com.eventoadmin.modelo.sede.Sede; /** * * @author Joao Pedro */ @ManagedBean @ViewScoped public class SedeMB extends AbstractBaseBean<Sede> implements Serializable { @EJB private SedeBO sedeBO; @Override public SedeBO getBO() { return sedeBO; } @Override public String getDataModelOrder() { return "id"; } }
Java
UTF-8
3,773
2.140625
2
[]
no_license
package com.restkeeper.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.restkeeper.entity.*; import com.restkeeper.mapper.*; import com.restkeeper.service.OrderHistoryService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import java.util.List; @Service public class OrderHistoryServiceImpl implements OrderHistoryService { @Autowired private OrderMapper orderMapper; @Autowired private OrderHistoryMapper orderHistoryMapper; @Autowired private OrderDetailMapper orderDetailMapper; @Autowired private OrderDetailHistoryMapper orderDetailHistoryMapper; @Autowired private OrderDetailMealMapper orderDetailMealMapper; @Override @Transactional(rollbackFor = {Exception.class}) public void exportToHistory() { LocalDate nowDate = LocalDate.now(); //查询出小于今天的订单记录 QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>(); wrapper.lambda().lt(OrderEntity::getLastUpdateTime,nowDate); List<OrderEntity> orderEntityList = orderMapper.selectList(wrapper); //遍历集合,嵌入到历史订单表中,同时删除原有的订单记录信息 orderEntityList.forEach(orderEntity -> { //订单主表 OrderHistoryEntity orderHistoryEntity = new OrderHistoryEntity(); BeanUtils.copyProperties(orderEntity,orderHistoryEntity); orderHistoryMapper.insert(orderHistoryEntity); //查询出关联的订单明细(t_order_detail t_order_detail_meal) QueryWrapper<OrderDetailEntity> detailWrapper = new QueryWrapper<>(); detailWrapper.lambda().eq(OrderDetailEntity::getOrderId,orderEntity.getOrderId()); List<OrderDetailEntity> orderDetailEntityList = orderDetailMapper.selectList(detailWrapper); orderDetailEntityList.forEach(orderDetailEntity -> { if (orderDetailEntity.getDishType() == 1){ //普通菜品 //添加到历史表中t_his_order_detail OrderDetailHistoryEntity orderDetailHistoryEntity = new OrderDetailHistoryEntity(); BeanUtils.copyProperties(orderDetailEntity,orderDetailHistoryEntity); orderDetailHistoryMapper.insert(orderDetailHistoryEntity); orderDetailMapper.deleteById(orderDetailEntity.getDetailId()); } if (orderDetailEntity.getDishType() == 2){ //套餐。获取当前套餐下的相关菜品信息 QueryWrapper<OrderDetailMealEntity> mealWrapper = new QueryWrapper<>(); mealWrapper.lambda().eq(OrderDetailMealEntity::getOrderId,orderDetailEntity.getOrderId()); List<OrderDetailMealEntity> detailMealEntityList = orderDetailMealMapper.selectList(mealWrapper); for (OrderDetailMealEntity orderDetailMealEntity : detailMealEntityList) { OrderDetailHistoryEntity orderDetailHistoryEntity = new OrderDetailHistoryEntity(); BeanUtils.copyProperties(orderDetailMealEntity,orderDetailHistoryEntity); orderDetailHistoryMapper.insert(orderDetailHistoryEntity); orderDetailMealMapper.deleteById(orderDetailMealEntity.getDetailId()); } } }); //删除订单的信息 orderMapper.deleteById(orderEntity.getOrderId()); }); } }
Java
UTF-8
5,580
1.757813
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 Broadband Forum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package org.broadband_forum.obbaa.netconf.server.model.notification; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.broadband_forum.obbaa.netconf.server.model.notification.rpchandlers.CreateSubscriptionRpcHandlerImpl; import org.broadband_forum.obbaa.netconf.stack.logging.AdvancedLogger; import org.broadband_forum.obbaa.netconf.stack.logging.AdvancedLoggerUtil; import org.broadband_forum.obbaa.netconf.stack.logging.LogAppNames; import org.joda.time.DateTime; import org.broadband_forum.obbaa.netconf.api.messages.Notification; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.FilterNode; import org.broadband_forum.obbaa.netconf.server.model.notification.utils.NotificationFilterUtil; import com.google.common.collect.Range; import com.google.common.collect.RangeMap; import com.google.common.collect.TreeRangeMap; /** * @author gnanavek * */ public class StreamLoggerInMemoryImpl implements StreamLogger { private static final AdvancedLogger LOGGER = AdvancedLoggerUtil.getGlobalDebugLogger(CreateSubscriptionRpcHandlerImpl.class, LogAppNames .NETCONF_NOTIFICATION); private String m_streamName; private int defaultQueueSize = 100000; private int m_size; private DateTime m_replayLogCreationTime; private RangeMap<DateTime, List<Notification>> m_streamLogger = TreeRangeMap.<DateTime, List<Notification>>create(); private Object lock_Object = new Object(); private boolean m_replaySupport; private DateTime m_testForReplayLogAgedTime; public StreamLoggerInMemoryImpl(String streamName, boolean isReplaySupport) { m_streamName = streamName; m_size = 0; m_replayLogCreationTime = DateTime.now(); m_replaySupport = isReplaySupport; m_testForReplayLogAgedTime = null; } public StreamLoggerInMemoryImpl(String streamName, boolean isReplaySupport, int queueSize) { m_streamName = streamName; m_size = 0; m_replayLogCreationTime = DateTime.now(); m_replaySupport = isReplaySupport; m_testForReplayLogAgedTime = null; defaultQueueSize = queueSize; } public String getStreamName() { return m_streamName; } public int getSize() { return m_size; } @Override public void logNotification(DateTime eventTime, Notification notification) { synchronized (lock_Object ) { if (m_size >= defaultQueueSize) { DateTime oldestLoggedTime = m_streamLogger.span().lowerEndpoint(); m_streamLogger.remove(Range.singleton(oldestLoggedTime)); m_size--; } if (m_streamLogger.asMapOfRanges().containsKey(Range.singleton(eventTime))) { m_streamLogger.get(eventTime).add(notification); } else { List<Notification> notificationList = new ArrayList<Notification>(); notificationList.add(notification); m_streamLogger.put(Range.singleton(eventTime), notificationList); } m_size++; m_testForReplayLogAgedTime = null; } } @Override public List<Notification> retrieveNotifications(DateTime startTime, DateTime stopTime, FilterNode filterNode) { LOGGER.debug(null, "Retrieve notifications between startTime: {} and stopTime: {}", startTime, stopTime); Map<Range<DateTime>, List<Notification>> subRangeLogger; if (stopTime == null){ subRangeLogger = m_streamLogger.subRangeMap(Range.atLeast(startTime)).asMapOfRanges(); } else { subRangeLogger = m_streamLogger.subRangeMap(Range.closed(startTime, stopTime)).asMapOfRanges(); } List<Notification> notificationList = new ArrayList<Notification>(); for(Entry<Range<DateTime>, List<Notification>> notificationEntry : subRangeLogger.entrySet()) { for (Notification notification : notificationEntry.getValue()) { if (NotificationFilterUtil.matches(notification, filterNode)) { notificationList.add(notification); } } } return notificationList; } @Override public DateTime getReplayLogCreationTime() { return m_replayLogCreationTime; } @Override public DateTime getReplayLogAgedTime() { DateTime result=null; if (m_testForReplayLogAgedTime != null) { result = m_testForReplayLogAgedTime; } else { if (!m_streamLogger.asMapOfRanges().isEmpty()) { result = m_streamLogger.span().lowerEndpoint(); } } return result; } public RangeMap<DateTime, List<Notification>> getNotificationsRangeMap() { return m_streamLogger; } @Override public void setReplaySupport(boolean isReplaySpport) { this.m_replaySupport = isReplaySpport; } @Override public boolean isReplaySupport() { return m_replaySupport; } @Override public void setReplayLogCreationTime(DateTime logCreationTime) { m_replayLogCreationTime = logCreationTime; } @Override public void setTestForReplayLogAgedTime(DateTime logAgedTime) { m_testForReplayLogAgedTime = logAgedTime; } }
Java
UTF-8
1,651
2.875
3
[]
no_license
package br.com.professorisidro.isilanguage.main; import br.com.professorisidro.isilanguage.exceptions.IsiSemanticException; import br.com.professorisidro.isilanguage.exceptions.IsiTypeException; import br.com.professorisidro.isilanguage.parser.IsiLangLexer; import br.com.professorisidro.isilanguage.parser.IsiLangParser; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; /** Esta é a classe que é responsável por criar a interação com o usuário * instanciando nosso parser e apontando para o aroquivo fonte. * * Arquivo fonte: *.isi */ public class MainClass { public static void main(String[] args) { try { IsiLangLexer lexer; IsiLangParser parser; // Leio o arquivo "input.isi" e isso é entrada para analisador lexico lexer = new IsiLangLexer(CharStreams.fromFileName("input.isi")); // Crio um fluxo de tokens para passar para o parser CommonTokenStream tokenStream = new CommonTokenStream(lexer); // Crio meu parser a partir do token stream parser = new IsiLangParser(tokenStream); parser.prog(); System.out.println("Compilation success!"); parser.exibeComandos(); parser.generateCode(); } catch (IsiSemanticException e) { System.err.println("Semantic Error: " + e.getMessage()); } catch (IsiTypeException e) { System.err.println("Assigned type Error: " + e.getMessage()); } catch (Exception e) { System.err.println("Generic Error: " + e.getMessage()); } } }
Python
UTF-8
5,495
3.375
3
[ "Apache-2.0" ]
permissive
''' Polygon As Line Tool for Text Extractor --------------------------------------- This module provides a function to extract panoptes annotations from projects using a polygon tool to mark words in a transcribed document and provide the transcribed text as a sub-task. ''' from collections import OrderedDict import copy import numpy as np from .extractor_wrapper import extractor_wrapper from .tool_wrapper import tool_wrapper import warnings @extractor_wrapper(gold_standard=True) @tool_wrapper def poly_line_text_extractor(classification, dot_freq='line', gold_standard=False, **kwargs): '''Extract annotations from a polygon tool with a text sub-task Parameters ---------- classification : dict A dictionary containing an `annotations` key that is a list of panoptes annotations Returns ------- extraction : dict A dictionary with one key for each `frame`. The value for each frame is a dict with `text` a list-of-lists of transcribe words, `points` a dict with the list-of-lists of `x` and `y` postions of each space between words, `slope` a list of the slopes (in deg) of each line drawn, and `gold_standard` a bool indicating if the annotation was made in gold standard mode in the classifier. For `points` and `text` there is one inner list for each annotaiton made on the frame. Examples -------- >>> classification = {'annotations': [ 'value': [ { 'frame': 0, 'points': [ {'x': 756, 'y': 197}, {'x': 856', y': 197} ], 'details': [ {'value': '[unclear]Cipher[/unclear]'} ], }, { 'frame': 0, 'points': [ {'x': 756, 'y': 97}, {'x': 856, 'y': 97}, {'x': 956, 'y': 97} ], 'details': [ {'value': 'A word'} ], } ]} >>> poly_line_text_extractor(classification) {'frame0': { 'points': {'x': [[756, 856], [756, 856, 956]], 'y': [[197, 197], [97, 97, 97]]}, 'text': [['[unclear]Cipher[/unclear]'], ['A', 'word']] 'slope': [0, 0], 'gold_standard': False }} ''' if dot_freq not in ['word', 'line']: raise ValueError('dot_freq must be either "word" or "line"') blank_frame = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('slope', []), ('gold_standard', gold_standard) ]) extract = OrderedDict() if len(classification['annotations']) > 0: annotation = classification['annotations'][0] for value in annotation['value']: frame = 'frame{0}'.format(value['frame']) extract.setdefault(frame, copy.deepcopy(blank_frame)) text = value['details'][0]['value'] x = [point['x'] for point in value['points']] y = [point['y'] for point in value['points']] if len(x) > 1: with warnings.catch_warnings(): warnings.filterwarnings('error') try: fit = np.polyfit(x, y, 1) y_fit = np.polyval(fit, [x[0], x[-1]]) dx = x[-1] - x[0] dy = y_fit[-1] - y_fit[0] slope = np.rad2deg(np.arctan2(dy, dx)) except np.RankWarning: try: # rotate by 90 before fitting x_tmp = -np.array(y) y_tmp = np.array(x) fit = np.polyfit(x_tmp, y_tmp, 1) y_fit = np.polyval(fit, [x_tmp[0], x_tmp[-1]]) dx = x_tmp[-1] - x_tmp[0] dy = y_fit[-1] - y_fit[0] if dy.round(6) == 0: # convert -0 into 0 so `arctan2` gives the expect results for horizontal lines dy = 0.0 # rotate by -90 to bring back into correct coordinates slope = np.rad2deg(np.arctan2(dy, dx)) - 90 except np.RankWarning: # this is the case where dx = dy = 0 (a line of zero length) slope = 0 if dot_freq == 'word': # NOTE: if `words` + 1 and `points` are different lengths # the extract is not used words = text.split(' ') if len(words) + 1 == len(x): extract[frame]['text'].append(words) extract[frame]['points']['x'].append(x) extract[frame]['points']['y'].append(y) extract[frame]['slope'].append(slope) elif (dot_freq == 'line'): # NOTE: if there are not two `points` the extract is not used if len(x) == 2: extract[frame]['text'].append([text]) extract[frame]['points']['x'].append(x) extract[frame]['points']['y'].append(y) extract[frame]['slope'].append(slope) return extract
C#
UTF-8
1,728
3.203125
3
[]
no_license
using System; using System.Security.Cryptography; using Rij; namespace CommandChecker { public class Checker { //encryption class RijAlgo rij = new RijAlgo(); string output_file_name = "Default_Encrypted.txt"; private void encrypt_with_flags_check(string[] command_params,AesManaged aes) { if (command_params.Length == 3) { string key = Convert.ToBase64String(aes.Key); rij.EncryptFile(command_params[2], output_file_name); Console.WriteLine(key); } else { //save key (in file) flag option } } private void route_valid_command ( AesManaged aes, string[] command_params) { if (command_params[0] == "encrypt" && command_params[1] == "-r") { encrypt_with_flags_check(command_params, aes); } else if (command_params[0] == "encrypt") { Console.WriteLine("Works well"); } else { Console.WriteLine("Invalid Command!"); } } public void route_command(string command , AesManaged aes) { string[] command_params = command.Split(" "); if (command_params[0] == "--help") { } else if (command_params.Length < 2) { Console.WriteLine("Please make sure you provide a second parameter"); } else { route_valid_command(aes,command_params); } } } }
Markdown
UTF-8
6,869
3.234375
3
[]
no_license
### Goal Implement a database design and architecture of a restaurant booking system for web and mobile. ### Assumption & Scope - Neet to manage a restaurant - A restaurant have many branchs with different location - Need to manage open hour of a branch - Need to manage table of a branch - Need to manage reservations - Need to manage guests - Analytics **Example**: - Restaurant A, have two branchs: *branch 01* & *branch 02* - Branch 01, have two sections: - Area A have 3 tables: A01, A02, A03 - Area B have 3 tables: B01, B02, B03 - Branch 02, have two sections: - Floor 1 have 3 tables: F101, F102, F103 - Floor 2 have 3 tables: F201, F202, F203 ![Restaurant](./assets/screenshot/restaurant01.png) ### Architecture ![Architecture](./assets/screenshot/architecture.png) ### Database Schema ![Schema](./assets/screenshot/schema.png) ### Flow create a new reservation ![Reservation](./assets/screenshot/flow_create_reservation.png) ### How to run application - Config file `.env` ``` bash #Config app NODE_ENV=local PORT=4000 DEBUG_LOG=1 # Database SQL_HOST=localhost SQL_DATABASE=postgres SQL_USERNAME=postgres SQL_PASSWORD=password ``` - Install packages: `npm install` - Start Database: `make startDB` or `docker-compose -f docker-compose.yml up -d --build postgres` - Run application: `npm run start` ### API - Get a restaurant info Request: ``` bash curl -H "Content-Type: application/json" http://localhost:4000/api/restaurant/1 ``` Response: ```json { "status": "SUCCESS", "message": "Okie", "data": { "id": 1, "name": "Demo Restaurant", "desciption": "non enim praesent elementum facilisis leo vel fringilla est ullamcorper", "logo": "logo", "hotline": "hotline", "status": "active", "createdAt": "2020-10-12T06:30:25.484Z", "updatedAt": "2020-10-12T06:30:25.484Z" } } ``` - Get a branch info Request: ``` bash curl -H "Content-Type: application/json" http://localhost:4000/api/branch/1 ``` Response: ```json { "status": "SUCCESS", "message": "Okie", "data": { "id": 1, "restaurant_id": 1, "name": "Branch 01", "location": "localtion 01", "status": "active", "hotline": "hotline branch 01", "createdAt": "2020-10-12T06:30:25.501Z", "updatedAt": "2020-10-12T06:30:25.501Z" } } ``` - Get list branchs of a restaurant Request: ``` bash curl -H "Content-Type: application/json" http://localhost:4000/api/branch/restaurant/1 ``` Response: ```json { "status": "SUCCESS", "message": "Okie", "data": [ { "id": 1, "restaurant_id": 1, "name": "Branch 01", "location": "localtion 01", "status": "active", "hotline": "hotline branch 01", "createdAt": "2020-10-12T06:30:25.501Z", "updatedAt": "2020-10-12T06:30:25.501Z" }, { "id": 2, "restaurant_id": 1, "name": "Branch 02", "location": "localtion 02", "status": "active", "hotline": "hotline branch 02", "createdAt": "2020-10-12T06:30:25.501Z", "updatedAt": "2020-10-12T06:30:25.501Z" } ] } ``` - Get list open hours of a branch Request: ``` bash curl -H "Content-Type: application/json" http://localhost:4000/api/openhour/branch/1 ``` Response: ```json { "status": "SUCCESS", "message": "Okie", "data": [ { "id": 1, "branch_id": 1, "day_of_week": 0, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" }, { "id": 2, "branch_id": 1, "day_of_week": 1, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" }, { "id": 3, "branch_id": 1, "day_of_week": 2, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" }, { "id": 4, "branch_id": 1, "day_of_week": 3, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" }, { "id": 5, "branch_id": 1, "day_of_week": 4, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" }, { "id": 6, "branch_id": 1, "day_of_week": 5, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" }, { "id": 7, "branch_id": 1, "day_of_week": 6, "open_time": 600, "close_time": 1380, "last_order": 1140, "createdAt": "2020-10-12T06:30:25.512Z", "updatedAt": "2020-10-12T06:30:25.512Z" } ] } ``` - Submit a reservation Request: ``` bash curl -H "Content-Type: application/json" -X POST http://localhost:4000/api/branch/1/reservation \ -d '{ "reservationDate": "2020-10-15 18:00:00", "adults":2, "children":2, "note": "Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups", "guest": { "firstName": "John", "lastName": "Wick", "email": "john@yopmail.com", "phoneNumber":"+65111111" } }' ``` Response: ```json { "status": "SUCCESS", "message": "Okie", "data": { "id": 1, "branch_id": 1, "guest_id": 1, "reservation_date": "2020-10-15", "reservation_time": "18:00:00", "adults": 2, "children": 2, "note": "Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups", "status": "active", "updatedAt": "2020-10-13T04:32:08.799Z", "createdAt": "2020-10-13T04:32:08.799Z", "table_id": null } } ``` - Get list reservations of branch by date Request: ``` bash curl -H "Content-Type: application/json" http://localhost:4000/api/branch/1/reservation?reservation_date=2020-10-15 ``` Response: ```json { "status": "SUCCESS", "message": "Okie", "data": [ { "id": 2, "branch_id": 1, "guest_id": 1, "table_id": null, "reservation_date": "2020-10-15", "reservation_time": "18:00:00", "adults": 2, "children": 2, "note": "Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups", "status": "active", "createdAt": "2020-10-13T04:22:35.103Z", "updatedAt": "2020-10-13T04:22:35.103Z" } ] } ``` ## Author chuongtrh@gmail.com | [Github](https://github.com/chuongtrh)
Java
UTF-8
349
1.507813
2
[]
no_license
package com.house.variety.modules.system.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.house.variety.modules.system.entity.SysUserOnline; /** * <p> * 在线用户记录 Mapper 接口 * </p> * * @author HuangChao * @since 2018-08-27 */ public interface SysUserOnlineMapper extends BaseMapper<SysUserOnline> { }
C#
UTF-8
943
3.53125
4
[]
no_license
/****************************************************************************** fibonacci 1. *******************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fibonacci { class Program { static void Main(string[] args) { int x = 0; int y = 1; int z; int n; Console.WriteLine("enter step"); n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); Console.WriteLine(x + " " + "\n" + y + " "); for(int i=0; i< n-2; i++) { z = x + y; Console.WriteLine( z ); x = y; y = z; } Console.ReadKey(); //Program sonunda konsolun kapanmaması komutu } } }
Ruby
UTF-8
368
2.515625
3
[]
no_license
class Route < ActiveRecord::Base has_many :route_stops has_many :bus_stops, through: :route_stops scope :most_stops, ->() { order("number_of_stops DESC") } class << self def least_stops select('routes.*, COUNT(bus_stops.id) AS bus_stop_count'). joins(:bus_stops). group('routes.id'). order('bus_stop_count ASC') end end end
Markdown
UTF-8
68,813
3.4375
3
[ "MIT" ]
permissive
# I. Tổng quan ## 1. Kubernetes là gì Kubernetes là một nền tảng mã nguồn mở giúp tự động triển khai, mở rộng và vận hành các app Container trên các nhóm máy chủ, cung cấp cơ sở hạ tầng tập trung vào container. ### Tại sao lại dùng containers ![](https://kubernetes.io/images/docs/why_containers.svg) Cách cũ để triển khai ứng dụng là cài đặt ứng dụng trên một máy chủ sử dụng trình quản lý gói hệ điều hành. Điều này gây khó khăn cho việc thực thi, cấu hình, thư viện, và vòng đời giữa các ứng dụng với nhau và với hệ điều hành của máy chủ. Cách mới là triển khai các container dựa trên OS-level hơn là hardware virtualization. Các container bị cô lập với nhau và từ máy chủ: chúng có hệ thống tệp tin của riêng mình, chúng không thể nhìn thấy tài nguyên của nhau và việc sử dụng tài nguyên tính toán có thể bị giới hạn. Chúng dễ xây dựng hơn các máy ảo, và vì chúng được tách riêng với cơ sở hạ tầng cơ bản, và từ hệ thống tệp tin máy chủ, chúng có thể đi qua clouds và phân bố của hệ điều hành. ## 2. Làm việc với các đối tượng Kubernetes ### 2.1. Tìm hiểu các đối tượng Kubernetes Kubernetes Objects là các thực thể trong hệ thống Kubernetes. Kubernetes sử dụng các thực thể này để biểu thị trạng thái các cluster. Nó mô tả: - Ứng dụng container nào đang chạy (và trên các node nào) - Các tài nguyên sẵn có cho các ứng dụng đó - Những chính sách xung quanh việc cách ứng dụng đó hoạt động, chẳng hạn như khởi động lại chính sách, nâng cấp và khả năng chịu lỗi. Để làm việc với các Kubernetes Objects, như thêm, sửa hoặc xóa chúng - bạn cần phải sử dụng API Kubernetes. #### 2.1.1 Object Spec và Status Mỗi Kubernetes object bao gồm 2 trường đối tượng lồng nhau quản lý cấu hình của đối tượng: object spec và object status. Spec mô tả trạng thái mong muốn của bạn cho đối tượng - các đặc tính mà bạn muốn các đối tượng có. Status mô tả các trạng thái thực tế của các đối tượng, và được cung cấp, cập nhật bởi hệ thống Kubernetes. #### 2.1.2 Mô tả một Kubernetes object Khi tạo một đối tượng trong Kubernetes, bạn phải cung cấp cho object spec mô tả trạng thái mong muốn và một số thông tin cơ bản. Khi bạn sử dụng API Kubernetes để tạo đối tượng (trực tiếp hoặc thông qua `kubectl`), yêu cầu API đó phải bao gồm thông tin là JSON. Thông thường, bạn cung cấp thông tin đến `kubectl` trong tệp **.yaml** Ví dụ: ``` apiVersion: apps/v1beta1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 3 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.7.9 ports: - containerPort: 80 ``` #### 2.1.3 Phần bắt buộc Trong tệp tin **.yaml** của Kubernetes object bạn muốn tạo, bạn cần đặt gía trị cho các trường sau: - `apiVersion` - Phiên bản API Kubernetes nào bạn đang sử dụng để tạo ra đối tượng này - `kind` - Bạn muốn tạo loại đối tượng nào - `metadata` - dữ liệu giúp xác định đối tượng là duy nhất, bao gồm name string, UID và tùy chọn namespace. Bạn cũng cần cung cấp trường object spec. Định dạng đúng của object spec của các Kubernetes object là khác nhau, và chứa các trường lồng nhau của riêng đối tượng đó. ### 2.2 Name Tất cả các đối tượng trong Kubernetes REST API được xác định rõ ràng bởi một tên và một UID. Đối với các thuộc tính non-unique user-provided, Kubernetes cung cấp label và chú thích. #### Name Tên thường được cung cấp bởi khách hàng. Chỉ có một đối tượng của một loại nhất định có thể có một tên được đặt tại một thời điểm. Nhưng nếu bạn xóa một đối tượng, bạn có thể tạo ra một đối tượng mới có cùng tên. Tên được sử dụng trong một tài nguyên URL. #### UIDs UID được tạo ra bởi Kubernetes. Mỗi đối tượng được tạo ra trong toàn bộ vòng đời của một Kubernetes cluster có một UID riêng biệt. ### 2.3 Namespace Kubernetes hỗ trợ nhiều virtual clusters bởi cùng một physical cluster. Các virtual clusters này được gọi là namespace. Namespace giúp cô lập các project, team hay các khách hàng trên cùng 1 cluster với nhau. #### Khi nào sử dụng nhiều namespace Namespace được sử dụng trong môi trường với nhiều người dùng trải rộng trên nhiều nhóm hoặc nhiều project. Đối với các nhóm có một vài đến vài chục người dùng, bạn không cần phải tạo hoặc suy nghĩ về namespace nào cả. Sử dụng namespace khi bạn cần các tính năng mà chúng cung cấp. Namespace cung cấp phạm vi cho tên. Tên của tài nguyên cần phải là duy nhất trong một namespace. Namespace là một cách phân chia các tài nguyên của cluster giữa nhiều lần sử dụng (thông qua resource quota). #### Làm việc với namespace ##### Xem namespace ``` $ kubectl get namespaces NAME STATUS AGE default Active 1d kube-system Active 1d ``` Kubernetes bắt đầu với hai không gian tên ban đầu: - **default** Namespace mặc định cho các đối tượng không có namespace. - **kube-system** Namespace cho các đối tượng được tạo bởi hệ thống Kubernetes ##### Cài đặt namespace cho một request ``` $ kubectl --namespace=<insert-namespace-name-here> run nginx --image=nginx $ kubectl --namespace=<insert-namespace-name-here> get pods ``` ### 2.4 Label Label là cặp key/value gắn liền với các đối tượng, chẳng hạn như pod. Label được sử dụng để xác định thuộc tính của các đối tượng có ý nghĩa và có liên quan đến người dùng. Label có thể được sử dụng để tổ chức và chọn các tập hợp con của đối tượng. Label có thể gắn liền với đối tượng trong thời gian tạo và có thể thêm hoặc sửa đổi bất kỳ lúc nào. Mỗi đối tượng có thể có một bộ label key/value được xác định. Mỗi key phải là duy nhất cho một đối tượng. ### 2.5 Annotations Bạn có thể chọn label hoặc annotation để đính kèm metadata vào đối tượng Kubernetes. Label có thể được sử dụng để chọn các đối tượng và tìm các collection của đối tượng đáp ứng được một số điều kiện nhất định. Ngược lại các annotation không được sử dụng để xác định và chọn đối tượng. Metadata trong annotation có thể nhỏ hoặc lớn, có cấu trúc hoặc không có cấu trúc và có thể bao gồm các ký tự mà label không cho phép. # II. Kubernetes Architecture ## 1.Nodes ### Định nghĩa Một node là một worker machine trong Kubernetes. Một node có thể là một máy ảo hoặc máy vật lý, tùy thuộc vào cluster. Mỗi node có các dịch vụ cần thiết để chạy các pod và được quản lý bởi master conponent. Các dịch vụ trên một node bao gồm Docker, kubelet và kube-proxy. ### Trạng thái node Trạng thái node chứa các thông tin sau: - Addresses - Phase - Condition - Capacity - Info #### Addresses Việc sử dụng các trường này tùy thuộc vào nhà cung cấp cloud của bạn hoặc bare metal configuration. - HostName: Tên máy chủ lưu trữ được report bởi nhân của node. Có thể được ghi đè bằng tham số **`--hostname-override`**. - ExternalIP: Thông thường địa chỉ IP của node có thể được định tuyến bên ngoài (có sẵn từ bên ngoài cluster). - InternalIP: Thông thường địa chỉ IP của node chỉ có thể định tuyến trong cluster. #### Phase Node phase không còn được sử dụng. #### Condition Trường Condition mô tả trạng thái của tất cả các node đang chạy | Node Condition | Description | | ------ | ------ | | OutOfDisk | **True** nếu không có đủ không gian trống trên node để thêm các pod mới, ngược lại là **False**| | Ready | **True** nếu node đó khỏe mạnh và sẵn sàng chấp nhận pod, **False** nếu node không khỏe mạnh và không chấp nhận pod, **Unknown** nếu node controller không nghe thấy từ node trong 40 giây cuối| | MemoryPressure | **True** nếu node không có sức ép memory, ngược lại là **False**| | DiskPressure | **True** nếu không có sức ép disk, ngược lại là **False** | #### Capacity Mô tả các tài nguyên sẵn có trên node: CPU, bộ nhớ và số lượng tối đa các pod có thể được lên kế hoạch trên node. #### Info Thông tin chung về node, chẳng hạn như phiên bản kernel, phiên bản Kubernetes (phiên bản kubelet và kube-proxy), phiên bản Docker (nếu được sử dụng), tên hệ điều hành. Info được thu thập bởi Kubelet từ node. ### Management Không giống như pod và các service, một node vốn không phải được tạo ra bởi Kubernetes: nó được tạo ra từ bên ngoài bởi các nhà cung cấp cloud, hoặc tồn tại trong pool của máy vật lý hay máy ảo. Khi Kubernetes tạo ra một node, nó chỉ là tạo ra một đối tượng đại diện cho node. Sau khi tạo, Kubernetes sẽ kiểm tra xem node có hợp lệ hay không. Nếu hợp lệ, nó có đủ điều kiện để chạy một pod. Nếu không hợp lệ, nó sẽ bị bỏ qua trong các hoạt động của cluster. Lưu ý rằng, Kubernetes sẽ gĩư lại các node không hợp lệ, trừ khi nó bị xóa bởi client, và nó sẽ tiếp tục kiểm tra xem node có hợp lệ hay không. Hiện tại, có ba thành phần tương tác với giao diện Kubernetes node: node controller, kubelet và kubectl. #### Node Controller Node Controller là một Kubernetes master component quản lý các khía cạnh khác nhau của các node. Node Controller có nhiều vai trò trong vòng đời của một Node. Đầu tiên là gán một khối CIDR cho node khi nó được tạo (nếu CIDR được bật). Thứ hai là duy trì danh sách bên trong node controller của node cập nhật với danh sách các máy có sẵn của nhà cung cấp cloud. Thứ ba là theo dõi tình trạng của các node. Node controller có trách nhiệm cập nhật trạng thái NodeReady của NodeStatus thành ConditionUnknown nếu không thể truy cập được node. #### Tự tạo node Khi **`--register-node`** là true, kubelet sẽ cố gắng đăng ký chính nó với API server. Để tự đăng ký, kubelet được bắt đầu với các option: - **`--api-servers`** Vị trí của apiserver. - **`--kubeconfig`** Đường dẫn tới các chứng chỉ để xác thực chính nó với apiserver. - **`--cloud-provider`** Cách nói chuyện với nhà cung cấp cloud để đọc metadata về chính nó. - **`--register-node`** Tự động tạo với API server - **`--register-with-taints`** Tạo các node với danh sách các taints nhất định - **`--node-ip`** Địa chỉ IP của node. - **`--node-labels`** Label để thêm khi tạo node trong cluster. - **`--node-status-update-frequency`** Xác định tần suất kubelet posts node status đến master. #### Node capacity Dung lượng của node (số lượng CPU và dung lượng bộ nhớ) là một phần của đối tượng node. Thông thường, các node tự tạo và báo cáo dung lượng của chúng khi tạo đối tượng node. Nếu quản lý node thủ công thì bạn cần thiết lập dung lượng node khi thêm node. ## 2. Master-Node communication ### Tổng quan Tài liệu này liệt kê các đường dẫn truyền thông giữa các master (apiserver) và Kubernetes cluster. Mục đích là để cho phép người dùng tùy chỉnh cài đặt để làm cứng cấu hình mạng sao cho cluster có thể chạy trên một mạng không đáng tin cậy (hoặc trên các IP công cộng trên một nhà cung cấp cloud). ### Cluster -> Master Tất cả các đường dẫn truyền thông từ cluster đến master sẽ kết thúc tại apiserver (không có master component nào được thiết kế để expose các dịch vụ từ xa). Các apiserver được cấu hình để lắng nghe các kết nối từ xa trên một cổng HTTPS an toàn (443) với một hoặc nhiều form client xác thực được kích hoạt. Node cần được cung cấp với chứng chỉ root công khai cho cluster sao cho chúng có thể kết nối an toàn với apiserver cùng với chứng chỉ client hợp lệ. Pod muốn kết nối với apiserver có thể thực hiện bằng cách tận dụng tài khoản dịch vụ để Kubernetes tự động chèn vào chứng chỉ root công cộng và một token hợp lệ vào pod khi nó được khởi tạo. Các dịch vụ `kubernetes` (trong tất cả các namespace) được cấu hình với một địa chỉ IP ảo và được chuyển hướng (thông qua Kube-proxy) cho HTTPS endpoints trên apiserver. Các master component kết nối với cluster apiserver qua cổng không an toàn (không được mã hóa hoặc chứng thực). Cổng này thường chỉ được hiển thị trên giao diện localhost của máy chủ, do đó các master component, tất cả chạy trên cùng một máy, có thể giao tiếp với cluster apiserver. Theo thời gian, các master component sẽ được di chuyển để sử dụng cổng an toàn với xác thực và ủy quyền. ### Master -> Cluster Có hai đường liên lạc chính từ master (apiserver) đến cluster. Đầu tiên là từ apiserver đến quá trình kubelet chạy trên mỗi node trong cluster. Thứ hai là từ apiserver đến node, pod hoặc service bất kỳ thông qua chức năng proxy của apiserver. #### Apiserver -> kubelet Các kết nối từ apiserver đến kubelet được sử dụng để tìm kiếm các bản ghi cho các pod, gắn kết (thông qua kubectl) với các pod đang chạy, và sử dụng chức năng kubelet port-forwarding. Các kết nối này kết thúc tại điểm cuối HTTPS của kubelet. Theo mặc định, máy apiserver không xác minh chứng chỉ phục vụ của kubelet, làm cho kết nối này bị tấn công man-in-the-middle, và không an toàn khi chạy qua các mạng không tin cậy và/hoặc mạng public. Để xác minh kết nối này, sử dụng **`--kubelet-certificate-authority`** để cung cấp cho apiserver một gói chứng chỉ root để sử dụng để xác minh chứng chỉ phục vụ của kubelet. Nếu không thể, sử dụng đường hầm SSH giữa apiserver và kubelet để tránh kết nối qua mạng không tin cậy hoặc mạng public. Cuối cùng,Kubelet xác thực và/hoặc ủy quyền được kích hoạt để đảm bảo API kubelet. #### Apiserver -> node, pod và service Các kết nối từ apiserver đến node, pod hoặc service mặc định là kết nối HTTP thông thường, do đó không được chứng thực hay mã hóa. #### Đường hầm SSH Google Container Engine sử dụng đường hầm SSH để bảo vệ đường dẫn truyền thông của Master -> Cluster. Trong này, apiserver sẽ khởi tạo một đường hầm SSH tới mỗi node trong cluster (kết nối đến máy chủ ssh nghe trên cổng 22) và truyền tất cả các lưu lượng cho một kubelet, node, pod, hoặc service qua đường hầm. # III. Containers ## 1. Images Bạn tạo image Docker và push nó vào một registry trước khi đề cập đến nó trong Kubernetes pod. Tính chất **image** của một container hỗ trợ cú pháp giống như lệnh **docker**. ### Updating Images Kubernetes sẽ không pull một image nếu nó đã tồn tại. Nếu bạn không chỉ định tag của image, nó sẽ được gỉa sử là **`:latest`**. Lưu ý rằng bạn nên tránh sử dụng **`:latest`** tag. ## 2. Container Environment Variables ### Container environment Môi trường container Kubernetes cung cấp một số tài nguyên quan trọng cho container: - Một hệ thống tệp tin, là sự kết hợp của một image và một hoặc nhiều volumes. - Thông tin về chính container - Thông tin về các đối tượng khác trong cluster. #### Thông tin container Tên hostname của một container là tên của Pod, trong đó container đang chạy. Nó có sẵn thông qua lệnh **hostname** hay gọi hàm `gethostname` trong libc. Tên Pod và không gian tên có sẵn dưới dạng các biến môi trường thông qua **downward API**. #### Thông tin cluster Một danh sách chứa tất cả các service đang chạy khi một container được tạo ra là có sẵn cho container đó như các biến môi trường. Những biến môi trường phù hợp với cú pháp của liên kết Docker. ## 3. Container Lifecycle Hooks Tương tự như nhiều framework ngôn ngữ lập trình có component lifecycle hooks, Kubernetes cung cấp Containers với các lifecycle hooks. Hooks cho phép Container nhận biết được các sự kiện trong vòng đời quản lý của chúng và code được thực hiện trong một handler khi hook lifecycle tương ứng được thực thi. ### Container hooks Có 2 hooks được tiếp xúc với Containers: **PostStart** Hook này thực hiện ngay sau khi một container được tạo ra. Tuy nhiên không có gì đảm bảo rằng hook này sẽ thực thi trước container ENTRYPOINT. Không có tham số nào được truyền cho handler. **PreStop** Hook này được gọi ngay trước khi container được kết thúc. Đó là chặn, có nghĩa là nó đồng bộ, do đó nó phải hoàn thành trước khi lời gọi xóa các container được gửi. Không có tham số nào được truyền cho handler. #### Hook xử lý triển khai Container có thể truy cập vào hook bằng cách thực hiện và tạo một handler cho hook đó. Có 2 loại hook xử lý có thể được thực hiện cho container: - Exec - Thực hiện một lệnh cụ thể, chẳng hạn như **`pre-stop.sh`** bên trong cgroups và namespace của container. Tài nguyên được tiêu thụ bởi lệnh này được tính vào container. - HTTP - Thực hiện một HTTP request đối với một endpoint xác định trên container. #### Hook xử lý thực hiện Khi một hook quản lý vòng đời của container được gọi, hệ thống quản lý Kubernetes sẽ thực hiện xử lý trong container được tạo ra bởi hook đó. Hook xử lý các lời gọi được đồng bộ trong bối cảnh của Pod chứa container. Điều này có nghĩa là đối với hook **`PostStart`**, container ENTRYPOINT và hook fire không đồng bộ. Tuy nhiên nếu hook mất quá nhiều thời gian để chạy hoặc treo, container sẽ không đạt được trạng thái **`running`**. Tương tự đối với hook **`PreStop`**. Nếu hook treo trong quá trình thực hiện, Pod sẽ ở trạng thái **`running`** và không bị **`failed`**. Nếu một hook **`PostStart`** hoặc **`PreStop`** bị lỗi, container sẽ bị chết. # IV. Workloads ## 1. Pods ### 1.1 Tổng quan về Pod Pod là khối xây dựng cơ bản của Kubernetes - đơn vị nhỏ nhất và đơn giản nhất trong mô hình đối tượng Kubernetes mà bạn tạo ra hoặc triển khai. Một Pod đại diện cho một tiến trình đang chạy trên cluster của bạn. Một Pod bao gồm một app container (hoặc nhiều container), các tài nguyên lưu trữ, một mạng IP duy nhất và các option để tùy chỉnh các container. Một Pod đại diện cho một đơn vị triển khai: một ví dụ của một ứng dụng trong Kubernetes, có thể có một container đơn hoặc một số lượng nhỏ các container được kết nối chặt chẽ và chia sẻ tài nguyên. Pods được sử dụng theo một số cách trong Kubernetes cluster như sau: - Pods chạy một container: Mô hình "one-container-per-Pod" là trường hợp phổ biến nhất. Trong đó Pods như một cái vỏ bao xung quanh container, và Kubernetes quản lý Pods chứ không trực tiếp quản lý container. - Pods chạy nhiều container cùng làm việc với nhau: Một Pod có thể gói gọn một ứng dụng bao gồm nhiều container được kết nối chặt chẽ và cần chia sẻ tài nguyên. Pod bao gồm các container và các tài nguyên lưu trữ như một thực thể và quản lý nó. Mỗi Pod chạy một thể hiện duy nhất của một ứng dụng nhất định. Nếu bạn muốn scale ứng dụng theo chiều ngang (ví dụ chạy nhiều thể hiện), bạn nên sử dụng nhiều Pods, một Pod cho một thể hiện. Trong Kubernetes, điều này thường được gọi là sao chép . Các bản sao lặp lại thường được tạo và quản lý bởi một nhóm trừu tượng gọi là Controller. #### Làm thế nào Pods quản lý nhiều Containers Pods được thiết kế để hỗ trợ nhiều quá trình hợp tác (như container) tạo thành một đơn vị kết hợp của service. Các container trong một Pod được tự động định vị và lập lịch trên cùng một máy ảo hoặc vật lý trong cluster. Các container có thể chia sẻ tài nguyên, phụ thuộc, giao tiếp và phối hợp với nhau. Lưu ý rằng nhóm nhiều co-located và co-managed trong một pod đơn là một trường hợp sử dụng tương đối khó. Bạn chỉ nên sử dụng nó trong các trường hợp cụ thể mà trong đó các container được liên kết chặt chẽ. Ví dụ: bạn có thể có một container hoạt động giống như một web server cho các file trong một volume chia sẻ, và một container "sidecar" riêng biệt cập nhật các file đó từ một nguồn từ xa, như trong sơ đồ sau: ![](https://kubernetes.io/images/docs/pod.svg) Pods cung cấp hai loại tài nguyên chia sẻ: networking và storage ##### Networking Mỗi Pod được gán một địa chỉ IP duy nhất. Các container trong một Pod chia sẻ network namespace bao gồm địa chỉ IP và cổng mạng, có thể giao tiếp với nhau thông qua **`localhost`**. Khi các container giao tiếp với các thực thể bên ngoài, chúng phải sử dụng tài nguyên mạng chia sẻ (như các cổng). ##### Storage Một Pod có thể chỉ định một tập hợp các volume lưu trữ chia sẻ. Tất cả các container trong Pod có thể truy cập đến các volume chia sẻ, cho phép các container chia sẻ dữ liệu. Volumes cũng cho phép dữ liệu tồn tại khi một container khởi động lại. #### Làm việc với Pod Không nên nhầm lẫn giữa việc khởi động lại container trong Pod với việc khởi động lại Pod. Bản thân Pod không chạy, nhưng nó là môi trường để các container hoạt động và tồn tại đến khi nó bị xóa. Pod không có khả năng tự phục hồi. Nếu một Pod được lập lịch đến một Node không thành công, hoặc nếu bản thân quá trình lập lịch không thành công, Pod sẽ bị xóa. Tương tự, Pod sẽ không tồn tại nếu nó gặp trục trặc do thiếu tài nguyên hoặc bảo trì Node. ##### Pod and Controller Một Controller có thể tạo và quản lý nhiều Pod, xử lý nhân rộng, triển khai và cung cấp khả năng self-healing ở phạm vi cluster. Ví dụ: nếu một Node bị lỗi, Controller có thể tự động thay thế Pod bằng cách lập lịch một sự thay thế giống nhau trên một Node khác. Một vài ví dụ của Controller chứa một hoặc nhiều Pod bao gồm: - Deployment - StatefulSet - DaemonSet ### 1.2 Pod Lifecycle #### Pod phase Pod phase là một bản tóm tắt đơn giản, cấp cao về nơi Pod ở trong vòng đời của nó. Các giá trị có thể có cho **`phase`**: - Pending: Pod đã được chấp nhận bởi hệ thống Kubernetes nhưng một hoặc nhiều image container không được tạo ra. Điều này bao gồm thời gian trước khi được lập lịch cũng như thời gian tải các image, sẽ mất một khoảng thời gian. - Running: Pod đã được ràng buộc với một node, và tất cả các container đã được tạo. Ít nhất một container vẫn đang chạy, hoặc đang trong quá trình khởi động hoặc khởi động lại. - Succeeded: Tất cả các container trong Pods đã kết thúc thành công, và sẽ không được khởi động lại. - Failed: Tất cả các Container trong Pod đã bị kết thúc, và ít nhất một Container đã bị hủy. Tức là, Container hoặc đã thoát với trạng thái khác 0 hoặc đã bị hệ thống kết thúc. - Unknown: Đối với một số lý do, trạng thái của Pod không thể đạt được, thông thường do một lỗi trong giao tiếp với các máy chủ của Pod. #### Pod condition Mỗi Pod có một PodStatus, trong đó có một mảng PodCondition. Mỗi phần tử của mảng PodCondition có một trường **`type`** và một trường **`status`**. Trường **`type`** là một chuỗi, với gía trị có thể: PodScheduled, Ready, Initialized và Unschedulable. Trường **`status`** là một chuỗi, với gía trị có thể: True, False và Unknown. #### Container probes Một Probe là một chuẩn đoán được thực hiện định kỳ bởi kubelet trên một container. Để thực hiện một chuẩn đoán, kubelet gọi một Handler được thực hiện bởi Container. Có 3 loại handler: - ExecAction: Thực hiện một lệnh được chỉ định bên trong Container. Chuẩn đoán là thành công nếu lệnh xuất hiện với mã trạng thái là 0. - TCPSocketAction: Thực hiện kiểm tra TCP với địa chỉ IP của Container trên một cổng được chỉ định. Chuẩn đoán là thành công nếu cổng mở. - HTTPGetAction: Thực hiện một HTTP Get request với địa chỉ IP của Container trên một cổng và đường dẫn được chỉ định. Chuẩn đoán là thành công nếu response có mã trạng thái >= 200 và < 400. Mỗi một probe có một trong ba kết quả: - Success: Container vượt qua việc chuẩn đoán. - Failure: Container thất bại trong việc chuẩn đoán. - Unknown: Chuẩn đoán không thành công, do đó không có hành động nào được thực hiện. Kubelet có thể tùy ý thực hiện và phản ứng với 2 loại probe khi chạy container: - **`livenessProbe`**: Cho biết container đang chạy hay không. Nếu liveness probe không thành công, kubelet sẽ kill Container, và Container phải tuân theo chính sách khởi động lại của nó. Nếu một Container không cung cấp một liveness probe, trạng thái mặc định là **`Success`**. - **`readinessProbe`**: Cho biết Container đã sẵn sàng để yêu cầu dịch vụ hay không. Nếu readiness probe không thành công, endpoint controller sẽ xóa địa chỉ IP của Pod khỏi các endpoint của tất cả các service ứng với Pod. ### 1.3 Init Containers #### Tìm hiểu Init Container Một Pod có thể có nhiều Container chạy các ứng dụng bên trong nó, nhưng nó cũng có thể có một hoặc nhiều Init Container, được chạy trước khi app Containers được chạy. Init container giống với container thông thường, ngoại trừ: - Chúng luôn chạy đến khi kết thúc - Mỗi cái phải kết thúc thành công trước khi cái tiếp theo được bắt đầu Nếu một Init Container chạy thất bại, Kubernetes khởi động lại Pod cho đến khi Init Container thành công. Tuy nhiên, nếu trường **`restartPolicy`** của Pod có gía trị Never thì không phải khởi động lại. Để chỉ định là một Init Container, hãy thêm trường **`initContainers`** trên PodSpec dưới dạng mảng JSON của các đối tượng thuộc loại v1.Container bên cạnh mảng app container. Trạng thái của các Init Container được trả về trong trường **`status.initContainerStatuses`** như một mảng các trạng thái container (tương tự như trường **`status.containerStatues`**). ##### Khác biệt với các container thông thường Init Containers hỗ trợ tất cả các lĩnh vực và tính năng của app container, bao gồm giới hạn tài nguyên, volumes và cài đặt bảo mật. Tuy nhiên các yêu cầu và giới hạn về tài nguyên của một Init Container được xử lý hơi khác. Ngoài ra Init Container không hỗ trợ readiness probes bởi vì chúng phải chạy đến khi kết thúc trước khi Pod có thể sẵn sàng. Nếu có nhiều Init Container được chỉ định cho một Pod, những container này sẽ được chạy tuần tự. Cái trước phải chạy thành công trước khi cái sau chạy. Khi tất cả các Init Container kết thúc, Kubernetes sẽ khởi tạo Pod và chạy app Container như bình thường. #### Init Container có thể được sử dụng để làm gì Vì các Init Container chứa các image riêng biệt từ các app container, chúng có một số start-up related code: - Chúng có thể chứa và chạy các tiện ích không mong muốn bao gồm app container image với lý do bảo mật. - Chúng có thể chứa các tiện ích hoặc custom code để thiết lập những cái không có trong app image. Ví dụ không cần phải làm một image **`FROM`** image khác chỉ để sử dụng tool như **`sed`**, **`awk`**, **`python`**, **`dig`** trong quá trình cài đặt. - The application image builder và deployer roles có thể hoạt động độc lập mà không cần phải cùng nhau xây dựng một app image. - Chúng sử dụng Linux namespaces để có các cách khác nhau có thể xem hệ thống tệp tin từ các app Container. Do đó, chúng có thể được cấp quyền truy cập đến Secret mà các app Container không thể truy cập. - Chúng chạy đến khi hoàn thành trước khi bất kỳ app Containers nào bắt đầu, trong khi đó app Containers chạy song song, do đó Init Container cung cấp một cách đơn giản để chặn hoặc trì hoãn việc khởi động app Containers cho đến khi một số điều kiện tiên quyết được đáp ứng. ##### Init Container in use Ta sẽ tạo ra 1 pod đơn giản trong đó có 2 Init Container. Đầu tiên là **`myservice`**, tiếp theo là **`mydb`**. Khi cả 2 container này hoàn thành, Pod sẽ bắt đầu. Với phiên bản Kubernetes v1.6: ``` apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: myapp spec: containers: - name: myapp-container image: busybox command: ['sh', '-c', 'echo The app is running! && sleep 3600'] initContainers: - name: init-myservice image: busybox command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;'] - name: init-mydb image: busybox command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;'] ``` #### Detailed behavior Trong quá trình khởi động của một Pod, Init Containers được khởi động theo thứ tự, sau khi network và volume được khởi tạo. Một Pod không thể **`Ready`** nếu tất cả các Init container chưa thành công. Nếu Pod khởi động lại, tất cả Init Containers sẽ thực hiện lại. Các thay đổi đối với Init Container spec được giới hạn trong trường container image. Thay đổi trường container image bằng với việc khởi động lại Pod. Tên của mỗi app và Init Container trong một Pod phải là duy nhất. ##### Lý do Pod khởi động lại Một Pod có thể khởi động lại, gây ra việc thực hiện lại các Init Containers, vì những lý do sau: - Một người dùng cập nhật PodSpec làm cho Init Container image thay đổi. Thay đổi app Container image chỉ khởi động lại app Container. - Pod infrastructure container được khởi động lại. Điều này ít khi xảy ra và phải được thực hiện bởi một người có quyền truy cập root vào các Node. - Tất cả các container trong Pod bị ngắt, trong khi **`restartPolicy`** được thiết lập là Always, bắt buộc phải khởi động lại và bản ghi hoàn thành của Init Container đã bị mất do thu gom rác. ## 2. Controller ### 2.1. Replica Sets ReplicaSet là thế hệ kế tiếp của Replication Controller. Sự khác biệt duy nhất giữa ReplicaSet và Replication Controller là selector support. ReplicaSet hỗ trợ các yêu cầu new set-based selector. Trong khi Replication Controller chỉ hỗ trợ các yêu cầu equality-based selector. ### 2.2. Replication Controller Một Replication Controller đảm bảo rằng một pod hay homogeneous set (bộ đồng nhất) của pod luôn sẵn sàng và sẵn có. Nếu có quá nhiều pod, nó sẽ xóa bớt đi, nếu có quá ít, nó sẽ khởi động nhiều hơn. Không giống như các pod được tạo thủ công, các pod được duy trì bởi một ReplicationController sẽ tự động được thay thế nếu chúng bị lỗi, bị xóa hoặc bị kết thúc. Một trường hợp đơn giản là tạo một đối tượng ReplicationController để chạy một thể hiện của một Pod. Một trường hợp sử dụng phức tạp hơn là chạy một số bản sao giống nhau của một replicated service, ví dụ như các web server. #### Ví dụ một ReplicationController Đây là một ví dụ cấu hình ReplicationController. Nó chạy 3 bản sao của nginx web server. ``` apiVersion: v1 kind: ReplicationController metadata: name: nginx spec: replicas: 3 selector: app: nginx template: metadata: name: nginx labels: app: nginx spec: containers: - name: nginx image: nginx ports: - containerPort: 80 ``` #### Viết một ReplicationController Spec ##### Pod Template **`.spec.template`** là trường bắt buộc duy nhất của **`.spec`**. **`.spec.template`** là một pod template. Nó giống như schema của Pod, ngoại trừ nó được lồng và không có **`apiVersion`** hoặc **`kind`**. Ngoài các trường bắt buộc của Pod, pod template trong một ReplicationController phải chỉ rõ label thích hợp (nghĩa là không chồng chéo với các controller khác) và chính sách khởi động lại thích hợp. **`.spec.template.spec.restartPolicy`** chỉ được phép là **`Always`**. là default nếu nó không được chỉ định. ##### Labels trên ReplicationController Các ReplicationController có thể tự nó có label (**`.metadata.labels`**). Thông thường bạn sẽ thiết lập nó là **`.spec.template.metadata.labels`**; nếu **`metadata.labels`** không được chỉ định thì nó sẽ mặc định là **`.spec.template.metadata.labels`**. Tuy nhiên chúng được cho phép khác nhau, và **`metadata.labels`** không ảnh hưởng đến hành vi của ReplicationController. ##### Pod Selector Trường **`.spec.selector`** là một label selector. Một replication controller quản lý tất cả các pod với các label khớp với selector. Nó không phân biệt việc các pod được tạo ra hay bị xóa do nó làm hay do người khác hoặc quá trình làm. Điều này cho phép ReplicationController được thay thế mà không ảnh hưởng đến các pod đang chạy. Nếu được chỉ định, **`.spec.template.metadata.labels`** phải bằng **`.spec.selector`**, hoặc nó sẽ bị API từ chối. Nếu **`.spec.selector`** không xác định, nó sẽ được mặc định là **`.spec.template.metadata.labels`**. ##### Multiple Replicas Bạn có thể chỉ định số lượng các Pod chạy đồng thời bằng cách thiết lập **`.spec.replicas`**. Nếu không chỉ định, **`.spec.replicas`** mặc định là 1. #### Làm việc với ReplicationControllers ##### Xóa một ReplicationController và các Pod của nó Để xóa một ReplicationController và tất cả các Pod của nó, sử dụng **`kubectl delete`**. Kubectl sẽ scale ReplicationController về 0 và chờ cho nó xóa từng Pod trước khi xóa ReplicationController. Nếu lệnh này bị ngắt, nó có thể được khởi động lại. ##### Chỉ xóa một ReplicationController Bạn có thể xóa một ReplicationController mà không ảnh hưởng đến các Pod của nó. Sử dụng **`kubectl delete`** với option **`cascade=false`**. Khi sử dụng REST API hoặc go client library, chỉ cần xóa đối tượng ReplicationController. Một khi bản gốc bị xóa, bạn có thể tạo một ReplicationController mới để thay thế. Miễn **`.spec.selector`** của bản cũ và bản mới là như nhau, sau đó bản mới sẽ chấp nhận các Pod cũ. Tuy nhiên nó sẽ không thực hiện bất kỳ điều gì để làm cho các Pod hiện có phù hợp với một pod template khác. ##### Cô lập các Pod từ một ReplicationController Pods có thể được xóa bỏ từ một ReplicationController's target set bằng cách thay đổi label của chúng. Kỹ thuật có thể sử dụng để loại bỏ các Pod từ service để debugging, phục hồi dữ liệu,... Các Pod được gỡ bỏ theo cách này sẽ được thay thế tự động (gỉa sử số lượng các replicas không thay đổi). ### 2.3. Deployment Deployment cung cấp thông tin cập nhật cho Pods và ReplicaSets. Bạn chỉ cần mô tả trạng thái mong muốn trong một đối tượng Deployment, và Deployment controller sẽ thay đổi trạng thái thực tế sang trạng thái mong muốn với tỷ lệ được kiểm soát. Bạn có thể định nghĩa các Deployment để tạo mới ReplicaSets, hoặc gỡ bỏ Deployments hiện tại và sử dụng tất cả các tài nguyên của nó cho Deployments mới. #### Tạo Deployment Ví dụ: ``` apiVersion: apps/v1beta1 # for versions before 1.6.0 use extensions/v1beta1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 3 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.7.9 ports: - containerPort: 80 ``` Chạy ví dụ bằng lệnh: ``` $ kubectl create -f docs/user-guide/nginx-deployment.yaml --record deployment "nginx-deployment" created ``` ### 2.4 StatefulSets StatefulSets là một Controller cung cấp định dạng duy nhất cho Pods của nó. Nó cung cấp bảo đảm về thứ tự deployment và scaling. #### Sử dụng StatefulSets StatefulSets đáp ứng yêu cầu của application: - Stable, xác định mạng duy nhất - Stable, lưu trữ liên tục - Ordered, graceful deployment và scale - Ordered, graceful deletion và termination. Stabe đồng nghĩa với sự kiên trì trong việc lập lịch Pod (lại). #### Các thành phần Ví dụ dưới đây thể hiện các thành phần của StatefulSet - Một Headless Service tên là nginx, được sử dụng để kiểm soát miền mạng. - StatefulSet tên là web, Spec chỉ ra rằng có 3 replicas của các container nginx. - VolumeClaimTemplates cung cấp stable storage bằng cách sử dụng PersistentVolumes được cung cấp bởi một PersistentVolume Provisioner. ``` apiVersion: v1 kind: Service metadata: name: nginx labels: app: nginx spec: ports: - port: 80 name: web clusterIP: None selector: app: nginx --- apiVersion: apps/v1beta1 kind: StatefulSet metadata: name: web spec: serviceName: "nginx" replicas: 3 template: metadata: labels: app: nginx spec: terminationGracePeriodSeconds: 10 containers: - name: nginx image: gcr.io/google_containers/nginx-slim:0.8 ports: - containerPort: 80 name: web volumeMounts: - name: www mountPath: /usr/share/nginx/html volumeClaimTemplates: - metadata: name: www annotations: volume.beta.kubernetes.io/storage-class: anything spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi ``` ### 2.5 DaemonSet DaemonSet đảm bảo tất cả (hoặc một số) node chạy một bản sao của một pod. Khi một node được thêm vào cluster, các pod sẽ được thêm vào. Xóa một DaemonSet sẽ xóa các Pod do nó tạo ra. Một số sử dụng điển hình của DaemonSet: - Chạy một daemon lưu trữ cluster, chẳng hạn như **`glusterd`**, **`ceph`** trên mỗi node. - Chạy một logs collection daemon trên mỗi node, chẳng hạn như **`fluentd`** hoặc **`logstash`** - Chạy một node monitoring daemon trên mỗi node ### 2.6 PetSet Mục tiêu của PetSet là tách riêng sự phụ thuộc bằng cách gán các đặc điểm nhận dạng cho các thể hiện riêng biệt của một ứng dụng không bị gắn kết với cơ sở hạ tầng vật chất bên dưới. **Mối quan hệ giữa Pets và Pods**: PetSet yêu cầu có {0...N-1} Pets. Mỗi Pet có một tên xác định - PetSetName-Ordinal và một định danh duy nhất. Mỗi Pet có nhiều nhất một Pod, và mỗi PetSet có tối đa một Pet với một định danh nhất định. #### Ví dụ về PetSet ``` # A headless service to create DNS records apiVersion: v1 kind: Service metadata: name: nginx labels: app: nginx spec: ports: - port: 80 name: web # *.nginx.default.svc.cluster.local clusterIP: None selector: app: nginx --- apiVersion: apps/v1alpha1 kind: PetSet metadata: name: web spec: serviceName: "nginx" replicas: 2 template: metadata: labels: app: nginx annotations: pod.alpha.kubernetes.io/initialized: "true" spec: terminationGracePeriodSeconds: 0 containers: - name: nginx image: gcr.io/google_containers/nginx-slim:0.8 ports: - containerPort: 80 name: web volumeMounts: - name: www mountPath: /usr/share/nginx/html volumeClaimTemplates: - metadata: name: www annotations: volume.alpha.kubernetes.io/storage-class: anything spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi ``` # V. Configuration ## 1. Configuration Best Practices ### General Config Tips - Khi xác định cấu hình, chỉ định phiên bản API ổn định mới nhất. - File cấu hình nên được lưu trữ trong version controll trước khi được push vào cluster. Điều này cho phép nhanh chóng roll-back lại cấu hình nếu cần. Nó cũng hỗ trợ việc tái tạo và khôi phục lại cluster nếu cần thiết. - Viết các file cấu hình bằng YAML chứ không phải JSON. Mặc dù các định dạng này có thể thay thế cho nhau, nhưng YAML có xu hướng thân thiện hơn. - Nhóm các đối tượng liên quan vào một file. Một file thường dễ quản lý hơn nhiều file. - Không chỉ định các gía trị mặc định không cần thiết, để đơn giản hóa, giảm bớt cấu hình và giảm lỗi. Ví dụ: bỏ qua selector và label trong **`ReplicationController`** nếu bạn muốn chúng giống như label **`podTemplate`**, vì các trường đó được nhập từ label **`podTemplate`** theo mặc định. - Đặt một mô tả đối tượng trong một annotation để cho phép theo dõi tốt hơn. ### Services - Tốt nhất là tạo ra một service trước các replication controller tương ứng. Điều này cho phép scheduler phân bố các pod bao gồm service. Bạn cũng có thể sử dụng quá trình này để đảm bảo rằng ít nhất một replica hoạt động trước khi tạo ra nhiều hơn: 1. Tạo một replication controller mà không cần xác định replicas (điều này sẽ thiết lập replicas = 1) 2. Tạo một service 3. Sau đó scale up replication controller - Không sử dụng **`hostPort`** trừ khi cần thiết (ví dụ: cho một node daemon). Nó chỉ định số cổng để expose trên máy chủ. Nếu bạn cần expose mọt cổng của Pod hãy xem xét sử dụng NodePort trước khi sử dụng hostPort. - Tránh sử dụng **`hostNetwork`**, vì những lý do tương tự như **`hostPort`** - Sử dụng các headless service để tìm service dễ dàng khi bạn không cần kube-proxy cân bằng tải. ### Sử dụng labels - Labels xác định thuộc tính ngữ nghĩa của ứng dụng hoặc deployment. Ví dụ thay vì gán label vào một tập các pod để mô tả một số service (ví dụ: **service: myservice**), hoặc mô tả cho replication controller quản lý các pod (ví dụ **controller: mycontroller**), hãy đính kèm các label xác định thuộc tính ngữ nghĩa. Điều này sẽ cho phép bạn chọn các nhóm đối tượng thích hợp. - Bạn có thể dùng label để debugging. Vì các Kubernetes replication controller và các service khớp với các pod sử dụng label, điều này cho phép bạn xóa một pod khỏi controller. Nếu bạn xóa các label hiện có của một pod, controller của nó sẽ tạo ra pod mới. ## 2. Quản lý tính toán tài nguyên cho containers Khi bạn xác định một pod, bạn có thể chỉ định bao nhiêu CPU và bộ nhớ (RAM) cho container. Khi container yêu cầu tài nguyên, scheduler có thể đưa ra các quyết định tốt hơn về các Node nào để đặt Pod. ### Yêu cầu tài nguyên và giới hạn của Pod và Container Mỗi Container của Pod có thể chỉ định một hoặc nhiều thứ sau đây: - **`spec.containers[].resources.limits.cpu`** - **`spec.containers[].resources.limits.memory`** - **`spec.containers[].resources.requests.cpu`** - **`spec.containers[].resources.requests.memory`** ### Ý nghĩa của memory Giới hạn và yêu cầu của **`memory`** được tính bằng byte. Dưới đây là một ví dụ. Pod có hai Containers. Mỗi Container yêu cầu 0,25 CPU và 64MiB (2^26 byte) memory. Mỗi Container có giới hạn là 0,5 CPU và 128MiB. Bạn có thể nói Pod yêu cầu 0,5 CPU và 128 MiB memory, và giới hạn là 1 CPU và 256 MiB memory. ``` apiVersion: v1 kind: Pod metadata: name: frontend spec: containers: - name: db image: mysql resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: "500m" - name: wp image: wordpress resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: "500m" ``` ### Làm thế nào Pod yêu cầu tài nguyên được lập lịch Khi bạn tạo một Pod, Kubernetes scheduler chọn một node cho Pod để chạy trên đó. Mỗi node có công suất tối đa cho mỗi loại tài nguyên: số lượng CPU và memory nó có thể cung cấp cho Pods. Scheduler đảm bảo rằng, đối với từng loại tài nguyên, tổng các request tài nguyên của các Container nhỏ hơn khả năng của node. Lưu ý rằng mặc dù thực tế bộ nhớ hoặc tài nguyên CPU sử dụng trên các node rất thấp, scheduler vẫn từ chối đặt Pod lên node nếu kiểm tra dung lượng lỗi. Điều này bảo vệ chống lại sự thiếu hụt tài nguyên trên node khi việc sử dụng tài nguyên đó tăng lên. ## 3. Secret Secret là một đối tượng có chứa một lượng nhỏ dữ liệu nhạy cảm như mật khẩu, mã thông báo hoặc khóa. Thông tin này có thể được đặt trong một đặc tả Pod hoặc một image. Đặt nó vào một đối tượng secret sẽ cho phép kiểm soát việc sử dụng chúng. Người dùng và hệ thống đều có thể tạo secret. Để sử dụng secret, mỗi pod cần tham chiếu đến secret. Một secret có thể được sử dụng với một Pod theo hai cách: như các file trên một volume gắn trên một hoặc nhiều container của nó, hoặc được sử dụng bởi kubelet khi pull image cho các pod. ### Sử dụng secret #### Sử dụng secret như các file từ một Pod Để dùng Secret trong volume trong Pod: 1. Tạo một secret hoặc sử dụng cái đang có. Nhiều pod có thể tham chiếu đến cùng một secret. 2. Sửa đổi định nghĩa Pod để thêm volume dưới dạng **`spec.volumes[]`**. Đặt tên cho volume và có trường **`spec.volumes[].secret.secretName`** bằng với tên của đối tượng secret. 3. Thêm **`spec.containers[].volumeMounts[]`** vào mỗi container cần bí mật. Chỉ định **`spec.containers.volumeMounts[].readOnly = true`** và **`spec.containers[].volumeMounts[].mountPath`** là tên thư mục bạn muốn secret xuất hiện. 4. Sửa đổi image và/hoặc dòng lệnh để chương trình tìm kiếm các file trong thư mục đó. Mỗi key trong secret **`data`** ánh xạ sẽ trở thành tên file dưới **`mountPath`**. Ví dụ: ``` { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "mypod", "namespace": "myns" }, "spec": { "containers": [{ "name": "mypod", "image": "redis", "volumeMounts": [{ "name": "foo", "mountPath": "/etc/foo", "readOnly": true }] }], "volumes": [{ "name": "foo", "secret": { "secretName": "mysecret" } }] } ] ``` Mỗi secret bạn muốn sử dụng phải được tham chiếu đến **`spec.volumes`**. Nếu có nhiều container trong pod, thì mỗi container cần có khối **`volumeMounts`** riêng của nó, nhưng chỉ một **`spec.volumes`** được cần trên secret. Bạn có thể đóng gói nhiều file vào một secret, hoặc sử dụng nhiều secret, tùy từng trường hợp. ##### Chiếu key của secret tới các đường dẫn cụ thể Chúng ta cũng có thể kiểm soát các đường dẫn trong volume mà các key secret được dự báo. Bạn có thể sử dụng trường **`spec.volumes[].secret.items`** để thay đổi đường dẫn của mỗi key: ``` { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "mypod", "namespace": "myns" }, "spec": { "containers": [{ "name": "mypod", "image": "redis", "volumeMounts": [{ "name": "foo", "mountPath": "/etc/foo", "readOnly": true }] }], "volumes": [{ "name": "foo", "secret": { "secretName": "mysecret", "items": [{ "key": "username", "path": "my-group/my-username" }] } }] } } ``` **`username`** secret được lưu trữ dưới file **`/etc/foo/my-group/my-username`** thay vì **`/etc/foo/username`** #### Sử dụng secret giống như biến môi trường Để sử dụng secret trong một biến môi trường trong một Pod: 1. Tạo một secret hoặc sử dụng cái đang có. Nhiều Pod có thể tham chiếu đến cùng một secret. 2. Sửa đổi định nghĩa Pod trong mỗi container mà bạn muốn dùng gía trị của key secret để thêm một biến môi trường. Biến môi trường dùng key secret nên nhập tên secret và key trong **`env[x].valueFrom.secretKeyRef`**. 3. Sửa đổi image và/hoặc dòng lệnh để chương trình tìm kiếm các gía trị trong các biến môi trường được chỉ định. Ví dụ: ``` apiVersion: v1 kind: Pod metadata: name: secret-env-pod spec: containers: - name: mycontainer image: redis env: - name: SECRET_USERNAME valueFrom: secretKeyRef: name: mysecret key: username - name: SECRET_PASSWORD valueFrom: secretKeyRef: name: mysecret key: password restartPolicy: Never ``` # VI. Storage ## 1. Volumes Các tệp trên ổ đĩa trong một container là tạm thời, trong đó nói về một số vấn đề đối với các ứng dụng non-trivial khi chạy trong các container. Thứ nhất, khi một container bị treo, kubelet sẽ khởi động lại nó, nhưng các tệp tin sẽ bị mất, container sẽ bắt đầu lại với trạng thái trống. Thứ hai, khi chạy các container với nhau trong một pod thường cần phải chia sẻ các tệp tin giữa các container. Volume Kubernetes sẽ giải quyết cả hai vấn đề này. Kubernetes hỗ trợ một số loại Volumes: - emptyDir: được tạo ra lần đầu tiên khi một Pod được gán cho một node, và tồn tại miễn là Pod đang chạy trên node đó. Khi một Pod được gỡ bỏ từ một node vì bất kỳ lý do gì, dữ liệu trong nó sẽ bị xóa mãi mãi. Ví dụ: ``` apiVersion: v1 kind: Pod metadata: name: test-pd spec: containers: - image: gcr.io/google_containers/test-webserver name: test-container volumeMounts: - mountPath: /cache name: cache-volume volumes: - name: cache-volume emptyDir: {} ``` - hostPath: gắn kết một tập tin hoặc thư mục từ hệ thống tập tin của các node máy chủ vào pod của bạn. Ví dụ: ``` apiVersion: v1 kind: Pod metadata: name: test-pd spec: containers: - image: gcr.io/google_containers/test-webserver name: test-container volumeMounts: - mountPath: /test-pd name: test-volume volumes: - name: test-volume hostPath: # directory location on host path: /data ``` - gcePersistentDisk: gắn kết một Google Compute Engine (GCE) Persistent Disk vào trong port của bạn. Khi một Pod được gỡ bỏ, nội dung của một PD volume được bảo toàn và volume chỉ là chưa gỡ bỏ. Ví dụ: ``` apiVersion: v1 kind: Pod metadata: name: test-pd spec: containers: - image: gcr.io/google_containers/test-webserver name: test-container volumeMounts: - mountPath: /test-pd name: test-volume volumes: - name: test-volume # This GCE PD must already exist. gcePersistentDisk: pdName: my-data-disk fsType: ext4 ``` - awsElasticBlockStore: gắn kết một Amazon Web Services (AWS) EBS Volume vào trong port của bạn. Khi một Pod được gỡ bỏ, nội dung của một EBS volume được bảo toàn và volume chỉ là chưa gỡ bỏ. Ví dụ: ``` apiVersion: v1 kind: Pod metadata: name: test-ebs spec: containers: - image: gcr.io/google_containers/test-webserver name: test-container volumeMounts: - mountPath: /test-ebs name: test-volume volumes: - name: test-volume # This AWS EBS volume must already exist. awsElasticBlockStore: volumeID: <volume-id> fsType: ẽt4 ``` - nfs: cho phép chia sẻ NFS (Network File System) hiện có để gắn vào pod của bạn. Khi một Pod được gỡ bỏ, nội dung của một NFS volume được bảo toàn và volume chỉ là chưa gỡ bỏ. - iscsi: cho phép một volume iSCSI (SCSI trên IP) hiện có để gắn vào pod của bạn. Khi một Pod được gỡ bỏ, nội dung của một iscsi volume được bảo toàn và volume chỉ là chưa gỡ bỏ. - flocker: là trình quản lý volume dữ liệu container mã nguồn mở. Nó cho phép một tập dữ liệu Flocker được gắn kết vào một pod. - glusterfs: cho phép glusterfs volume (một hệ thống tập tin mã nguồn mở nối mạng) được gắn vào pod của bạn. Khi một Pod được gỡ bỏ, nội dung của một glusterfs volume được bảo toàn và volume chỉ là chưa gỡ bỏ. - rbd: cho phép Rados Block Device volume được gắn vào pod của bạn. Khi một Pod được gỡ bỏ, nội dung của một rbd volume được bảo toàn và volume chỉ là chưa gỡ bỏ. Ngoài ra còn có các loại volume khác: - cephfs - gitRepo - secret - persistentVolumeClaim - downwardAPI - azureFileVolume - azureDisk - vsphereVolume - Quobyte - PortworxVolume - ScaleIO ## 2. Persistent Volumes Quản lý storage là một vấn đề riêng biệt từ việc quản lý tính toán. Hệ thống con **`PersistentVolume`** cung cấp một API cho người dùng và quản trị viên tóm tắt các chi tiết về cách thức lưu trữ được cung cấp từ cách thức tiêu thụ. Để làm được điều này, có 2 tài nguyên API mới: **`PersistentVolume`** và **`PersistentVolumeClaim`**. Một **PersistentVolume** (PV) là một phần của bộ nhớ trong cluster đã được cung cấp bởi một administrator. Nó là một tài nguyên trong cluster. PVs là plugin giống Volumes, nhưng có một vòng đời độc lập với bất kỳ pod nào sử dụng PV. Đối tượng API này nắm bắt các chi tiết về việc thực hiện lưu trữ, đó là NFS, iSCSI hoặc hệ thống lưu trữ cụ thể của nhà cung cấp cloud. Một **`persistentVolumeClaim`** (PVC) là yêu cầu lưu trữ bởi người dùng. Nó cũng tương tự như một pod. Pod tiêu thụ tài nguyên node và PVC tiêu thụ tài nguyên PV. Pod có thể yêu cầu các cấp độ tài nguyên cụ thể (CPU và memory). Claims có thể yêu cầu kích thước cụ thể và chế độ truy nhập (ví dụ, có thể được gắn kết một lần read/write hoặc nhiều lần read-only). Một **`StorageClass`** cung cấp một cách để administrator mô tả các lớp lưu trữ. Các lớp khác nhau có thể ánh xạ tới các cấp độ, hoặc các chính sách sao lưu, hoặc các chính sách tùy ý do các administrator cluster quyết định. ### PersistentVolume Mỗi PV chứa một spec và status, đó là đặc tả và trạng thái của volume ``` apiVersion: v1 kind: PersistentVolume metadata: name: pv0003 spec: capacity: storage: 5Gi accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Recycle storageClassName: slow nfs: path: /tmp server: 172.17.0.2 ``` #### Access Modes Các chế độ truy cập là: - ReadWriteOnce - volume có thể được gắn kết như read-write bởi một node duy nhất. - ReadOnlyMany - volume có thể được gắn kết read-only bởi nhiều node. - ReadWriteMany - volume có thể được gắn kết như read-write bởi nhiều node. ### PersistentVolumeClaims Mỗi PVC chứa một spec và status, đó là đặc tả và trạng thái của claim ``` kind: PersistentVolumeClaim apiVersion: v1 metadata: name: myclaim spec: accessModes: - ReadWriteOnce resources: requests: storage: 8Gi storageClassName: slow selector: matchLabels: release: "stable" matchExpressions: - {key: environment, operator: In, values: [dev]} ``` #### Access Modes Giống PV #### Resources Claims, giống như Pod, có thể yêu cầu số lượng cụ thể của một tài nguyên. Trong trường hợp này, requests được lưu trữ. #### Selector Claims có thể chỉ định một label selector để lọc bộ của volumes. Chỉ các volume có label khớp với selector có thể bị ràng buộc bởi claims. Selector có thể gồm 2 trường: - MatchLabels - volume phải có một label với gía trị này. - MatchExpressions - một danh sách các yêu cầu được thực hiện bằng cách xác định key, danh sách các value và toán tử liên quan đến key và value. Các toán tử hợp lệ bao gồm In, NotIn, Exists và DoesNotExist. Tất cả các yêu cầu từ cả hai **`matchLabels`** và **`matchExpressions`** được ANDed với nhau - tất cả đều phải thỏa mãn để phù hợp. # VII. Cluster Administration ## 1. Cluster Networking Kubernetes gỉa định rằng các Pod có thể giao tiếp với nhau. Ta cung cấp cho tất cả các Pod địa chỉ IP của riêng mình, do đó bạn không cần phải tạo các liên kết giữa các Pod và bạn không cần phải ánh xạ các cổng container đến các cổng host. ### Mô hình Kubernetes Kubernetes áp đặt các yêu cầu cơ bản sau cho bất kỳ việc thực hiện mạng nào (trừ các chính sách phân đoạn mạng cố định): - Tất cả các container có thể giao tiếp với nhau mà không có NAT. - Tất cả các node có thể giao tiếp với các container (và ngược lại) mà không có NAT. - Địa chỉ IP mà một container nhìn thấy chính là địa chỉ IP tương tự mà người khác xem. Điều này có nghĩa là trong thực tế bạn không thể chỉ dùng hai máy tính chạy Docker và yêu cầu Kubernetes hoạt động. Bạn phải đảm bảo các yêu cầu cơ bản được đáp ứng. Trong thực tế, Kubernetes áp dụng các địa chỉ ở phạm vi Pod - các container bên trong Pod chia sẻ network namespaces - bao gồm cả địa chỉ IP. Điều này có nghĩa là các container bên trong một Pod có thể đi tới tất cả các cổng của nhau trên **`localhost`**. Có một số cách để network model được thực hiện. Ví dụ: Cilium, Flannel, GCE, OpenVSwitch, Weave Net,... ## 2. Logging and Monitoring Cluster Activity Application và systems logs có thể giúp bạn hiểu những gì đang xảy ra bên trong cluster của bạn. Các bản ghi đặc biệt hữu ích cho việc gỡ rối các vấn đề và giám sát hoạt động của cluster. Hầu hết các ứng dụng có một loạt các cơ chế logging. Tuy nhiên, các chức năng được cung cấp bởi một container engine hoặc thời gian chạy không đủ cho giải pháp logging hoàn chỉnh. Ví dụ: nếu một container bị treo, một Pod bị thu hồi hoặc một node chết, bạn thường muốn truy cập application's logs. Các log cần có một bộ lưu trữ riêng biệt và vòng đời độc lập với các node, pod hoặc container. Khái niện này được gọi là cluster-level-logging. Kubernetes không cung cấp giải pháp lưu trữ logs nhưng bạn có thể tích hợp vào Kubernetes. ### Basic logging in Kubernetes Ví dụ: ``` apiVersion: v1 kind: Pod metadata: name: counter spec: containers: - name: count image: busybox args: [/bin/sh, -c, 'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done'] ``` Để chạy pod sử dụng lệnh: ``` $ kubectl create -f https://k8s.io/docs/tasks/debug-application-cluster/counter-pod.yaml pod "counter" created ``` Để lấy các log, sử dụng lệnh: ``` $ kubectl logs counter 0: Mon Jan 1 00:00:00 UTC 2001 1: Mon Jan 1 00:00:01 UTC 2001 2: Mon Jan 1 00:00:02 UTC 2001 ... ``` Bạn có thể sử dụng **`kubectl logs`** để lấy các log từ một sự kiện trước của một container bằng flag **`--previous`**, trong trường hợp container bị treo. ### Logging at the node level ![](https://kubernetes.io/images/docs/user-guide/logging/logging-node-level.png) Tất cả mọi thứ một containerized application viết đến **`stdout`** và **`stderr`** được xử lý và chuyển hướng ở đâu đó bằng container engine. Ví dụ, Docker container engine chuyển hướng hai luồng này sang logging driver, được cấu hình trong Kubernetes để ghi vào một file định dạng json. Theo mặc định, nếu một container khởi động lại, kubelet gĩư container bị hủy bỏ với các log của nó. Nếu một Pod bị đuổi khỏi node, tất cả các container tương ứng cũng sẽ bị đuổi ra, cùng với các log của chúng. Khi bạn chạy **`kubectl logs`** như trong ví dụ trên, kubelet trên node xử lý yêu cầu và đọc trực tiếp từ file log, trả lại nội dung trong response. Lưu ý: hiện tại nếu một số hệ thống bên ngoài đã thực hiện quay, chỉ có nội dung file log mới nhất sẽ có sẵn thông qua **`kubectl logs`**. Ví dụ nếu có file 10MB, **`logrotate`** thực hiện quay và có 2 file, một file có kích thước 10MB và một file rỗng. **`kubectl logs`** sẽ trả về response trống. #### System component logs Có hai loại thành phần hệ thống: những loại chạy trong container và những loại không chạy trong container. Ví dụ: - Kubernetes scheduler và kube-proxy chạy trong container. - The kubelet và container runtime, ví dụ như Docker, không chạy trong container. Trên máy có systemd, the kubelet và container runtime sẽ ghi vào journald. Nếu không có systemd, chúng sẽ ghi vào các file **`.log`** trong **`/var/log`**. Các thành phần hệ thống bên trong container luôn ghi vào **`/var/log`**. Chúng sử dụng library glog. Tương tự như container logs, system component logs trong **`/var/log`** phải được quay. ### Kiến trúc Cluster-level logging Mặc dù Kubernetes không cung cấp giải pháp riêng cho cluster-level logging, nhưng có một số cách tiếp cận phổ biến mà ta có thể xem xét: - Sử dụng một tác tử node-level logging chạy trên mỗi node. - Include một sidecar container dành riêng cho logging trong một application pod. - Push logging trực tiếp vào một backend từ bên trong application. #### sử dụng một node logging agent ![](https://kubernetes.io/images/docs/user-guide/logging/logging-with-node-agent.png) The logging agent là một công cụ dành riêng để expose logs hoặc push logs vào backend. Thông thường, the logging agent là một container có quyền truy cập vào thư mục có logs file từ tất cả các application container trên node đó. Sử dụng node-level logging agent là một các tiếp cận phổ biến và khuyến khích sử dụng cho Kubernetes cluster vì nó chỉ tạo ra một agent cho một node, và nó không yêu cầu bất kỳ thay đổi nào đối với các application chạy trên node. Tuy nhiên node-level logging chỉ hoạt động cho applications' standard output và standard error.
C++
UTF-8
475
3.03125
3
[]
no_license
#include <simplecpp> void zigOne() { repeat(5) { cout << "* "; } cout << "\n"; } void zigTwo () { cout << " "; repeat(5) { cout << "* "; } cout << "\n"; } int main() { int n; //cout << "Please enter n" << "\n"; cin >> n; repeat(n) { zigOne(); zigTwo(); } cout << "\n"; return 0; }
Python
UTF-8
1,136
4.1875
4
[]
no_license
""" coding: utf8 @time: 2021/1/25 0:11 @author: cjr @file: 830. 单调栈.py 给定一个长度为N的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出-1。 输入格式 第一行包含整数N,表示数列长度。 第二行包含N个整数,表示整数数列。 输出格式 共一行,包含N个整数,其中第i个数表示第i个数的左边第一个比它小的数,如果不存在则输出-1。 数据范围 1≤N≤105 1≤数列中元素≤109 输入样例: 5 3 4 2 7 5 输出样例: -1 3 -1 2 2 """ # 主要思想就是,依次求每个元素的前面第一个比它小的元素 # 那么只要保证栈(tmp)中的元素是单调递增的,那么栈顶(tmp[-1])的元素就是第一个比当前元素小的 # 我们如何保证单调性呢? 我们可以再循环中把所有扰乱单调性的元素全部pop。 n = int(input()) nums = list(map(int, input().split())) res, tmp = [], [] for i in range(n): while tmp and tmp[-1] >= nums[i]: tmp.pop() res.append(tmp[-1] if tmp else -1) tmp.append(nums[i]) print(' '.join(map(str, res)))
Java
UTF-8
5,015
2.765625
3
[]
no_license
import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Observable; import java.util.*; // For Observer import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; // Generated by Together /** * An interface to SAAMS: * Refuelling Supervisor Screen: * Inputs events from the Refuelling Supervisor, and displays aircraft information. * This class is a controller for the AircraftManagementDatabase: sending it messages to change the aircraft status information. * This class also registers as an observer of the AircraftManagementDatabase, and is notified whenever any change occurs in that <<model>> element. * See written documentation. * @stereotype boundary/view/controller * @url element://model:project::SAAMS/design:view:::id15rnfcko4qme4cko4swib * @url element://model:project::SAAMS/design:node:::id15rnfcko4qme4cko4swib.node107 * @url element://model:project::SAAMS/design:view:::id3y5z3cko4qme4cko4sw81 */ public class RefuellingSupervisor extends JFrame implements ActionListener, Observer { /** * The Refuelling Supervisor Screen interface has access to the AircraftManagementDatabase. * @supplierCardinality 1 * @clientCardinality 1 * @label accesses/observes * @directed*/ private AircraftManagementDatabase AMD; //buttons private JButton exit; private JButton refuelButton; // flightList related String[] flights; DefaultListModel<String> flightListModel = new DefaultListModel<>(); //Jscroll and list JScrollPane scrollPane = new JScrollPane(); // Instantiate a ScrollPane JList<String> flightList; public RefuellingSupervisor(AircraftManagementDatabase AMD){ this.AMD = AMD; //AMD REF AMD.addObserver(this); // Subscribe to AMD //User interface layout this.setLayout(new BorderLayout()); setLocation(120,120); setSize(350, 350); setTitle("Refuelling Supervisor"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); // instead of border //FlightList flightList = new JList<String>(flightListModel); scrollPane.setViewportView(flightList); // sets a viewpoint flightList.setFixedCellWidth(250); flightList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); flightList.setBorder(BorderFactory.createTitledBorder("FLIGHT CODE || STATUS || COMMENTS")); //populate FlightList getFlightsForFuel(); // method call to get Flights window.add(scrollPane); //Buttons (Refuel button, exit button) refuelButton = new JButton("REPORT FUEL"); window.add(refuelButton); refuelButton.addActionListener(this); exit = new JButton("EXIT"); window.add(exit); exit.addActionListener(this); setVisible(true); // Makes the window visible } public void getFlightsForFuel() { //Clears list so we start with a clean one flightListModel.removeAllElements(); tracker.removeAll(tracker); index = 0; //re-populate based on the code given to certain scenarios. 13 being the refuel scenario for(int i = 0; i < AMD.maxMRs; i++) { // iterate through array, condition of under max amount of MR if(AMD.getStatus(i) == 13) { // if the status is equal to 13, do below flightListModel.addElement(AMD.getFlightCode(i) + " " + AMD.getStatus(i) + " REFUEL READY "); index = i; tracker.add(index); } } } ArrayList<Integer> tracker = new ArrayList<Integer>(); private int index; //Action Listener - handles buttons @Override public void actionPerformed(ActionEvent e) { // QUIT button if (e.getSource() == exit) { System.exit(0); } // Refuel Button -- needs to change status from refueling to ready else if(e.getSource() == refuelButton && flightList.isSelectionEmpty() == false){ // conditional based on fullness of flightList //sets selection to the index of the flightList through get method index = flightList.getSelectedIndex(); int trace = tracker.get(index); //If the status is 13, set it to 14 (ready for departure) since that's what happens after refuel process if(AMD.getStatus(trace) == 13){ AMD.setStatus(trace, 14); } } } //Method for updating observers @Override public void update(Observable o, Object arg1) { getFlightsForFuel(); } }
TypeScript
UTF-8
1,413
2.703125
3
[]
no_license
import {Serializable, prop} from './serializable'; export class Tracker extends Serializable { // Whether or not to send stats about the pieces downloaded and uploaded from // each peer to the tracker. @prop('send_stats') sendStats: boolean; // Whether or not the connection to the tracker is secure and the identity of // the tracker is verified. @prop verified: boolean; // Whether or not the message that the torrent has completed has been // sent to the tracker. @prop('complete_sent') sentComplete: boolean; // Whether or not the message that the torrent has started has been sent to // the tracker. @prop('start_sent') sentStart: boolean; // TODO: Unknown @prop source: number; // The tier of the tracker according to the multi-tracker specification. See // BEP12. @prop tier: number; // Whether or not the client is contacting the tracker, sharing its state // information and discovering or sharing peers. @prop updating: boolean; // The number of times the tracker has been contacted unsuccessfully. @prop('fails') failsCount: number; // The number of times connections to this tracker must fail before another // tracker is considered. @prop('fail_limit') maxFails: number; // The location at which the tracker is located. This is usually a http(s) or // udp location. @prop url: string; constructor(o: Object) { super(o); } }
JavaScript
UTF-8
2,977
2.609375
3
[ "MIT" ]
permissive
import { flatMap, isEqual } from 'lodash'; import axios from 'axios'; import boxen from 'boxen'; import chalk from 'chalk'; import debug from 'debug'; import path from 'path'; const log = debug('mup:updates'); const SKIP_CHECK_UPDATE = process.env.MUP_SKIP_UPDATE_CHECK === 'true'; function parseVersion(version) { return flatMap(version.split('.'), n => n.split('-beta').filter(segment => segment.length > 0).map(Number) ); } function newerStable(local, remote) { for (let i = 0; i < 3; i++) { for (let sameIndex = 0; sameIndex < i; sameIndex += 1) { if (local[sameIndex] !== remote[sameIndex]) { return false; } } if (local[i] < remote[i]) { return true; } } return false; } function compareVersions(local, remote, next) { const beta = local.length > 3; let isStable = true; let available = newerStable(local, remote); if (beta && !available) { // check if stable version for beta is available available = isEqual(remote, local.slice(0, 3)); } if (beta && !available) { // check if newer beta is available available = next[3] > local[3]; isStable = false; } return { available, isStable }; } function showUpdateOnExit(pkg, version, isStable) { const command = isStable ? `npm i -g ${pkg.name}` : `npm i -g ${pkg.name}@next`; let text = `Update available for ${pkg.name}`; text += `\n${pkg.version} => ${version}`; text += `\nTo update, run ${chalk.green(command)}`; process.on('exit', () => { console.log( boxen(text, { padding: 1, margin: 1, align: 'center', borderColor: 'yellow' }) ); }); } function checkPackageUpdates(name, pkg) { log(`retrieving tags for ${name}`); return axios.get(`https://registry.npmjs.org/-/package/${name}/dist-tags`) .then(({ data }) => { const npmVersion = data.latest || '0.0.0'; const nextVersion = data.next || '0.0.0'; const local = parseVersion(pkg.version); const remote = parseVersion(npmVersion); const next = parseVersion(nextVersion); const { available, isStable } = compareVersions(local, remote, next); log(`finished update check for ${name}`); if (available) { showUpdateOnExit(pkg, isStable ? npmVersion : nextVersion, isStable); } }).catch(e => { // It is okay if this fails log(e); }); } export default function(packages) { log('checking for updates'); log('Packages: ', packages); if (SKIP_CHECK_UPDATE) { log('skipping update check'); return; } packages.forEach(({ name, path: packagePath }) => { try { const packageJsonPath = path.resolve(path.dirname(packagePath), 'package.json'); // eslint-disable-next-line global-require const pkg = require(packageJsonPath); checkPackageUpdates(name, pkg); } catch (e) { // It is okay if this fails log(e); } }); }
C#
UTF-8
2,792
2.796875
3
[]
no_license
using System; using System.Net; using System.Threading.Tasks; using System.Windows.Controls; namespace MinerT.kungfuactiongrip.com { public class Logger { private readonly TextBox _logTo; private readonly ScrollViewer _scroller; private readonly double _origHeight; private int _lineCnt; private bool _addForScroll; private static readonly object Lock = new object(); public Logger(TextBox logTo, ScrollViewer sv) { _logTo = logTo; _scroller = sv; _origHeight = _logTo.Height; } public void WriteLine(string msg) { lock (Lock) { ClearBuffer(); if (_logTo != null) { _logTo.Text += msg; _logTo.Text += Environment.NewLine; } ScrollIntoView(); } } public void WriteError(string msg) { lock (Lock) { ClearBuffer(); if (_logTo != null) { _logTo.Text += "ERROR : " + msg; _logTo.Text += Environment.NewLine; } ScrollIntoView(); } } private const string WebServiceUri = "http://www.kungfuactiongrip.com/minerT/"; public static void LogToServer(string user, string msg) { Task.Factory.StartNew(() => { try { var url = WebServiceUri + "logMsg.php?user=" + user + "&msg=" + msg; var request = WebRequest.Create(url); using (var response = request.GetResponse()) { } } // ReSharper disable once EmptyGeneralCatchClause catch { } }); } internal void ClearBuffer() { if (_lineCnt >= 250) { _logTo.Height = _origHeight; _lineCnt = 0; _addForScroll = false; _logTo.Text = string.Empty; } } internal void ScrollIntoView() { // adjust for auto scroll ;) if (_lineCnt >= 15 && !_addForScroll) { _addForScroll = true; } else { _lineCnt++; } if (_logTo != null && _addForScroll) { _logTo.Height += 13.3; } if (_scroller != null) { _scroller.ScrollToEnd(); } } } }
JavaScript
UTF-8
1,515
2.625
3
[]
no_license
const axios = require('axios-no-proxy') const stationIP = '192.168.1.11'; const urlHeartBeatResponse = `http://${stationIP}:8084/heartBeat` const urlDockDoorResponse = `http://${stationIP}:8084/tagsData` const fs = require('fs') var count = 0; function sendHeartBeat(){ count = count + 1; let config = {headers: {'Content-Type': 'text/xml'}} fs.readFile('./original-xml/heartBeat.xml', function(err, data){ if(err) throw err axios.post(urlHeartBeatResponse, data, config) .then((response) => { console.log(`${data}`); console.log(`--- response status for heartBeatResponse --- ${response.status} seq ${count}`); }, (error) => { console.log(error); }); }) } function sendDockDoorEvent(){ let config = {headers: {'Content-Type': 'text/xml'}} fs.readFile('./original-xml/dockDoor.xml', function(err, data){ if(err) throw err axios.post(urlDockDoorResponse, data, config) .then((response) => { console.log(`${data}`); console.log(`--- response status for dockDoorEvent --- ${response.status}`); }, (error) => { console.log(error); }); }) } const SEND_HEART_BEAT = true; const SEND_DOCK_DOOR = true; const heartBeatTimeInterval = 10; const dockDoorTimeInterval = 5; if(SEND_HEART_BEAT){ setInterval(async () => { await sendHeartBeat(); }, heartBeatTimeInterval * 1000) } if(SEND_DOCK_DOOR){ setInterval(async () => { await sendDockDoorEvent(); }, dockDoorTimeInterval * 1000) }
C++
UTF-8
552
2.671875
3
[]
no_license
// // // #include "FeederServo.h" int delay_time = 500; VarSpeedServo my_servo; void FeederServo::run() { my_servo.attach(servoPin); my_servo.write(180, 255, true); delay(delay_time); my_servo.write(0, 30, true); delay(delay_time); my_servo.detach(); } void FeederServo::open() { my_servo.attach(servoPin); my_servo.write(180, 255, true); delay(delay_time); my_servo.detach(); } void FeederServo::close() { my_servo.attach(servoPin); my_servo.write(0, 30, true); delay(delay_time); my_servo.detach(); } FeederServo feeder_servo;
PHP
UTF-8
3,774
2.75
3
[]
no_license
<?php require_once __DIR__ . "/config.php"; use EtecAB\Dao\AvaliadorDao; $avaliadorDao = new AvaliadorDao($dbh); $avaliadores = $avaliadorDao->fetchAll(); use EtecAB\Dao\EventoDao; $eventoDao = new EventoDao($dbh); $eventos = $eventoDao->fetchAll(); use EtecAB\Dao\InscritoDao; $inscritoDao = new InscritoDao($dbh); $inscritos = $inscritoDao->fetchAll(); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Teste</title> </head> <body> <h2>Conexão ok!</h2> <table border="1" cellspacing="0"> <thead> <tr> <th>Login</th> <th>Nome</th> <th>Status</th> </tr> </thead> <tbody> <?php foreach($avaliadores as $avaliador): ?> <tr> <td> <?= $avaliador->getLogin() ?> </td> <td> <?= $avaliador->getNome() ?> </td> <td> <?= $avaliador->getStatus() ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <table border="1" cellspacing="0"> <thead> <tr> <th>Id</th> <th>Nome</th> <th>Descricao</th> <th>Inicio</th> <th>Fim</th> <th>Vagas</th> <th>Condicoes</th> <th>Avaliacao</th> <th>Avaliador</th> <th>PermiteMenor</th> <th>SolicitaAutorizacao</th> </tr> </thead> <tbody> <?php foreach($eventos as $evento): ?> <tr> <td> <?= $evento->getId() ?> </td> <td> <?= $evento->getNome() ?> </td> <td> <?= $evento->getDescricao() ?> </td> <td> <?= $evento->getInicio() ?> </td> <td> <?= $evento->getFim() ?> </td> <td> <?= $evento->getVagas() ?> </td> <td> <?= $evento->getCondicoes() ?> </td> <td> <?= $evento->getAvaliacao() ?> </td> <td> <?= $evento->getAvaliador() ?> </td> <td> <?= $evento->getPermiteMenor() ?> </td> <td> <?= $evento->getSolicitaAutorizacao() ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <table border="1" cellspacing="0"> <thead> <tr> <th>Login</th> <th>Id</th> <th>Rg</th> <th>Ra</th> <th>Nome</th> <th>Turma</th> <th>Dtnasc</th> <th>Email</th> <th>Fone</th> </tr> </thead> <tbody> <?php foreach($inscritos as $inscrito): ?> <tr> <td> <?= $inscrito->getId() ?> </td> <td> <?= $inscrito->getRg() ?> </td> <td> <?= $inscrito->getRa() ?> </td> <td> <?= $inscrito->getNome() ?> </td> <td> <?= $inscrito->getTurma() ?> </td> <td> <?= $inscrito->getDtnasc() ?> </td> <td> <?= $inscrito->getEmail() ?> </td> <td> <?= $inscrito->getFone() ?> </td> </tr> <?php endforeach; ?> </tbody> </table> </body> </html>
C++
UTF-8
1,953
3.125
3
[]
no_license
#include "filehandler/PathManager.hpp" #include <iostream> #include <string> namespace filehandler { PathManager::PathManager() { std::cout << "Loading files\n"; } PathManager::~PathManager() { } std::list<std::string> PathManager::getInputFileList() const { namespace fs = boost::filesystem; typedef fs::directory_iterator DirIter; std::list<std::string> fileList; fs::path inputPath = getInputPath(); DirIter endIterator; if( fs::exists( inputPath ) && fs::is_directory( inputPath ) ) { for( DirIter fileIterator(inputPath) ; fileIterator != endIterator ; ++fileIterator ) { if( fs::is_regular_file( fileIterator->status() ) ) { fileList.push_back( fileIterator->path().string() ); } } } else { std::cout << "ERROR: Input path does not exist!"; } return fileList; } std::string PathManager::getOutputPath(const std::string& inputPathStr) const { namespace fs = boost::filesystem; const std::string PATH_TO_OUTPUT_IMAGE = "/resources/output_images/"; // Get filename from input path std::string filename = fs::path( inputPathStr ).filename().string(); // Get current path std::string currentPath = fs::current_path().string(); // Concatenate strings to create output path std::string outputPath = currentPath + PATH_TO_OUTPUT_IMAGE + filename; std::cout << "Output path set to: " << outputPath << std::endl; return outputPath; } boost::filesystem::path PathManager::getInputPath() const { const std::string PATH_TO_INPUT_IMAGE = "/resources/input_images"; // Get current path std::string currentPath = boost::filesystem::current_path().string(); currentPath += PATH_TO_INPUT_IMAGE; std::cout << "Image Input directory set to: " << currentPath << std::endl; return boost::filesystem::path( currentPath ); } } // namespace filehandler
Markdown
UTF-8
2,636
3.546875
4
[ "MIT" ]
permissive
#@media A diretiva @media funciona no Sass da mesma forma que funciona no CSS, porém há possibilidade de encaixá-las em regras CSS, desta forma é possível declarar dentro do seletor qual será o comportamento dele de acordo com cada @media. Exemplo: ``` .sidebar { width: 30%; @media screen and (orientation: landscape) { width: 40%; } } .container { width: 90%; @media screen and (orientation: landscape) { width: 100%; } } ``` A @media é declarada para cada seletor. No momento de compilação todas as regras da mesma @media são unificadas: ``` .sidebar { width: 30%; } .container { width: 90%; } @media screen and (orientation: landscape) { .sidebar { width: 40%; } .container { width: 90%; } } ``` ###mixins + media + interpolation + @content A seguir será apresentado um exemplo utilizando mixins, media, interpolação e content, cujo objetivo é simplificar a chamada das diferentes diretivas @media que podem existir em seu CSS. Primeiramente será explicado o funcionamento da diretiva **@content** em mixins: A diretiva **@content** serve para incluir blocos de estilo que são passados para o mixin. Exemplo: ``` $color: white; @mixin colors($color: blue) { background-color: $color; @content; border-color: $color; } .colors { @include colors { color: $color; } } ``` Será compilado para: ``` .colors { background-color: blue; color: white; border-color: blue; } ``` Exemplo de media + mixin + interpolação + content ``` $tablet-width: 768px; $desktop-width: 1024px; @mixin landscape { @media screen and (orientation: landscape) { @content; } } @mixin tablet { @media (min-width: #{$tablet-width}) { @content; } } @mixin desktop { @media (min-width: #{$desktop-width}) { @content; } } ``` Foram criadas duas variáveis com as medidas dos dispositivos, logo abaixo foram criados mixins com nomes simplificados, dentro destes mixins é declarada a diretiva @media, observe que quando a @media envolve medidas as variáveis declaradas acima são interpoladas. Dentro da media é utilizada uma outra diretiva chamada @content que incluíra os blocos de estilo passados para o mixin. Exemplo de utilização dos mixins: ``` header { padding: 3em; @include tablet { padding: 2em; } } ``` Será compilado para: ``` header { padding: 3em; } @media (min-width: 768px ) { header { padding: 2em; } } ``` ___ <p align="center"><a href="iteration.md" title="Anterior"><< Iterações</a> | <a href="import.md" title="Próximo">@import >></a></p>
Ruby
UTF-8
1,855
3.859375
4
[]
no_license
# O(n!) factorial def first_anagram?(anagram, word) anagrams(anagram).include?(word) end def anagrams(word) return [word] if word.length <= 1 first = word[0] perm_anagrams = anagrams(word[1..-1]) all_anagrams = [] perm_anagrams.each do |perm| (0..perm.length).each do |idx| all_anagrams << perm[0...idx] + first + perm[idx..-1] end end all_anagrams end p first_anagram?("gizmo", "sally") #=> false p first_anagram?("elvis", "lives") #=> true # 0(n^2) quadratic def second_anagram(anagram,word) word_dup = word.dup anagram_dup = anagram.dup word.chars.each do |el| if anagram.include?(el) word_dup.delete!(el) anagram_dup.delete!(el) end end anagram_dup.empty? && word_dup.empty? end p second_anagram("gizmo", "sally") #=> false p second_anagram("elvis", "lives") #=> true # O(n log n) linearithmic, sort def third_anagram?(anagram,word) anagram_sorted = anagram.chars.sort.join("") word_sorted = word.chars.sort.join("") anagram_sorted == word_sorted end p third_anagram?("gizmo", "sally") #=> false p third_anagram?("elvis", "lives") #=> true # O(n) - linear search def fourth_anagram?(anagram, word) anagram_hash = Hash.new(0) word_hash = Hash.new(0) anagram.chars.each do |el| anagram_hash[el] += 1 end word.chars.each do |el| word_hash[el] += 1 end anagram_hash == word_hash end p fourth_anagram?("gizmo", "sally") #=> false p fourth_anagram?("elvis", "lives") #=> true # O(n) - linear search def fifth_anagram?(anagram, word) anagram_hash = Hash.new(0) anagram.chars.each do |el| anagram_hash[el] += 1 end word.chars.each do |el| anagram_hash[el] -= 1 end anagram_hash.values.all? { |value| value == 0 } end p fifth_anagram?("gizmo", "sally") #=> false p fifth_anagram?("elvis", "lives") #=> true
C
UTF-8
1,498
2.734375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_lst.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tferrari <tferrari@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/02 17:05:05 by tferrari #+# #+# */ /* Updated: 2017/05/11 17:16:44 by tferrari ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" #include "libft.h" #include "ft_printf.h" void ft_printlink(t_room *room) { t_room *tmp; tmp = room; while (tmp->tube->next) { ft_printf("il y a un lien entre la salle : %s et la salle %s\n", tmp->name, room->tube->salle->name); tmp->tube = tmp->tube->next; } } void ft_printroom(t_room *room) { while (room) { ft_printf("\nnom de salle : %s\n", room->name); ft_printf("poid de passage : %d\n", room->way); while (room->tube) { if (room->tube->salle) ft_printf("link : %s\n", room->tube->salle->name); room->tube = room->tube->next; } room = room->next; } }
Go
UTF-8
880
3.640625
4
[]
no_license
package main import "fmt" func main() { fmt.Println(majorityElement([]int{3, 3, 4})) } //给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 // //你可以假设数组是非空的,并且给定的数组总是存在众数。 //majority-element //func majorityElement(nums []int) int { // result := make(map[int]int, 0) // for _, num := range nums { // if _, ok := result[num]; !ok { // result[num] = 1 // } else { // result[num] = result[num] + 1 // } // if result[num] > len(nums)/2 { // return num // } // } // return 0 //} // 摩尔投票法 func majorityElement(nums []int) int { result, count := nums[0], 1 for i := 1; i < len(nums); i++ { if result == nums[i] { count++ } else { count-- if count == 0 { result = nums[i] count = 1 } } } return result }
Swift
UTF-8
938
2.796875
3
[ "Apache-2.0" ]
permissive
// // Drafts.swift // Slide for Reddit // // Created by Carlos Crane on 1/22/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import UIKit class Drafts { public static var drafts: [NSString] = [] public static func addDraft(s: String) { for draft in drafts { if String(draft).trimmed() == s.trimmed() { return } } drafts.append(s as NSString) saveAndUpdate() } public static func initialize() { Drafts.drafts = UserDefaults.standard.array(forKey: "drafts") as! [NSString]? ?? [] } public static func saveAndUpdate() { UserDefaults.standard.set(Drafts.drafts, forKey: "drafts") UserDefaults.standard.synchronize() initialize() } public static func deleteDraft(s: String) { drafts.remove(at: drafts.index(of: s as NSString)!) saveAndUpdate() } }
Markdown
UTF-8
20,069
2.546875
3
[]
no_license
# RA_BLOS_Umich # BICYCLIST PERCEIVED LEVEL OF TRAFFIC STRESS: A QUALITY OF SERVICE MEASURE #### Author: Charlene Mingus, Georgia Institute of Technology, May 2015 #### Feb. 4, 2019 #### Draft Review # Contents - [Introduction](#introduction) - [Research Background](#research-background) - [Bicyclist-Typology](#bicyclist-typology) - [ABC Bicyclists (Skill level)](#abc-bicyclists-skill-level) - [Level of User Skill and Comfort](#level-of-user-skill-and-comfort) - [Bicycling Frequency](#bicycling-frequency) - [Stated Comfort Level: Four Types of Cyclists](#stated-comfort-level-four-types-of-cyclists) - [Sociodemographic and the Four Types of Cyclists](#sociodemographic-and-the-four-types-of-cyclists) - [Variables That Influence the Choice to Bicycle](#variables-that-influence-the-choice-to-bicycle) - [Models to Estimate Bicyclist Perception of the Quality of Service of a Facility](#models-to-estimate-bicyclist-perception-of-the-quality-of-service-of-a-facility) - [Methodology](#methodology) - [Typology - Cycle Atlanta LTS](#typology---cycle-atlanta-lts) - [Bicycle network](#bicycle-network) - [LTS Quality of Service Measure](#lts-quality-of-service-measure) - [Traffic Stress Criteria for Links](#traffic-stress-criteria-for-links) - [Signalized Intersections](#signalized-intersections) - [Criteria for Unsignalized Intersections](#criteria-for-unsignalized-intersections) - [Case Study](#case-study) - [Data](#data) - [Model](#model) - [Result](#result) - [Conclusion](#conclusion) - [Future Research](#future-research) - [Criteria for Links](#criteria-for-links) - [Criteria for Signalized Intersections](#criteria-for-signalized-intersections) - [Criteria for Unsignalized Intersections](#criteria-for-unsignalized-intersections-1) - [Validating LTS Typology](#validating-lts-typology) - [Validating LTS Quality of Service Tool Criteria](#validating-lts-quality-of-service-tool-criteria) <a name="Introduction"></a> # Introduction The objective of this study is to refine and apply a bicycle quality of service tool which will allow the assessment of transportation infrastructure design based on users’ perceived stress also known as Level of Traffic Stress (LTS). This study builds upon the Mineta Transportation Institute’s Level of Traffic Stress tool. Unlike other quality of service tools, LTS determines the stress of a route by the link or intersection with the highest link, not by the average stress. The tool was then applied to a case study area, a six mile buffer around the Atlanta BeltLine Eastside Trail in Atlanta, Georgia, to understand the facility designs and traffic conditions that create a bicycle network that people who do not currently bike, but are interested in biking would be comfortable riding on. The bicycle network includes not only facilities with bicycle specific accommodations, but also any roadway that does not prohibit bicycling by statute or regulation. Michigan Department of Transportation and the Center for Advancing Transportation Leadership and Safety (ATLAS Center), a University Transportation Center and Collaboration between the University of Michigan Transportation Research Institute (UMTRI) and the Texas A&M Transportation Institute (TTI) sponsored by the US Department of Transportation, Research and Innovative Technology Administration (RITA) funded this research. <a name="Research-Background"></a> # Research Background <a name="Bicyclist-Typology"></a> ### Bicyclist Typology <a name="ABC-Bicyclists-(Skill-level)"></a> ##### ABC Bicyclists (Skill level) In a 1994 report, Selecting Roadway Design Treatments to Accommodate Bicycles, the FHWA classified cyclists based on skill level as Advanced Bicyclists, Basic Bicyclists, and Children. The recommendation was to encourage designing bicycle facilities for “B” or basic bicyclists, but the proportion of the population that could be classified into each category still needed to be quantified. <a name="Level-of-User-Skill-and-Comfort"></a> ##### Level of User Skill and Comfort The 2012 AASHTO Guide for the Development of Bicycle Facilities categorizes bicyclists based on age, experience and confidence. It identified two rider types: Experienced and Confident rider type which includes, “bicyclists who are comfortable riding on most types of facilities,” such as roads without any bicycle specific treatments, and riders who prefer low-traffic residential streets or separated paths; Casual and Less Confident riders, which may ride frequently for many purposes, bicycle occasionally and only ride on low-traffic streets or separated paths, ride for recreation possibly with children, or use the bicycle as a necessary mode for transportation. <a name="Bicycling-Frequency"></a> ##### Bicycling Frequency Winters et al: regular cyclists who cycle at least once a week; frequent cyclists who ride at least monthly; occasional cyclists who ride at least once a year; and potential cyclists who had no ridden in the previous year, but would like to ride in the future. Dill and Voros: Non-Cyclists who never ride a bicycle or who occasionally ride but did not ride during the past summer of in non-summer months; Irregular Cyclists who rode in the past summer, but not in non-summer months or those who rode year-round, but less than once a week; and Regular Year-Round Cyclists who rode year-round at least once a week. Sanders: Non-cyclist; Infrequent cyclist; and Frequent cyclist Ahmed et al.: Committed Cyclists and Casual Cyclists <a name="Stated-Comfort-Level:-Four-Types-of-Cyclists"></a> ##### Stated Comfort Level: Four Types of Cyclists Roger Geller, the City of Portland’s Bicycle Coordinator in 2006, attempted to categorize the entire population, current and potential bicyclists, by their comfort riding on different types of bicycle facilities. Four categories were then defined as. - The Strong and Fearless: individuals who would bicycle in almost any road or traffic condition with no consideration of separated bicycle facilities. - The Enthused and Confident: individuals who are comfortable riding in the roadway with motor vehicles but they prefer their own facilities. - The Interested but Concerned: interested in bicycling, however, they are unwilling to bicycle on shared roadways with high motor vehicle travel speeds and traffic volumes and will only bicycle on roadways with low speeds and low traffic volumes like neighborhood roads and prefer to ride on bicycle or shared-use only facilities. - No Way No How: people who would never considering bicycling for various reasons from physical inability to bicycle, topography, or lack of interest. The Interested but Concerned category makes up approximately 60 percent of Portland’s population. Thus, The Portland Bicycle Master Plan stated that its target was the Interested but Concerned category. This classification was developed based on professional experience, which must be verified and refined with additional research. Dill and McNeil conducted a random phone survey in Portland, Oregon and verified these categories. But still, additional survey should be conducted in other cities in the U.S. to verify if the typology is applicable or other adjustments should be made. <a name="Sociodemographic-and-the-Four-Types-of-Cyclists"></a> ##### Sociodemographic and the Four Types of Cyclists Misra et al. further modified the topology by dividing the Interested but Concerned category into two groups: Comfortable but Cautious and Interested but Concerned. Under this scenario, they were defined as: - Comfortable but Cautious group: include female bicyclists and/or older bicyclists who are bicycle enthusiasts, but may be more risk adverse which makes the type appear less confident than the Enthused but Confident type. - Interested but Concerned: contain people who were interested in bicycling, but who had significant safety concerns The study also showed that sociodemographic characteristics, particularly age, gender, and rider history, were significant predictors of people’s self-classification into different types. Using socio-demographic characteristics to predict user type can help predict facility design needs for a city as potential cyclist’s preferences can be predicted. <a name="Variables-That-Influence-the-Choice-to-Bicycle"></a> ### Variables That Influence the Choice to Bicycle - Weather: temperature, precipitation and wind, no consistent influence. - Actual and Perceived Safety: the public perception of bicycling accidents as an inescapable element of bicycling and blaming bicyclists for placing themselves in peril - City Size and Population Density: cities or metropolitan areas with higher levels of density have higher cycling mode share - Public attitude toward bicycling: people consider bicycling as abnormal in the U.S.. “Fewer bicyclists  more abnormal” is a self-perpetuating cycle. - Relative Cost of Motor Vehicles and Public Transit: In the U.S., “less robust transit system” and “lower cost of utilizing a motor vehicle” both encourage the use of motor vehicles even for short trips that could be walked or biked. - Income and Sociodemographic: higher income level  less likely to bicycle; women bicycle less than men - Topography: The impact of hilliness on the decision to bicycle as compared to other variables is thought to be moderate. - Bicycle Parking and End of Destination Infrastructure: the availability of bicycle parking improves the cyclists’ perception and when located at transit stops encourages multi-modal trips - Distance from Origin to Destination: distance threshold is only being set by current bicyclists with no consideration of potential bicyclists - Traffic, Roadway, and Bikeway Characteristics: positive impact, Misra et al.’s research showed all cyclist types preferred separated bicycle facilities Winters analysis found that environmental and engineering factors carried the strongest influence; including facility design, safety issues, topography, scenery, and weather. <a name="Models-to-Estimate-Bicyclist-Perception-of-the-Quality-of-Service-of-a-Facility"></a> ### Models to Estimate Bicyclist Perception of the Quality of Service of a Facility ![Image12](https://github.com/cadtju/RABLOSUMICH/blob/master/image/12.PNG) <a name="Methodology"></a> # Methodology By outlining the criteria to classify roadways and separated bicycle facilities by level of traffic stress based on geometric design and traffic characteristics, this study tried to create a quality of service measure which connects user tolerance for perceived traffic stress with roadway and bikeway characteristics that can be measured in the field. <a name="Typology---Cycle-Atlanta-LTS"></a> ##### Typology - Cycle Atlanta LTS The Cycle Atlanta LTS typology is used in this research as the basis for the LTS roadway and bikeway criteria which are discussed in more detail later. By associating a specific typology with LTS levels for roadway and bikeway criteria it will be possible for future research to validate the criteria based on revealed and stated preference. Misra is currently conducting research to compare the LTS classification of routes that people chose to bicycle and the Cycle Atlanta LTS typology that they identify as. This research can help refine the LTS criteria for classifying roadways and bikeways. ![Image1](https://github.com/cadtju/RABLOSUMICH/blob/master/image/1.png) <a name="Bicycle-network"></a> ##### Bicycle network In the context of this research, the bicycle network includes any facility that a bicycle is allowed to travel on from streets to shared use paths or greenways. ![Image2](https://github.com/cadtju/RABLOSUMICH/blob/master/image/2.png) ![Image3](https://github.com/cadtju/RABLOSUMICH/blob/master/image/3.png) ![Image4](https://github.com/cadtju/RABLOSUMICH/blob/master/image/4.png) ![Image5](https://github.com/cadtju/RABLOSUMICH/blob/master/image/5.png) <a name="LTS-Quality-of-Service-Measure"></a> ##### LTS Quality of Service Measure The LTS quality of service measure outlined below builds upon the MTI LTS. Roadways and bikeways categorized at LTS 1 are the least stressful and have low traffic volumes and low speed limits, while roadways and bikeways categorized as LTS 4 are the most stressful and have the highest traffic volumes and speed limits. It is estimated that the majority of current and potential bicyclists find LTS 1 and LTS 2 facilities comfortable. Within the LTS quality of service measure, a person who identifies as LTS 3 will find LTS 3, LTS 2, and LTS 1 facilities comfortable, a person who identifies as LTS 2 will find LTS 2 and LTS 1 facilities comfortable and so on. The criteria matrices follow the rule that the aspect of a link or intersection with the highest LTS determines the LTS of that segment or intersection. ![Image13](https://github.com/cadtju/RABLOSUMICH/blob/master/image/13.png) <a name="Traffic-Stress-Criteria-for-Links"></a> ##### Traffic Stress Criteria for Links Level of traffic stress was applied to links or segments between intersections for separated, protected, and on street bicycle facilities. The roadway and traffic characteristics which are considered for all roadways and bicycle facility links except for shared-use paths, side paths, and protected cycle tracks are: 1. street width or through lanes per direction, 2. traffic volume of annual average daily traffic (AADT) and functional class 3. posted speed limit. 4. On street Parking (data availability) - Criteria for Separated Bicycle Facilities - Criteria for Bicycle Lanes With and Without On Street Parking - Criteria for Buffered Bike Lanes With and Without On Street Parking - Criteria for Shared Travel Lanes <a name="Signalized-Intersections"></a> ##### Signalized Intersections Intersection design is a very important component of perceived level of traffic stress for users. Unfortunately, very little research has been conducted on the topic, especially intersection design for protected bicycle facilities. studies have shown that intersection crossings and right and left turns are important for bicyclist route choice. Broach, Dill, and Gliebe’s study found that bicyclists preferred intersections without traffic signals or stop signs since they increased delay. However, when traffic volume was moderate or heavy on the crossing street bicyclists in the study preferred traffic signals <a name="Criteria-for-Unsignalized-Intersections"></a> ##### Criteria for Unsignalized Intersections ##### Data Summary - Protected Bicycle facility - Side path - Shard-use path - Street width - Traffic volume - Functional class - Speed limit <a name="Case-Study"></a> # Case Study This study focused on the Atlanta BeltLine Eastside trail in Atlanta, Georgia. A six-mile buffer around the Atlanta BeltLine Eastside Trail was designated as the study area. <a name="Data"></a> ### Data ![Image6](https://github.com/cadtju/RABLOSUMICH/blob/master/image/6.png) The RC_ROUTES_ARC attribute information had to be transferred to NAVTEQ Streets 2014 through a manual process due to the lack of common field. They further manually geocoded: the location of on street parking on roadways with conventional bicycle lanes and buffered bicycle lanes; intersections with right turn only motor vehicle lanes that connect to links with conventional bicycle lanes, buffered bicycle lanes, or protected cycle tracks, the location of bike boxes. The process was extremely time consuming. <a name="Model"></a> ### Model Join and relate --> Geocoding --> Buffer and Intersect --> SQL Query and Symbology (Categorization) --> Filed Calculator (Length Summary) --> Add NPU Layer --> Network Analyst (Unsignalized Intersection Analysis) --> Add the Bike Boxes Layer <a name="Result"></a> ### Result - Criteria for left-turning bicyclist at signalized intersections and criteria for bicycle through movement at unsignalized intersections are excluded from this map. The map has a limited number of roadways and bikeways coded blue or LTS 1, however, a large portion of the map has green or LTS 2 roadways and bikeways. ![Image7](https://github.com/cadtju/RABLOSUMICH/blob/master/image/7.png) ![Image8](https://github.com/cadtju/RABLOSUMICH/blob/master/image/8.png) - While a majority of the roadways and bikeways in the study area are classified as LTS 1 and LTS 2, these facilities appear to not be well connected. Connectivity analysis was not conducted in this thesis. Instead an analysis of the bikeshed of the Atlanta BeltLine Eastside Trail for LTS 1 and LTS 2 facilities was completed. A bikeshed is the distance that a bicyclist can travel from a given point outward, in this case the Atlanta BeltLine Eastside Trail. ![Image9](https://github.com/cadtju/RABLOSUMICH/blob/master/image/9.png) - They study then look into the connectivity between the bikesheds and different Neighborhood Planning Units (NPUs). The majority of NPU E, M, and W are not reached by the Eastside Trail LTS 1 and LTS 2 bikeshed. NPU E and M are likely to see mode share increase due to the concentration of students if low stress infrastructure is installed. ![Image10](https://github.com/cadtju/RABLOSUMICH/blob/master/image/10.png) - The next image compares the bikeshed with and without this criteria applied. The dark grey facilities are those that were included in Figure 12-14, but which were excluded in Figure 14 due to the presence of unsignalized intersections which exceeded LTS 1 and LTS 2 criteria. ![Image11](https://github.com/cadtju/RABLOSUMICH/blob/master/image/11.png) <a name="Conclusion"></a> # Conclusion This research refined the LTS tool introduced by the MTI, however, the current and potential bicyclist typology and the design and traffic criteria used in the LTS quality of service tool should be modified. By orienting the bicycle network toward low stress bikeways and roadways the LTS quality of service tool avoids trying to place bicycle facilities on arterials and other roadways with high traffic volume, posted speed, and number of through lanes, which are preferred for motor vehicle traffic. Simplifying the roadway and bikeway network assists in creating maps which can be easily read. However, the roadway and bikeway network should be developed in the future to include directionality. The primary issues with this simplification were: - roadway links with a bicycle facility in one direction, but not the other resulting in a lower LTS categorization - intersection approaches where the bicycle facility was dropped in one direction, but not the other resulting in a higher LTS categorization for the link, - roadways where bicycling is restricted due to streetcar rails in one direction, but not the other resulting in an LTS categorization in a restricted access area, - on street parking located by a bicycle facility in one direction by not the other resulting in a lower LTS categorization. <a name="Future-Research"></a> # Future Research <a name="Criteria-for-Links"></a> ### Criteria for Links - Pavement Markings and Signage - Traffic Calming - Slope - Bicycle Lane Blockage - Bicycle Boulevards <a name="Criteria-for-Signalized-Intersections"></a> ### Criteria for Signalized Intersections - Signalized Separated Turning Movements: Bicycle signals may be installed at signalized intersections to reduce conflict between motor vehicles and bicycles by creating separate signal phasing for motor vehicle and bicycle movements. - The vehicle entry point <a name="Criteria-for-Unsignalized-Intersections"></a> ### Criteria for Unsignalized Intersections - Bicycle Through Movement at Unsignalized Intersections with and without a Median Refuge Island <a name="Validating-LTS-Typology"></a> ### Validating LTS Typology - Reaching potential bicyclist groups <a name="Validating-LTS-Quality-of-Service-Tool-Criteria"></a> ### Validating LTS Quality of Service Tool Criteria - Stated preference VS. Actual Preference
PHP
UTF-8
1,005
2.59375
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); /** * Test project. * @license http://www.spdx.org/licenses/MIT MIT License */ namespace ChainCommandBundle\EventListener; use ChainCommandBundle\Console\ChainManager; use Symfony\Component\Console\Event\ConsoleTerminateEvent; /** * Terminate listener for manage command chaining. * @author Mykola Zyk <mykola.zyk@dinecat.com> */ class TerminateListener { /** * @var ChainManager */ private $manager; /** * Constructor. * * @param ChainManager $manager */ public function __construct(ChainManager $manager) { $this->manager = $manager; } /** * Update exit code after launch chain of commands. * * @param ConsoleTerminateEvent $event */ public function onConsoleTerminate(ConsoleTerminateEvent $event) { if ($this->manager->getLastChain() === $event->getCommand()->getName()) { $event->setExitCode($this->manager->getChainExitCode()); } } }
Markdown
UTF-8
1,939
3.375
3
[]
no_license
# react-basic-slider A slider with basic markup, easy to style. ## Demo http://alexjoffroy.github.io/react-basic-slider/example/ ## Usage ### Install (not yet) ``` npm install --save react-basic-slider ``` ### Properties | Property | Type | Description | Default value | Required | | ------------- | ---- | ----------- | ------------- | -------- | | className | string | Custom classname for the component | _ | no | | currentIndex | number | Index of the first slide to display on render | 0 | no | | interval | number | Delay (ms) between each slide. Set to 0 to disable autoloop | 0 | no | | onSlideChange | function | Closure when changing slide, called with state.currentIndex as argument | _ | no | | style | object | Custom styles | {} | no | | transitionDuration | number | Duration (ms) of the transition when changing slide | 0 | no | ### Methods | Method | Description | | ------------- | ----------- | | goTo(index) | Displays the specified slide | | next() | Shortcut to display the next slide | | previous() | Shortcut to display the previous slide | ### Example ```javascript <Slider style={ { height: '400px' } } transitionDuration={500} interval={2000} > <div>Slide1</div> <div>Slide2</div> <div>Slide3</div> </Slider> ``` You'll also have to include the CSS or SCSS file in your project. See example to get more details. ## Development Clone the repository: ``` git clone https://github.com/the-cormoran/react-basic-slider.git ``` Install dependencies: ``` cd react-fitted-image && npm install ``` Commands: ```shell npm run lib # build the lib npm run example # build the example npm run test # run the tests npm run lint # lint the code npm run build # run lint, test, and lib in order to publish the package ```
Shell
UTF-8
2,777
3.890625
4
[ "CC0-1.0" ]
permissive
#!/bin/bash CDIR=`dirname ${0}` cd ${CDIR}/ CONF_FILE='ctrl_aircleaner_config.txt' ALERT_FILE='../logging/logs/kafun_alert.txt' LOG_FILE=logs_aircleaner/log_`date +"%Y%m%d"`.txt NOW=`date +"%Y-%m-%dT%T"` NOW_DATE=`date +"%Y-%m-%d"` NOW_UNIXTIME=`date +%s` RETRY_TIME=45 #sec #check today is holiday(sat,sun,national holiday) or not TODAY=`date +"%Y-%m-%d"` DOW=`date +"%w"` JPHOLIDAY=`cat ../holiday.json | grep ${TODAY} | wc -l` HOLIDAY=0 if [ ${DOW} -eq 0 -o ${DOW} -eq 6 -o ${JPHOLIDAY} -eq 1 ]; then HOLIDAY=1 fi #initialize STARTUP_TIME=0 TURN_ON_FLAG=0 #check kafun alert flag LAST_KAFUN_ALERT_DATE=`tail -n 1 ${ALERT_FILE}` if [ ${LAST_KAFUN_ALERT_DATE} = ${NOW_DATE} ]; then TURN_ON_FLAG=1 fi #read config while read conf_str; do #parse config if [ `echo ${conf_str} | cut -c 1` = "#" ]; then #echo "comment" continue fi TRIGGER_DAY_TYPE=`echo ${conf_str} | cut -d',' -f 1` TRIGGER_HOUR=`echo ${conf_str} | cut -d',' -f 2 | sed 's/^[ ]*//'` TRIGGER_MIN=`echo ${conf_str} | cut -d',' -f 3 | sed 's/^[ ]*//'` case "${TRIGGER_DAY_TYPE}" in "WEEK_DAY" ) TRIGGER_DAY_TYPE=0 ;; "HOLIDAY" ) TRIGGER_DAY_TYPE=1 ;; * ) echo "[READ_CONF_ERROR]" TIME=${NOW}, TRIGGER_DAY_TYPE=${TRIGGER_DAY_TYPE} >> ${LOG_FILE} exit ;; esac #check time trigger STARTUP_UNIXTIME=`date +%s --date "${NOW_DATE} ${TRIGGER_HOUR}:${TRIGGER_MIN}"` if [ ${TRIGGER_DAY_TYPE} -eq ${HOLIDAY} ] && [ ${NOW_UNIXTIME} -ge ${STARTUP_UNIXTIME} ] && [ ${NOW_UNIXTIME} -le `expr ${STARTUP_UNIXTIME} + ${RETRY_TIME}` ]; then STARTUP_TIME=1 fi #set send signal type if [ ${STARTUP_TIME} -eq 1 ]; then TRIGGER_MODE=`echo ${conf_str} | cut -d',' -f 4 | sed 's/^[ ]*//'` break fi done < ${CONF_FILE} #send IR Signal if [ ${STARTUP_TIME} -eq 1 ] && [ ${TURN_ON_FLAG} -eq 1 ]; then case "${TRIGGER_MODE}" in "on" ) ./ctrl_aircleaner.sh on echo "[**STARTUP-AIR-CLEANER**]" TIME=${NOW} MODE=${TRIGGER_MODE} >> ${LOG_FILE} ;; "turbo" ) ./ctrl_aircleaner.sh on sleep 10 ./ctrl_aircleaner.sh turbo echo "[**STARTUP-AIR-CLEANER-TURBO**]" TIME=${NOW} MODE=${TRIGGER_MODE} >> ${LOG_FILE} ;; "off" ) ./ctrl_aircleaner.sh off echo "[**SHUTDOWN-AIR-CLEANER**]" TIME=${NOW} MODE=${TRIGGER_MODE} >> ${LOG_FILE} ;; * ) echo "[SIGNAL_TYPE_ERROR]" TIME=${NOW}, HOLIDAY=${HOLIDAY}, STARTUP_TIME=${STARTUP_TIME}, TURN_ON_FLAG=${TURN_ON_FLAG}, MODE=${TRIGGER_MODE} >> ${LOG_FILE} exit ;; esac fi #Logging echo "[CHECK]" TIME=${NOW}, HOLIDAY=${HOLIDAY}, STARTUP_TIME=${STARTUP_TIME}, TURN_ON_FLAG=${TURN_ON_FLAG} >> ${LOG_FILE}
Java
UTF-8
165
2.109375
2
[]
no_license
package zillowdata; public class ZillowID { private String zID; public ZillowID(){ //do Http Get to get zpid } public String getID(){ return zID; } }
Java
UTF-8
2,357
2.40625
2
[]
no_license
package com.groth.android.videotoserver.buttonBar; import android.content.Context; import android.view.View; import com.groth.android.videotoserver.ConnectionServiceListeners; import com.groth.android.videotoserver.connection.ConnectionHandler; import com.groth.android.videotoserver.connection.ssh.ServerCommand; import java.util.Collection; import java.util.HashMap; public class ServerButtonCollection implements View.OnClickListener, ConnectionServiceListeners { private HashMap<Integer, ServerCommandButton> buttons = new HashMap<>(); private ConnectionHandler serverConnectionService; public ServerCommandButton initNewButton(Context context, int imageResource, ServerCommand serverCommand) { ServerCommandButton button = new ServerCommandButton(context, serverCommand); button.setImageResource(imageResource); button.setOnClickListener(this); button.setId(View.generateViewId()); if (serverConnectionService == null) { button.setEnabled(false); } buttons.put(button.getId(), button); return button; } public void registerButton(ServerCommandButton button) { buttons.put(button.getId(), button); } @Override public void setServerConnectionService(ConnectionHandler serverConnectionService) { this.serverConnectionService = serverConnectionService; getButtons().forEach(but -> but.setEnabled(true)); } @Override public void onServiceStopped() { getButtons().forEach(but -> but.setEnabled(false)); } @Override public void onClick(View view) { if (buttons.containsKey(view.getId())) { ServerCommandButton button = buttons.get(view.getId()); handleServerCommand(button.getCommand()); } } private void handleServerCommand(ServerCommand cmd) { if (validateServerConnection()) { serverConnectionService.getConnection().sendShellCommand(cmd); } } private boolean validateServerConnection() { return serverConnectionService != null && serverConnectionService.getConnection() != null; } public Collection<ServerCommandButton> getButtons() { return buttons.values(); } public HashMap<Integer, ServerCommandButton> getButtonHashMap() { return buttons; } }
C++
UTF-8
925
2.578125
3
[]
no_license
#include "Distance.h" Distance::Distance(): _proximityThreshold(DEFAULT_THRESHOLD), _hysteresis(DEFAULT_HYSTERESIS), _isWithinRange(false) { } uint8_t Distance::Init() { return begin(); } uint16_t Distance::GetDistance() { update(); return _distance; } bool Distance::IsWithinThreshold() { update(); return _isWithinThreshold; } bool Distance::IsWithinRange() { update(); return _isWithinRange; } void Distance::update() { rangingTest(&_measure, false); if (_measure.RangeStatus != 4) { _distance = _measure.RangeMilliMeter; _isWithinRange = true; } else { _isWithinRange = false; } uint16_t threshold; if (_isWithinThreshold) { threshold = _proximityThreshold + _hysteresis; } else { threshold = _proximityThreshold - _hysteresis; } _isWithinThreshold = (_distance < threshold); }
Python
UTF-8
2,487
2.625
3
[]
no_license
import numpy as np import librosa from librosa import display import pyaudio as pa import wave import scipy.io.wavfile as sciwavf import matplotlib.pyplot as plt import struct """ Basic wav file i/o """ def record(filename, time = 5, rate = 22050, chunk = 1024): CHUNK = chunk FORMAT = pa.paInt16 CHANNELS = 1 RATE = rate RECORD_SECONDS = time WAVE_OUTPUT_FILENAME = filename p = pa.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("* recording") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) print("* done recording") stream.stop_stream() stream.close() p.terminate() wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() def play(filename): CHUNK = 1024 wf = wave.open(filename, 'rb') p = pa.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(CHUNK) while data != b'': stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate() def store(filename, chunk, f): sciwavf.write(filename, f, chunk) def load(filename, sr = 22050): wav, f = librosa.load(filename, sr = 22050) print('wav file infomation:') print('length of wav file: %d' % len(wav)) print('sampling frequency is: %d' % f) return wav, f """ Raw data operation """ def getRawData(filename): CHUNK = 1024 wf = wave.open(filename, 'rb') p = pa.PyAudio() raw_data = [] data = wf.readframes(CHUNK) while data != b'': # stream.write(data) data = wf.readframes(CHUNK) raw_data.append(data) p.terminate() return raw_data def decodePCM(rawData): npts=len(rawData) formatstr='%dh' % (npts/2) int_data=struct.unpack(formatstr,rawData) f_data = np.array([float(val) / pow(2, 15) for val in int_data]) return f_data
Java
UTF-8
3,030
2.8125
3
[]
no_license
package ch.uzh.ifi.rerg.se16_climeter.client.filter; import java.util.Date; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.widgetideas.client.SliderBar; import ch.uzh.ifi.rerg.se16_climeter.client.Console; /** * The class TimeLine extends the SliderBar class * and creates a SliderBar object which is used * in the MapComposite class. * * @author Timo Surbeck * @history 2016-11-23 TS First Version * 2016-11-26 TS on-change stub method * 2016-12-02 TS step size fixed * 2016-12-03 TS added updateValue method * 2016-12-03 TS fixed arrow key problem * 2016-12-05 TS submitting new filter objects * to MapComposite class * @version 2016-12-05 TS 1.2 * @responsibilities */ public class TimeLine extends SliderBar { // reference time value for change checking in updateValue(double value) protected double value; private Filterable filterable; public TimeLine(Filterable filterable, double minValue, double maxValue) { super(minValue, maxValue, new LabelFormatter() { @Override public String formatLabel(SliderBar slider, double value) { return (int) value + ""; } }); this.filterable = filterable; this.setStepSize(1); this.setCurrentValue(minValue + ((maxValue-minValue)/2)); this.setNumTicks((int)(maxValue - minValue)/2); this.setNumLabels((int)(maxValue - minValue)/20); this.setSize("100%", "100%"); this.addMouseUpHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { updateValue(getCurrentValue()); } }); this.addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if(event.isRightArrow() && getCurrentValue() < getMaxValue()){ updateValue(getCurrentValue()+1); } if(event.isLeftArrow() && getCurrentValue() > getMinValue()){ updateValue(getCurrentValue()-1); } } }); updateValue(this.getCurrentValue()); } /** * Checks whether there has been an actual change on the currentValue. * If there was a change on value, the method creates a new filter * object containing new date info (year) and submits it to the * MapComposite class object. * @pre this.value != null * @post this.value == value * @return - */ @SuppressWarnings("deprecation") public void updateValue(double value){ if(this.value != value){ this.value = value; Console.log("TimeLine: Value changed, new year: " + value); Filter filter = this.filterable.getOldFilter(); Date chosenYear = new Date((int) value-1900, 0, 1); filter.setBeginDate(chosenYear); filter.setEndDate(chosenYear); filterable.apply(filter); } else { Console.log("TimeLine: NO change on value, year: " + this.value); } } }
Markdown
UTF-8
754
2.703125
3
[]
no_license
Phpass Starter is an easy way to learn more about and get started with [Phpass](http://www.openwall.com/phpass/). The purpose of this project is to get more developers to move away from functions such as `md5();` that weren't meant for password hashing. Using proper password encryption techniques is now easier thanks to the many frameworks out there such as Phpass, but can seem a bit confusing at first. Phpass Starter is meant to lower the learning curve so that developers of various skills can finally build more secure websites. # What's Inside `PasswordHash.php`: The actual Phpass framework. `signup.php`: Example code for creating a hash of a user's password. `login.php`: Example code for checking a user's password against a stored hash.
Python
UTF-8
284
2.84375
3
[]
no_license
from abc import ABCMeta, abstractmethod class StudentVisitor(metaclass=ABCMeta): @abstractmethod def startVisit(self): pass @abstractmethod def visitStudent(self, number, student): pass @abstractmethod def finishVisit(self): pass
JavaScript
UTF-8
1,319
2.8125
3
[ "MIT" ]
permissive
const { default: axios } = require('axios'); const moment = require('moment') const Horoscope = class { constructor(data) { this.sign = data.sign; this.rank = data.rank; this.total = data.total; this.content = data.content; this.item = data.item; this.color = data.color; this.money = data.money; this.job = data.job; this.day = data.day; this.love = data.love; } }; async function fetchHoroscope(date) { const d = moment(date).format('YYYY/MM/DD'); const urlbase = "http://api.jugemkey.jp/api/horoscope/free/" const response = await axios.get(urlbase + d); const { horoscope } = response.data; return horoscope[d].map((horo) => new Horoscope(horo)); } module.exports = { /** * @param {Date} date * @returns {Horoscope[]} */ get: async function (date) { return await fetchHoroscope(date); }, /** * @returns {Horoscope[]} */ today: async function () { return await fetchHoroscope(); }, /** * @param {Date} date * @returns {Horoscope} */ random: async function (date) { const d = date ? moment(date) : moment(); const horoscopes = await fetchHoroscope(d); const rnd = Math.floor(Math.random() * horoscopes.length); return horoscopes[rnd]; } }