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
Ruby
UTF-8
646
2.5625
3
[ "MIT" ]
permissive
require "strategy" module AuthStrategies class Manager def initialize(app, &block) @app = app @auth_strategies = StrategyManager.new instance_eval(&block) if block_given? end def register(name, &block) @auth_strategies.register name, &block end def authenticate @auth_strategies.each do |name, strategy| if strategy.valid? return strategy.authenticate! end end :fail end def call(env) @env = env env["authstrategies"] = self @auth_strategies.each { |_, strategy| strategy.load(env) } @app.call(env) end end end
C++
UTF-8
701
2.625
3
[]
no_license
#include "stdafx.h" #include "CppUnitTest.h" #include "../PQ12/FileReader.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace PQ1_UT { TEST_CLASS(FileReaderTest) { public: TEST_METHOD(read_file_content_test) { FileReader fr; std::vector<int> nums; std::string path = "..\\gistfile1.txt"; nums = fr.read_file_content("..\\gistfile1.txt"); Assert::IsTrue(nums.size() != 0); } TEST_METHOD(sum_elements_test) { FileReader f; std::vector<int> nums; unsigned long long sum = 5000050000; std::string path = "..\\gistfile1.txt"; nums = f.read_file_content("..\\gistfile1.txt"); Assert::AreEqual(sum, f.get_sum(nums)); } }; }
Java
UTF-8
1,436
2.15625
2
[]
no_license
package com.example.service; import com.example.client.BookClient; import com.example.pojo.Book; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class CBookService { @Autowired RestTemplate restTemplate; @Autowired BookClient bookClient; @HystrixCommand(fallbackMethod = "SellErro") //回调方法的参数列表,返回值类型必须与下面方法的一致,否则会出现fallback method wasn't found: addServiceFallback([class java.lang.Integer]) public Book sellBook(String bookNmae){ /*String serviceId="BOOK-SERVICE"; // 该值就是book-service:8763或者 book-service:8764,必须在RestTemplate注入的地方@LoadBalanced //return restTemplate.getForObject("http://"+serviceId+"/book/findByName/"+bookNmae,Book.class); return restTemplate.getForObject("http://localhost:8763/book/findByName/"+bookNmae,Book.class);*/ return bookClient.sellBook(bookNmae); } @HystrixCommand(fallbackMethod ="countErro" ) public String findAll() { return bookClient.findAll(); } public String countErro(){ return "系统繁忙,请稍后再试"; } public String SellErro(String bookNmae){ return "抱歉,请稍后再试"; } }
Python
UTF-8
730
3.53125
4
[]
no_license
import random A = { 1:"Rock", 2:"Scissors", 3:"Paper" } c = 0 u = 0 while True: choose = random.randint(1,3) computer = A[choose] print("------------------------\nComputer; {} User; {}\n------------------------".format(c,u)) user = A[int(input("1-Rock 2-Scissors 3-Paper\n;"))] print("Computer Choose {}".format(computer)) if user == "Rock" and computer != "Paper": print("User Won") u +=1 elif user == "Scissors" and computer !="Rock": print("User Won") u +=1 elif user == "Paper" and computer != "Scissors": print("User Won") u +=1 else: print("Computer Won") c +=1 # Rock > Scissors > Paper > Rock
Ruby
UTF-8
11,716
2.578125
3
[]
no_license
require "spec_helper" module InMemory describe LogTimeRepo do before(:each) do @file_wrapper = double @json_store = JsonStore.new(@file_wrapper) data = { "employees": [ { "id": 1, "username": "defaultadmin", "admin": true, "log_time": [ { "id": 1, "date": "2017-01-01", "hours_worked": 1, "timecode": "Non-Billable", "client": nil } ] }, { "id": 2, "username": "rstarr", "admin": false, "log_time": [ { "id": 2, "date": "2017-01-02", "hours_worked": 1, "timecode": "Non-Billable", "client": nil }, { "id": 3, "date": "2017-01-02", "hours_worked": 1, "timecode": "Non-Billable", "client": nil } ] } ], "clients": [ { "id": 1, "name": "Google" } ] } data = JSON.parse(JSON.generate(data)) expect(@file_wrapper).to receive(:read_data).and_return(data) @json_store.load @employee_repo = EmployeeRepo.new(@json_store) @log_time_repo = LogTimeRepo.new(@json_store) end def create_log_entry(employee_id, date, hours_worked, timecode,client=nil) params = { "employee_id": employee_id, "date": date, "hours_worked": hours_worked, "timecode": timecode, "client": client } @log_time_repo.create(params) end def generate_entry_hash(id, employee_id, date, hours_worked, timecode, client) { "id": id, "employee_id": employee_id, "date": Date.strptime(date, '%Y-%m-%d'), "hours_worked": hours_worked.to_i, "timecode": timecode, "client": client } end describe ".log_time_entries" do it "returns an array of log time objects from the data array" do entry_hash_1 = generate_entry_hash(1, 1, "2017-01-01", 1, "Non-Billable", nil) entry_hash_2 = generate_entry_hash(2, 2, "2017-01-02", 1, "Non-Billable", nil) expected_array = [ TimeLogger::LogTimeEntry.new(entry_hash_1), TimeLogger::LogTimeEntry.new(entry_hash_2) ] result_array = @log_time_repo.log_time_entries expect(result_array[0].id).to eq(expected_array[0].id) expect(result_array[1].hours_worked).to eq(expected_array[1].hours_worked) end end describe ".create" do context "the user has entered their log time" do it "creates an instance of the object LogTimeEntry and add it to entries" do create_log_entry(1,"2016-09-07", "8","Non-Billable") result = @log_time_repo.log_time_entries expect(result.count).to eq(4) expect(result[1].id).to eq(4) expect(result[1].hours_worked).to eq(8) end end end describe ".find_by" do it "takes in a log entry id and returns the object that corresponds to that id" do result = @log_time_repo.find_by(1) expect(result.id).to eq(1) expect(result.date.day).to eq(1) end it "returns nil if the id does not exist" do result = @log_time_repo.find_by(6) expect(result).to eq(nil) end end describe ".all" do it "returns a list of objects of all the log time entries that exist" do result = @log_time_repo.all expect(result.count).to eq(3) end end describe ".find_by_employee_id" do context "the employee has logged times" it "retrieves all the log times for a given employee" do result_array = @log_time_repo.find_by_employee_id(2) result_array.count(2) result_array.each do |result| expect(result.employee_id).to eq(2) end end context "the employee does not have logged times" do it "returns nil" do result = @log_time_repo.find_by_employee_id(6) expect(result).to eq(nil) end end end describe ".find_total_hours_worked_for_date" do it "returns the total hours for a given date" do create_log_entry(1,"2016-09-07", "8","Non-Billable") create_log_entry(1,"2016-09-07", "8","Non-Billable") create_log_entry(1,"2016-09-08", "7","Non-Billable") result = @log_time_repo.find_total_hours_worked_for_date(1, "09-07-2016") expect(result).to eq(16) end context "there are no entries for a given date" do it "returns 0" do create_log_entry(1,"2016-09-08", "7","Non-Billable") result = @log_time_repo.find_total_hours_worked_for_date(1, "09-07-2016") expect(result).to eq(0) end end end describe ".sorted_current_month_entries_by_employee_id" do it "returns the log entries for the current month sorted by date and filtered by employee id" do create_log_entry(1,"2016-09-04", "8","Non-Billable") create_log_entry(1,"2016-09-02", "8","Non-Billable") allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) result = @log_time_repo.sorted_current_month_entries_by_employee_id(1) expect(result[0].date.day).to eq(2) expect(result.count).to eq(2) end it "returns nil if there are no entries for an employee" do result = @log_time_repo.sorted_current_month_entries_by_employee_id(3) expect(result).to eq(nil) end end describe ".employee_client_hours" do context "all entries have a client" do it "returns a hash of the client name and hours worked for each client" do create_log_entry(1,"2016-09-05", "8","Billable", "Google") create_log_entry(1,"2016-09-07", "8","Billable", "Google") create_log_entry(1,"2016-09-07", "6","Billable", "Microsoft") create_log_entry(2,"2016-09-07", "6","Billable", "Microsoft") allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) result = @log_time_repo.employee_client_hours(1) client_hash = { "Google" => 16, "Microsoft" => 6 } expect(result).to eq(client_hash) end end context "not all entries have a client" do it "filters out the entries without a client and returns a hash hours worked for each client" do create_log_entry(1,"2016-09-05", "8","Billable", "Google") allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) result = @log_time_repo.employee_client_hours(1) client_hash = { "Google" => 8 } expect(result).to eq(client_hash) end end context "no entries have a client" do it "returns an empty hash" do allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) result = @log_time_repo.employee_client_hours(1) client_hash = {} expect(result).to eq(client_hash) end end context "no log time entries exist" do it "returns an empty hash" do @employee_repo.create("gharrison", false) result = @log_time_repo.employee_client_hours(3) client_hash = {} expect(result).to eq(client_hash) end end end describe ".employee_timecode_hours" do it "returns a hash of timecode and hours worked for each timecode" do create_log_entry(1,"2016-09-05", "8","Billable", "Google") create_log_entry(1,"2016-09-07", "8","PTO") create_log_entry(1,"2016-09-07", "6", "PTO") allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) result = @log_time_repo.employee_timecode_hours(1) timecode_hash = { "Billable" => 8, "PTO" => 14 } expect(result).to eq(timecode_hash) end context "no log time entries exist" do it "returns an empty hash" do @employee_repo.create("gharrison", false) result = @log_time_repo.employee_timecode_hours(3) timecode_hash = {} expect(result).to eq(timecode_hash) end end end describe ".company_timecode_hours" do context "all entries are for the current month of September" do it "returns a hash of the timecode and total hours per timecode" do allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) create_log_entry(1,"2016-09-05", "8","Billable", "Google") create_log_entry(2,"2016-09-07", "8","Non-Billable") create_log_entry(2,"2016-09-07", "6","Billable", "Microsoft") create_log_entry(2,"2016-09-07", "6", "PTO") result = @log_time_repo.company_timecode_hours timecode_hash = { "Billable" => 14, "Non-Billable" => 8, "PTO" => 6 } expect(result).to eq(timecode_hash) end end context "entries have date entries other than current month or year" do it "returns a hash of timecodes for the current month and year" do allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) create_log_entry(1,"2016-08-05", "8","Billable", "Google") create_log_entry(2,"2015-09-07", "8","Non-Billable") create_log_entry(2,"2016-09-07", "6","Billable", "Microsoft") create_log_entry(2,"2016-09-07", "6", "PTO") result = @log_time_repo.company_timecode_hours timecode_hash = { "Billable" => 6, "PTO" => 6 } expect(result).to eq(timecode_hash) end end end describe ".company_client_hours" do context "all entries are for the current month of September" do it "returns a hash of the client and total hours per client" do allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) create_log_entry(1,"2016-09-05", "8","Billable", "Google") create_log_entry(2,"2016-09-07", "8","Non-Billable") create_log_entry(2,"2016-09-07", "6","Billable", "Microsoft") create_log_entry(2,"2016-09-07", "6", "PTO") result = @log_time_repo.company_client_hours client_hash = { "Google" => 8, "Microsoft" => 6, } expect(result).to eq(client_hash) end end context "entries have date entries other than current month or year" do it "returns a hash of clients for the current month and year" do allow(Date).to receive(:today).and_return(Date.new(2016, 9, 28)) create_log_entry(1,"2016-08-05", "8","Billable", "Google") create_log_entry(2,"2015-09-07", "8","Non-Billable") create_log_entry(2,"2016-09-07", "6","Billable", "Microsoft") create_log_entry(2,"2016-09-07", "6", "PTO") result = @log_time_repo.company_client_hours client_hash = { "Microsoft" => 6 } expect(result).to eq(client_hash) end end end end end
C++
UTF-8
2,603
3.59375
4
[]
no_license
#include <bits/stdc++.h> using namespace std; bool isoperator(char ch); bool isoperand(char ch); bool ishigh(char ch1, char ch2); bool isopen(char ch); bool isclose(char ch); int getWeight(char ch); int evaluate(string exp); int operation(char op, int a, int b); string intopost(string exp); int main(){ int result; string infix; cout << "Enter an expression which evaluate less than 10" << endl; cin >> infix; result = evaluate(intopost(infix)); cout << result << endl; return 0; } bool isoperator(char ch){ if(ch == '+' || ch == '-' || ch == '*' || ch == '/') return true; return false; } bool isoperand(char ch){ if(ch >= '0' && ch <= '9') return true; return false; } bool isopen(char ch){ if(ch == '(') return true; return false; } bool isclose(char ch){ if(ch == ')') return true; return false; } bool ishigh(char ch1, char ch2){ if(getWeight(ch1) >= getWeight(ch2)) return true; return false; } int getWeight(char ch){ switch(ch){ case '/': case '*': return 2; case '+': case '-': return 1; default: return 0; } } string intopost(string exp){ char ch; string postfix = ""; stack <char> st; for(int i = 0; i < exp.size(); i++){ ch = exp[i]; if(isoperator(ch)){ while(!st.empty() && !isclose(st.top()) && ishigh(st.top(), ch)){ postfix += st.top(); st.pop(); } st.push(ch); } else if(isoperand(ch)) postfix += ch; else if(isopen(ch)) st.push(ch); else if(isclose(ch)){ while(!st.empty() && !isopen(st.top())){ postfix += st.top(); st.pop(); } st.pop(); } } while(!st.empty()){ postfix += st.top(); st.pop(); } return postfix; } int evaluate(string exp){ char ch; stack <int> st; for(int i = 0; i < exp.size(); i++){ ch = exp[i]; if(isoperator(ch)){ int n2 = st.top(); st.pop(); int n1 = st.top(); st.pop(); int res = operation(ch, n1, n2); st.push(res); } else if(isoperand(ch)){ int n = ch - '0'; st.push(n); } } return st.top(); } int operation(char op, int a, int b){ if(op == '+') return a + b; else if(op == '-') return a - b; else if(op == '*') return a * b; else if(op == '/' && b != 0) return a / b; else{ cout << "Unexpected Error!" << endl; return -1; } }
Java
UTF-8
240
2.5
2
[]
no_license
package mine.free.test; public class Test { int a = 0; int b = 0; public static void main(String[] args) throws Exception { final Test t = new Test(); t.a = 1; t.b = 2; System.out.println(t.a); System.out.println(t.b); } }
SQL
UTF-8
2,257
3
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Apr 22, 2018 at 10:33 PM -- Server version: 10.1.13-MariaDB -- PHP Version: 7.0.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `registration` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `user_role` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `email`, `password`, `user_role`) VALUES (1, 'dinesh', 'dineshnandi1996@gmail.com', '4074c2e6936f06672e9455e9f81664ab', 'admin'), (2, 'raj', 'raj@gmail.com', '67719c4c2dae2189c6a83110e9461c15', 'patient'), (4, 'rajesh', 'rajesh@gmail.com', 'af4e5834b08749e4351722895ad14f5a', 'patient'), (5, 'amit', 'amit@yahoo.com', '71f05ae4b4a6425bc883ba68ae96c6da', 'patient'), (6, 'vinay', 'vinay@yahoo.com', '78ffb54cea01b365797d0b883eba44fc', 'patient'), (8, 'salman', 'salman@gmail.com', '03346657feea0490a4d4f677faa0583d', 'patient'), (9, 'shahrukh', 'shahrukh@gmail.com', '44b9d0ad6994b0cd9b0a85152610895f', 'admin'), (11, 'anuj', 'anuj@gmail.com', 'ab6bc387cd023c16cb84ea7f407ae62e', 'patient'), (12, 'bajaj', 'bajajp@bajaj.com', 'a4b4038112fae25d8172bd054f655ed2', 'insurance'), (14, 'Metro_pathology', 'metro.pathology@gmail.com', 'b79d2096c66248cad58c309283bcd8d4', 'pathologist'), (15, 'bharat_pathology', 'bp@patho.com', 'dfb57b2e5f36c1f893dbc12dd66897d4', ''), (16, 'maxbupa', 'maxbupa@ins.com', '2ffe4e77325d9a7152f7086ea7aa5114', 'insurance'); -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
551
2.921875
3
[]
no_license
package linkedStack; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Employee a =new Employee("a", 1); Employee b =new Employee("b", 2); Employee c =new Employee("c", 3); Employee d =new Employee("d", 4); Employee e =new Employee("e", 5); Employee f =new Employee("f", 6); LinkedStack stack = new LinkedStack(); stack.push(a); stack.push(b); stack.push(c); stack.push(d); System.out.println(stack.peek()); //stack.printStack(); } }
Java
UTF-8
923
3.109375
3
[]
no_license
package Kattis.com; import java.util.Scanner; public class Trik { public static void main(String args[]){ Scanner sc=new Scanner(System.in); String str=sc.nextLine(); char [] position={'A','B','C'}; for(int i=0;i<str.length();i++){ if(str.charAt(i)=='A'){ char temp=position[0]; position[0]=position[1]; position[1]=temp; } else if(str.charAt(i)=='B'){ char temp=position[2]; position[2]=position[1]; position[1]=temp; } else if(str.charAt(i)=='C'){ char temp=position[2]; position[2]=position[0]; position[0]=temp; } } for(int i=0;i<3;i++){ if(position[i]=='A'){ System.out.println(""+(i+1)); } } } }
JavaScript
UTF-8
1,420
2.59375
3
[]
no_license
import { FETCH_FRIENDS_FAIL, FETCH_FRIENDS_START, FETCH_FRIENDS_SUCCESS, LOGIN_SUCCESS, LOGIN_FAIL, POST_FRIEND_START, POST_FRIEND_SUCCESS, POST_FRIEND_FAIL, DELE_FRIEND_START, DELETE_FRIEND_SUCCESS, DELETE_FRIEND_FAIL } from '../actions'; const initialState = { friends: [], isLoading: false, error: '' }; export const friendsReducer = (state = initialState, action) => { switch (action.type) { case FETCH_FRIENDS_START: return { ...state, isLoading: true, error: '' }; case FETCH_FRIENDS_SUCCESS: //console.log('reducer ',action.payload) return { ...state, friends: action.payload, isLoading: false, error: '' }; case FETCH_FRIENDS_FAIL: return { ...state, isLoading: false, error: action.payload }; case POST_FRIEND_START: return { ...state, isLoading: true, error: '' }; case POST_FRIEND_SUCCESS: return { ...state, friends: state.friends.concat(action.payload), isLoading: false, error: '' }; case POST_FRIEND_FAIL: return { ...state, isLoading: false, error: action.payload }; case DELETE_FRIEND_SUCCESS: //console.log('reducer',action.payload) return { ...state, friends: state.friends.filter(fr=> fr.id !== action.payload), isLoading: false, error: '' } default: return state; } };
Ruby
UTF-8
1,555
3.5
4
[]
no_license
# Author:: Mara von Kroge, Emilie Schuller # 27.11.2017 # TeamChallenger # Tests zur Klasse Stack # Dateien werden angefordert. require 'test/unit' require_relative 'stack_exceptions' # Testklasse wird erstellt. class TestStack < Test::Unit::TestCase # Neues Array wird erstellt. def setup() @stack=Stack.new end # Test - Initialize def test_initialize assert_not_equal(nil, @stack, "Dies ist kein leeres Array!") end # Test - Neues Element hinzufügen def test_push @stack.push("Dame") assert_equal("Dame", @stack.peek, "Diese Karte ist falsch!") assert_raise TypeError do @stack.push(nil) end end # Test - Länge def test_length assert_equal(0, @stack.length, "Die Länge ist falsch!") end # Test - Letztes Element wird entfernt def test_pop @stack.push("König") assert_equal("König", @stack.peek, "Diese Karte ist falsch!") @stack.pop assert_equal(0, @stack.length, "Diese Karte ist falsch!") assert_raise IndexError do @stack.pop end end # Test - Oberstes Element wird ausgegeben def test_peek @stack.push("Ass") assert_equal("Ass", @stack.peek, "Diese Karte ist falsch!") @stack.pop assert_equal(0, @stack.length, "Diese Karte ist falsch!") assert_raise IndexError do @stack.peek end end # Test - Empty def test_empty assert_equal(true, @stack.empty?, "Fehler!") end # Test - To_s def test_to_s @stack.push("Sieben") assert_equal("Sieben", @stack.peek, "Diese Karte ist falsch!") @stack.pop assert_equal(0, @stack.length, "Diese Karte ist falsch!!") assert_raise IndexError do @stack.to_s end end end
C++
UTF-8
5,137
2.8125
3
[]
no_license
#pragma once #ifndef Grid2D_H_758B1030_6F18_46B7_9EA5_9E7974186B6E #define Grid2D_H_758B1030_6F18_46B7_9EA5_9E7974186B6E #include <cassert> #include "Math/TVector2.h" #include "CppVersion.h" template< class T > class MappingPolicy { T& getData( T* storage , int sx , int sy , int i , int j ); T const& getData( T const* storage , int sx , int sy , int i , int j ) const; void build( T* storage , int sx , int sy ); void cleanup(); void swap( MappingPolicy& p ); }; template< class T > struct SimpleMapping { public: static T& getData( T* storage , int sx , int sy , int i , int j ) { assert( storage ); return storage[ i + sx * j ]; } static T const& getData( T const* storage , int sx , int sy , int i , int j ) { assert( storage ); return storage[ i + sx * j ]; } void build( T* storage , int sx , int sy ){} void cleanup( int sx , int sy ){} void swap( SimpleMapping& p ){} }; template < class T > struct FastMapping { FastMapping(){ mMap = 0; } #if CPP_RVALUE_REFENCE_SUPPORT FastMapping( FastMapping&& rhs ) :mMap( rhs.mMap ) { rhs.mMap = 0; } #endif T& getData( T* storage , int sx , int sy , int i , int j ) { assert( mMap ); return mMap[j][i]; } T const& getData( T const* storage , int sx , int sy , int i , int j ) const { assert( mMap ); return mMap[j][i]; } inline void build( T* storage , int sx , int sy ) { mMap = new T*[ sy ]; T** ptrMap = mMap; for( int i = 0 ; i < sy; ++i ) { *ptrMap = storage; ++ptrMap; storage += sx; } } inline void cleanup( int sx , int sy ) { delete [] mMap; mMap = 0; } void swap( FastMapping& p ) { using std::swap; swap( mMap , p.mMap ); } T** mMap; }; template < class T , template< class > class MappingPolicy = SimpleMapping > class TGrid2D : private MappingPolicy< T > { typedef MappingPolicy< T > MP; public: TGrid2D() { mStorage = nullptr; mSize = TVector2<int>::Zero(); } TGrid2D( int sx , int sy ) { build( sx , sy ); } TGrid2D( TVector2<int> const& size) : TGrid2D( size.x , size.y ){} TGrid2D( TGrid2D const& rhs ){ construct( rhs ); } ~TGrid2D(){ cleanup(); } #if CPP_RVALUE_REFENCE_SUPPORT TGrid2D( TGrid2D&& rhs ) :MP( rhs ) ,mStorage( rhs.mStorage ) ,mSize( rhs.mSize ) { rhs.mStorage = 0; rhs.mSize = TVector2<int>::Zero(); } TGrid2D& operator = ( TGrid2D&& rhs ) { this->swap( rhs ); return *this; } #endif typedef T* iterator; typedef T const* const_iterator; iterator begin(){ return mStorage; } iterator end() { return mStorage + getRawDataSize(); } T& getData( int i , int j ) { assert( checkRange( i , j ) ); return MP::getData( mStorage , mSize.x , mSize.y , i , j ); } T const& getData( int i , int j ) const { assert( checkRange( i , j ) ); return MP::getData( mStorage , mSize.x , mSize.y , i , j ); } T& operator()( int i , int j ) { return getData( i , j ); } T const& operator()( int i , int j ) const { return getData( i , j ); } T& operator()(TVector2<int> const& pos) { return getData(pos.x, pos.y); } T const& operator()(TVector2<int> const& pos) const { return getData(pos.x, pos.y); } T& operator[]( int idx ) { assert( 0 <= idx && idx < getRawDataSize()); return mStorage[ idx ]; } T const& operator[]( int idx ) const { assert( 0 <= idx && idx < getRawDataSize()); return mStorage[ idx ]; } T* getRawData() { return mStorage; } T const* getRawData() const { return mStorage; } int toIndex( int x , int y ) const { return x + y * mSize.x; } void toCoord( int index , int& outX , int& outY ) const { outX = index % mSize.x; outY = index / mSize.x; } void resize( int x , int y ) { cleanup(); build( x , y ); } void fillValue( T const& val ){ std::fill_n( mStorage , mSize.x * mSize.y , val ); } bool checkRange( int i , int j ) const { return 0 <= i && i < mSize.x && 0 <= j && j < mSize.y; } bool checkRange(TVector2<int> const& pos) const { return 0 <= pos.x && pos.x < mSize.x && 0 <= pos.y && pos.y < mSize.y; } TGrid2D& operator = ( TGrid2D const& rhs ) { copy( rhs ); return *this; } TVector2<int> const& getSize() const { return mSize; } int getSizeX() const { return mSize.x; } int getSizeY() const { return mSize.y; } int getRawDataSize() const { return mSize.x * mSize.y; } void swap( TGrid2D& other ) { using std::swap; MP::swap( other ); swap( mStorage , other.mStorage ); swap( mSize , other.mSize ); } private: void build( int x , int y ) { mSize.x = x; mSize.y = y; mStorage = new T[ mSize.x * mSize.y ]; MP::build( mStorage , x , y ); } void cleanup() { delete [] mStorage; mStorage = 0; MP::cleanup( mSize.x , mSize.y ); mSize = TVector2<int>::Zero(); } void construct(TGrid2D const& rhs) { build(rhs.mSize.x, rhs.mSize.y); std::copy(rhs.mStorage, rhs.mStorage + rhs.getRawDataSize(), mStorage); } void copy( TGrid2D const& rhs ) { cleanup(); construct(rhs); } T* mStorage; TVector2< int > mSize; }; #endif // Grid2D_H_758B1030_6F18_46B7_9EA5_9E7974186B6E
C++
UTF-8
2,857
2.59375
3
[]
no_license
#ifndef __PVX_ENCODE_H__ #define __PVX_ENCODE_H__ #include<vector> #include<string> #include<array> #include<type_traits> #include<string_view> namespace PVX{ namespace Encode{ std::string ToString(const std::vector<unsigned char> & data); std::string ToString(const std::wstring & data); std::wstring ToString(const std::string & data); std::string Base64(const void * data, size_t size); std::string Base64(const std::vector<unsigned char>& data); template<int Size> inline std::string Base64(const std::array<unsigned char, Size>& data) { return Base64(data.data(), Size); } std::string Base64Url(const void* data, size_t size, bool NoPadding = false); template<typename T> inline std::string Base64Url(const T& data, bool NoPadding = false) { return Base64Url(data.data(), data.size(), NoPadding); } inline std::string Base64Url(const char* data, bool NoPadding = false) { return Base64Url(data, strlen(data), NoPadding); } std::vector<unsigned char> UTF0(const std::wstring & Text); std::vector<unsigned char> UTF(const std::wstring & Text); void UTF(std::vector<unsigned char> & utf, const std::wstring & Text); size_t UTF(unsigned char * Data, const wchar_t * Str); size_t UTF_Length(const wchar_t * Str); size_t UTF_Length(const std::wstring & Str); size_t Uri_Length(const char * u); std::string UriEncode(const std::string & s); std::string UriEncode(const std::vector<unsigned char> & s); std::string Uri(const std::wstring & s); std::string Windows1253_Greek(const std::wstring & data); std::string ToHex(const std::vector<unsigned char>& Data); std::string ToHexUpper(const std::vector<unsigned char>& Data); std::wstring wToHex(const std::vector<unsigned char>& Data); std::wstring wToHexUpper(const std::vector<unsigned char>& Data); } namespace Decode{ std::vector<unsigned char> Base64(const std::string & base64); std::vector<unsigned char> Base64(const std::wstring & base64); std::string Base64_String(const std::string & base64); std::vector<unsigned char> Base64Url(const char* Base64, size_t sz); std::vector<unsigned char> Base64Url(const std::string& base64); std::vector<unsigned char> Base64Url(const wchar_t* Base64, size_t sz); std::vector<unsigned char> Base64Url(const std::wstring& base64); std::wstring UTF(const unsigned char * utf, size_t sz); std::wstring UTF(const std::vector<unsigned char> & Utf); wchar_t * pUTF(const unsigned char * utf); std::wstring Windows1253(const std::vector<unsigned char> & s); std::wstring Windows1253(const char * s); std::wstring Uri(const std::string & s); std::wstring Uri(const std::wstring & s); std::wstring Unescape(const std::wstring& x); std::vector<unsigned char> FromHex(const std::string_view& str); std::vector<unsigned char> FromHex(const std::wstring_view& str); } } #endif
Python
UTF-8
1,426
3.09375
3
[]
no_license
from enum import Enum class StructuredViewBase(object): """The base class for lazy views on numpy structured arrays.""" def __init__(self, arr, slice, lazy=None): self.arr = arr self.slice = slice self.lazy = lazy def create_view(cls_name, fields, lazy=True): """Returns a lazy view class for the given SOA fields.""" the_view = {} if lazy: def init(self, arr, slice): StructuredViewBase.__init__(self, arr, slice, lazy=True) the_view['__init__'] = init else: def init(self, arr, slice): StructuredViewBase.__init__(self, arr[slice], slice, lazy=False) the_view['__init__'] = init if issubclass(fields, Enum): fields = [e.value for e in fields] # Attach a r/w property for each field for f in fields: def gen_property_lazy(name): return property( lambda self: self.arr[self.slice][name], lambda self, value: self.arr[self.slice].__setitem__(name, value) ) def gen_property(name): return property( lambda self: self.arr[name], lambda self, value: self.arr.__setitem__(name, value) ) the_view[f[0]] = gen_property_lazy(f[0]) if lazy else gen_property(f[0]) view_cls = type(cls_name, (StructuredViewBase,), the_view) return view_cls
Ruby
UTF-8
2,032
2.96875
3
[]
no_license
require 'mandrill' class EmailNotifier MANDRILL_SUCCESS_STATUSES = ['sent', 'queued', 'scheduled'] def initialize(user) @user = user end def send(remembrance) begin mandrill = Mandrill::API.new response = mandrill.messages.send build_message(remembrance) log_response(response) rescue Exception log_error($!) rescue StandardError log_error($!) end end private def message_text(remembrance) return <<-EOS.strip_heredoc #{remembrance.url} #{remembrance.title} #{remembrance.preview} ----- If you don't want to get these emails anymore, go to http://madelein.es/settings to change your notification preferences. EOS end def message_html(remembrance) return <<-EOS.strip_heredoc <a href="#{remembrance.url}">#{remembrance.title}</a> <p>#{remembrance.preview}</p> <hr /> <p>If you don't want to get these emails aymore, go to the <a href="http://madeleines.es/settings">Madeleines settings page</a> to change your notification preferences.</p> EOS end def build_message(remembrance) return { :subject => remembrance.title, :text => message_text(remembrance), :html => message_html(remembrance), :from_email => 'notify@madelein.es', :from_name => 'Madeleines', :to => [ {:email => @user.email, :type => 'to'} ] } end def log_response(response) # We only send one message at a time, so assume that we only # get one response. response = response.first if MANDRILL_SUCCESS_STATUSES.include?(response['status']) and response['reject_reason'].nil? puts "Successfully sent daily email to #{@user}" else puts "Mandrill error sending daily email to #{@user}" puts "Mandrill rejection reason: #{response['reject_reason']}" end end def log_error(error) puts "Exception thrown while sending daily email to #{@user}:" puts "#{error}" puts "\t#{error.backtrace.join("\n\t")}" end end
Shell
UTF-8
1,230
2.859375
3
[]
no_license
# Maintainer: lorim <lorimz AT gmail DOT com> # Contributor: damir <damir@archlinux.org> # Contributor: Kevin Edmonds <edmondskevin@hotmail.com> pkgname=libmtp-cvs pkgver=20101126 pkgrel=1 pkgdesc="library implementation of the Media Transfer Protocol -- CVS build" arch=("i686" "x86_64") url="http://libmtp.sourceforge.net" license=("LGPL") depends=("libusb") makedepends=('cvs' 'doxygen') provides=('libmtp=1.0.3') conflicts=('libmtp') options=('!libtool') source=() md5sums=() _cvsroot=":pserver:anonymous@libmtp.cvs.sourceforge.net:/cvsroot/libmtp" _cvsmod="libmtp" build() { cd "$srcdir" msg "Connecting to $_cvsmod.sourceforge.net CVS server...." if [ -d $_cvsmod/CVS ]; then cd $_cvsmod cvs -z3 update -d else cvs -z3 -d $_cvsroot co -D $pkgver -f $_cvsmod cd $_cvsmod fi msg "CVS checkout done or server timeout" msg "Starting make..." rm -rf "$srcdir/$_cvsmod-build" cp -r "$srcdir/$_cvsmod" "$srcdir/$_cvsmod-build" cd "$srcdir/$_cvsmod-build" yes n | ./autogen.sh ./configure --prefix=/usr make make DESTDIR=$pkgdir install install -D -m0644 libmtp.rules \ $pkgdir/lib/udev/rules.d/52-libmtp.rules install -D -m0644 libmtp.fdi \ $pkgdir/usr/share/hal/fdi/information/20thirdparty/libmtp.fdi }
Markdown
UTF-8
21,312
3.140625
3
[ "MIT" ]
permissive
# rebenchmark [![npm](https://img.shields.io/npm/v/rebenchmark.svg)](https://www.npmjs.com/package/rebenchmark) [Benchmark.js](https://benchmarkjs.com) runner for [Node.js](https://nodejs.org) and browsers with BDD interface (like [Mocha](https://mochajs.org/)). [Online Playground](https://jsfiddle.net/evg656e/hz4co8x3/) Based on @venkatperi's [bench-runner](https://github.com/venkatperi/bench-runner). ## Table of contents * [Getting Started](#Getting%20Started) * [Suites & Benchmarks](#Suites%20%26%20Benchmarks) * [Paths](#Paths) * [Nested Suites & Benchmarks](#Nested%20Suites%20%26%20Benchmarks) * [Benchmarking Asynchronous Functions](#Benchmarking%20Asynchronous%20Functions) * [Dynamically Generating Benchmarks](#Dynamically%20Generating%20Benchmarks) * [Exclusive & Inclusive Benchmarks](#Exclusive%20%26%20Inclusive%20Benchmarks) * [Usage](#Usage) * [CLI](#CLI) * [Node.js](#Node.js) * [Browsers](#Browsers) * [TypeScript](#TypeScript) * [Hooks](#Hooks) * [Reporters](#Reporters) * [console](#console) * [json](#json) * [html](#html) * [null](#null) ## Getting Started Install with `npm`: ```console npm install rebenchmark -g mkdir benchmarks $EDITOR benchmarks/string.js # open with your favorite editor ``` In your editor: ```js suite('find in string', () => { bench('RegExp#test', () => /o/.test('Hello World!')); bench('String#indexOf', () => 'Hello World!'.indexOf('o') > -1); bench('String#match', () => !!'Hello World!'.match(/o/)); }); ``` Back in the terminal: ```console $ rebenchmark [find in string] RegExp#test x 37,304,988 ops/sec ±1.81% (88 runs sampled) String#indexOf x 873,212,283 ops/sec ±1.68% (89 runs sampled) String#match x 17,030,626 ops/sec ±1.25% (85 runs sampled) ``` For elder versions of node (< 12), use `rebenchmark-cjs` command instead. ## Suites & Benchmarks Group benchmarks in a suite: ```js suite('group-of-tests', () => { bench('a-benchmark', ...); bench('yet-a-benchmark', ...); }); ``` ### Paths Suites and benchmarks are assigned paths which are useful, for example, for filtering with the `grep` option. Paths are constructed by concatenating the names of suites and benchmarks leading to the target, separated with a colon `:`. In the above snippet, benchmark `a-benchmark` has the path `:group-of-tests:a-benchmark`. ### Nested Suites & Benchmarks Suites can be nested: ```js suite('es5 vs es6', () => { suite('classes', () => { function ES5() { this.foo = 'bar'; } ES5.prototype.bar = function () { }; class ES6 { constructor() { this.foo = 'bar'; } bar() { } } bench('es5', () => new ES5()); bench('es6', () => new ES6()); }); suite('arrow functions', () => { const es5obj = { value: 42, fn() { return function () { return es5obj.value; }; } }; const es5fn = es5obj.fn(); const es6obj = { value: 42, fn() { return () => this.value; } }; const es6fn = es6obj.fn(); bench('es5', es5fn); bench('es6', es6fn); }); }); ``` Output: ```console $ rebenchmark [es5 vs es6] [arrow functions] es5 x 957,326,571 ops/sec ±1.53% (94 runs sampled) es6 x 957,566,235 ops/sec ±1.40% (93 runs sampled) [classes] es5 x 932,924,301 ops/sec ±1.26% (92 runs sampled) es6 x 896,497,968 ops/sec ±2.84% (91 runs sampled) [generator] es5 x 15,930,495 ops/sec ±1.70% (89 runs sampled) es6 x 16,374,339 ops/sec ±1.90% (89 runs sampled) ``` ### Benchmarking Asynchronous Functions To defer a benchmark, pass an callback argument to the benchmark function. The callback must be called to end the benchmark. ```js suite('deferred', () => { bench('timeout', (done) => setTimeout(done, 100)); }); ``` Output: ```console [deferred] timeout x 9.72 ops/sec ±0.41% (49 runs sampled) ``` ### Dynamically Generating Benchmarks Use javascript to generate benchmarks or suites dynamically: ```js suite('buffer allocation', () => { for (let size = minSize; size <= maxSize; size *= 2) { bench(size, () => Buffer.allocUnsafe(size)); } }) ``` The above code will produce a suite with multiple benchmarks: ```console [buffer allocation] 1024 x 2,958,389 ops/sec ±2.85% (81 runs sampled) 2048 x 1,138,591 ops/sec ±2.42% (52 runs sampled) 4096 x 462,223 ops/sec ±2.48% (54 runs sampled) 8192 x 324,956 ops/sec ±1.56% (44 runs sampled) 16384 x 199,686 ops/sec ±0.94% (80 runs sampled) ``` ### Exclusive & Inclusive Benchmarks The exclusivity feature allows you to run only the specified suite or benchmark by appending `.only()` to the function. Here’s an example of executing only a particular suite: ```js suite('es5 vs es6', () => { suite.only('arrow functions', () => { const es5obj = { value: 42, fn() { return function () { return es5obj.value; }; } }; const es5fn = es5obj.fn(); const es6obj = { value: 42, fn() { return () => this.value; } }; const es6fn = es6obj.fn(); bench('es5', es5fn); bench('es6', es6fn); }); suite('classes', () => { function ES5() { this.foo = 'bar'; } ES5.prototype.bar = function () { }; class ES6 { constructor() { this.foo = 'bar'; } bar() { } } bench('es5', () => new ES5()); bench('es6', () => new ES6()); }); }); ``` Only `arrow functions` suite will be run. The inclusitiy feature is the inverse of `.only()`. By appending `.skip()`, you may tell runner to ignore test case(s). Here’s an example of skipping an individual test: ```js suite('es5 vs es6', () => { suite.skip('arrow functions', () => { const es5obj = { value: 42, fn() { return function () { return es5obj.value; }; } }; const es5fn = es5obj.fn(); const es6obj = { value: 42, fn() { return () => this.value; } }; const es6fn = es6obj.fn(); bench('es5', es5fn); bench('es6', es6fn); }); suite('classes', () => { function ES5() { this.foo = 'bar'; } ES5.prototype.bar = function () { }; class ES6 { constructor() { this.foo = 'bar'; } bar() { } } bench('es5', () => new ES5()); bench('es6', () => new ES6()); }); }); ``` `arrow functions` suite will be skipped. ## Usage ### CLI ```console rebenchmark [options] <benchmarks..> Options: --include, -i File pattern(s) to include [array] --exclude, -x File pattern(s) to exclude [array] --grep, -g Run only tests matching pattern(s) [array] --dry, -d Do a dry run without executing benchmarks [boolean] --reporter, -R Specify which reporter to use [string] [default: "console"] --reporter-options, -O Reporter-specific options (<k1=v1[,k2=v2,..]>) [array] --platform, -p Print platform information [boolean] --delay The delay between test cycles (secs) [number] --init-count The default number of times to execute a test on a benchmark’s first cycle [number] --max-time The maximum time a benchmark is allowed to run before finishing (secs) [number] --min-samples The minimum sample size required to perform statistical analysis [number] --min-time The time needed to reduce the percent uncertainty of measurement to 1% (secs) [number] --config, -c Path to JSON config file --help, -h Show help [boolean] --version, -v Show version number [boolean] ``` By default, `rebenchmark` looks for `*.js` files under the `benchmarks/` subdirectory only. To configure where `rebenchmark` looks for tests, you may pass your own glob: ```console rebenchmark 'benches/**/*.{js,mjs}' ``` **-i, --include=`<regex>`** Run benchmarks files with paths match the given regex, e.g.: ```console rebenchmark -i string ``` **-x, --exclude=`<regex>`** Skip benchmarks files with paths match the given regex, e.g.: ```console rebenchmark -x deferred ``` **-g, --grep=`<regex>`** The `--grep` option will trigger runner to only run tests whose paths match the given regex. In the snippet below: * `rebenchmark -g es5` will match only `:compare:classes:es5` and `:compare:arrow functions:es5` * `rebenchmark -g arrow` will match `:compare:arrow functions:es5` and `:compare:arrow functions:es6` ```js suite('compare', () => { suite('classes', () => { bench('es5', () => new ES5()); bench('es6', () => new ES6()); }); suite('arrow functions', () => { bench('es5', es5fn); bench('es6', es6fn); }); }); ``` **-d, --dry** Enables dry-run mode which cycles through the suites and benchmarks selected by other settings such as `grep` without actually executing the benchmark code. This mode can be useful to verify the selection by a particular grep filter. **-R, --reporter=`<name|url>`** The `--reporter` option allows you to specify the reporter that will be used. Could be the name of one of the predefined printers (see [reporters](#Reporters) section), or the url of the module with default exported class that will be used as reporter. **-O, --reporter-options=`<k1=v1[,k2=v2,..]>`** Reporter-specific options, e.g.: ```console rebenchmark -O indent=4,results,format=full ``` **--delay, --init-count, --max-time, --min-samples, --min-time** These options are passed directly to `benchmark.js`. **-c, --config=`<path>`** You can save frequently used sets of options to the JSON file and use it when starting the runner: ```console rebenchmark -c rebenchmark.config.json ``` rebenchmark.config.json: ```json { "benchmarks": [ "benches/**/*.js" ], "platform": true, "reporter": "console", "reporterOptions": { "indent": 4, "results": "true", "format": "full" } } ``` ### Node.js ```js import { suite, bench, run, resetOptions, reporters } from 'rebenchmark'; resetOptions({ reporter: new reporters.ConsoleReporter({ indent: 4 }), platform: true, filter: 'fastest' }); suite('find in string', () => { bench('RegExp#test', () => /o/.test('Hello World!')); bench('String#indexOf', () => 'Hello World!'.indexOf('o') > -1); bench('String#match', () => !!'Hello World!'.match(/o/)); }); run().then(() => { console.log('All done!'); }); ``` ### Browsers Automatic setup: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Rebenchmark</title> <!-- Benchmark.js dependencies are not included, therefore must be provided manually --> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script> </head> <body> <!-- The output is printed to the element with the identifier 'rebenchmark', if any, and duplicated to the console --> <pre id="rebenchmark"></pre> <!-- Options can be passed using data-attributes --> <script src="https://unpkg.com/rebenchmark/stage/browser/rebenchmark.min.js" data-platform="true"></script> <!-- Include this script to automatic setup --> <script src="https://unpkg.com/rebenchmark/stage/browser/rebenchmark-autosetup.min.js"></script> <!-- Suites can be specified with files --> <script src="benchmarks/es5_vs_es6.js"></script> <!-- Or be the inline scripts --> <script> suite('find in string', () => { bench('RegExp#test', () => /o/.test('Hello World!')); bench('String#indexOf', () => 'Hello World!'.indexOf('o') > -1); bench('String#match', () => !!'Hello World!'.match(/o/)); }); </script> </body> </html> ``` Manual setup: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Rebenchmark</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script> </head> <body> <pre id="rebenchmark"></pre> <!-- To disable automatic setup, set "data-no-auto-setup" to "true" --> <script src="https://unpkg.com/rebenchmark/stage/browser/rebenchmark.min.js"></script> <script> rebenchmark.setup({ reporter: new rebenchmark.reporters.HTMLReporter({ root: document.querySelector('#rebenchmark'), results: true }), platform: true }); </script> <script src="benchmarks/es5_vs_es6.js"></script> <script> suite('find in string', () => { bench('RegExp#test', () => /o/.test('Hello World!')); bench('String#indexOf', () => 'Hello World!'.indexOf('o') > -1); bench('String#match', () => !!'Hello World!'.match(/o/)); }); </script> <script> rebenchmark.run().then(() => { console.log('All done!'); }); </script> </body> </html> ``` ### Legacy browsers support At the moment, the main entry point is compiling using ES6+. If you need support for older browsers, use `rebenchmark-legacy.js` or `rebenchmark-legacy.min.js`, e.g.: ```html <script src="https://unpkg.com/rebenchmark/stage/browser/rebenchmark-legacy.min.js"></script> ``` ### TypeScript You can write and run benchmarks with TypeScript. ```ts /// <reference types="rebenchmark" /> suite('forLoop', () => { function forEach<T>(array: ArrayLike<T>, callbackfn: (value: T, index: number, array: ArrayLike<T>) => void, thisArg?: any) { for (let i = 0; i < array.length; i++) callbackfn.call(thisArg, array[i], i, array); } ([ ['empty array', []], ['small array', new Array(10).fill(1)], ['medium array', new Array(100).fill(1)], ['large array', new Array(10000).fill(1)] ] as [string, number[]][]).forEach(([title, array]) => { suite(title, () => { bench('conventional for', () => { let sum = 0; for (let i = 0; i < array.length; i++) { const value = array[i]; sum += value; sum += i; sum += value; } return sum; }); bench('for of', () => { let sum = 0; let i = 0; for (const value of array) { sum += value; sum += i; sum += value; i++; } return sum; }); bench('forEach', () => { let sum = 0; array.forEach((value, i) => { sum += value; sum += i; sum += value }); return sum; }); bench('self-made forEach', () => { let sum = 0; forEach(array, (value, i) => { sum += value; sum += i; sum += value }); return sum; }); }); }); }); ``` If you don't like [triple-slash directives](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-), you can specify types with [types](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) compiler option: ```json { "compilerOptions": { "types": [ "rebenchmark" ] } } ``` To run benchmarks, install [ts-node](https://github.com/TypeStrong/ts-node), then use following commands. With ESM modules: ```console node --loader ts-node/esm ./node_modules/rebenchmark/module/node/entry.js -- ./benchmarks/*.ts ``` With CJS modules: ```console node --require ts-node/register ./node_modules/rebenchmark/commonjs/node/entry.js -- ./benchmarks/*.ts ``` It is handy to save this command in the `package.json`'s `script` section, e.g. ```json { "scripts": { "ts-bench": "node --loader ts-node/esm ./node_modules/rebenchmark/module/node/entry.js" } } ``` ## Hooks Hooks must be synchronous since they are called by `benchmark.js` which does not support async hooks at this time. Also, `setup` and `teardown` are compiled into the test function. Including either may place restrictions on the scoping/availability of variables in the test function (see `benchmark.js` [docs](https://benchmarkjs.com/docs) for more information). ```js suite('hooks', () => { before(() => { // runs before all tests in this suite }); after(() => { // runs after all tests in this suite }); beforeEach(() => { // runs before each benchmark test function in this suite }); afterEach(() => { // runs after each benchmark test function in this suite }); bench('name', { setup() { // setup is compiled into the test function and runs before each cycle of the test } }) bench('name', { teardown() { // teardown is compiled into the test function and runs after each cycle of the test } }, testFn) // benchmarks here... }); ``` ## Reporters ### console The default reporter. Pretty prints results via `console.log`. Options: * `indent` - number of spaces used to insert white space into the output for readability purposes * `results` - print benchmark results (boolean). You can specify `format` option when `results` option is set, choices: `full`, `short` (default). Examples: ```console rebenchmark -O results [find in string] RegExp#test x 39,657,648 ops/sec ±2.77% (83 runs sampled) String#indexOf x 916,877,868 ops/sec ±1.76% (90 runs sampled) String#match x 21,233,309 ops/sec ±2.18% (89 runs sampled) ┌────────────────┬────────────────┐ │ (bench) │ find in string │ ├────────────────┼────────────────┤ │ RegExp#test │ 96% slower │ │ String#indexOf │ fastest │ │ String#match │ 98% slower │ └────────────────┴────────────────┘ rebenchmark -O results,format=full [find in string] RegExp#test x 38,496,031 ops/sec ±4.35% (85 runs sampled) String#indexOf x 890,481,584 ops/sec ±1.74% (89 runs sampled) String#match x 19,204,268 ops/sec ±2.12% (83 runs sampled) ┌────────────────┬─────────────────────┐ │ │ │ │ (bench) │ find in string │ │ │ │ ├────────────────┼─────────────────────┤ │ │ 38,496,031 ops/sec │ │ RegExp#test │ ±4.35% │ │ │ 96% slower │ ├────────────────┼─────────────────────┤ │ │ 890,481,584 ops/sec │ │ String#indexOf │ ±1.74% │ │ │ fastest │ ├────────────────┼─────────────────────┤ │ │ 19,204,268 ops/sec │ │ String#match │ ±2.12% │ │ │ 98% slower │ └────────────────┴─────────────────────┘ ``` ### json Outputs a single large JSON object when the tests have completed. Options: * `indent` - number of spaces used to insert white space into the output for readability purposes. ### html Prints results into HTML element. Intended for use only on browsers. Options: * `root` - CSS-selector or HTML-element by itself where to print results * `echo` - whether to duplicate output to console (`true` by default) And all options inherited from [console](#console) reporter. ### null Discards all output.
Python
UTF-8
4,525
2.859375
3
[]
no_license
import chess import chess.pgn from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error import numpy as np import time import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-deep') import json TRAIN_FILE = 'data/std_train_big.clean.pgn' TEST_FILE = 'data/std_june.clean.pgn' def test_cached_features(pipe, train_count, test_count, filename, depth, description=None): ''' Same as test(), but uses pre-processed features stored on disk. This allows for much more faster testing. ''' X_train_o = np.genfromtxt("data/x/short_features/std_x_%s_%d.csv" % (50000, depth), dtype=float, delimiter=',', names=None) y_train_o = np.genfromtxt("data/y/short_features/std_y_%s_%d.csv" % (50000, depth), dtype=int, delimiter=',', names=None) X_train = X_train_o[:train_count,:] y_train = y_train_o[:train_count,:] fit_start = time.time() pipe.fit(X_train, y_train) fit_end = time.time() fit_time = (fit_end - fit_start) y_pred = pipe.predict(X_train) train_R2 = r2_score(y_train, y_pred) train_MSE = mean_squared_error(y_train, y_pred) X_test = np.genfromtxt("data/x/short_features/new_test_std_x_%s_%d.csv" % (12000, depth), dtype=float, delimiter=',', names=None) y_test = np.genfromtxt("data/y/short_features/new_test_std_y_%s_%d.csv" % (12000, depth), dtype=int, delimiter=',', names=None) X_test = X_test[:test_count,:] y_test = y_test[:test_count,:] pred_start = time.time() y_pred = pipe.predict(X_test) pred_end = time.time() pred_time = (pred_end - pred_start) test_R2 = r2_score(y_test, y_pred) test_MSE = mean_squared_error(y_test, y_pred) print("ypred: ",y_pred[0], y_pred[1]) bins = np.linspace(500, 3000, 30) plt.hist([y_pred[:,0], y_pred[:,1]], bins, label=['white elo', 'black elo']) plt.title("Resulting ELO Predictions") plt.xlabel("Predicted ELO rating") plt.ylabel("Frequency") plt.legend(loc='upper right') plt.show() results = { 'Description': description, 'Pipeline': str(pipe.named_steps), '# Games for training': train_count, '# Games for testing': test_count, 'Train Fit time': fit_time, 'Train R2 score': train_R2, 'Train MSE': train_MSE, 'Test Predict time': pred_time, 'Test R2 score': test_R2, 'Test MSE': test_MSE } print(results) with open(f'reports/{filename}.json', 'w') as file: json.dump(results, file) def test(pipe, train_count, test_count, filename, description=None): ''' Trains a given pipeline 'pipe' on 'train_count' games of chess from TRAIN_FILE and then evaluates it on 'test_count' unseen games of chess from TEST_FILE. The pipeline is then evaluated and a json report saved in reports/<filename>.json ''' train_pgn = open(TRAIN_FILE) X_train = [] y_train = [] for i in range(train_count): game = chess.pgn.read_game(train_pgn) if game is not None: X_train.append(game) y_train.append([int(game.headers['WhiteElo']),int(game.headers['BlackElo'])]) fit_start = time.time() pipe.fit(X_train, y_train) fit_end = time.time() fit_time = (fit_end - fit_start) y_pred = pipe.predict(X_train) train_R2 = r2_score(y_train, y_pred) train_MSE = mean_squared_error(y_train, y_pred) test_pgn = open(TEST_FILE) X_test = [] y_test = [] for i in range(test_count): game = chess.pgn.read_game(train_pgn) if game is not None: X_test.append(game) y_test.append([int(game.headers['WhiteElo']),int(game.headers['BlackElo'])]) pred_start = time.time() y_pred = pipe.predict(X_test) pred_end = time.time() pred_time = (pred_end - pred_start) test_R2 = r2_score(y_test, y_pred) test_MSE = mean_squared_error(y_test, y_pred) results = { 'Description': description, 'Pipeline': str(pipe.named_steps), '# Games for training': train_count, '# Games for testing': test_count, 'Train Fit time': fit_time, 'Train R2 score': train_R2, 'Train MSE': train_MSE, 'Test Predict time': pred_time, 'Test R2 score': test_R2, 'Test MSE': test_MSE } print(results) with open(f'test_reports/{filename}.json', 'w') as file: json.dump(results, file)
Java
UTF-8
1,015
1.59375
2
[]
no_license
package com.hxgis.util; import com.hxgis.timer.ParseGrbFileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; /** * Created by Li Hong on 2018/5/27 0027. */ @RestController @RequestMapping("cc") public class Test { @Autowired ParseGrbFileService parseGrbFileService; @RequestMapping("/dd") public void test() throws Exception{ Map<String, String> map = new HashMap<>(); //map.put("EDA10", "Z_NWGD_C_BCWH_20180205100000_P_RFFC_SPCC-EDA10_201802050800_24003.GRB2"); //map.put("ER03", "Z_NWGD_C_BCWH_20180214101311_P_RFFC_SPCC-ER03_201802140800_24003 (1).GRB2"); map.put("ER03", "201805272000.GRB2"); //ParseGrbFileService service = new ParseGrbFileService(); parseGrbFileService.parse(map); //float[][][] aa = service.parse(map); } }
Java
UTF-8
646
3.625
4
[]
no_license
public class SortedMatrix { public void search(int[][] matrix, int n, int key) { int i=0; int j=n-1; while(i<n && j>=0) { if(matrix[i][j] == key) { System.out.println(key + " found at " + i+","+j); return; } if(matrix[i][j]>key) { j--; } else { i++; } } System.out.println("No Element found!! "); } public static void main(String[] args) { int [][] matrix= { {10,20,30,40}, {15,25,35,45}, {27,29,37,48}, {32,33,39,51} }; SortedMatrix sm=new SortedMatrix(); sm.search(matrix, matrix.length,32); } }
Java
UTF-8
908
1.914063
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
/** * (c) 2014 by Christian Schenk **/ package de.schenk.jrtrace.enginex.testclasses; import de.schenk.jrtrace.annotations.XClass; import de.schenk.jrtrace.annotations.XClassLoaderPolicy; import de.schenk.jrtrace.annotations.XInvokeReturn; import de.schenk.jrtrace.annotations.XInvokeThis; import de.schenk.jrtrace.annotations.XLocation; import de.schenk.jrtrace.annotations.XMethod; import de.schenk.jrtrace.enginex.testscripts.Test20; @XClass(classes = "de.schenk.jrtrace.enginex.testscripts.Test20", classloaderpolicy = XClassLoaderPolicy.TARGET) public class Test20Script { @XMethod(location=XLocation.AFTER_INVOCATION,invokedname="test20sub") public Integer testinstrumentation(@XInvokeReturn Integer x,@XInvokeThis Test20 xinvokeThis) { if(!xinvokeThis.getId().equals("invokedObject")) { throw new RuntimeException("wrong instance"); } return x+5; } }
Java
UTF-8
1,355
3.375
3
[]
no_license
package mypackage; import javax.sound.midi.Soundbank; public class Metods { public static void main(String[] args) { int a = 3; int b = 10; int sum; sum = getSum(a,b); System.out.println(sum); sum = getSum(32342,32423); System.out.println(sum); showSum(13221,23212,43423); saySmth(); sayHello("Igor"); showSumToPerson("Vasya",3,5,6); } static int getSum(int x, int y){ int sum; sum = x * y; return sum; } static void showSum(int x, int y, int z){ int sum = x * y + z; System.out.println("Show sum is: "+sum); } static void saySmth(){ System.out.println(); System.out.println("First string"); System.out.println("Second string"); System.out.println("Third string"); } static void sayHello(String name){ System.out.println(); System.out.println("Hello " + name + "!"); } static void showSumToPerson(String name, int a, int b, int c){ String nameOfMethod = new Object(){}.getClass().getName(); System.out.println(); System.out.println("Start of "+nameOfMethod+"."); sayHello(name); showSum(a,b,c); System.out.println(); System.out.println("End of programm."); } }
JavaScript
UTF-8
1,556
3.765625
4
[]
no_license
// write standalone functions implementing bubble sort for arrays function arrayBubbleSort(arr){ // pass in the array to be sorted var len = arr.length; // store the length of the array in a variable to use later var temp; // declare the temp variable that we'll use inside our sorting algorithm while(len != 0){ // do this loop as long as len (set originally as array's length) isn't 0 for(var i=0;i<len;i++){ // setup our inner loop to iterate through the array if(arr[i] > arr[i+1]){ // check if the value at our current index is greater than the value at the next index temp = arr[i]; // if it is then these 2 values aren't sorted so we need to swap them arr[i] = arr[i+1]; arr[i+1] = temp; } } // at this point we'll have iterated through the array and whatever the largest value was will have been moved to the end len--; // decrement our len because we now know that the end of the array is sorted } // so when we loop back we only need to sort from the beginning of the array up until we get to where the sorted portion starts return arr; } //es6ified // function arrayBubbleSort(arr) { // let len = arr.length; // while (len != 0) { // for (let i = 0; i < len; i++) { // if (arr[i] > arr[i+1]) { // [arr[i], arr[i+1]] = [arr[i+1], arr[i]]; // } // } // len--; // } // return arr; // } // ====================================================================== // Code below exports this functions for Mocha testing if (typeof exports !== 'undefined') { exports.bubbleSort = arrayBubbleSort; }
Markdown
UTF-8
4,783
3.5625
4
[]
no_license
--- title: "Python Text Adveture: Part 2" kind: activity --- ### User 2 - Add a `current` read-only [`property`][property] to `World` that returns the current Room object. - rename the instance variable `self.current` to `self._current`. The underscore is a message to the programmer that this variable should be considered private (but remember: Python does not distinguish between public/private and so does not protect against miss-use of private data). - Use the `property` [decorator] on a function with the name `current` that simple returns the value of `self._current` - Add a `go` method to `World` that takes a direction name (`north`,`south`, `east` or `west`) as a parameter and, if a path in that direction exists from the current room, updates the current room to the one in that direction. ~~~ python class NoPath(RuntimeError): pass class World: ... def go(self,direction): # if a path of 'direction' exists from self.current # then set self._current to the room associated with 'direction' ... # else raise NoPath(direction) ~~~ [decorator]: https://docs.python.org/3/glossary.html#term-decorator [property]: https://docs.python.org/3/library/functions.html#property ### User 1 Add a simple command parser that can correctly interpret 'go' commands. You may need to make some changes to the way data is stored in World or Room to accomodate the requirements of the new functionality. When doing so, keep changes as simple as possible and data as restricted as possible (e.g. the `World.go` method only needs to know if the direction requested is valid for the current room, it does not need to know all available directions for the current room). - split the command string into an `action` and `arguments`. You can use Python's [str.partition] to partition a string by a separator into three pieces. ~~~~ pycon >>> "go north".partition(' ') ('go', ' ', 'north') >>> "look".partition(' ') ('look', '', '') ~~~~ Unlike [str.split], the partition method always returns a 3-tuple, even if the string doesn't contain the partition separator, as in the `"look"` example above. This is one way to deal with optional arguments without having to worry about `IndexError` or `ValueError` ~~~ pycon >>> action, arguments = "go north".split() >>> # no error, split returned a list of 2 items >>> action, arguments = "look".split() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 1 value to unpack >>> # ValueError because split() returned a list of only 1 item ~~~ We can also unpack the return of [str.partition] into three variables ~~~ pycon >>> before, sep, after = "a string with several words".partition(' ') ~~~ but if we are never going to use the `sep` variable it's just getting in the way. We can use Python's slicing syntax to retrieve every *other* item from a sequence ~~~ pycon >>> action, arguments = "go north".partition(' ')[::2] ~~~ The `[::2]` means "pick every other element starting from index 0" (the general form looks like `[n::m]` and means "pick every m'th element starting from index n. If `n` is omitted, it is assume to be 0). - we *could* use a dict to simulate a switch/case statement found in other languages: ~~~ python ... myworld = world.World( ... ) while True: # get cmd_string from user ... cmd_action = { 'go': World.go, 'look': World.look } action, arguments = cmd_string.partition(' ')[::2] # call the method associated with the action cmd_action[action](arguments) ~~~ But as we discussed this requires that we update the code for our command parser *and* the World API whenever we implement a new command. Duplicating information in this way should always make you think "can I do this in a different way without duplicating information". Depending on the language, it can be tricky to always separate knowledge between modules. If we make the rule that all command actions will have an API method defined in 'World' with the same name, then we can use Python's `getattr` method to return a function object associated with an arbitrary action string: ~~~ python ... myworld = world.World( ... ) while True: # command loop # get cmd_string from user ... action, arguments = cmd_string.partition(' ')[::2] # call the method associated with the action getattr(myworld, action)(arguments) ~~~ [str.partition]: https://docs.python.org/3.1/library/stdtypes.html#str.partition [str.split]: https://docs.python.org/3.1/library/stdtypes.html#str.split
Markdown
UTF-8
20,404
2.71875
3
[ "Apache-2.0", "CC0-1.0" ]
permissive
--- linkTitle: Enabling the Terraform Integration Stage title: Enabling the Terraform Integration Stage in the Armory Platform aliases: - /spinnaker/terraform_integration/ - /spinnaker/terraform-configure-integration/ - /docs/spinnaker/terraform-enable-integration/ description: > Learn how to configure the Terraform Integration and an artifact provider to support either GitHub or BitBucket. --- ## Overview of Terraform Integration in Spinnaker The examples on this page describe how to configure the Terraform Integration and an artifact provider to support either GitHub or BitBucket. Note that the Terraform Integration also requires a `git/repo` artifact account. For information about how to use the stage, see [Using the Terraform Integration]({{< ref "terraform-use-integration" >}}). Armory's Terraform Integration integrates your infrastructure-as-code Terraform workflow into your SDLC. The integration interacts with a source repository you specify to deploy your infrastructure as part of a Spinnaker pipeline. ## Supported Terraform versions Armory ships several versions of Terraform as part of the Terraform Integration feature. The Terraform binaries are verified by checksum and with Hashicorp's GPG key before being installed into an Armory release. When creating a Terraform Integration stage, pipeline creators select a specific available version from a list of available versions: ![Terraform version to use](/images/terraform_version.png) Note that all Terraform stages within a Pipeline that affect state must use the same Terraform version. ## Requirements * Credentials (in the form of basic auth) for the Git repository where your Terraform scripts are stored. The Terraform Integration needs access to credentials to download directories that house your Terraform templates. * Git Repo can be configured with any of the following: * a Personal Access Token (potentially associated with a service account). For more information, see [Generating a Github Personal Access Token (PAT)](#generating-a-github-personal-access-token-pat). * SSH protocol in the form of an SSH key or an SSH key file * basic auth in the form of a user and password, or a user-password file * A source for Terraform Input Variable Files (`tfvar`) or a backend config. You must have a separate artifact provider that can pull your `tfvar` file(s). The Terraform Integration supports the following artifact providers for `tfvar` files and backend configs: * GitHub * BitBucket * HTTP artifact Although not required, Armory recommends an external Redis instance for the Terraform Integration. For more information, see [Redis](#redis). ### Redis The Terraform Integration uses Redis to store Terraform logs and plans. An external Redis instance is highly recommended for production use. **Note:** The Terraform Integration can only be configured to use a password with the default Redis user. To set/override the Spinnaker Redis settings do the following: **Operator** In `SpinnakerService` manifest: ```yaml apiVersion: spinnaker.armory.io/{{< param operator-extended-crd-version >}} kind: SpinnakerService metadata: name: spinnaker spec: spinnakerConfig: profiles: terraformer: redis: baseUrl: "redis://spin-redis:6379" password: "password" ``` ```bash kubectl -n spinnaker apply -f spinnakerservice.yml ``` **Halyard** Edit the `~/.hal/default/profiles/terraformer-local.yml` file and add the following: ```yaml redis: baseUrl: "redis://spin-redis:6379" password: "password" ``` Then run `hal deploy apply` to deploy the changes. ### Generating a GitHub Personal Access Token (PAT) Skip this section if you are using BitBucket, which requires your username and password. Before you start, you need a GitHub Personal Access Token (PAT). The Terraform Integration authenticates itself using the PAT to interact with your GitHub repositories. You must create and configure a PAT so that the Terraform Integration can pull a directory of Terraform Templates from GitHub. Additionally, the Spinnaker GitHub artifact provider require a PAT for `tfvar` files. Make sure the PAT you create meets the following requirements: * The token uses a distinct name and has the **repo** scope. * If your GitHub organization uses Single Sign-On (SSO), enable the SSO option for the organizations that host the Terraform template(s) and Terraform `tfvar` files. For more information about how to generate a GitHub PAT, see [Creating a Personal Access Token for the Command Line](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line). ## Configure your artifact accounts The Terraform Integration uses the following artifact accounts: * **Git Repo** - To fetch the repo housing your main Terraform files. * **GitHub, BitBucket or HTTP** - *Optional*. To fetch single files such as var-files or backend config files. ### Configure the Git Repo artifact Spinnaker uses the Git Repo Artifact Provider to download the repo containing your main Terraform templates If you already have a Git Repo artifact account configured in Spinnaker, skip this section. **Operator** Edit the `SpinnakerService` manifest to add the following: ```yaml apiVersion: spinnaker.armory.io/{{< param operator-extended-crd-version >}} kind: SpinnakerService metadata: name: spinnaker spec: spinnakerConfig: profiles: clouddriver: artifacts: gitRepo: enabled: true accounts: - name: gitrepo token: <Your GitHub PAT> # GitHub personal access token ``` **Halyard** 1. Enable Git Repo as an artifact provider: ```bash hal config artifact gitrepo enable ``` 2. Add the Git Repo account: ```bash hal config artifact gitrepo account add gitrepo-for-terraform --token ``` The command prompts you for your Git Repo PAT. For more configuration options, see [Git Repo](https://spinnaker.io/setup/artifacts/gitrepo/). ## Configure the Terraform Integration for GitHub *(optional)* These steps describe how to configure GitHub as an artifact provider for the Terraform Integration. For information about BitBucket, see [Configuring the Terraform Integration with BitBucket](#configuring-the-terraform-integration-with-bitbucket). #### Enabling and configuring the GitHub Artifact Provider Spinnaker uses the Github Artifact Provider to download any referenced `tfvar` files. If you already have a GitHub artifact account configured in Spinnaker, skip this section. {{% alert title="Note" %}}The following examples use `github-for-terraform` as a unique identifier for the artifact account. Replace it with your own identifier. {{% /alert %}} **Operator** Edit the `SpinnakerService` manifest to add the following: ```yaml apiVersion: spinnaker.armory.io/{{< param operator-extended-crd-version >}} kind: SpinnakerService metadata: name: spinnaker spec: spinnakerConfig: config: artifacts: github: accounts: - name: github-for-terraform token: <Your GitHub PAT> # GitHub personal access token # PAT GitHub token. This field supports "encrypted" field references (https://docs.armory.io/spinnaker-install-admin-guides/secrets/) enabled: true ``` **Halyard** 1. Enable GitHub as an artifact provider: ```bash hal config artifact github enable ``` 2. Add the GitHub account: ```bash hal config artifact github account add github-for-terraform --token ``` The command prompts you for your GitHub PAT. ## Configure the Terraform Integration for BitBucket *(optional)* ### Enabling and configuring the BitBucket Artifact Provider Spinnaker uses the BitBucket Artifact Provider to download any referenced `tfvar` files, so it must be configured with the BitBucket token to pull these files. If you already have a BitBucket artifact account configured in Spinnaker, skip this step. Replace `bitbucket-for-terraform` with any unique identifier to identify the artifact account. **Operator** ```yaml apiVersion: spinnaker.armory.io/{{< param operator-extended-crd-version >}} kind: SpinnakerService metadata: name: spinnaker spec: spinnakerConfig: config: artifacts: bitbucket: enabled: true accounts: - name: bitbucket-for-terraform username: <Your Bitbucket username> password: <Your Bitbucket password> # This field supports "encrypted" field references (https://docs.armory.io/spinnaker-install-admin-guides/secrets/) ``` **Halyard** ```bash hal config artifact bitbucket enable # This will prompt for the password hal config artifact bitbucket account add bitbucket-for-terraform \ --username <USERNAME> \ --password ``` ## Enabling the Terraform Integration Enable the Terraform Integration: **Operator** In `SpinnakerService` manifest: ```yaml apiVersion: spinnaker.armory.io/{{< param operator-extended-crd-version >}} kind: SpinnakerService metadata: name: spinnaker spec: spinnakerConfig: config: armory: terraform: enabled: true profiles: deck: # Enables the UI for the Terraform Integration stage settings-local.js: | window.spinnakerSettings.feature.terraform = true; ``` This example manifest also enables the Terraform Integration UI. **Halyard** ```bash hal armory terraform enable ``` ### Remote backends {{< include "early-access-feature.html" >}} The Terraform Integration supports using remote backends provided by Terraform Cloud and Terraform Enterprise. When using remote backends, keep the following in mind: * The Terraform stage must use the same Terraform version that your Terraform Cloud/Enterprise workspace is configured to run. * The minimum supported Terraform version is 0.12.0. * In the Terraform Cloud/Enterprise UI, the type of `plan` action that the Terraform Integration performs is a "speculative plan." For more information, see [Speculative Plans](https://www.terraform.io/docs/cloud/run/index.html#speculative-plans). * You cannot save and apply a plan file. #### Enable remote backend support End users can use remote backends by configuring the Terraform Integration stage with the following parameters: * A Terraform version that is 0.12.0 or later and matches the version that your Terraform Cloud/Enterprise runs. * Reference a remote backend in your Terraform code. To enable support, add the following config to your `terraformer-local.yml` file in the `.hal/default/profiles` directory: ```bash terraform: remoteBackendSupport: true ``` ## Enabling the Terraform Integration UI If you previously used the Terraform Integration stage by editing the JSON representation of the stage, those stages are automatically converted to use the UI. Manually enable the stage UI for Deck: **Operator** See the example manifest in [Enabling the Terraform Integration](#enabling-the-terraform-integration). **Halyard** Edit `~/.hal/default/profiles/settings-local.js` and add the following: ```js window.spinnakerSettings.feature.terraform = true; ``` ## Completing the installation After you finish your Terraform integration configuration, perform the following steps: 1. Apply the changes: **Operator** Assuming that Spinnaker lives in the namespace `spinnaker` and the `SpinnakerService` manifest is named `spinnakerservice.yml`: ```bash kubectl -n spinnaker apply -f spinnakerservice.yml ``` **Halyard** ```bash hal deploy apply ``` 2. Confirm that the Terraform Integration service (Terraformer) is deployed with your Spinnaker deployment: ```bash kubectl get pods -n <your-spinnaker-namespace> ``` In the command output, look for a line similar to the following: ```bash spin-terraformer-d4334g795-sv4vz 2/2 Running 0 0d ``` ## Configure Terraform for your cloud provider Since the Terraform Integration executes all Terraform commands against the `terraform` binary, all methods of configuring authentication are supported for your desired cloud provider. This section describes how to accomplish this for various cloud providers. You can also configure a profile that grants access to resources, like AWS. ## Named Profiles {{% alert title="New feature" %}}Named Profiles is a new feature in Armory 2.20. Previously, you needed to mount a sidecar that contained your credentials. If you are on an earlier version, see the v.2.0-2.19 version of this [page](https://archive.docs.armory.io/docs/spinnaker/terraform-enable-integration/#configure-terraform-for-your-cloud-provider) to learn more about mounting a sidecar. {{% /alert %}} A Named Profile gives users the ability to reference certain kinds of external sources, such as a private remote repository, when creating pipelines. The supported credentials are described in [Types of credentials](#types-of-credentials). ### Types of credentials The Terraform integration supports multiple types of credentials for Named Profiles to handle the various use cases that you can use the Terraform integration for: * AWS * SSH * Static * Terraform remote backend If you don't see a credential that suits your use case, [let us know](https://feedback.armory.io/feature-requests)! For information about how to configure a Profile, see [Configuring a profile](#configuring-a-named-profile). **AWS** Use the `aws` credential type to provide authentication to AWS. There are two methods you can use to provide authentication - by defining a static key pair or a role that should be assumed before a Terraform action is executed. For defining a static key pair, supply an `accessKeyId` and a `secretAccessKey`: ```yaml - name: devops # Unique name for the profile. Shows up in Deck. variables: - kind: aws # Type of credential options: accessKeyId: AKIAIOWQXTLW36DV7IEA secretAccessKey: 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 ``` For assuming a role instead of defining a static set of credentials, supply the ARN of the role to assume: ```yaml - name: devops # Unique name for the profile. Shows up in Deck. variables: - kind: aws # Type of credential options: assumeRole: arn:aws:iam::012345567:role/roleAssume ``` *When assuming a role, if `accessKeyId` and `secretAccessKey` are supplied, the Terraform integration uses these credentials to assume the role. Otherwise, the environment gets used for authentication, such as a machine role or a shared credentials file.* **SSH Key** Use the `git-ssh` credential kind to provide authentication to private Git repositories used as modules within your Terraform actions. The supplied SSH key will be available to Terraform for the duration of your execution, allowing it to fetch any modules it needs: ```yaml - name: pixel-git # Unique name for the profile. Shows up in Deck. variables: - kind: git-ssh # Type of credential options: sshPrivateKey: encrypted:vault!e:<secret engine>!p:<path to secret>!k:<key>!b:<is base64 encoded?> ``` **Static** Use the `static` credential kind to provide any arbitrary key/value pair that isn't supported by any of the other credential kinds. For example, if you want all users of the `devops` profile to execute against the `AWS_REGION=us-west-2`, use the following `static` credential configuration. ```yaml - name: devops # Unique name for the profile. Shows up in Deck. variables: - kind: static # Type of credential options: name: AWS_REGION value: us-west-2 ``` **Terraform remote backend** Use the `tfc` credential kind to provide authentication to remote Terraform backends. ```yaml - name: milton-tfc # Unique name for the profile. Shows up in Deck. variables: - kind: tfc options: domain: app.terraform.io # or Terraform Enterprise URL token: <authentication-token> # Replace with your token ``` ### Configuring a Named Profile Configure profiles that users can select when creating a Terraform Integration stage: 1. In the `.hal/default/profiles` directory, create or edit `terraformer-local.yml`. 2. Add the values for the profile(s) you want to add under the `profiles` section. The following example adds a profile named `pixel-git` for an SSH key secured in Vault. ```yaml - name: pixel-git # Unique profile name displayed in Deck variables: - kind: git-ssh options: sshPrivateKey: encrypted:vault!e:<secret engine>!p:<path to secret>!k:<key>!b:<is base64 encoded?> ``` When a user creates or edits a Terraform Integration stage in Deck, they can select the profile `pixel-git` from a dropdown. Keep the following in mind when adding profiles: * You can add multiple profiles under the `profiles` section. * Do not commit plain text secrets to `terraformer-local.yml`. Instead, use a secret store: [Vault]({{< ref "secrets-vault" >}}), an [encrypted S3 bucket]({{< ref "secrets-s3" >}}), or an [encrypted GCS bucket]({{< ref "secrets-gcs" >}}). * For SSH keys, one option parameter at a time is supported for each Profile. This means that you can use a private key file (`sshPrivateKeyFilePath`) or the key (`sshPrivateKey`) as the option. To use the key file path, use `sshPrivateKeyFilePath` for the option and provide the path to the key file. The path can also be encrypted using a secret store such as Vault. The following `option` example uses `sshPrivateKeyFilePath`: ```yaml options: sshPrivateKeyFilePath: encryptedFile:<secret_store>!e:... ``` For more information, see the documentation for your secret store. 3. Save the file. 4. Apply your changes: ```bash hal deploy apply ``` ### Adding authz to Named Profiles Armory recommends that you enable authorization for your Named Profiles to provide more granular control and give App Developers better guardrails. When you configure authz for Named Profiles, you need to explicitly grant permission to the role(s) you want to have access to the profile. Users who do not have permission to use a certain Named Profile do not see it as an option in Deck. And any stage with that uses a Named Profile that a user is not authorized for fails. You can see a demo here: [Named Profiles for the Terraform Integration](https://www.youtube.com/watch?v=RYO-b1kyEU0). {{% alert color=note title="Note" %}}Before you start, make sure you enable Fiat. For more information about Fiat, see [Fiat Overview]({{< ref "fiat-permissions-overview" >}}) and [Authorization (RBAC)](https://spinnaker.io/setup/security/authorization/).{{% /alert %}} #### Halyard To start, edit `~/.hal/default/profiles/terraformer-local.yml` and add the following config: ```yaml fiat: enabled: true baseUrL: ${services.fiat.baseUrl} # If you are using a custom URL for Fiat, replace with your Fiat URL. ``` Now, you can specify permissions for any profiles you have: ```yaml profiles: ... ... ... permissions: - <role that should have access> - <role that should have access> - ... ``` This is what a Named Profile for a team named `dev-team` looks like for AWS credentials: ```yaml profiles: - name: dev-team variables: - kind: aws options: assumeRole: my-role permissions: - dev - ops ``` In the example, only users who belong to the `dev` or `ops` groups can use the credentials that correspond to this profile. Don't forget to run `hal deploy apply` once you finish making changes! ## Retries The Terraformer service can retry connections if it fails to fetch artifacts from Clouddriver. Configure the retry behavior in your `terraformer-local.yml` file by adding the following snippet: ```yaml # terraformer-local.yml clouddriver: retry: enabled: true minWait: 4s # must be a duration, such as 4s for 4 seconds maxWait: 8s # must be a duration, such as 8s for 8 seconds maxRetries: 5 ``` The preceding example enables retries and sets the minimum wait between attempts to 4 seconds, the maximum wait between attempts to 8s, and the maximum number of retries to 5. ## Submit feedback Let us know what you think at [go.armory.io/ideas](https://go.armory.io/ideas) or [feedback.armory.io](https://feedback.armory.io). We're constantly iterating on customer feedback to ensure that the features we build make your life easier!
Markdown
UTF-8
6,266
4.1875
4
[]
no_license
# 运算 ## 一、赋值运算符(=) - 赋值运算符为变量分配一个值。 ```c++ x = 5; ``` ## 二、算数运算符 ( +, -, *, /, % ) ```c++ x = 1 + 1; x = 1 - 1; x = 1 * 1; x = 1 / 1; x = 1 % 1; ``` ## 三、 复合赋值(+=,-=,* =,/=,%=,>>=,<<=,&=,^=,|=) - 复合赋值运算符通过对其执行操作来修改变量的当前值 ```c++ x += 2; x -= 2; x /= 2; x *= 2; x %= 2; x >>= 2; x <<= 2; x &= 2; x ^= 2; x |= 2; ``` ## 四、增量和减量(++, --) ```c++ x++; ++x; x--; --x; ``` ## 五、 关系运算符和比较运算符(==, !=, >, <, >=, <=) - 可以使用关系和相等运算符比较两个表达式。例如,要知道两个值是否相等,或者一个值是否大于另一个值。 - 此类操作的结果为true或false(即布尔值)。 ```c++ 3 == 4; 5 != 6; 6 > 7; 7 < 8; 8 >= 9; 9 <= 10 ``` ## 六、逻辑运算符(!,&&,||) ```c++ // NOT运算 !true; //result is false // &&(和)运算 true && false; // result is false // ||(或)运算 true || false; // result is true ``` ## 七、三元运算符(?) - 条件运算符计算一个表达式,如果该表达式计算为`true`,则返回一个值,如果该表达式计算为,则返回另一个值`false`。其语法为: $$ condition ? result1 : result2 $$ ```c++ 7 == 5 ? 4 : 3; // result is 3 7 == 7 ? 4 : 3; // result is 4 ``` ## 八、按位运算符(&, |, ^, ~, <<, >>) - 按位运算符会考虑代表它们存储的值的位模式来修改变量 | 运算符 | 等价于 | 描述 | | ------ | ------ | ------------------ | | & | AND | 按位和 | | \| | OR | 按位或 | | ^ | XOR | 按位异或 | | ~ | NOT | 一元补码(位反转) | | << | SHL | 左位移 | | >> | SHR | 右位移 | ## 九、显式操作符类型转换 - 类型转换运算符允许将给定类型的值转换为另一种类型。 ```c++ int i; float f = 3.14; i = (int)f; // result is 3 ``` ## 十、`sizeof` - 此运算符接受一个参数,该参数可以是类型,也可以是变量,并返回该类型或对象的字节大小(整型) ```c++ int x = sizeof(char); ``` ## 十一、运算符的优先级 | 级别 | 优先组 | 运算符 | 描述 | 分组 | | ------------ | ---------------------------- | ---------------------------------- | -------------------------------- | ------------- | | 1 | Scope | `::` | scope qualifier | Left-to-right | | 2 | Postfix (unary) | `++ --` | postfix increment / decrement | Left-to-right | | `()` | functional forms | | | | | `[]` | subscript | | | | | `. ->` | member access | | | | | 3 | Prefix (unary) | `++ --` | prefix increment / decrement | Right-to-left | | `~ !` | bitwise NOT / logical NOT | | | | | `+ -` | unary prefix | | | | | `& *` | reference / dereference | | | | | `new delete` | allocation / deallocation | | | | | `sizeof` | parameter pack | | | | | `(*type*)` | C-style type-casting | | | | | 4 | Pointer-to-member | `.* ->*` | access pointer | Left-to-right | | 5 | Arithmetic: scaling | `* / %` | multiply, divide, modulo | Left-to-right | | 6 | Arithmetic: addition | `+ -` | addition, subtraction | Left-to-right | | 7 | Bitwise shift | `<< >>` | shift left, shift right | Left-to-right | | 8 | Relational | `< > <= >=` | comparison operators | Left-to-right | | 9 | Equality | `== !=` | equality / inequality | Left-to-right | | 10 | And | `&` | bitwise AND | Left-to-right | | 11 | Exclusive or | `^` | bitwise XOR | Left-to-right | | 12 | Inclusive or | `|` | bitwise OR | Left-to-right | | 13 | Conjunction | `&&` | logical AND | Left-to-right | | 14 | Disjunction | `||` | logical OR | Left-to-right | | 15 | Assignment-level expressions | `= *= /= %= += -=>>= <<= &= ^= |=` | assignment / compound assignment | Right-to-left | | `?:` | conditional operator | | | | | 16 | Sequencing | `,` | comma separator | Left-to-right |
Java
UTF-8
3,884
2.796875
3
[]
no_license
public class RestaurantLogistics extends Restaurants { private String entreeOne; private String entreeTwo; private String entreeThree; private String drinkOne; private String drinkTwo; private String sideOne; private String sideTwo; private int entreeOnePrice; private int entreeTwoPrice; private int entreeThreePrice; private int drinkOnePrice; private int drinkTwoPrice; private int sideOnePrice; private int sideTwoPrice; public RestaurantLogistics (String restaurantName, int backHouseWorkers, int frontHouseWorkers, int managers, int backHouseWage, int frontHouseWage, int managerWage, String entreeOne, String entreeTwo, String entreeThree, String drinkOne, String drinkTwo, String sideOne, String sideTwo, int entreeOnePrice, int entreeTwoPrice, int entreeThreePrice, int drinkOnePrice, int drinkTwoPrice, int sideOnePrice, int sideTwoPrice) { super(restaurantName, backHouseWorkers, frontHouseWorkers, managers, backHouseWage, frontHouseWage, managerWage); this.setEntreeOne(entreeOne); this.setEntreeTwo(entreeTwo); this.setEntreeThree(entreeThree); this.setDrinkOne(drinkOne); this.setDrinkTwo(drinkTwo); this.setSideOne(sideOne); this.setSideTwo(sideTwo); this.setEntreeOnePrice(entreeOnePrice); this.setEntreeTwoPrice(entreeTwoPrice); this.setEntreeThreePrice(entreeThreePrice); this.setDrinkOnePrice(drinkOnePrice); this.setDrinkTwoPrice(drinkTwoPrice); this.setSideOnePrice(sideOnePrice); this.setSideTwoPrice(sideTwoPrice); } public void setEntreeOne(String entreeOne) { this.entreeOne = entreeOne; } public void setEntreeTwo(String entreeTwo) { this.entreeTwo = entreeTwo; } public void setEntreeThree(String entreeThree) { this.entreeThree = entreeThree; } public void setDrinkOne(String drinkOne) { this.drinkOne = drinkOne; } public void setDrinkTwo(String drinkTwo) { this.drinkTwo = drinkTwo; } public void setSideOne(String sideOne) { this.sideOne = sideOne; } public void setSideTwo(String sideTwo) { this.sideTwo = sideTwo; } public void setEntreeOnePrice(int EntreeOnePrice) { this.entreeOnePrice = entreeOnePrice; } public void setEntreeTwoPrice(int EntreeTwoPrice) { this.entreeTwoPrice = entreeTwoPrice; } public void setEntreeThreePrice(int EntreeThreePrice) { this.entreeThreePrice = entreeThreePrice; } public void setDrinkOnePrice(int drinkOnePrice) { this.drinkOnePrice = drinkOnePrice; } public void setDrinkTwoPrice(int drinkTwoPrice) { this.drinkTwoPrice = drinkTwoPrice; } public void setSideOnePrice(int sideOnePrice) { this.sideOnePrice = sideOnePrice; } public void setSideTwoPrice(int sideTwoPrice) { this.sideTwoPrice = sideTwoPrice; } public String getEntreeOne() { return this.entreeOne; } public String getEntreeTwo() { return this.entreeTwo; } public String getEntreeThree() { return this.entreeThree; } public String getDrinkOne() { return this.drinkOne; } public String getDrinkTwo() { return this.drinkTwo; } public String getSideOne() { return this.sideOne; } public String getSideTwo() { return this.sideTwo; } public int getEntreeOnePrice() { return this.entreeOnePrice; } public int getEntreeTwoPrice() { return this.entreeTwoPrice; } public int getEntreeThreePrice() { return this.entreeThreePrice; } public int getDrinkOnePrice() { return this.drinkOnePrice; } public int getDrinkTwoPrice() { return this.drinkTwoPrice; } public int getSideOnePrice() { return this.sideOnePrice; } public int getSideTwoPrice() { return this.sideTwoPrice; } }
PHP
UTF-8
1,401
2.75
3
[]
no_license
<?php namespace Tests\DeeToo\Essentials\Laravel\Eloquent\Types; use DateTime; use DeeToo\Essentials\Laravel\Eloquent\Types\DateTimeType; use Tests\TestCase; /** * Class DateTimeTypeTest * * @package Tests\DeeToo\Essentials\Laravel\Eloquent\Types */ class DateTimeTypeTest extends TestCase { public function test_to_primitive() { $obj = new DateTimeType(); $now = new DateTime(); $this->assertSame($obj->castToPrimitive(new $now), $now->format(DateTimeType::$format)); } public function test_cast_from_primitive() { $obj = new DateTimeType(); $now = new DateTime(); $this->assertSame($obj->castFromPrimitive($now->format($obj::$format))->getTimestamp(), $now->getTimestamp()); $cast = $obj->castFromPrimitive($now->format(DateTimeType::$format)); $this->assertInstanceOf(DateTime::class, $cast); $this->assertSame($cast->getTimestamp(), $now->getTimestamp()); } public function test_passes_validates() { $obj = new DateTimeType(); $obj->validate(new DateTime()); $this->assertTrue(true); } /** * @expectedException \DeeToo\Essentials\Exceptions\Error * @expectedExceptionMessage must be a date time */ public function test_fails_validates() { $obj = new DateTimeType(); $obj->validate('some string'); } }
C++
UTF-8
1,155
2.90625
3
[]
no_license
#include "UI.h" #include "Game.h" UI::UI(Game* game) { this->game = game; } void UI::Draw() { olc::vf2d healthBarPosition = {60, 8}; olc::vf2d healthBarSize = { static_cast<float>(game->ScreenWidth() - 70) * (game->GetPlayerHealth() / 100), 10.0f }; game->DrawString({10, 10}, "Health:"); game->FillRect(healthBarPosition, healthBarSize, olc::BLUE); game->DrawString({10, 30}, "Score: " + std::to_string(game->score)); } void UI::DrawTitleScreen() { game->DrawString({game->ScreenWidth() / 2 - 200, game->ScreenHeight() / 2 - 150}, "pgeBulletHell", olc::DARK_RED, 4); game->DrawString({game->ScreenWidth() / 2 - 75, game->ScreenHeight() / 2 - 75}, "Press space to start", olc::WHITE); game->DrawString({game->ScreenWidth() / 2 - 100, game->ScreenHeight() - 40}, "Developed by SaladinAkara", olc::WHITE); } void UI::DrawGameOver() { game->DrawString({game->ScreenWidth() / 2 - 175, game->ScreenHeight() / 2 - 150}, "Game Over!", olc::RED, 4); game->DrawString ({game->ScreenWidth() / 2 - 50, game->ScreenHeight() / 2 - 75}, "Score: " + std::to_string(game->score), olc::WHITE); }
Java
UTF-8
1,259
3.140625
3
[]
no_license
package com.kodilla.good.patterns.challenges.food2Door; import java.util.HashMap; import java.util.Map; public class HealthyShop implements Producent{ private ProductsAvaliablity productsAvaliablity = new ProductsAvaliablity(); private Map<String, Integer> listOfProducts = new HashMap<>(); @Override public Map<String, Integer> productsList (){ if(listOfProducts!=null) { listOfProducts.put("grain", 10000); listOfProducts.put("chia", 200000); listOfProducts.put("coconut", 1000); } return listOfProducts; } @Override public void process(OrderRequest orderRequest) { System.out.println("Checking products from HealthyShop"); OrderDto orderDto = productsAvaliablity.checkAvaliablity(orderRequest, productsList()); Map<String, Integer> ordered = orderDto.getReadyToSent(); Map<String, Integer> available = orderDto.getRemainingProducts(); if(ordered.size()!=0){ System.out.println("Products from HealthyShop in basket, ready to sent: "+ordered); System.out.println("Products reamaining: "+available); } else { System.out.println("Not avaliable products."); } } }
Python
UTF-8
6,398
2.921875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Sep 18 19:10:41 2016 @author: mamid """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import math as math import pylab as pl def compute_error_for_graph_given_points(thetha1,x,y): totalError = 0 max_x=np.amax(x) min_x=np.amin(x) mean_x=np.mean(x) for i in range(1, len(x)): feature_x= (x[i]-mean_x)/(max_x-min_x) h_thetha= 1/(1+np.e**(-feature_x*thetha1)) #np.exp(thetha1*feature_x)/(1+np.exp(thetha1*feature_x)) #print("error here is....",h_thetha) totalError += (((y[i])*(math.log(h_thetha)))+((1-y[i])*(math.log(1-h_thetha)))) #print("total error here is....",totalError) error_features=-(totalError / (float(len(x)))) #print("total error after summation here is....",error_features) return error_features def step_gradient(thetha_current, x,y, learningRate): thetha_gradient = 0 N = float(len(x)) max_x=np.amax(x) min_x=np.amin(x) mean_x=np.mean(x) for i in range(1, len(x)): feature_x= (x[i]-mean_x)/(max_x-min_x) h_thetha= 1/(1+np.e**(-feature_x*thetha_current)) #print("hypothesis is::::",h_thetha) #np.exp(thetha_current*feature_x)/(1+np.exp(thetha_current*feature_x)) exp_factor=np.e**(-thetha_current*feature_x) x_factor=((x[i]*exp_factor)/((1+exp_factor)*(1+exp_factor))) #print("x factor is::::",x_factor) thetha_gradient += (((y[i])*(math.log(h_thetha)))+((1-y[i])*(math.log(1-h_thetha))))*x_factor new_thetha = thetha_current - ((learningRate/N) * thetha_gradient) #print("thetha after gradient descent",new_thetha) return new_thetha def gradient_descent_runner(x,y, starting_thetha, learning_rate, num_iterations): thetha1 = starting_thetha for i in range(num_iterations): new_thetha = step_gradient(thetha1, x,y, learning_rate) return new_thetha def sigmoid(b,x): a = [] max_x=np.amax(x) min_x=np.amin(x) mean_x=np.mean(x) # print("length of x is:::",len(x)) # print("value of b is::::",b) for item in x: #print("item is::::",item) feature_x = (item-mean_x)/(max_x-min_x) #print("value of feature x is:",feature_x) #y=np.exp(b*feature_x)/(1+np.exp(b*feature_x)) a.append(1/(1+np.e**(-(feature_x*b)))) print ("value of a is:::",len(a)) return a def run(): points_training = pd.read_csv("training.csv", delimiter=",") points_test = pd.read_csv("test.csv", delimiter=",") x = np.array(points_training['Texture']) y = np.array(points_training['Recurrent']) x_test = np.array(points_test['Texture']) y_test = np.array(points_test['Recurrent']) print("test values of x are:::",len(x_test)) #y_actual = pd.Series(points_training['Recurrent'],name='Actual') #y_predicted=pd.Series(points_test['Recurrent'],name='Predicted') #print("actual y is:::",y_actual) #print("predicted y is:::",y_predicted) x_features= [] y_predicted = [] #print (x,y) learning_rate = 0.01 initial_b = -0.1 num_iterations = 5000 threshold= 0.5 # plt.show() print ("Starting gradient descent at b = {0}, error = {1}".format(initial_b, compute_error_for_graph_given_points(initial_b, x,y))) print ("Running...") b = gradient_descent_runner(x,y, initial_b, learning_rate, num_iterations) max_x=np.amax(x_test) min_x=np.amin(x_test) mean_x=np.mean(x_test) for item in x_test: feature_x= (item-mean_x)/(max_x-min_x) x_features.append(feature_x) #y=np.exp(b*feature_x)/(1+np.exp(b*feature_x)) #print("value of feature x is:::",feature_x) #x_features.append(feature_x) #print("value of feature x after appending is:::",x_features) #x_array = np.array(x_features) # print("value of feature x after appending array is:::",x_array) plt.scatter(x_features, y_test) y_sigmoid=sigmoid(b,x_test) print("sigmoid y values are:::",y_sigmoid) for item in y_sigmoid: if item < threshold : y_predicted.append(0) else: y_predicted.append(1) y_actual = pd.Series(y_test,name='Actual') y_predict=pd.Series(y_predicted,name='Predicted') print("predicted y len values are:::",len(y_predict)) #print("actual values of y are::::",y_actual) df_confusion = pd.crosstab(y_actual, y_predict,rownames=['Actual'], colnames=['Predicted'], margins=True) true_neg = df_confusion[0][0] false_pos = df_confusion[1][0] true_pos = df_confusion[1][1] false_neg = df_confusion[0][1] print("confusion matrix is::",df_confusion) print("true neg is:::",df_confusion[0][0]) print("false positive is:::",df_confusion[0][1]) print("false neg is:::",df_confusion[1][0]) print("true positive is:::",df_confusion[1][1]) print("true neg is:::",true_neg) print("false positive is:::",false_pos) print("false neg is:::",false_neg) print("true positive is:::",true_pos) precision = true_pos/(true_pos+false_pos) recall = true_pos/(true_pos+false_neg) f1_score= 2*((precision*recall)/(precision+recall)) print("precsion is::::",precision) print("Recall is::::",recall) print("f1-score is::::",f1_score) plt.ylabel('Recurrent') plt.xlabel('Texture') plt.plot(x_features,y_predict, color='r') plt.show() #print ('F1 score:', f1_score(y_actual, y_predict)) #print("x value is:::",x) #print("y value is::::",y) labels= ['texture','recurrent'] fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(df_confusion) pl.title('Confusion matrix of the classifier') fig.colorbar(cax) ax.set_xticklabels([''] + labels) ax.set_yticklabels([''] + labels) pl.xlabel('Predicted') pl.ylabel('True') pl.show() # This is the ROC curve #plt.plot(false_pos,true_pos) #plt.show() # This is the AUC # auc = np.trapz(true_pos,false_pos) print("After {0} iterations b = {1},error = {2}".format(num_iterations, b, compute_error_for_graph_given_points(b, x,y))) if __name__ == '__main__': run()
Markdown
UTF-8
1,694
2.6875
3
[]
no_license
# Comentario Lectura 1-2 En este árticulo el autor nos muestra su camino lógico seguido para la creación de un algoritmo recomendador enfocado en la particiáción del Netflix Prize, nos va dando diferentes pasos y cambios que realizó en el diseño durante su desarrollo explicando el porqué de cada paso. Mi primera crítica al texto presentado es que a mi parecer se necesita bastante conociemiento base del tema para terminar de entenderlo, ya que se nos plantean muchos puntos que son mejoras a un algoritmo implemntado pero no se presenta una introducción al mismo, por lo que no es recomendable como un texto introductorio. Luego, la forma en que estan presentados los cambios , además a mi parecer hace falta un mayor respaldo en resultados de las decisiones de diseño mostradas, y también una mejora en la forma de presentar los datos que ya están en el texto actual. En el texto si se aprecia una base teórica fuerte y se presentan las fórmulas de manera explícita, con lo que se obtiene un sustento fuerte en las mejoras realizadas, lo que da válidez para una futura replicación y uso del aporte generado. El texto aporta una mirada muy práctica del ambiente actual en el desarrollo de algoritmos recomendadores y nos da un ejemplo muy claro de un trabajo actual y su campo de aplicación, lo que sirve como punto para enfocar una investigación propia, ya sea desde lo presentado por él o un tabajo análogo sobre otras técnicas. En conclusión la lectura de este articulo me parece que no sirve para un fin introductorio y requiere de bastante conocimiento previo para poder seguir el hilo de ideas presentado por el autor. Por otro lado, esta publicación .
Java
UTF-8
3,286
2.125
2
[]
no_license
package com.example.seastec.forumtec; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class PreguntasActivity extends Activity { //public String[] preguntas; public ArrayList<String> preguntas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preguntas); Button btactualizar = (Button)findViewById(R.id.btactualizar); Button btBxCategoria = (Button)findViewById(R.id.btBxCategoria); preguntas = new ArrayList<String>(); preguntas.add("q es python"); preguntas.add("que es un lenguaje de programacion??"); preguntas.add("como instalar android studio"); final Bundle bundle = this.getIntent().getExtras(); final ArrayAdapter<String> adapter; adapter = new ArrayAdapter<String>(PreguntasActivity.this,android.R.layout.simple_list_item_1,preguntas); final ListView lv = (ListView)findViewById(R.id.expandableListView); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent verPregunta = new Intent(PreguntasActivity.this,ResponderActivity.class); Bundle b = new Bundle(); b.putString("Preguntas", lv.getAdapter().getItem(position).toString()); verPregunta.putExtras(b); startActivity(verPregunta); } }); btactualizar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { preguntas.add(0,bundle.getString("Pregunta")); lv.setAdapter(adapter); } }); btBxCategoria.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent a = new Intent(PreguntasActivity.this,CategoriasActivity.class); startActivity(a); } }); } @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_preguntas, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_sing_out: Intent a = new Intent(PreguntasActivity.this,LoginActivity.class); startActivity(a); return true; case R.id.action_preguntar: Intent preguntar = new Intent(PreguntasActivity.this,PreguntarActivity.class); startActivity(preguntar); return true; default: return super.onOptionsItemSelected(item); } } }
Java
UTF-8
2,452
2.984375
3
[]
no_license
package BackEnd.Graph; import BackEnd.Geometry.Node.Node; import BackEnd.Geometry.Node.NodeType; import BackEnd.Geometry.Point2D; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class BaseLayerTest { BaseLayer bl; List<Node> nodeList; @BeforeEach void setUp() { nodeList = new ArrayList<>(); // Create nodes in a layer 36x12 for (int x = 0; x < 36; x++) { for (int y = 0; y < 12; y++) { Node node = new Node(new Point2D(x, y)); nodeList.add(node); } } bl = new BaseLayer(nodeList); } @Test void testMethod_getNodeList() { List<Node> nodeListTest = new ArrayList<>(); for (int x = 0; x < 36; x++) { for (int y = 0; y < 12; y++) { Node node = new Node(new Point2D(x, y)); nodeListTest.add(node); } } for (int i = 0; i < 36 * 12; i++) { // BaseLayer does not contain 'time'. Therefore we test equality among the x and y. assertEquals(nodeListTest.get(i).getX(), nodeList.get(i).getX()); assertEquals(nodeListTest.get(i).getY(), nodeList.get(i).getY()); } } @Test void testMethod_getStationaryObstacles_01() { assertTrue(bl.getStationaryObstacles().isEmpty()); } @Test void testMethod_getStationaryObstacles_02() { List<Node> nodeListTest = new ArrayList<>(); for (int x = 0; x < 36; x++) { for (int y = 0; y < 12; y++) { Node node = new Node(new Point2D(x, y)); if (x == 20 && y == 10) node.setNodeType(NodeType.OBSTACLE); nodeListTest.add(node); } } BaseLayer baseLayer = new BaseLayer(nodeListTest); List<Node> obstacleArray = new ArrayList<>(); Node node = new Node(new Point2D(20, 10)); node.setNodeType(NodeType.OBSTACLE); obstacleArray.add(node); assertTrue(!baseLayer.getStationaryObstacles().isEmpty()); assertEquals(1, baseLayer.getStationaryObstacles().size()); assertEquals(obstacleArray.get(0).getX(), baseLayer.getStationaryObstacles().get(0).getX()); } }
Java
UTF-8
6,817
2.078125
2
[]
no_license
package papa.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.ifdag.log.Log; import papa.DoubanBookByNo; import papa.DoubanBookGetGoodPro; import papa.bean.BookInfoBean; /** * * @author xj */ public class SqlDao extends SqldbBase { private Connection con; public SqlDao(Connection con) { super(); this.con = con; } public boolean insertBookInfo(List<BookInfoBean>list) { PreparedStatement pstmt = null; boolean result =false; try { String sql = "INSERT INTO book_info (bookName,zuozhe,zuozheCountry,chubanshe,fubiaoti,yuanzhuoming,yizhe,chubannian,pageCount,price" + ",zhuangzhen,congshu,tags,doubanScore,doubanScorePersonCount,isbn,synopsis,doubanID,updateTime) " + //8 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(sql); Timestamp d= new Timestamp(System.currentTimeMillis()); for(BookInfoBean b :list){ pstmt.setString(1,b.getBookName()); pstmt.setString(2,b.getZuozhe()); pstmt.setString(3,b.getZuozheCountry()); pstmt.setString(4,b.getChubanshe()); pstmt.setString(5,b.getFubiaoti()); pstmt.setString(6,b.getYuanzhuoming()); pstmt.setString(7,b.getYizhe()); pstmt.setDate(8,b.getChubannian()); pstmt.setInt(9,b.getPageCount()); pstmt.setDouble(10,b.getPrice()); pstmt.setString(11,b.getZhuangzhen()); pstmt.setString(12,b.getCongshu()); pstmt.setString(13,b.getTags()); pstmt.setDouble(14,b.getDoubanScore()); pstmt.setInt(15,b.getDoubanScorePersonCount()); pstmt.setString(16,b.getIsbn()); pstmt.setString(17,b.getSynopsis()); pstmt.setString(18,b.getDoubanID()); pstmt.setTimestamp(19, d); pstmt.addBatch(); } pstmt.executeBatch(); result=true; } catch(Exception e){ Log.error("-------------------------ERROR DATE----------------------------"); for(BookInfoBean b :list){ Log.error(b.toString()); } Log.error("-----------------------------------------------------------"); Log.exception(this,e); } finally { close(pstmt); } return result; } public long getMaxIppTime(){ PreparedStatement pstmt = null; ResultSet rs=null; long time=0l; boolean result =false; try { String sql = "select max(updateTime) from ip_proxy "; pstmt = con.prepareStatement(sql); rs= pstmt.executeQuery(); if(rs.next()){ time =rs.getTimestamp(1).getTime(); } } catch(Exception e){ e.printStackTrace(); } finally { close(rs); close(pstmt); } return time; } public boolean insertIP(List<String[]>list) { PreparedStatement pstmt = null; boolean result =false; try { String sql = "INSERT INTO ip_proxy (ip,port,status,updateTime) " + //8 " VALUES (?,?,0,?)"; pstmt = con.prepareStatement(sql); for(String [] b :list){ pstmt.setString(1,b[0]); pstmt.setString(2,b[1]); pstmt.setTimestamp(3, new Timestamp(Long.parseLong(b[2]))); pstmt.addBatch(); } pstmt.executeBatch(); result=true; } catch(Exception e){ e.printStackTrace(); } finally { close(pstmt); } return result; } public List<String[]> getporxyList(int status){ PreparedStatement pstmt = null; ResultSet rs=null; List<String[]> list =new ArrayList<String[]>(); try { String sql = "select ip,port from ip_proxy where status =? "; pstmt = con.prepareStatement(sql); pstmt.setInt(1, status); rs= pstmt.executeQuery(); while(rs.next()){ list.add(new String[] {rs.getString(1),rs.getString(2)}); } } catch(Exception e){ e.printStackTrace(); } finally { close(rs); close(pstmt); } return list; } public boolean updateProxyIP (int dest, int orign) { PreparedStatement pstmt = null; boolean result =false; try { String sql = "update ip_proxy set status= ? where status =? limit "+DoubanBookGetGoodPro.MaxProxy ; pstmt = con.prepareStatement(sql); pstmt.setInt(1, dest); pstmt.setInt(2, orign); pstmt.executeUpdate(); result=true; } catch(Exception e){ e.printStackTrace(); } finally { close(pstmt); } return result; } public boolean deleteProxyIP (String ip, String port) { PreparedStatement pstmt = null; boolean result =false; try { String sql = "delete from ip_proxy where ip= ? and port =? " ; pstmt = con.prepareStatement(sql); pstmt.setString(1, ip); pstmt.setString(2, port); pstmt.execute(); result=true; } catch(Exception e){ e.printStackTrace(); } finally { close(pstmt); } return result; } public String getLastDouBanID(){ PreparedStatement pstmt = null; ResultSet rs=null; String id=null; try { String sql = "SELECT doubanID FROM book_info order by updatetime desc LIMIT 1 "; pstmt = con.prepareStatement(sql); rs= pstmt.executeQuery(); if(rs.next()){ id =rs.getString(1); } } catch(Exception e){ e.printStackTrace(); } finally { close(rs); close(pstmt); } return id; } }
Java
UTF-8
1,203
3.078125
3
[]
no_license
package jTensor; public abstract class TensorOperation{ // Executes operation, derivative inputs should come after output gradient public abstract void execute(Tensor outputTensor, Tensor... inputs); // Gives tensor output dimensions given array of input dimensions (by default identity) // returns null if illegal input public int[] getOutputDimensions(int[][] inputDimensions){ return inputDimensions[0]; } // Returns gradients of operation with respect to given input (index base 0 of execute param) public TensorDerivativeInfo getDerivative(final int inputIndex){ TensorOperation derivativeOp = new TensorOperation(){ public void execute(Tensor output, Tensor... inputs){ inputs[0].copyTo(output, CopyOp.identity); } }; int[] inputsNeeded = {}; return new TensorDerivativeInfo(derivativeOp, inputsNeeded); } public static class TensorDerivativeInfo{ TensorOperation op; int[] inputsNeeded; // original inputs that the derivative will also // need, will become input[i+1] (due to gradient being first) public TensorDerivativeInfo(TensorOperation op, int[] inputsNeeded){ this.op = op; this.inputsNeeded = inputsNeeded; } } }
Java
UTF-8
550
1.859375
2
[ "Apache-2.0" ]
permissive
package biz.netcentric.nclabs.groovyconsole.groovy.impl.extension; import biz.netcentric.nclabs.groovyconsole.ScriptExecutionContext; import groovy.lang.Binding; /** * Provides access to object and variable {@link Binding}s * * @author thomas.hartmann@netcentric.biz * @since 11/2015 */ public interface BindingExtensionsProviderService { /** * Get's the aggregated binding for console specific extensions. * * @param context The context * @return The Binding */ Binding createBindings(final ScriptExecutionContext context); }
C
UTF-8
689
2.765625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <string.h> #define MAX 10000 int gcd(int i, int j) { if(i%j==0) return j; else return gcd(j, i%j); } int main() { #ifndef ONLINE_JUDGE freopen("filename.txt", "r", stdin); #endif //freopen("test.txt", "r", stdin); int ncase; scanf("%d", &ncase); while(ncase--) { int max=-1, min=99999, n, tmp; scanf("%d", &n); while(n--) { scanf("%d", &tmp); if(max<tmp) max=tmp; if(min>tmp) min=tmp; } printf("%d\n", gcd(max, min)); } return 0; }
Python
UTF-8
2,868
3.390625
3
[ "MIT" ]
permissive
class Node: value: str = None def __init__(self, value: str): self.value = value def __repr__(self) -> str: return self.value class Graph: edges: dict = dict() def addChild(self, parent: Node, child: Node, weight=1) -> None: self.edges[(parent, child)] = weight def addParent(self, parent: Node, child: Node, weight=1) -> None: self.edges[(child, parent)] = weight def getChildren(self, node: Node) -> set: children = set() for edge in self.edges: if node is edge[0]: children.add(edge[1]) return children def getParents(self, node: Node) -> set: parents = set() for edge in self.edges: if node is edge[1]: parents.add(edge[0]) return parents def getDescendants(self, node: Node) -> set: descendants = set() for child in self.getChildren(node): descendants.add(child) descendants |= self.getDescendants(child) return descendants def getAncestors(self, node: Node) -> set: ancestors = set() for parent in self.getParents(node): ancestors.add(parent) ancestors |= self.getAncestors(parent) return ancestors relationships = Graph() football = Node("Football") player = Node("Player") competition = Node("Competition") champtionsLeague = Node("Champtions League") premierLeague = Node("Premier League") manUtd = Node("Manchester United") manCity = Node("Manchester City") relationships.addChild(football, player) relationships.addChild(football, competition) relationships.addChild(competition, champtionsLeague) relationships.addChild(competition, premierLeague) relationships.addChild(champtionsLeague, manUtd) relationships.addChild(premierLeague, manUtd) relationships.addChild(premierLeague, manCity) print("Children of %s: %s" % (football, relationships.getChildren(football))) print("Children of %s: %s" % (player, relationships.getChildren(player))) print("Children of %s: %s" % (premierLeague, relationships.getChildren(premierLeague))) print("Parents of %s: %s" % (football, relationships.getParents(football))) print("Parents of %s: %s" % (player, relationships.getParents(player))) print("Parents of %s: %s" % (manUtd, relationships.getParents(manUtd))) print("Descendants of %s: %s" % (football, relationships.getDescendants(football))) print("Descendants of %s: %s" % (player, relationships.getDescendants(player))) print("Descendants of %s: %s" % (premierLeague, relationships.getDescendants(premierLeague))) print("Ancestors of %s: %s" % (football, relationships.getAncestors(football))) print("Ancestors of %s: %s" % (player, relationships.getAncestors(player))) print("Ancestors of %s: %s" % (manUtd, relationships.getAncestors(manUtd)))
TypeScript
UTF-8
1,216
2.875
3
[]
no_license
// Types import { IChatData } from "interfaces"; /** Definitions */ const UNITS_IN_MILLISECONDS = { day: 86400000, hour: 3600000, minute: 60000, second: 1000 }; /** Utils */ export const setPeriod = (hour: number, minute: number, second: number) => { if (process.browser) { const now = new Date().getTime(); const hoursFormatted = hour * UNITS_IN_MILLISECONDS.hour; const minutesFormatted = minute * UNITS_IN_MILLISECONDS.minute; const secondsFormatted = second * UNITS_IN_MILLISECONDS.second; const period = new Date( now + hoursFormatted - minutesFormatted - secondsFormatted ); const hh = period.getHours(); const hours = hh > 12 ? hh - 12 : hh; const min = period.getMinutes(); const minutes = min < 10 ? `0${min}` : min; const descrip = hh < 12 ? "AM" : "PM"; return { full: period, brief: `${hours}:${minutes} ${descrip}` }; } }; export const orderByLastMessage = (chatData: IChatData[]) => { const messagesOrdered = chatData.sort(({ messages: a }, { messages: b }) => { const lastMessageA = a[a.length - 1].date.full; const lastMessageB = b[b.length - 1].date.full; // @ts-ignore return lastMessageB - lastMessageA; }); return messagesOrdered; };
Python
UTF-8
1,788
2.59375
3
[]
no_license
from morbid import StompFactory from twisted.protocols import basic from twisted.internet import reactor, protocol from twisted.internet.task import LoopingCall from stompservice import StompClientFactory import simplejson as json class MyReceiver(basic.LineReceiver): delimiter = '\0' def connectionMade(self): print "Got new client!" self.factory.clients.append(self) def connectionLost(self, reason): print "Lost a client!" self.factory.clients.remove(self) def lineReceived(self,line): if line == "<policy-file-request/>": print "\t sending policy file" self.sendLine("<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"61613\" /></cross-domain-policy>") else: print line class XMLSocket(protocol.Factory): clients=[] def __init__(self, protocol=None): self.protocol=protocol ''' The DataProducer is an example of how you can hook into the broker. Here, we send a simple text string every second given that shouldSend is true. ''' class DataProducer(StompClientFactory): shouldSend = True def recv_connected(self, msg): self.timer = LoopingCall(self.send_data) self.timer.start(1000/1000.0) def send_data(self): if self.shouldSend: self.send("/topic/directmessaging-outgoing", "Hello world") def main(): # The STOMP broker reactor.listenTCP(61613, StompFactory()) # Flash socket policy serving reactor.listenTCP(33333, XMLSocket(MyReceiver)) # And the example DataProducer dp = DataProducer() dp.shouldSend = False reactor.connectTCP('localhost', 61613, dp) # Start everything reactor.run() if __name__ == "__main__": main()
C++
UTF-8
290
2.515625
3
[]
no_license
class Solution { public: int numSub(string s) { int ans=0; int length=0; for(auto i:s){ if(i=='1'){ length++; ans=(ans+length)%1000000007; } else length=0; } return ans; } };
Java
UTF-8
2,315
1.765625
2
[]
no_license
/* * Decompiled with CFR 0.151. * * Could not load the following classes: * android.content.Context */ package com.huawei.hms.hatool; import android.content.Context; import com.huawei.hms.hatool.i; import com.huawei.hms.hatool.l; import com.huawei.hms.hatool.q0; import com.huawei.hms.hatool.x0; import com.huawei.hms.hatool.y; public final class f1 { public static f1 b; public static final Object c; public Context a; static { Object object; c = object = new Object(); } public static f1 a() { f1 f12 = b; if (f12 == null) { f1.b(); } return b; } /* * Enabled aggressive block sorting * Enabled unnecessary exception pruning * Enabled aggressive exception aggregation */ public static void b() { Class<f1> clazz = f1.class; synchronized (clazz) { f1 f12 = b; if (f12 == null) { b = f12 = new f1(); } return; } } /* * Enabled aggressive block sorting * Enabled unnecessary exception pruning * Enabled aggressive exception aggregation */ public void a(Context object) { Object object2; Object object3 = c; synchronized (object3) { object2 = this.a; if (object2 != null) { object = "hmsSdk"; object2 = "DataManager already initialized."; y.f((String)object, (String)object2); return; } this.a = object; } object3 = i.c().b(); object2 = this.a; ((l)object3).a((Context)object2); object3 = i.c().b(); object2 = object.getPackageName(); ((l)object3).g((String)object2); x0.a().a((Context)object); } public void a(String string2) { String string3 = "hmsSdk"; y.c(string3, "HiAnalyticsDataManager.setAppid(String appid) is execute."); Context context = this.a; if (context == null) { y.e(string3, "sdk is not init"); return; } string3 = context.getPackageName(); string2 = q0.a("appID", string2, "[a-zA-Z0-9_][a-zA-Z0-9. _-]{0,255}", string3); i.c().b().f(string2); } }
Java
UTF-8
5,208
2.109375
2
[]
no_license
package com.bishe.aapay.view; import java.util.Date; import java.util.List; import com.bishe.aapay.activity.ConsumeActivity.TimeSelecror; import com.bishe.aapay.activity.R; import com.bishe.aapay.dao.ConsumptionDao; import com.bishe.aapay.dto.Consumption; import com.bishe.aapay.util.AApayDateUtil; import android.R.integer; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class LvConsumptionListAdapter extends BaseAdapter { private Context context; private LayoutInflater inflater = null; private ConsumptionDao consumptionDao; private long teamId; private List<Consumption> consumptionList; private TimeSelecror timeSelector; private String startTime; private String endTime; private int interval = 0; public LvConsumptionListAdapter(Context context,ConsumptionDao consumptionDao,long teamId,TimeSelecror timeSelector,int interval) { this.context = context; this.inflater = LayoutInflater.from(context); this.consumptionDao = consumptionDao; this.teamId = teamId; this.timeSelector = timeSelector; this.interval = interval; AApayDateUtil.setGivenDate(new Date()); switch (timeSelector) { case ALL: this.consumptionList = consumptionDao.getConsumptionsByTeamId(teamId); break; case TODAY: startTime = AApayDateUtil.getBeginTimeOfDate(AApayDateUtil.getDateByInterval(interval)); endTime = AApayDateUtil.getEndTimeOfDate(AApayDateUtil.getDateByInterval(interval)); this.consumptionList = consumptionDao.getConsumptions(teamId,startTime,endTime); break; case WEEK: startTime = AApayDateUtil.getBeginTimeOfDate(AApayDateUtil.getMondayByInterval((interval))); endTime = AApayDateUtil.getEndTimeOfDate(AApayDateUtil.getSundayByInterval(interval)); this.consumptionList = consumptionDao.getConsumptions(teamId,startTime,endTime); break; case MONTH: startTime = AApayDateUtil.getBeginTimeOfDate(AApayDateUtil.getMonthBeginByInterval((interval))); endTime = AApayDateUtil.getEndTimeOfDate(AApayDateUtil.getMonthEndByInterval(interval)); this.consumptionList = consumptionDao.getConsumptions(teamId,startTime,endTime); break; } } @Override public int getCount() { return consumptionList.size(); } @Override public Object getItem(int position) { return consumptionList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.consumption_list, null); holder.viewName = (TextView) convertView.findViewById(R.id.list_item_name); holder.viewTime = (TextView) convertView.findViewById(R.id.list_consume_time); holder.viewPeopleNum = (TextView) convertView.findViewById(R.id.list_peple_num); holder.viewMoney = (TextView) convertView.findViewById(R.id.list_consumption_total); holder.viewPayoff = (TextView) convertView.findViewById(R.id.list_consumption_pay_off); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.viewName.setText(consumptionList.get(position).getName()); holder.viewTime.setText(consumptionList.get(position).getTime()); holder.viewPeopleNum.setText(String.valueOf(consumptionList.get(position).getParticipantNum())); holder.viewMoney.setText(String.valueOf(consumptionList.get(position).getMoney())); holder.viewPayoff.setText(consumptionList.get(position).getPayOFF()); return convertView; } public void setTeamId(long teamId,TimeSelecror timeSelector,int interval) { this.teamId = teamId; this.timeSelector = timeSelector; this.interval = interval; AApayDateUtil.setGivenDate(new Date()); switch (timeSelector) { case ALL: this.consumptionList = consumptionDao.getConsumptionsByTeamId(teamId); break; case TODAY: startTime = AApayDateUtil.getBeginTimeOfDate(AApayDateUtil.getDateByInterval(interval)); endTime = AApayDateUtil.getEndTimeOfDate(AApayDateUtil.getDateByInterval(interval)); this.consumptionList = consumptionDao.getConsumptions(teamId,startTime,endTime); break; case WEEK: startTime = AApayDateUtil.getBeginTimeOfDate(AApayDateUtil.getMondayByInterval((interval))); endTime = AApayDateUtil.getEndTimeOfDate(AApayDateUtil.getSundayByInterval(interval)); this.consumptionList = consumptionDao.getConsumptions(teamId,startTime,endTime); break; case MONTH: startTime = AApayDateUtil.getBeginTimeOfDate(AApayDateUtil.getMonthBeginByInterval((interval))); endTime = AApayDateUtil.getEndTimeOfDate(AApayDateUtil.getMonthEndByInterval(interval)); this.consumptionList = consumptionDao.getConsumptions(teamId,startTime,endTime); break; } } public class ViewHolder { public TextView viewName; public TextView viewTime; public TextView viewPeopleNum; public TextView viewMoney; public TextView viewPayoff; } }
Java
UTF-8
1,325
3.1875
3
[]
no_license
/* * Copyright(c) snowpic.cn 2019-2019.All rights reserved. */ package cn.snowpic.year_2020.month_01.month_01.day_14; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class GenericTest { /** * test1 * * @author lf * @time 2020-01-14 22:24 */ @Test public void test1() { int[] tom = {1, 1}; int[] cat = {2, 2}; int[] exchangeCandy = exchangeCandy(tom, cat); System.out.println("exchangeCandy = " + Arrays.toString(exchangeCandy)); } /** * exchange candy * * @author lf * @time 2020-01-14 22:33 * @param tom tom * @param bob bob * @return int[] */ private int[] exchangeCandy(int[] tom, int[] bob) { int tomSum = Arrays.stream(tom).sum(); int bobSum = Arrays.stream(bob).sum(); int delta = (bobSum - tomSum) / 2; Set<Integer> tomSet = new HashSet<>(); Set<Integer> bobSet = new HashSet<>(); for (int t : tom) tomSet.add(t); for (int b : bob) bobSet.add(b); for (Integer ts : tomSet) { int tep = ts + delta; if (bobSet.contains(tep)) { return new int[]{ts, ts + delta}; } } throw new RuntimeException(); } }
C#
UTF-8
1,136
3.203125
3
[ "MIT" ]
permissive
namespace NinjaAssassins.Models.Cards { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Fight : Card { public Fight(string filePath, int rank, int priority) : base(filePath, rank, CardType.Fight, priority, true) { } public override void Action(Game game) { Random random = new Random(); int ninjaRandom = random.Next(1, 100); int yourRandom = random.Next(1, 100); if (yourRandom > ninjaRandom) { game.Log = game.PlayerInTurn + "| fought and won! " + yourRandom + " to " + ninjaRandom; return; } else { if (game.CurrentCard.CardType == CardType.NinjaAssassin) { game.Log = game.PlayerInTurn + "| fought the ninja but lost!" + yourRandom + " to " + ninjaRandom; game.PlayerInTurn.IsDead = true; } return; } } } }
Shell
UTF-8
380
2.625
3
[ "MIT" ]
permissive
#!/bin/bash -ex source $HOME/miniconda/etc/profile.d/conda.sh conda activate test if [ "$USE_CONDA" = "Yes" ]; then # There are no conda packages for PySide2 exit 0 else pip uninstall -q -y pyqt5 sip # Simple solution to avoid failures with the # Qt3D modules pip install -q pyside2==5.12.3 fi python qtpy/tests/runtests.py pip uninstall -y -q pyside2
Python
UTF-8
5,663
2.625
3
[]
no_license
#!/usr/bin/env python ''' car detection using haar cascades USAGE: facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>] ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv # local modules #from video import create_capture from common import clock, draw_str vfile_src = "G:/fotovideo/video_src/U524806_6.avi" vfile_src = "G:/fotovideo/video_src/U524802_14.avi" vfile_src = "G:/fotovideo/video_src/U524802_15.avi" #vfile_src = "G:/fotovideo/video_src/U524802_16.avi" vfile_src = "G:/fotovideo/video_src/U524806_3.avi" #vfile_src = "G:/fotovideo/video_src/sunny.avi" USE_GAMMA = False def detect(img, cascade): # rects = cascade.detectMultiScale(img, scaleFactor=1.7, minNeighbors=9, minSize=(30, 30),flags=cv.CASCADE_SCALE_IMAGE) # rects = cascade.detectMultiScale(img, scaleFactor=1.03, minNeighbors=7, minSize=(30, 30),flags=cv.CASCADE_SCALE_IMAGE) rects = cascade.detectMultiScale(img, scaleFactor=1.5, minNeighbors=7, minSize=(50, 50),flags=cv.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects def square_calc(x1,y1,x2,y2): return (x2-x1)*(y2-y1) def square_overlap(rect1, rect2): """ возвращает площадь прямоугольника перекрытия""" #print('rect1 ', rect1) x11,y11,x21,y21 = rect1 x12,y12,x22,y22 = rect2 x1=max(x11,x12) y1=max(y11,y12) x2=min(x21,x22) y2=min(y21,y22) sq_rect = square_calc(x1,y2,x2,y2) sq_rect1 = square_calc(rect1) sq_rect2 = square_calc(rect2) if sq_rect1<=sq_rect2: return sq_rect else: return -sq-rect def gamma(image,gamma = 0.5): img_float = np.float32(image) max_pixel = np.max(img_float) #image pixel normalisation img_normalised = img_float/max_pixel #gamma correction exponent calulated gamma_corr = np.log(img_normalised)*gamma #gamma correction being applied gamma_corrected = np.exp(gamma_corr)*255.0 #conversion to unsigned int 8 bit gamma_corrected = np.uint8(gamma_corrected) return gamma_corrected def draw_rects(img, rects, color): # print('\n\n ', ) # print('rects ', rects) for x1, y1, x2, y2 in rects: #square = square_calc(x1, y1, x2, y2) #print('square ',square ) #print('x1, y1, x2, y2 ',x1, y1, x2, y2, ' ', square) cv.rectangle(img, (x1, y1), (x2, y2), color, 2) def remove_bad_rects(rects): """удаляет лишние полигоны""" # ищем один полигон внутри другого и больший удаляем, внутренний оставляем for i, rect in enumerate (rects): for j in len(rects): sq = square_overlap(rect, rects[j]) # получаем площадь зоны перекрытия текущего прямоугольника в каждым # далее надо написать удалялку. но лень if __name__ == '__main__': import sys, getopt print(__doc__) args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade=']) try: video_src = video_src[1] except: video_src = 1 args = dict(args) print('args ', args) #cascade_fn = args.get('--cascade', "data/haarcascades/cas3.xml") #cascade_fn = args.get('--cascade', "cascade10.xml") #cascade_fn = args.get('--cascade', "cascadeLBP.xml") #cascade_fn = args.get('--cascade', "cascadeLBP16.xml") #cascade_fn = args.get('--cascade', "cascade_lbp_w25_h25_p17116_n35275.xml") #cascade_fn = args.get('--cascade', "cascadeHaar_w25_h25_p17116_n35275.xml") #cascade_fn = args.get('--cascade', "cascadeLBP_w25_h25_p2572_n45259.xml") # пластины номеров #cascade_fn = args.get('--cascade', "plate_cascade_haar_12.xml") cascade_fn = args.get('--cascade', "vehicles_cascadeLBP_w25_h25_p2572_n58652_neg_roof.xml") #cascade_fn = args.get('--cascade', "night_cascadeLBP_gamma_w25_h25_p9004_n13679.xml") #cascade_fn = args.get('--cascade', "night_cascadeLBP_w25_h25_p2454_n6734.xml") #cascade_fn = args.get('--cascade', "night_cascadeLBP_gamma_w25_h25_p9004_n23457.xml") #print('cascade_fn ',cascade_fn ) # cascade = cv.CascadeClassifier(cv.samples.findFile(cascade_fn)) cascade = cv.CascadeClassifier(cascade_fn) #nested = cv.CascadeClassifier(cv.samples.findFile(nested_fn)) #cam = create_capture(video_src, fallback='synth:bg={}:noise=0.05'.format(cv.samples.findFile('samples/data/lena.jpg'))) cam = cv.VideoCapture(vfile_src) ret, img = cam.read() print('img schape ', img.shape) while ret: ret, img = cam.read() if ret: img = cv.resize(img, (640, 480)) # img = cv.resize(img, (1440, 1200)) if USE_GAMMA: img = gamma(img) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) #gray = cv.equalizeHist(gray) t = clock() rects = detect(gray, cascade) #remove_bad_rects(rects) dt = clock() - t vis = img.copy() draw_rects(vis, rects, (0, 255, 0)) draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000)) cv.imshow(str(cascade_fn), vis) if cv.waitKey(1) == 27: break cam.release() cv.destroyAllWindows() print('THE END')
C++
UTF-8
929
3.078125
3
[]
no_license
#ifndef __PROJECTILE_H__ #define __PROJECTILE_H__ #include "util/game_util.h" #include "util/texture2d.h" class Projectile { private: Texture2D *m_texture; Vector2 m_position; Rect m_viewport; bool m_active; int m_damage; float m_projectileMoveSpeed; public: Projectile(); virtual ~Projectile(); void initialize(Rect viewport, Texture2D *texture, Vector2 position); void update(float gameTime); void draw(); bool isActive() {return m_active;} float getX() {return m_position.x;} float getY() {return m_position.y;} Vector2 getPos() {return m_position;} int getWidth() {return m_texture->getWidth();} int getHeight() {return m_texture->getHeight();} int getDamage() {return m_damage;} void setActive(bool active) {m_active = active;} }; #endif // __PROJECTILE_H__
C++
UTF-8
3,075
2.71875
3
[]
no_license
#include "SettingState.hpp" #include <cstdint> #include <functional> #include "Utility.hpp" void SettingState::addButtonLabel(Player::Action action, float y, std::string text, State::Context context) { mBindingButtons[action] = std::make_shared<GUI::Button> ( context ); mBindingButtons[action]->setText(text); mBindingButtons[action]->setPosition(100.f , y); mBindingButtons[action]->setToggle(true); mGUIContainer.pack(mBindingButtons[action]); mBindingLabels[action] = std::make_shared<GUI::Label> ( "" , *context.mFontHolder ); mBindingLabels[action]->setPosition(100.f + mBindingButtons[action]->getBoundingSize().x , y + 15.f); mGUIContainer.pack(mBindingLabels[action]); } SettingState::SettingState(StateStack& mStateStack , Context context) : State(mStateStack,context) , mGUIContainer() { mBackgroundSprite.setTexture(context.mTextureHolder->get(Textures::TitleScreen)); addButtonLabel(Player::Action::moveDown , 150.f , "Move Down" , context); addButtonLabel(Player::Action::moveLeft , 200.f , "Move Left" , context); addButtonLabel(Player::Action::moveRight , 250.f , "Move Right" , context); addButtonLabel(Player::Action::moveUp , 300.f , "Move Up" , context); addButtonLabel(Player::Action::Fire, 350.f, "Fire", context ); addButtonLabel(Player::Action::LaunchMissile, 400.f, "Launch Missile" , context ); updateLabels(); auto lBackButton = std::make_shared<GUI::Button>( context ); lBackButton->setText("Go Back."); lBackButton->setPosition(250.f , 50.f); lBackButton->setCallback( std::bind( &SettingState::requestStackPop , this) ); mGUIContainer.pack(lBackButton); } bool SettingState::handleEvent(const sf::Event& event) { bool isKeyBinding = false; for(std::size_t action = 0 ; action < Player::Action::ActionCount ; action++) { if(mBindingButtons[action]->isActive()) { isKeyBinding = true; if(event.type == sf::Event::KeyReleased ) { getContext().mPlayer->assignKey(static_cast<Player::Action>(action) , event.key.code); mBindingButtons[action]->deactivate(); } break; } } if(isKeyBinding) updateLabels(); else { mGUIContainer.handleEvent(event); } return false; } bool SettingState::update(sf::Time) { } void SettingState::draw() { sf::RenderTarget & lTarget = *( getContext().mRenderWindow ); sf::RectangleShape darken_back; darken_back.setFillColor( sf::Color{0 , 0 , 0 , 255} ); darken_back.setSize( static_cast<sf::Vector2f> ( lTarget.getSize() ) ); lTarget.draw(darken_back); lTarget.draw(mBackgroundSprite); lTarget.draw(mGUIContainer); } void SettingState::updateLabels() { Player& lPlayer = *getContext().mPlayer; for(std::size_t i = 0 ; i < Player::ActionCount ; i++) { sf::Keyboard::Key key = lPlayer.getAssignedKey( static_cast<Player::Action>(i)); mBindingLabels[i]->setText( toString(key) ); } }
Java
UTF-8
12,452
1.617188
2
[ "Apache-2.0" ]
permissive
/* * Copyright © 2020 photowey (photowey@gmail.com) * * 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 com.photowey.ext.core.repository; import org.flowable.bpmn.model.BpmnModel; import org.flowable.dmn.api.DmnDecision; import org.flowable.engine.RepositoryService; import org.flowable.engine.app.AppModel; import org.flowable.engine.repository.*; import org.flowable.form.api.FormDefinition; import org.flowable.identitylink.api.IdentityLink; import org.flowable.validation.ValidationError; import java.io.InputStream; import java.util.Date; import java.util.List; /** * {@code AbstractRepositoryServiceDelegate} * * @author photowey * @date 2021/01/19 * @since 1.0.0 */ public abstract class AbstractRepositoryServiceDelegate implements RepositoryService { /** * Get {@link RepositoryService} instance. * * @return {@link RepositoryService} */ public abstract RepositoryService getRepositoryService(); @Override public DeploymentBuilder createDeployment() { return this.getRepositoryService().createDeployment(); } @Override public void deleteDeployment(String deploymentId) { this.getRepositoryService().deleteDeployment(deploymentId); } @Override public void deleteDeployment(String deploymentId, boolean cascade) { this.getRepositoryService().deleteDeployment(deploymentId, cascade); } @Override public void setDeploymentCategory(String deploymentId, String category) { this.getRepositoryService().setDeploymentCategory(deploymentId, category); } @Override public void setDeploymentKey(String deploymentId, String key) { this.getRepositoryService().setDeploymentKey(deploymentId, key); } @Override public List<String> getDeploymentResourceNames(String deploymentId) { return this.getRepositoryService().getDeploymentResourceNames(deploymentId); } @Override public InputStream getResourceAsStream(String deploymentId, String resourceName) { return this.getRepositoryService().getResourceAsStream(deploymentId, resourceName); } @Override public void changeDeploymentTenantId(String deploymentId, String newTenantId) { this.getRepositoryService().changeDeploymentTenantId(deploymentId, newTenantId); } @Override public void changeDeploymentTenantId(String deploymentId, String newTenantId, MergeMode mergeMode) { this.getRepositoryService().changeDeploymentTenantId(deploymentId, newTenantId, mergeMode); } @Override public void changeDeploymentTenantId(String deploymentId, String newTenantId, DeploymentMergeStrategy deploymentMergeStrategy) { this.getRepositoryService().changeDeploymentTenantId(deploymentId, newTenantId, deploymentMergeStrategy); } @Override public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) { this.getRepositoryService().changeDeploymentParentDeploymentId(deploymentId, newParentDeploymentId); } @Override public ProcessDefinitionQuery createProcessDefinitionQuery() { return this.getRepositoryService().createProcessDefinitionQuery(); } @Override public NativeProcessDefinitionQuery createNativeProcessDefinitionQuery() { return this.getRepositoryService().createNativeProcessDefinitionQuery(); } @Override public DeploymentQuery createDeploymentQuery() { return this.getRepositoryService().createDeploymentQuery(); } @Override public NativeDeploymentQuery createNativeDeploymentQuery() { return this.getRepositoryService().createNativeDeploymentQuery(); } @Override public void suspendProcessDefinitionById(String processDefinitionId) { this.getRepositoryService().suspendProcessDefinitionById(processDefinitionId); } @Override public void suspendProcessDefinitionById(String processDefinitionId, boolean suspendProcessInstances, Date suspensionDate) { this.getRepositoryService().suspendProcessDefinitionById(processDefinitionId, suspendProcessInstances, suspensionDate); } @Override public void suspendProcessDefinitionByKey(String processDefinitionKey) { this.getRepositoryService().suspendProcessDefinitionByKey(processDefinitionKey); } @Override public void suspendProcessDefinitionByKey(String processDefinitionKey, boolean suspendProcessInstances, Date suspensionDate) { this.getRepositoryService().suspendProcessDefinitionByKey(processDefinitionKey, suspendProcessInstances, suspensionDate); } @Override public void suspendProcessDefinitionByKey(String processDefinitionKey, String tenantId) { this.getRepositoryService().suspendProcessDefinitionByKey(processDefinitionKey, tenantId); } @Override public void suspendProcessDefinitionByKey(String processDefinitionKey, boolean suspendProcessInstances, Date suspensionDate, String tenantId) { this.getRepositoryService().suspendProcessDefinitionByKey(processDefinitionKey, suspendProcessInstances, suspensionDate, tenantId); } @Override public void activateProcessDefinitionById(String processDefinitionId) { this.getRepositoryService().activateProcessDefinitionById(processDefinitionId); } @Override public void activateProcessDefinitionById(String processDefinitionId, boolean activateProcessInstances, Date activationDate) { this.getRepositoryService().activateProcessDefinitionById(processDefinitionId, activateProcessInstances, activationDate); } @Override public void activateProcessDefinitionByKey(String processDefinitionKey) { this.getRepositoryService().activateProcessDefinitionByKey(processDefinitionKey); } @Override public void activateProcessDefinitionByKey(String processDefinitionKey, boolean activateProcessInstances, Date activationDate) { this.getRepositoryService().activateProcessDefinitionByKey(processDefinitionKey, activateProcessInstances, activationDate); } @Override public void activateProcessDefinitionByKey(String processDefinitionKey, String tenantId) { this.getRepositoryService().activateProcessDefinitionByKey(processDefinitionKey, tenantId); } @Override public void activateProcessDefinitionByKey(String processDefinitionKey, boolean activateProcessInstances, Date activationDate, String tenantId) { this.getRepositoryService().activateProcessDefinitionByKey(processDefinitionKey, activateProcessInstances, activationDate, tenantId); } @Override public void setProcessDefinitionCategory(String processDefinitionId, String category) { this.getRepositoryService().setProcessDefinitionCategory(processDefinitionId, category); } @Override public InputStream getProcessModel(String processDefinitionId) { return this.getRepositoryService().getProcessModel(processDefinitionId); } @Override public InputStream getProcessDiagram(String processDefinitionId) { return this.getRepositoryService().getProcessDiagram(processDefinitionId); } @Override public ProcessDefinition getProcessDefinition(String processDefinitionId) { return this.getRepositoryService().getProcessDefinition(processDefinitionId); } @Override public Boolean isFlowable5ProcessDefinition(String processDefinitionId) { return this.getRepositoryService().isFlowable5ProcessDefinition(processDefinitionId); } @Override public boolean isProcessDefinitionSuspended(String processDefinitionId) { return this.getRepositoryService().isProcessDefinitionSuspended(processDefinitionId); } @Override public BpmnModel getBpmnModel(String processDefinitionId) { return this.getRepositoryService().getBpmnModel(processDefinitionId); } @Override public DiagramLayout getProcessDiagramLayout(String processDefinitionId) { return this.getRepositoryService().getProcessDiagramLayout(processDefinitionId); } @Override public Object getAppResourceObject(String deploymentId) { return this.getRepositoryService().getAppResourceObject(deploymentId); } @Override public AppModel getAppResourceModel(String deploymentId) { return this.getRepositoryService().getAppResourceModel(deploymentId); } @Override public Model newModel() { return this.getRepositoryService().newModel(); } @Override public void saveModel(Model model) { this.getRepositoryService().saveModel(model); } @Override public void deleteModel(String modelId) { this.getRepositoryService().deleteModel(modelId); } @Override public void addModelEditorSource(String modelId, byte[] bytes) { this.getRepositoryService().addModelEditorSource(modelId, bytes); } @Override public void addModelEditorSourceExtra(String modelId, byte[] bytes) { this.getRepositoryService().addModelEditorSourceExtra(modelId, bytes); } @Override public ModelQuery createModelQuery() { return this.getRepositoryService().createModelQuery(); } @Override public NativeModelQuery createNativeModelQuery() { return this.getRepositoryService().createNativeModelQuery(); } @Override public Model getModel(String modelId) { return this.getRepositoryService().getModel(modelId); } @Override public byte[] getModelEditorSource(String modelId) { return this.getRepositoryService().getModelEditorSource(modelId); } @Override public byte[] getModelEditorSourceExtra(String modelId) { return this.getRepositoryService().getModelEditorSourceExtra(modelId); } @Override public void addCandidateStarterUser(String processDefinitionId, String userId) { this.getRepositoryService().addCandidateStarterUser(processDefinitionId, userId); } @Override public void addCandidateStarterGroup(String processDefinitionId, String groupId) { this.getRepositoryService().addCandidateStarterGroup(processDefinitionId, groupId); } @Override public void deleteCandidateStarterUser(String processDefinitionId, String userId) { this.getRepositoryService().deleteCandidateStarterUser(processDefinitionId, userId); } @Override public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) { this.getRepositoryService().deleteCandidateStarterGroup(processDefinitionId, groupId); } @Override public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) { return this.getRepositoryService().getIdentityLinksForProcessDefinition(processDefinitionId); } @Override public List<ValidationError> validateProcess(BpmnModel bpmnModel) { return this.getRepositoryService().validateProcess(bpmnModel); } @Override public List<DmnDecision> getDecisionsForProcessDefinition(String processDefinitionId) { return this.getRepositoryService().getDecisionsForProcessDefinition(processDefinitionId); } /** * Retrieves the {@link DmnDecision}s associated with the given process definition. * * @param processDefinitionId id of the process definition, cannot be null. * @deprecated replaced by getDecisionsForProcessDefinition(String processDefinitionId) */ @Override public List<DmnDecision> getDecisionTablesForProcessDefinition(String processDefinitionId) { return this.getRepositoryService().getDecisionTablesForProcessDefinition(processDefinitionId); } @Override public List<FormDefinition> getFormDefinitionsForProcessDefinition(String processDefinitionId) { return this.getRepositoryService().getFormDefinitionsForProcessDefinition(processDefinitionId); } }
Java
UTF-8
660
2.859375
3
[]
no_license
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ReadCSV1 { public static void main(String ... krishna) throws IOException { try { BufferedReader reader = new BufferedReader(new FileReader(System.getProperty("user.dir")+"///"+"Krishna.csv")); List<String> lines = new ArrayList<>(); String line = null; while ((line = reader.readLine()) != null) { lines.add(line); } int i=0; while(lines.get(i)!=null) { System.out.println(lines.get(i)); i++; } System.out.println(lines.get(1)); }catch(Exception e) { } } }
Java
UTF-8
6,345
2.234375
2
[]
no_license
package log.nginx; import com.alibaba.fastjson.JSON; import com.opencsv.bean.CsvToBeanBuilder; import log.nginx.beans.DataInRequests; import log.nginx.beans.GoaccessRoot; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; import java.util.Map.Entry; /** * Hello world! */ public class App { public static void main(String[] args) { System.out.println("Hello World!"); String filePath = "D:\\qdlog\\240history3.json"; String fileName = "D:\\qdlog\\240history4.csv"; String fileName2 = "D:\\qdlog\\m.csv"; List requestLogs = new App().parseLogCsv(fileName); List mobileInterfaceList = new App().getMobileInterfaceList(fileName2); Map analysisMap = new HashMap<String, AnalysisData>(); Map map = new App().getMobileInterfaceList(mobileInterfaceList); if (requestLogs != null && !requestLogs.isEmpty()) { for (int i = 0; i < requestLogs.size(); i++) { RequestData data = (RequestData) requestLogs.get(i); //分析移动端接口访问数量 String key = StringUtils.substringBefore(data.getUrl(), "?"); if (map.containsKey(key)) { long hitCount = Long.parseLong(data.getHits_count()); long visitorCount = Long.parseLong(data.getVisitors_count()); if (!analysisMap.containsKey(key)) { AnalysisData analysisData = new AnalysisData(); analysisData.setName((String) map.get(key)); analysisData.setHitCount(hitCount); analysisData.setVisitorCount(visitorCount); analysisMap.put(key, analysisData); } else { AnalysisData d = (AnalysisData) analysisMap.get(key); d.setHitCount(d.getHitCount() + hitCount); d.setVisitorCount(d.getVisitorCount() + visitorCount); } } } } Iterator iterator = analysisMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, AnalysisData> entry = (Entry<String, AnalysisData>) iterator.next(); System.out.println("\"" + entry.getValue().getName() + "\",\"" + entry.getValue().getHitCount() + "\""); } } public void parseLogJson(String filePath) { try { FileInputStream inputStream = new FileInputStream(filePath); String logJsonStr = IOUtils.toString(inputStream); GoaccessRoot root = JSON.parseObject(logJsonStr, GoaccessRoot.class); List<DataInRequests> dataInRequests = JSON.parseArray(root.getRequests().getData().toJSONString(), DataInRequests.class); for (DataInRequests dr : dataInRequests) { System.out.println(dr.getData()); } System.out.println("wwww"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public List parseLogCsv(String fileName) { List resultList = new ArrayList(); try { List list = new CsvToBeanBuilder(new FileReader(fileName)).withType(GoaccessCsv.class).build().parse(); if (list != null && !list.isEmpty()) { for (int i = 0; i < list.size(); i++) { GoaccessCsv goaccessCsv = (GoaccessCsv) list.get(i); if ("requests".equals(goaccessCsv.getColumn3())) { RequestData data = new RequestData(); data.setNum(goaccessCsv.getColumn1()); data.setColumn2(goaccessCsv.getColumn2()); data.setKey(goaccessCsv.getColumn3()); data.setHits_count(goaccessCsv.getColumn4()); data.setHits_percent(goaccessCsv.getColumn5()); data.setVisitors_count(goaccessCsv.getColumn6()); data.setVisitors_percent(goaccessCsv.getColumn7()); data.setBytes_count(goaccessCsv.getColumn8()); data.setBytes_percent(goaccessCsv.getColumn9()); data.setMethod(goaccessCsv.getColumn10()); data.setProtocol(goaccessCsv.getColumn11()); data.setUrl(goaccessCsv.getColumn12()); resultList.add(data); // System.out.println(goaccessCsv.getColumn12()); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } return resultList; } public List getMobileInterfaceList(String fileName) { List list = null; try { list = new CsvToBeanBuilder(new FileReader(fileName)).withType(MobileInterface.class).build().parse(); if (list != null && !list.isEmpty()) { for (int i = 0; i < list.size(); i++) { MobileInterface mobileInterface = (MobileInterface) list.get(i); // System.out.println(mobileInterface.getFunction()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } return list; } public Map getMobileInterfaceList(List mobileInterfaceList) { Map map = new HashMap<String, String>(); if (mobileInterfaceList != null && !mobileInterfaceList.isEmpty()) { for (int i = 0; i < mobileInterfaceList.size(); i++) { MobileInterface m = (MobileInterface) mobileInterfaceList.get(i); String url = m.getRequest(); String key = StringUtils.substringBefore(url, "?"); if (map.isEmpty() || !map.containsKey(key)) { map.put(key, m.getFunction()); } else { String value = map.get(key) + "," + m.getFunction(); map.put(key, value); } } } return map; } }
Python
UTF-8
512
3.125
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding:UTF-8 -*- import threading import time event=threading.Event() def func(): #等待事件,进入等待阻塞状态 print'%s wait for event...'%threading.currentThread().getName() event.wait() #收到事件后进入运行状态 print'%s recv event.'% threading.currentThread().getName() t1=threading.Thread(target=func) t2=threading.Thread(target=func) t1.start() t2.start() time.sleep(2) #发送事件通知 print'MainThread set event.' event.set()
C
UTF-8
2,761
3.03125
3
[]
no_license
/*----------------------------------------------------------------------------- | File: com.h | | Implements funktionality for converting incoming byte data into | command structure and vice versa | | Note: - |------------------------------------------------------------------------------ | Datatypes: | com_command_t -- used to store command key words | com_src_t -- used to store data source | com_dest_t -- used to store data destination | com_data_t -- used to store command-set |------------------------------------------------------------------------------ | Functions: | com_init -- init subjacent modules, saves functionpointer for callback | com_send -- passes command-set to subjacent module ----------------------------------------------------------------------------*/ #ifndef _COM_H_ #define _COM_H_ #include <stdint.h> #include "types.h" #define COM_FRAME_LEN 19 // 1+8+8+2 Byte #define COM_PAGE_CMD 0x01 #define COM_WEIGHT_CMD 0x02 //############################################################################# // datatypes //############################################################################# typedef enum e_source {SRC_RF, SRC_SERIAL}com_src_t; typedef enum e_destination {DEST_RF, DEST_SERIAL}com_dest_t; /* structure to hold commands */ typedef struct s_com_data_fix { uint16 arg; uint64 product_id; uint64 box_id; uint8 command; }__attribute__ ((packed))com_data_fix_t; typedef union u_com_frame{ uint8 array[COM_FRAME_LEN]; com_data_fix_t frame; }com_frame_t; //############################################################################# // callback function definition //############################################################################# typedef void (*COM_CB)(com_frame_t* frame, com_src_t src); //############################################################################# // functions prototypes //############################################################################# /*------------------------------------------------------------------------------ | com_init -- init subjacent modules, saves functionpointer for callback | | Parameter: | function ptr to callback | | Return: | - | -----------------------------------------------------------------------------*/ extern void com_init(COM_CB callback); /*------------------------------------------------------------------------------ | com_send -- passes command set to subjacent module | | Parameter: | command data structure | | Return: | - | -----------------------------------------------------------------------------*/ extern void com_send_fix(com_frame_t* data, com_dest_t dest); #endif // _COM_H_
Java
UTF-8
10,249
2.546875
3
[]
no_license
package GUI; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DonationReport extends JFrame { private JPanel p1 , DonationReportHeader , DonationReport; private JLabel l1 , DonationReportTitle , DonationReportImage; private JButton[] b ,buDonationR; private JLabel[] lDonationR; private JTextField[] tDonationR; private JSeparator[] seDonationR; public DonationReport() { // getContentPane().setBackground(Color.GRAY); setLayout(null); p1 = new JPanel(null); p1.setBounds(800, 0, 200, 600); p1.setBackground(new java.awt.Color(204, 204, 204)); p1.setBorder(BorderFactory.createEtchedBorder()); l1 = new JLabel(); l1.setFont(new Font("", 0, 20)); Icon s = new ImageIcon(getClass().getResource("small2.png")); l1.setIcon(s); l1.setBounds(18, 50, 160, 87); p1.add(l1); /// DonationReportHeader = new JPanel(null); DonationReportHeader.setBounds(0, 0, 800, 100); DonationReportHeader.setBackground(Color.white); DonationReportHeader.setBorder(BorderFactory.createEtchedBorder()); DonationReportTitle = new JLabel("Donation Report"); DonationReportTitle.setFont(new Font("", 1, 26)); DonationReportTitle.setBounds(305, 40, 210, 30); DonationReportHeader.add(DonationReportTitle); Icon s1 = new ImageIcon("C:\\Users\\user\\Desktop\\Projects\\OOP Project\\Image\\icon\\2.png"); DonationReportImage = new JLabel(s1); DonationReportImage.setBounds(200 , 5 , 90 , 90); DonationReportHeader.add(DonationReportImage); //// b = new JButton[4]; b[0] = new JButton("Home"); b[0].setBounds(18, 200, 160, 40); b[1]= new JButton("Profile"); b[1].setBounds(18, 245, 160, 40); b[2]= new JButton("History"); b[2].setBounds(18, 290, 160, 40); b[3]= new JButton("Log Out"); b[3].setBounds(18, 550, 160, 40); for(int i=0;i<b.length;i++) { p1.add(b[i]); } add(p1); add(DonationReportHeader); ////////////////////////////////////////////////////////////////// /// DonationReport = new JPanel(null); DonationReport.setBounds(0,100, 800, 600); DonationReport.setBackground(Color.gray); add(DonationReport); /// buDonationR = new JButton[2]; lDonationR =new JLabel[12]; tDonationR= new JTextField[18]; seDonationR = new JSeparator[2]; /// lDonationR[1]= new JLabel("Donor Name :"); lDonationR[1].setForeground(Color.BLACK); lDonationR[1].setFont(new Font("", 0, 14)); lDonationR[1].setBounds(15 , 50 , 90 , 23); tDonationR[1] = new JTextField(); tDonationR[1].setBounds(107 , 50 ,90 ,23 ); tDonationR[2] = new JTextField(); tDonationR[2].setBounds(200 , 50 ,90 ,23 ); //Donor Name// tDonationR[3] = new JTextField(); tDonationR[3].setBounds(293 , 50 ,90 ,23 ); /// lDonationR[2]= new JLabel("Receiver Name :"); lDonationR[2].setForeground(Color.BLACK); lDonationR[2].setFont(new Font("", 0, 14)); lDonationR[2].setBounds(396 , 50 , 110 , 23); tDonationR[4] = new JTextField(); tDonationR[4].setBounds(506 , 50 ,90 ,23 ); tDonationR[5] = new JTextField(); tDonationR[5].setBounds(599 , 50 ,90 ,23 );//receiver name tDonationR[6] = new JTextField(); tDonationR[6].setBounds(692 , 50 ,90 ,23 ); /// lDonationR[3]= new JLabel("Donor ID :"); lDonationR[3].setForeground(Color.BLACK); lDonationR[3].setFont(new Font("", 0, 14)); lDonationR[3].setBounds(15 , 93 , 90 , 23);//Donor ID tDonationR[7] = new JTextField(); tDonationR[7].setBounds(107 , 93 ,275 ,23 ); /// lDonationR[4]= new JLabel("Receiver ID :"); lDonationR[4].setForeground(Color.BLACK); lDonationR[4].setFont(new Font("", 0, 14)); lDonationR[4].setBounds(396 , 93 , 110 , 23);//Receiver ID tDonationR[8] = new JTextField(); tDonationR[8].setBounds(506 , 93 ,275 ,23 ); /// lDonationR[5]= new JLabel("Blood Type :"); lDonationR[5].setForeground(Color.BLACK); lDonationR[5].setFont(new Font("", 0, 14)); lDonationR[5].setBounds(15 , 136 , 90 , 23);//Donor BT tDonationR[9] = new JTextField(); tDonationR[9].setBounds(227 , 136 ,35 ,23 ); /// lDonationR[6]= new JLabel("Blood Type :"); lDonationR[6].setForeground(Color.BLACK); lDonationR[6].setFont(new Font("", 0, 14)); lDonationR[6].setBounds(396 , 136 , 110 , 23);//Receiver BT tDonationR[10] = new JTextField(); tDonationR[10].setBounds(626 , 136 ,35 ,23 ); /// lDonationR[7]= new JLabel("Age :"); lDonationR[7].setForeground(Color.BLACK); lDonationR[7].setFont(new Font("", 0, 14)); lDonationR[7].setBounds(15 , 179 , 90 , 23);//Donor Age tDonationR[11] = new JTextField(); tDonationR[11].setBounds(227 , 179 ,35 ,23 ); /// lDonationR[8]= new JLabel("Age :"); lDonationR[8].setForeground(Color.BLACK); lDonationR[8].setFont(new Font("", 0, 14)); lDonationR[8].setBounds(396 , 179 , 110 , 23);//Receiver Age tDonationR[12] = new JTextField(); tDonationR[12].setBounds(626 , 179 ,35 ,23 ); /// seDonationR[0] = new JSeparator(); seDonationR[0].setBounds(15, 228, 781, 10); seDonationR[1] = new JSeparator(); //Separators seDonationR[1].setBounds(15, 295, 781, 10); /// lDonationR[9]=new JLabel("Appointment Date :"); lDonationR[9].setForeground(Color.BLACK); lDonationR[9].setFont(new Font("", 0, 14)); lDonationR[9].setBounds(15 , 250 , 140 , 23); tDonationR[13] = new JTextField(); tDonationR[13].setBounds(190 , 250 ,50 ,23 ); tDonationR[14] = new JTextField(); tDonationR[14].setBounds(243 , 250 ,35 ,23 ); //Appointment Date// tDonationR[15] = new JTextField(); tDonationR[15].setBounds(281 , 250 ,35 ,23 ); /// lDonationR[10]= new JLabel("hospital Name :"); lDonationR[10].setForeground(Color.BLACK); lDonationR[10].setFont(new Font("", 0, 14)); lDonationR[10].setBounds(396 , 250 , 110 , 23);//hspital name// tDonationR[16] = new JTextField(); tDonationR[16].setBounds(506 , 250 ,275 ,23 ); /// // l[11]= new JLabel("- For doctor -"); // l[11].setForeground(Color.BLACK); // l[11].setFont(new Font("", 1, 20)); // l[11].setBounds(335 , 336 , 130 , 30); /// lDonationR[0]=new JLabel("Donation Serial :"); lDonationR[0].setForeground(Color.BLACK); lDonationR[0].setFont(new Font("", 1, 14)); lDonationR[0].setBounds(15 , 325 , 140 , 23); tDonationR[0] = new JTextField(); tDonationR[0].setBounds(147 , 325 ,140 ,23 ); /// lDonationR[11]= new JLabel("Donation State :"); lDonationR[11].setForeground(Color.BLACK); lDonationR[11].setFont(new Font("", 1, 14)); lDonationR[11].setBounds(396 , 325 , 130 , 23); tDonationR[17] = new JTextField(); tDonationR[17].setBounds(529 , 325 ,140 ,23 ); ///^ // l[12]= new JLabel("- Check up the donor and recipient before proceeding to do the donation process to make sure hat they are compatible matches.");//t // l[12].setForeground(Color.BLACK); // l[12].setFont(new Font("", 5, 14)); // l[12].setBounds(15 , 365 , 770 , 23); //Strings Doctors // // l[13]= new JLabel("compatible matches."); // l[13].setForeground(Color.BLACK); // l[13].setFont(new Font("", 5, 14)); // l[13].setBounds(25 , 385 , 770 , 23); /// /// buDonationR[0] = new JButton("Save"); buDonationR[0].setBounds(15 , 465 , 75 ,25); // bu[0].addActionListener( new ActionListener() // { // @Override // public void actionPerformed(ActionEvent ae) // { // // } // }); /// buDonationR[1] = new JButton("Done"); buDonationR[1].setBounds(725 , 465 , 70 ,25); // bu[1].addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent ae) // { // DonationReport.setVisible(false); // DonationReportHeader.setVisible(false); // // DoctorSys.setVisible(true); // // p2.setVisible(true); // } // }); /// for (JButton b2 : buDonationR) { DonationReport.add(b2); // Cancel , NExt , Clear Button } for(JSeparator se1 : seDonationR) { DonationReport.add(se1); // Separator } for(JLabel JL : lDonationR) { DonationReport.add(JL); // Labels } for(JTextField JTF : tDonationR) { DonationReport.add(JTF); // TextFeiled } } public static void main(String[] args) { DonationReport a = new DonationReport(); a.setVisible(true); a.setDefaultCloseOperation(EXIT_ON_CLOSE); a.setSize(1000, 628); a.setResizable(false); } }
Java
UTF-8
10,872
1.679688
2
[ "Apache-2.0" ]
permissive
/*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. * Modifications Copyright (c) 2019 Samsung * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.so.adapters.tenant; import java.util.Map; import javax.annotation.Resource; import javax.jws.WebService; import javax.xml.ws.Holder; import javax.xml.ws.WebServiceContext; import org.onap.so.adapters.tenant.exceptions.TenantAlreadyExists; import org.onap.so.adapters.tenant.exceptions.TenantException; import org.onap.so.adapters.tenantrest.TenantRollback; import org.onap.so.entity.MsoRequest; import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.utils.MsoTenantUtils; import org.onap.so.openstack.utils.MsoTenantUtilsFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @WebService(serviceName = "TenantAdapter", endpointInterface = "org.onap.so.adapters.tenant.MsoTenantAdapter", targetNamespace = "http://org.onap.so/tenant") @Component public class MsoTenantAdapterImpl implements MsoTenantAdapter { public static final String CREATE_TENANT = "createTenant"; public static final String OPENSTACK = "OpenStack"; public static final String QUERY_TENANT = "QueryTenant"; public static final String DELETE_TENANT = "DeleteTenant"; public static final String ROLLBACK_TENANT = "RollbackTenant"; private static final String OPENSTACK_COMMUNICATE_EXCEPTION_MSG = "{} {} Exception while communicate with Open Stack "; @Resource private WebServiceContext wsContext; @Autowired private MsoTenantUtilsFactory tFactory; private static Logger logger = LoggerFactory.getLogger(MsoTenantAdapterImpl.class); /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override public void healthCheck() { logger.debug("Health check call in Tenant Adapter"); } /** * This is the "Create Tenant" web service implementation. It will create a new Tenant in the specified cloud. If * the tenant already exists, this can be considered a success or failure, depending on the value of the * 'failIfExists' parameter. * * The method returns the tenantId (the Openstack ID), and a TenantRollback object. This last object can be passed * as-is to the rollbackTenant method to undo what (if anything) was created. This is useful if a Tenant is * successfully created but the orchestrator fails on a subsequent operation. */ @Override public void createTenant(String cloudSiteId, String tenantName, Map<String, String> metadata, Boolean failIfExists, Boolean backout, MsoRequest msoRequest, Holder<String> tenantId, Holder<TenantRollback> rollback) throws TenantException { logger.debug("Call to MSO createTenant adapter. Creating Tenant: {} in {}", tenantName, cloudSiteId); // Start building up rollback object TenantRollback tenantRollback = new TenantRollback(); tenantRollback.setCloudId(cloudSiteId); tenantRollback.setMsoRequest(msoRequest); MsoTenantUtils tUtils; try { tUtils = tFactory.getTenantUtils(cloudSiteId); } catch (MsoCloudSiteNotFound me) { logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), cloudSiteId, me); throw new TenantException(me); } MsoTenant newTenant = null; String newTenantId; try { newTenant = tUtils.queryTenantByName(tenantName, cloudSiteId); } catch (MsoException me) { logger.error(OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), me); throw new TenantException(me); } if (newTenant == null) { if (backout == null) backout = true; try { newTenantId = tUtils.createTenant(tenantName, cloudSiteId, metadata, backout.booleanValue()); } catch (MsoException me) { logger.error(OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), me); throw new TenantException(me); } tenantRollback.setTenantId(newTenantId); tenantRollback.setTenantCreated(true); logger.debug("Tenant {} successfully created with ID {}", tenantName, newTenantId); } else { if (failIfExists != null && failIfExists) { logger.error("{} {} CreateTenant: Tenant {} already exists in {} ", MessageEnum.RA_TENANT_ALREADY_EXIST, ErrorCode.DataError.getValue(), tenantName, cloudSiteId); throw new TenantAlreadyExists(tenantName, cloudSiteId, newTenant.getTenantId()); } newTenantId = newTenant.getTenantId(); tenantRollback.setTenantCreated(false); logger.debug("Tenant {} already exists with ID {}", tenantName, newTenantId); } tenantId.value = newTenantId; rollback.value = tenantRollback; return; } @Override public void queryTenant(String cloudSiteId, String tenantNameOrId, MsoRequest msoRequest, Holder<String> tenantId, Holder<String> tenantName, Holder<Map<String, String>> metadata) throws TenantException { logger.debug("Querying Tenant {} in {}", tenantNameOrId, cloudSiteId); MsoTenantUtils tUtils; try { tUtils = tFactory.getTenantUtils(cloudSiteId); } catch (MsoCloudSiteNotFound me) { logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), cloudSiteId, me); throw new TenantException(me); } MsoTenant qTenant = null; try { qTenant = tUtils.queryTenant(tenantNameOrId, cloudSiteId); if (qTenant == null) { // Not found by ID, Try by name. qTenant = tUtils.queryTenantByName(tenantNameOrId, cloudSiteId); } if (qTenant == null) { logger.debug("QueryTenant: Tenant {} not found", tenantNameOrId); tenantId.value = null; tenantName.value = null; metadata.value = null; } else { logger.debug("QueryTenant: Tenant {} found with ID {}", tenantNameOrId, qTenant.getTenantId()); tenantId.value = qTenant.getTenantId(); tenantName.value = qTenant.getTenantName(); metadata.value = qTenant.getMetadata(); } } catch (MsoException me) { logger.error("Exception in queryTenant for {}: ", MessageEnum.RA_GENERAL_EXCEPTION, ErrorCode.DataError.getValue(), tenantNameOrId, me); throw new TenantException(me); } return; } @Override public void deleteTenant(String cloudSiteId, String tenantId, MsoRequest msoRequest, Holder<Boolean> tenantDeleted) throws TenantException { logger.debug("Deleting Tenant {} in {}", tenantId, cloudSiteId); // Delete the Tenant. try { MsoTenantUtils tUtils = tFactory.getTenantUtils(cloudSiteId); boolean deleted = tUtils.deleteTenant(tenantId, cloudSiteId); tenantDeleted.value = deleted; } catch (MsoException me) { logger.error("{} {} Exception - DeleteTenant {}: ", MessageEnum.RA_DELETE_TEMAMT_ERR, ErrorCode.DataError.getValue(), tenantId, me); throw new TenantException(me); } // On success, nothing is returned. return; } /** * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation * to undo the creation. * * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF * creation. */ @Override public void rollbackTenant(TenantRollback rollback) throws TenantException { // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { logger.warn("{} {} rollbackTenant, rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.DataError.getValue()); return; } // Get the elements of the VnfRollback object for easier access String cloudSiteId = rollback.getCloudId(); String tenantId = rollback.getTenantId(); logger.debug("Rolling Back Tenant {} in {}", rollback.getTenantId(), cloudSiteId); if (rollback.getTenantCreated()) { try { MsoTenantUtils tUtils = tFactory.getTenantUtils(cloudSiteId); tUtils.deleteTenant(tenantId, cloudSiteId); } catch (MsoException me) { me.addContext(ROLLBACK_TENANT); // Failed to delete the tenant. logger.error("{} {} Exception - rollbackTenant {}: ", MessageEnum.RA_ROLLBACK_TENANT_ERR, ErrorCode.DataError.getValue(), tenantId, me); throw new TenantException(me); } } return; } }
Java
UTF-8
2,847
1.828125
2
[ "Apache-2.0" ]
permissive
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package co.elastic.clients.transport; import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.rest_client.RestClientTransport; import com.sun.net.httpserver.HttpServer; import org.apache.http.HttpHost; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; public class TransportTest extends Assertions { @Test public void testXMLResponse() throws Exception { HttpServer httpServer = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); httpServer.createContext("/_cat/indices", exchange -> { exchange.sendResponseHeaders(401, 0); OutputStream out = exchange.getResponseBody(); out.write( "<?xml version=\"1.0\"?><error>Error</error>".getBytes(StandardCharsets.UTF_8) ); out.close(); }); httpServer.start(); InetSocketAddress address = httpServer.getAddress(); RestClient restClient = RestClient .builder(new HttpHost(address.getHostString(), address.getPort(), "http")) .build(); ElasticsearchClient esClient = new ElasticsearchClient(new RestClientTransport(restClient, new JacksonJsonpMapper())); TransportException ex = Assertions.assertThrows( TransportException.class, () -> esClient.cat().indices() ); httpServer.stop(0); assertEquals(401, ex.statusCode()); assertEquals("es/cat.indices", ex.endpointId()); // Original response is transport-dependent Response restClientResponse = (Response)ex.response().originalResponse(); assertEquals(401, restClientResponse.getStatusLine().getStatusCode()); } }
C
UTF-8
2,085
2.9375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_treat_pointer.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gumatos <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/06 15:15:44 by gumatos #+# #+# */ /* Updated: 2021/04/16 16:19:07 by gumatos ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_in_put_part_pointer(char *ponteiro, t_flags flags) { int contador; contador = 0; contador = ft_putstrprec("0x", 2); if (flags.ponto >= 0) { contador += ft_treat_largura(flags.ponto, ft_strlen(ponteiro), 1); contador += ft_putstrprec(ponteiro, flags.ponto); } else contador += ft_putstrprec(ponteiro, ft_strlen(ponteiro)); return (contador); } int ft_treat_pointer(unsigned long long ull, t_flags flags) { char *ponteiro; int contador; contador = 0; if (ull == 0 && flags.ponto == 0) { contador += ft_putstrprec("0x", 2); return (contador += ft_treat_largura(flags.largura, 0, 1)); } ponteiro = ft_ull_base(ull, 16); ponteiro = ft_str_tolower(ponteiro); if ((size_t)flags.ponto < ft_strlen(ponteiro)) flags.ponto = ft_strlen(ponteiro); if (flags.negativo == 1) contador += ft_in_put_part_pointer(ponteiro, flags); if (flags.largura > 1 && flags.ponto > 1) contador += ft_treat_largura(flags.largura, flags.ponto + 2, 0) - 1; else contador += ft_treat_largura(flags.largura, ft_strlen(ponteiro) + 2, 0); if (flags.negativo == 0) contador += ft_in_put_part_pointer(ponteiro, flags); free(ponteiro); return (contador); }
Java
UTF-8
808
2.609375
3
[ "MIT" ]
permissive
package guitests.guihandles; import javafx.scene.Node; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; /** * A handler for the {@code ResultDisplay} of the UI */ public class ResultDisplayHandle extends NodeHandle<TextFlow> { public static final String RESULT_DISPLAY_ID = "#resultDisplay"; public ResultDisplayHandle(TextFlow resultDisplayNode) { super(resultDisplayNode); } /** * Returns the text in the result display. */ public String getText() { StringBuilder sb = new StringBuilder(); for (Node node : getRootNode().getChildren()) { if (node instanceof Text) { sb.append(((Text) node).getText()); } } String fullText = sb.toString(); return fullText; } }
C#
UTF-8
6,757
3.0625
3
[]
no_license
using System; namespace w5d4m2 { class Program { static void Main(string[] args) { string de6 = "d6"; string twoD6 = "2d6"; string d6Plus4 = "d6+4"; string twoD6plus4 = "2d6+4"; string thirtyFour = "34"; string ad6 = "ad6"; string bunch = "33d4*2"; Console.WriteLine(de6); CollectionOfMethodsToCalculateTextToDiceNotation(de6); Console.WriteLine(twoD6); CollectionOfMethodsToCalculateTextToDiceNotation(twoD6); Console.WriteLine(d6Plus4); CollectionOfMethodsToCalculateTextToDiceNotation(d6Plus4); Console.WriteLine(twoD6plus4); CollectionOfMethodsToCalculateTextToDiceNotation(twoD6plus4); Console.WriteLine(thirtyFour); CollectionOfMethodsToCalculateTextToDiceNotation(thirtyFour); Console.WriteLine(ad6); CollectionOfMethodsToCalculateTextToDiceNotation(ad6); Console.WriteLine("33d4*2"); CollectionOfMethodsToCalculateTextToDiceNotation(bunch); } public static Random random = new Random(); public static char[] splitting = { 'd', '+', '-' }; public static void CollectionOfMethodsToCalculateTextToDiceNotation(string text) { if (checkSoThereAreNoDoublesOfSertainAscii(text) == true && IsItemsInOrder(text) == true && IsAsciiCorrectForText(text) == true) { int diceNotationOfText = DiceRoll(text); Console.WriteLine("Result is " + diceNotationOfText); } else Console.WriteLine($"Can't throw {text}, it is not in standard dice notation."); } public static bool IsAsciiCorrectForText(string text) { int count = 0; foreach (char s in text) { if (s == 'd' || s == '-' || s == '+' || s >= '1' && s <= '9') count ++; } if (count == text.Length) return true; return false; } public static bool checkSoThereAreNoDoublesOfSertainAscii(string text) { if (DetectNumberOfMinus(text) + DetectNumberOfPlus(text) < 2 && DetectNumberOfD(text) == 1) return true; return false; } public static bool IsItemsInOrder(string text) { if (DetectNumberOfMinus(text) > 0) { if (FindIndexOfD(text) < FindIndexOfLastNumber(text) && FindIndexOfD(text) < FindIndexOfMinus(text) && FindIndexOfMinus(text) < FindIndexOfLastNumber(text)) return true; } else if (DetectNumberOfPlus(text) > 0) { if (FindIndexOfD(text) < FindIndexOfLastNumber(text) && FindIndexOfD(text) < FindIndexOfPlus(text) && FindIndexOfPlus(text) < FindIndexOfLastNumber(text)) return true; } else if (FindIndexOfD(text) < FindIndexOfLastNumber(text)) return true; return false; } public static int FindIndexOfD(string text) { int lastD = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == 'd') lastD = i; } return lastD; } public static int FindIndexOfMinus(string text) { int lastMinus = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == '-') lastMinus = i; } return lastMinus; } public static int FindIndexOfPlus(string text) { int lastPlus = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == '+') lastPlus = i; } return lastPlus; } public static int FindIndexOfLastNumber(string text) { int lastNumber = 0; for (int i = 0; i < text.Length; i++) { if (text[i] >= '1' && text[i] <= '9' && text[i] % 2 == 0) lastNumber = i; } return lastNumber + 1; } public static int DetectNumberOfD(string text) { int numberOfDs = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == 'd') numberOfDs++; } return numberOfDs; } public static int DetectNumberOfMinus(string text) { int numberOfMinus = 0; foreach (char s in text) { if (s == '-') numberOfMinus++; } return numberOfMinus; } public static int DetectNumberOfPlus(string text) { int numberOfPlus = 0; foreach (char s in text) { if (s == '+') numberOfPlus++; } return numberOfPlus; } public static int takeStringMakeInt(string number) { return Int32.Parse(number); } public static string[] TakeStringMakeArray(string diceNotation) { string[] sortedNumbers = diceNotation.Split(splitting); if (sortedNumbers[0] == "") sortedNumbers[0] = "1"; return sortedNumbers; } public static int DiceRoll(int sidesOfDice, int numberOfDices = 1, int fixedBonus = 0) { int dicescore = 0; for (int i = 0; i < numberOfDices; i++) { dicescore += random.Next(1, sidesOfDice + 1); } dicescore += fixedBonus; return dicescore; } public static int DiceRoll(string diceNotation) { string[] sortedNumbers = TakeStringMakeArray(diceNotation); if (sortedNumbers.Length == 3 && DetectNumberOfMinus(diceNotation) == 1) return DiceRoll(takeStringMakeInt(sortedNumbers[1]), takeStringMakeInt(sortedNumbers[0]), takeStringMakeInt(sortedNumbers[2]) * -1); else if (sortedNumbers.Length == 3 && DetectNumberOfPlus(diceNotation) == 1) return DiceRoll(takeStringMakeInt(sortedNumbers[1]), takeStringMakeInt(sortedNumbers[0]), takeStringMakeInt(sortedNumbers[2])); else if (sortedNumbers.Length == 2 && DetectNumberOfMinus(diceNotation) == 1) return DiceRoll(takeStringMakeInt(sortedNumbers[1]), takeStringMakeInt(sortedNumbers[2]) * -1); else if (sortedNumbers.Length == 2 && DetectNumberOfPlus(diceNotation) == 1) return DiceRoll(takeStringMakeInt(sortedNumbers[1]), takeStringMakeInt(sortedNumbers[2])); else return DiceRoll(takeStringMakeInt(sortedNumbers[1]), takeStringMakeInt(sortedNumbers[0])); } } }
Java
UTF-8
580
2.046875
2
[]
no_license
package com.sujya.prj.auth.common; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Setter; import org.springframework.security.core.GrantedAuthority; import java.util.List; @Data @AllArgsConstructor public class UserContext { @Setter(AccessLevel.NONE) private final String userId; @Setter(AccessLevel.NONE) private final List<GrantedAuthority> authrorities; public static UserContext create(String userId, List<GrantedAuthority> authrorities) { return new UserContext(userId, authrorities); } }
Java
UTF-8
1,367
1.945313
2
[]
no_license
package com.jornada.client.service; import java.util.ArrayList; import java.util.Date; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.jornada.shared.classes.Clientes; import com.jornada.shared.classes.Reserva; import com.jornada.shared.classes.salao.Saloes; @RemoteServiceRelativePath("GWTServiceReserva") public interface GWTServiceReserva extends RemoteService { public String adicionarPeriodoString(Reserva periodo); public ArrayList<Reserva> getReservas(); public ArrayList<Reserva> getReservas(Date dataReserva, String strTurno); public String getReservasExcel(Date dataReserva, String strTurno); public Clientes getNumeroClientes(Date dataReserva, String strTurno, String strSalao); public Saloes getQuantidadeClientesNosSaloes(Date dataReserva, String strTurno); public Saloes getSaloes(); public boolean deleteRow(int idReserva); public boolean updateRow(Reserva object); /** * Utility class for simplifying access to the instance of async service. */ public static class Util { private static GWTServiceReservaAsync instance; public static GWTServiceReservaAsync getInstance(){ if (instance == null) { instance = GWT.create(GWTServiceReserva.class); } return instance; } } }
Markdown
UTF-8
7,321
2.671875
3
[ "MIT" ]
permissive
## Character Generator This is an app that can generate a Dungeons and Dragons-like character. ### Technologies It uses Angular as its client-side framework and BootstrapJS as its CSS library. It also utilizes Laravel, a PHP framework, and lo-dash for array utilities. #### Composer Packages * [Ardent](https://github.com/laravelbook/ardent) * Self-validating smart models for Laravel Framework 4's Eloquent O/RM. * [Laravel 4 Generators](https://github.com/JeffreyWay/Laravel-4-Generators/blob/master/readme.md) * This Laravel 4 package provides a variety of generators to speed up your development process. * [Presenter](https://github.com/robclancy/presenter) * Presenter is a very simply class that overloads methods and variables so that you can add extra logic to your objects or arrays without adding view logic to areas like your models or controllers and also keeps any extra logic our of your views. * [Entrust](https://github.com/zizaco/entrust) * Entrust provides a flexible way to add Role-based Permissions to Laravel 4. * [Laravel-ide-helper](https://github.com/barryvdh/laravel-ide-helper) * This packages generates a file that your IDE can understand, so it can provide accurate auto-completion. #### Bower Packages * [AngularJS](http://angularjs.org) * AngularJS lets you write client-side web applications as if you had a smarter browser. * [UI-Bootstrap](http://angular-ui.github.io/bootstrap/) * Native AngularJS directives based on Twitter Bootstrap's markup and CSS * [Yeti](http://bootswatch.com/yeti) * Twitter Bootstrap Theme #### Grunt Packages * [grunt-contrib-less](https://github.com/gruntjs/grunt-contrib-less) * Compile LESS files to CSS. * [grunt-contrib-cssmin](https://github.com/gruntjs/grunt-contrib-cssmin) * Compress CSS files. * [grunt-contrib-copy](https://github.com/gruntjs/grunt-contrib-copy) * Copy files and folders. * [grunt-contrib-clean](https://github.com/gruntjs/grunt-contrib-clean) * Clean files and folders. * [grunt-contrib-concat](https://github.com/gruntjs/grunt-contrib-concat) * Concatenate files. * [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify) * Minify files with UglifyJS. * [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch) * Run predefined tasks whenever watched file patterns are added, changed or deleted. ### Installation #### Requirements PHP >= 5.3.7 NodeJS Bower Grunt Composer If you haven't already, you might want to make [composer be installed globally](http://andrewelkins.com/programming/php/setting-up-composer-globally-for-laravel-4/) for future ease of use. Please note the use of the `--dev` flag. Some packages used for ease of development are required on the development environment. When you deploy your project on a production environment you will want to upload the ***composer.lock*** file used on the development environment and only run `php composer.phar install` on the production server. This will skip the development packages and ensure the version of the packages installed on the production server match those you developped on. NEVER run `php composer.phar update` on your production server. #### Step 1: Install dependencies composer install --dev npm install bower install grunt If you have issues using npm install use the code below npm install --no-bin-links #### Step 2: Configure Environments Laravel 4 will load configuration files depending on your environment. Basset will also build collections depending on this environment setting. Open ***bootstrap/start.php*** and edit the following lines to match your settings. You want to be using your machine name in Windows and your hostname in OS X and Linux (type `hostname` in terminal). Using the machine name will allow the `php artisan` command to use the right configuration files as well. $env = $app->detectEnvironment(array( 'local' => array('your-local-machine-name'), 'staging' => array('your-staging-machine-name'), 'production' => array('your-production-machine-name'), )); Now create the folder inside ***app/config*** that corresponds to the environment the code is deployed in. This will most likely be ***local*** when you first start a project. You will now be copying the initial configuration file inside this folder before editing it. Let's start with ***app/config/app.php***. So ***app/config/local/app.php*** will probably look something like this, as the rest of the configuration can be left to their defaults from the initial config file: <?php return array( 'url' => 'http://myproject.local', 'timezone' => 'UTC', 'key' => 'YourSecretKey!!!', 'providers' => array( [... Removed ...] /* Uncomment for use in development */ // 'Way\Generators\GeneratorsServiceProvider', // Generators // 'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider', // IDE Helpers ), ); #### Step 3: Configure Database Now that you have the environment configured, you need to create a database configuration for it. Copy the file ***app/config/database.php*** in ***app/config/local*** and edit it to match your local database settings. You can remove all the parts that you have not changed as this configuration file will be loaded over the initial one. #### Step 4: Configure Mailer In the same fashion, copy the ***app/config/mail.php*** configuration file in ***app/config/local/mail.php***. Now set the `address` and `name` from the `from` array in ***config/mail.php***. Those will be used to send account confirmation and password reset emails to the users. If you don't set that registration will fail because it cannot send the confirmation email. #### Step 5: Populate Database Run these commands to create and populate Users table: php artisan migrate php artisan db:seed #### Step 6: Make sure app/storage is writable by your web server. If permissions are set correctly: chmod -R 775 app/storage Should work, if not try chmod -R 777 app/storage ### Laravel 4 & AngularJS E2E secured SPA Link to the article: http://blog.neoxia.com/laravel4-and-angularjs/ ### Licensing The MIT License (MIT) Copyright (c) 2014 Benjamin Katznelson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Markdown
UTF-8
4,221
3.046875
3
[]
no_license
--- layout: post title: "UIWebView与Javascript交互" date: 2015-12-18 17:12:21 +0800 comments: true categories: --- > 现在越来越多的App使用H5页面作为App的一部分,尤其是一些运营的需求,需要快速上线下线,只能通过网页前端完成。那么网页前端与原生App的交互就显得尤为重要。 ### 原生对网页的调用 iOS原生App对网页前端的调用非常简单,只需要使用 ```objc - (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script; ``` 这个方法,调用相应的JavaScript方法、传参就可以了。 例如: ```objc [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"]; ``` ### 网页对原生的调用 网页对原生App调用相对复杂一些。在安卓App中,我们可以注册handler来监听某个`JS Function`的调用。 ```java webView.addJavascriptInterface(new Handler(), "SomeObject") ``` 在iOS中实现类似的功能,就要动一番脑筋了。 首先我们来看一下`UIWebView`能给我们提供哪些回调方法: ```objc @protocol UIWebViewDelegate <NSObject> @optional - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; - (void)webViewDidStartLoad:(UIWebView *)webView; - (void)webViewDidFinishLoad:(UIWebView *)webView; - (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error; @end ``` 其中,`- (void)webViewDidStartLoad:(UIWebView *)webView;`是在页面开始加载时调用,这个时候我们前端的页面和脚本都没有加载,Pass掉。 `- (void)webViewDidFinishLoad:(UIWebView *)webView;`是在加载完成时调用一次,不满足时序要求,Pass掉。 `- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;`这个更不用说,Pass。 那么只有`- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;`这个方法可以用了。 于是我们的思路确定了:__在webview中注入一个JS Function,调用这个function时进行重定向,利用重定向的URL进行传参。__ #### 编写JS脚本 ```javascript var %@ = {}; %@.%@ = function(cmd, param) { if (!param) { param = cmd; cmd = null; } var url = "objcjsbridge://" + cmd + "?" + escape(param); document.location = url; }; ``` #### 运行JS脚本 需要在每个页面加载完成时运行 ```objc @interface UIWebView (JavaScriptInject) - (void)injectJavaScriptObject:(NSString *)objectName function:(NSString *)functionName; @end @implementation UIWebView (JavaScriptInject) - (void)injectJavaScriptObject:(NSString *)objectName function:(NSString *)functionName { NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"ObjcJSBridge" ofType:@"js"]; NSError *error = nil; NSString *originJs = [[NSString alloc] initWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:&error]; NSString *formattedJs = [NSString stringWithFormat:originJs, objectName, objectName, functionName]; if (error) { NSLog(@"%@", error); } [self stringByEvaluatingJavaScriptFromString:formattedJs]; } @end // 注入JS脚本 - (void)webViewDidFinishLoad:(UIWebView *)webView { [super webViewDidFinishLoad:webView]; [self.webView injectJavaScriptObject:@"LETV_APP_Function" function:@"callBack"]; } ``` #### 监听回调 ```objc - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *url = request.URL; if ([url.scheme.lowercaseString isEqualToString:@"objcjsbridge"]) { NSString *command = url.host; NSString *parameter = url.query; if ([self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) { [self.delegate webviewInjecter:self didRecieveJSCall:command parameter:[parameter stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } // 这里return NO,保证不会重定向到这个无法访问的URL return NO; } return YES; } ```
TypeScript
UTF-8
3,392
2.90625
3
[]
no_license
import * as THREE from 'three'; import RubikModel from './model'; export default class Sprite { private length: number private canvas: HTMLCanvasElement private context: CanvasRenderingContext2D private textures: THREE.Texture[] private cellLength!: number public constructor(length: number) { this.length = length; this.canvas = document.createElement('canvas'); this.context = this.canvas.getContext('2d')!; this.textures = new Array(length * length); } private getStartEnd = (direction: number): THREE.Vector2 => { const row = RubikModel.getRow(direction, this.length); const col = RubikModel.getColumn(direction, this.length); const startX = col * this.cellLength; const startY = row * this.cellLength; return new THREE.Vector2(startX, startY); } private createTextures = () => { for (let i = 0; i < this.length * this.length; i += 1) { this.createTexture(i); } } public setImage = (name: string, onComplete: Function) => { const img = new Image(); img.src = require('../textures/chess.png'); img.onload = (e) => { const max = Math.max(img.width, img.height); this.cellLength = max / this.length; this.canvas.width = max; this.canvas.height = max; img.width = max; img.height = max; this.drawImage(img); try { localStorage.setItem('rubik-image', this.canvas.toDataURL('image/png')); } catch (err) { console.log(`Error: ${err}`); } this.createTextures(); onComplete(); }; } public getTexture = (direction: number): THREE.Texture => this.textures[direction]; public createTexture = (direction: number) => { const { x, y } = this.getStartEnd(direction); const imgData = this.context.getImageData(x, y, this.cellLength, this.cellLength); const texture = new THREE.DataTexture(imgData.data, this.cellLength, this.cellLength); texture.type = THREE.UnsignedByteType; texture.needsUpdate = true; // texture.flipY = true; this.textures[direction] = texture; } public fillSpriteWithDirections = () => { for (let i = 0; i < this.length * this.length; i += 1) { this.setTextOnSprite(i, i.toString()); this.createTexture(i); } } private setTextOnSprite = (direction: number, text: string) => { this.cellLength = 256; this.canvas.width = this.cellLength * this.length; this.canvas.height = this.cellLength * this.length; this.context.font = `Bold ${this.cellLength / 2}px Arial`; this.context.fillStyle = 'rgba(0,0,0,0.95)'; this.context.textAlign = 'center'; this.context.textBaseline = 'middle'; const { x, y } = this.getStartEnd(direction); this.context.fillText(text, x + this.cellLength / 2, y + this.cellLength / 2); } private drawImage(img: HTMLImageElement, horizontal: boolean = false, vertical: boolean = false, x: number = 0, y: number = 0) { this.context.save(); this.context.setTransform( horizontal ? -1 : 1, 0, 0, vertical ? -1 : 1, x + +horizontal ? img.width : 0, y + +vertical ? img.height : 0, ); this.context.drawImage(img, 0, 0); this.context.restore(); } public dispose = () => { for (let i = 0; i < this.length * this.length; i += 1) { if (this.textures[i]) { this.textures[i].dispose(); } } } }
Markdown
UTF-8
838
2.921875
3
[ "MIT" ]
permissive
--- date: "2022-10-23T20:09:22.405Z" title: "Let's talk about web components (by Brad Frost)" description: "Fantastic rallying cry by Brad Frost" tags: [link, progressiveenhancement, webcomponents] linkTarget: "https://bradfrost.com/blog/post/lets-talk-about-web-components/" --- Brad breaks down the good, bad and ugly of web components but also makes a compelling argument that we should get behind this technology. > I come from the Zeldman school of web standards, am a strong proponent of progressive enhancement, care deeply about accessibility, and want to do my part to make sure that the web lives up to its ideals. And I bet you feel similar. It’s in that spirit that I want to see web components succeed. Because web components are a part of the web! --- I’m with you, Brad. I just need to find practical ways to make them work.
JavaScript
UTF-8
11,362
3
3
[]
no_license
console.log("Snake game project"); alert("Welcome to snake game!"); let cnv = document.getElementById('gameCanvas'), ctx = cnv.getContext('2d'), segmentLength = 10, startingSegments = 20, spawn = { x: 0, y:cnv.height/2 }, snakeSpeed = 5, maxApples = 5, appleLife = 500, segmentsPerApple = 3, snakeWidth = 5, appleWidth = 5, cursorSize = 10, snakeColor = [ 100, 255, 100, 1], appleColor = [ 0, 255, 0, 1], cursorColor = [ 255, 255, 255, 1], cursorColorMod = [ 0,-255,-255, 0], targetColor = [ 0, 0, 255, 1], targetColorMod = [ 255, 0,-255, 0], scoreColor = [ 255, 255, 255, 1], cursorSpin = 0.075, snake, cursor, target, apples, score, gameState, deathMeans; function distance(p1,p2){ let dx = p2.x-p1.x; let dy = p2.y-p1.y; return Math.sqrt(dx*dx + dy*dy); } function lineIntersect(p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x, p3_y) { let s1_x = p1_x - p0_x, s1_y = p1_y - p0_y, s2_x = p3_x - p2_x, s2_y = p3_y - p2_y, s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y), t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { return true; } return false; } function SGM(angle, x, y) { this.x = x || 0; this.y = y || 0; this.angle = angle || 0; this.parent = null; }; SGM.prototype.endX = function() { return this.x + Math.cos(this.angle) * segmentLength; }; SGM.prototype.endY = function() { return this.y + Math.sin(this.angle) * segmentLength; }; SGM.prototype.pointAt = function(x, y) { let dx = x - this.x, dy = y - this.y; this.angle = Math.atan2(dy, dx); }; SGM.prototype.target = function(x, y) { this.targetX = x; this.targetY = y; this.arrived = false; this.totalDist = distance({x:this.endX(), y: this.endY()}, {x: this.targetX, y: this.targetY}); this.currentDist = parseInt(this.totalDist); }; SGM.prototype.gotoTarget = function() { if(!this.arrived) { if(this.targetX > this.x + segmentLength || this.targetX < this.x - segmentLength || this.targetY > this.y + segmentLength || this.targetY < this.y - segmentLength) { this.pointAt(this.targetX, this.targetY); } else { this.arrived = true; } this.currentDist = distance({x:this.endX(), y: this.endY()}, {x: this.targetX, y: this.targetY}); } this.x += (this.endX() - this.x) / snakeSpeed; this.y += (this.endY() - this.y) / snakeSpeed; this.parent.drag(this.x, this.y); }; SGM.prototype.drag = function(x, y) { this.pointAt(x, y); this.x = x - Math.cos(this.angle) * segmentLength; this.y = y - Math.sin(this.angle) * segmentLength; if(this.parent) { this.parent.drag(this.x, this.y); } }; SGM.prototype.render = function(context) { context.lineTo(this.endX(), this.endY()); }; function IKR(x, y) { this.ix = x || 0; this.iy = y || 0; this.sgms = []; this.lastArm = null; }; IKR.prototype.addSeg = function(angle) { let arm = new SGM(angle); if(this.lastArm !== null) { arm.x = this.lastArm.endX(); arm.y = this.lastArm.endY(); arm.parent = this.lastArm; } else { arm.x = this.ix; arm.y = this.iy; } this.sgms.push(arm); this.lastArm = arm; }; IKR.prototype.grow = function() { let tail = this.sgms[0], arm = new SGM(tail.angle); arm.x = tail.x - Math.cos(tail.angle) * segmentLength; arm.y = tail.y - Math.sin(tail.angle) * segmentLength; tail.parent = arm; this.sgms.unshift(arm); } IKR.prototype.drag = function(x, y) { this.lastArm.drag(x, y); }; function CUR(x,y) { this.x = x; this.y = y; this.rotation = 0; }; CUR.prototype.render = function(context) { context.save(); context.translate(this.x, this.y); context.rotate(this.rotation); context.beginPath(); context.moveTo(0, -cursorSize); context.lineTo(0, -cursorSize/2); context.moveTo(0, cursorSize/2); context.lineTo(0, cursorSize); context.moveTo(-cursorSize, 0); context.lineTo(-cursorSize/2, 0); context.moveTo(cursorSize/2, 0); context.lineTo(cursorSize, 0); context.stroke(); context.restore(); this.rotation = (this.rotation + cursorSpin) % 360; }; function Apple(x, y) { this.x = x; this.y = y; this.life = appleLife; this.rotation = 0; } Apple.prototype.update = function() { this.life--; }; Apple.prototype.render = function(context) { context.beginPath(); context.arc(this.x, this.y, appleWidth, 0, Math.PI*2); context.fill(); if(gameState !== 'dead') { context.save(); context.fillStyle = 'white'; context.font = '8px sans-serif'; context.fillText(this.life, this.x+10, this.y+10); context.restore(); CUR.prototype.render.call(this, context); } }; function init() { snake = new IKR(spawn.x, spawn.y); cursor = new CUR(-20, -20); target = new CUR(spawn.x + segmentLength * (startingSegments + 5), spawn.y); apples = []; score = 0; for(let i = 0; i < startingSegments; i++) { snake.addSeg(); } snake.lastArm.target(target.x, target.y); gameState = 'play'; } init(); cnv.addEventListener('mousemove', function(e) { switch(gameState) { case 'play': cursor.x = e.offsetX; cursor.y = e.offsetY; break; } }); cnv.addEventListener('mousedown', function(e) { switch(gameState) { case 'play': target.x = e.offsetX; target.y = e.offsetY; snake.lastArm.target(target.x, target.y); break; case 'dead': init(); break; } }); function badPlacement(apple) { for(let s = 0; s < snake.sgms.length; s++) { let seg = snake.sgms[s]; if(Math.min(distance(apple, {x:seg.endX(), y:seg.endY()}), distance(apple, {x:seg.x,y:seg.y})) < appleWidth*2) { return true; } } return false; } function addScoreSegments() { for(let i = 0; i < segmentsPerApple; i++) { snake.grow(); } } function update() { if(gameState !== 'dead') { snake.lastArm.gotoTarget(); if(snake.lastArm.endX() > cnv.width - 2 || snake.lastArm.endX() < 2 || snake.lastArm.endY() > cnv.height - 2 || snake.lastArm.endY() < 2) { gameState = 'dead'; deathMeans = 'You hit the wall...'; return; } for(let s = 0; s < snake.sgms.length-2; s++) { let seg = snake.sgms[s]; if(lineIntersect(snake.lastArm.x, snake.lastArm.y, snake.lastArm.endX(), snake.lastArm.endY(), seg.x, seg.y, seg.endX(), seg.endY())) { gameState = 'dead'; deathMeans = 'You bit yourself!'; return; } for(let a in apples) { let apple = apples[a]; if(Math.min(distance(apple, {x:seg.endX(), y:seg.endY()}), distance(apple, {x:seg.x,y:seg.y})) < appleWidth*2) { score += Math.round(apple.life/2); apples.splice(a, 1); addScoreSegments(); } } } for(let a in apples) { let apple = apples[a]; apple.update(); if(apple.life <= 0) { apples.splice(a,1); continue; } if(distance(apple,{x:snake.lastArm.endX(),y:snake.lastArm.endY()}) < appleWidth*2) { score += apple.life; apples.splice(a,1); addScoreSegments(); } } if(apples.length < maxApples && Math.random()<.1) { let offset = appleWidth*10, apple = new Apple( offset/2+Math.floor(Math.random()*(cnv.width-offset)), offset/2+Math.floor(Math.random()*(cnv.height-offset)) ); while(badPlacement(apple)) { apple.x = offset/2+Math.floor(Math.random()*(cnv.width-offset)); apple.y = offset/2+Math.floor(Math.random()*(cnv.height-offset)); } apples.push(apple); } } } function drawTarget(targetModFactor) { if(!snake.lastArm.arrived) { ctx.strokeStyle = 'rgba('+ (targetColor[0] + targetColorMod[0]*targetModFactor).toFixed(0) + ',' + (targetColor[1] + targetColorMod[1]*targetModFactor).toFixed(0) + ',' + (targetColor[2] + targetColorMod[2]*targetModFactor).toFixed(0) + ',' + (targetColor[3] + targetColorMod[3]*targetModFactor).toFixed(0) +')'; ctx.lineWidth = 1; target.render(ctx); } } function drawSnake() { ctx.beginPath(); ctx.strokeStyle = ctx.fillStyle = 'rgba('+ snakeColor[0] +','+ snakeColor[1] +','+ snakeColor[2] +','+ snakeColor[3]+')'; ctx.lineWidth = snakeWidth; ctx.moveTo(snake.sgms[0].x, snake.sgms[0].y); for(let s in snake.sgms) { snake.sgms[s].render(ctx); } ctx.stroke(); ctx.beginPath(); ctx.arc(snake.lastArm.endX(), snake.lastArm.endY(), appleWidth*.75, 0, Math.PI*2); ctx.fill(); } function drawCursor(targetModFactor) { ctx.strokeStyle = 'rgba('+ (cursorColor[0] + cursorColorMod[0]*targetModFactor).toFixed(0) + ',' + (cursorColor[1] + cursorColorMod[1]*targetModFactor).toFixed(0) + ',' + (cursorColor[2] + cursorColorMod[2]*targetModFactor).toFixed(0) + ',' + (cursorColor[3] + cursorColorMod[3]*targetModFactor).toFixed(0) ctx.lineWidth = 1; cursor.render(ctx); } function drawApples() { ctx.fillStyle = 'rgba('+ appleColor[0] +','+ appleColor[1] +','+ appleColor[2] +','+ appleColor[3] +')'; for(let a in apples) { let apple = apples[a], appleTargetMod = 1 - apple.life / appleLife; ctx.strokeStyle = 'rgba('+ (cursorColor[0] + cursorColorMod[0]*appleTargetMod).toFixed(0) + ',' + (cursorColor[1] + cursorColorMod[1]*appleTargetMod).toFixed(0) + ',' + (cursorColor[2] + cursorColorMod[2]*appleTargetMod).toFixed(0) + ',' + (cursorColor[3] + cursorColorMod[3]*appleTargetMod).toFixed(0) +')'; ctx.lineWidth = 1; apple.render(ctx); } } function render() { let targetModFactor = 1 - snake.lastArm.currentDist / snake.lastArm.totalDist; switch(gameState) { case 'play': ctx.clearRect(0, 0, cnv.width, cnv.height); drawTarget(targetModFactor); drawSnake(); drawApples(); drawCursor(targetModFactor); ctx.fillStyle = 'rgba('+ scoreColor[0] +','+ scoreColor[1] +','+ scoreColor[2] +','+ scoreColor[3] +')'; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; ctx.fillText('Score: '+score, 10, 10); break; case 'dead': ctx.clearRect(0, 0, cnv.width, cnv.height); drawSnake(); drawApples(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.fillRect(100, 100, cnv.width - 200, cnv.height - 200); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = ctx.strokeStyle = 'white'; ctx.font = 'bold 30px sans-serif' ctx.fillText('DEAD', cnv.width/2, cnv.height/2-70); ctx.font = 'bold 25px sans-serif' ctx.fillText(deathMeans, cnv.width/2, cnv.height/2-30); ctx.font = '20px sans-serif'; ctx.fillText('Score:', cnv.width/2, cnv.height/2+15); ctx.font = 'bold 60px sans-serif'; ctx.fillText(score, cnv.width/2, cnv.height/2+60); ctx.font = 'lighter 10px sans-serif'; ctx.lineWidth = 1; ctx.strokeRect(103, 103, cnv.width - 206, cnv.height - 206); break; } } function animate() { update(); render(); requestAnimationFrame(animate); } snake.lastArm.target(target.x, target.y); animate();
Markdown
UTF-8
31,236
3
3
[ "MIT" ]
permissive
# Lab: Add the Notes Feature In this lab, we will take what we have learned so far and add a whole new feature to our application. Specifically, we will add the "Tasting Notes" feature. In addition to exercising some skills we have already learned such as creating models, services, components, and pages, we will also use some Framework components we have not seen yet. These will include: - The modal overlay - Various form elements - The sliding Ion Item ## Preliminary Items There are a couple of preliminary items that we need to get out of the way first. - Create a data model - Create a data service that performs HTTP requests - Add the notes to the store **Important:** These are a few things we have done multiple times now. As such, we will often provide you with some skeleton code and leave you to fill in the logic. If you get stuck, you can look at the <a href="https://github.com/ionic-enterprise/tea-taster-angular" target="_blank">completed code</a>, but try not to. Once we have a good skeleton in place, we will get back to doing new things that are far less "copy-paste." ### Create Some Entities First let's generate some entities that we are going to need. We will fill these in as we go. ```bash ionic g service core/tasting-notes/tasting-notes ionic g component tasting-notes/tasting-note-editor ``` ### The `TastingNotes` Model Add the following model in `src/app/models/tasting-note.ts` and make sure to update the `src/app/models/index.ts` accordingly: ```typescript export interface TastingNote { id?: number; brand: string; name: string; notes: string; rating: number; teaCategoryId: number; } ``` ### The `TastingNotes` Service #### Test ```typescript import { TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TastingNotesService } from './tasting-notes.service'; import { environment } from '@env/environment'; describe('TastingNotesService', () => { let httpTestingController: HttpTestingController; let service: TastingNotesService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); httpTestingController = TestBed.inject(HttpTestingController); service = TestBed.inject(TastingNotesService); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('get all', () => { it('gets the user tasting notes', () => { service.getAll().subscribe(); const req = httpTestingController.expectOne(`${environment.dataService}/user-tasting-notes`); expect(req.request.method).toEqual('GET'); httpTestingController.verify(); }); }); describe('delete', () => { it('removes the specific note', () => { service.delete(4).subscribe(); const req = httpTestingController.expectOne(`${environment.dataService}/user-tasting-notes/4`); expect(req.request.method).toEqual('DELETE'); httpTestingController.verify(); }); }); describe('save', () => { it('saves a new note', () => { service .save({ brand: 'Lipton', name: 'Yellow Label', notes: 'Overly acidic, highly tannic flavor', rating: 1, teaCategoryId: 3, }) .subscribe(); const req = httpTestingController.expectOne(`${environment.dataService}/user-tasting-notes`); expect(req.request.method).toEqual('POST'); httpTestingController.verify(); }); it('saves an existing note', () => { service .save({ id: 7, brand: 'Lipton', name: 'Yellow Label', notes: 'Overly acidic, highly tannic flavor', rating: 1, teaCategoryId: 3, }) .subscribe(); const req = httpTestingController.expectOne(`${environment.dataService}/user-tasting-notes/7`); expect(req.request.method).toEqual('POST'); httpTestingController.verify(); }); }); }); ``` #### Code I'll provide the skeleton, you provide the actual logic. ```typescript import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { EMPTY, Observable } from 'rxjs'; import { TastingNote } from '@app/models'; import { environment } from '@env/environment'; @Injectable({ providedIn: 'root', }) export class TastingNotesService { constructor(private http: HttpClient) {} getAll(): Observable<Array<TastingNote>> { // TODO: Replace with actual code, see the tea service if you need a hint. // This one is a lot easier, though, as there are no data transforms. return EMPTY; } delete(id: number): Observable<void> { // TODO: Replace with actual code return EMPTY; } save(note: TastingNote): Observable<TastingNote> { // TODO: Replace with actual code return EMPTY; } } ``` #### Mock ```typescript import { EMPTY } from 'rxjs'; import { TastingNotesService } from './tasting-notes.service'; export const createTastingNotesServiceMock = () => jasmine.createSpyObj<TastingNotesService>('TastingNotesService', { getAll: EMPTY, delete: EMPTY, save: EMPTY, }); ``` **Important:** remember to update the `src/app/core/[index.ts|testing.ts]` files. ### The Editor Component #### `src/app/tasting-notes/tasting-note-editor/tasting-note-editor.component.spec.ts` ```typescript import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { TastingNotesService, TeaService } from '@app/core'; import { createTastingNotesServiceMock, createTeaServiceMock } from '@app/core/testing'; import { IonicModule, ModalController } from '@ionic/angular'; import { createOverlayControllerMock } from '@test/mocks'; import { of } from 'rxjs'; import { TastingNoteEditorComponent } from './tasting-note-editor.component'; describe('TastingNoteEditorComponent', () => { let component: TastingNoteEditorComponent; let fixture: ComponentFixture<TastingNoteEditorComponent>; let modalController: ModalController; const click = (button: HTMLElement) => { const event = new Event('click'); button.dispatchEvent(event); fixture.detectChanges(); }; beforeEach(waitForAsync(() => { modalController = createOverlayControllerMock('ModalController'); TestBed.configureTestingModule({ imports: [TastingNoteEditorComponent], }) .overrideProvider(TastingNotesService, { useFactory: createTastingNotesServiceMock }) .overrideProvider(TeaService, { useFactory: createTeaServiceMock }) .overrideProvider(ModalController, { useValue: modalController }) .compileComponents(); fixture = TestBed.createComponent(TastingNoteEditorComponent); component = fixture.componentInstance; const tea = TestBed.inject(TeaService); (tea.getAll as jasmine.Spy).and.returnValue( of([ { id: 7, name: 'White', image: 'assets/img/white.jpg', description: 'White tea description.', rating: 5, }, { id: 8, name: 'Yellow', image: 'assets/img/yellow.jpg', description: 'Yellow tea description.', rating: 3, }, ]) ); })); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); describe('initialization', () => { it('binds the tea select', () => { fixture.detectChanges(); const sel = fixture.debugElement.query(By.css('ion-select')); const opts = sel.queryAll(By.css('ion-select-option')); expect(opts.length).toEqual(2); expect(opts[0].nativeElement.value).toEqual(7); expect(opts[0].nativeElement.textContent.trim()).toEqual('White'); expect(opts[1].nativeElement.value).toEqual(8); expect(opts[1].nativeElement.textContent.trim()).toEqual('Yellow'); }); describe('without a note', () => { beforeEach(() => { fixture.detectChanges(); }); it('has the add title', () => { const el = fixture.debugElement.query(By.css('ion-title')); expect(el.nativeElement.textContent.trim()).toEqual('Add Note'); }); it('has the add button label', () => { const btn = fixture.debugElement.query(By.css('[data-testid="save-button"]')); expect(btn.nativeElement.textContent.trim()).toEqual('Add'); }); }); describe('with a note', () => { beforeEach(() => { component.note = { id: 7, brand: 'Lipton', name: 'Yellow Label', notes: 'Overly acidic, highly tannic flavor', rating: 1, teaCategoryId: 3, }; fixture.detectChanges(); }); it('sets the brand', () => { const brand = fixture.debugElement.query(By.css('[data-testid="brand-input"]')); expect(brand.nativeElement.value).toEqual('Lipton'); }); it('sets the name', () => { const name = fixture.debugElement.query(By.css('[data-testid="name-input"]')); expect(name.nativeElement.value).toEqual('Yellow Label'); }); it('sets the notes', () => { const notes = fixture.debugElement.query(By.css('[data-testid="notes-input"]')); expect(notes.nativeElement.value).toEqual('Overly acidic, highly tannic flavor'); }); it('sets the tea category id', () => { const sel = fixture.debugElement.query(By.css('[data-testid="tea-type-select"]')); expect(sel.nativeElement.value).toEqual(3); }); it('has the update title', () => { const el = fixture.debugElement.query(By.css('ion-title')); expect(el.nativeElement.textContent.trim()).toEqual('Update Note'); }); it('has the update button label', () => { const btn = fixture.debugElement.query(By.css('[data-testid="save-button"]')); expect(btn.nativeElement.textContent.trim()).toEqual('Update'); }); }); }); describe('save', () => { beforeEach(() => { const tastingNotes = TestBed.inject(TastingNotesService); (tastingNotes.save as jasmine.Spy).and.returnValue(of(null)); }); describe('a new note', () => { beforeEach(() => { fixture.detectChanges(); }); it('saves the entered data', () => { const tastingNotes = TestBed.inject(TastingNotesService); const btn = fixture.debugElement.query(By.css('[data-testid="save-button"]')); component.editorForm.controls.brand.setValue('Lipton'); component.editorForm.controls.name.setValue('Yellow Label'); component.editorForm.controls.teaCategoryId.setValue(3); component.editorForm.controls.rating.setValue(1); component.editorForm.controls.notes.setValue('ick'); click(btn.nativeElement); expect(tastingNotes.save).toHaveBeenCalledTimes(1); expect(tastingNotes.save).toHaveBeenCalledWith({ brand: 'Lipton', name: 'Yellow Label', teaCategoryId: 3, rating: 1, notes: 'ick', }); }); it('dismisses the modal', () => { const btn = fixture.debugElement.query(By.css('[data-testid="save-button"]')); click(btn.nativeElement); expect(modalController.dismiss).toHaveBeenCalledTimes(1); }); }); describe('an existing note', () => { beforeEach(() => { component.note = { id: 73, brand: 'Generic', name: 'White Label', teaCategoryId: 2, rating: 3, notes: 'it is ok', }; fixture.detectChanges(); }); it('dispatches the save with the data', () => { const tastingNotes = TestBed.inject(TastingNotesService); const btn = fixture.debugElement.query(By.css('[data-testid="save-button"]')); component.editorForm.controls.brand.setValue('Lipton'); component.editorForm.controls.name.setValue('Yellow Label'); component.editorForm.controls.teaCategoryId.setValue(3); component.editorForm.controls.rating.setValue(1); component.editorForm.controls.notes.setValue('ick'); click(btn.nativeElement); expect(tastingNotes.save).toHaveBeenCalledTimes(1); expect(tastingNotes.save).toHaveBeenCalledWith({ id: 73, brand: 'Lipton', name: 'Yellow Label', teaCategoryId: 3, rating: 1, notes: 'ick', }); }); it('dismisses the modal', () => { const btn = fixture.debugElement.query(By.css('[data-testid="save-button"]')); click(btn.nativeElement); expect(modalController.dismiss).toHaveBeenCalledTimes(1); }); }); }); describe('close', () => { beforeEach(() => { fixture.detectChanges(); }); it('dismisses the modal', () => { const btn = fixture.debugElement.query(By.css('[data-testid="cancel-button"]')); click(btn.nativeElement); expect(modalController.dismiss).toHaveBeenCalledTimes(1); }); }); }); ``` #### `src/app/tasting-notes/tasting-note-editor/tasting-note-editor.component.html` ```html <ion-header> <ion-toolbar> <ion-title class="ion-text-center">{{ title }}</ion-title> <ion-buttons slot="start"> <ion-button id="cancel-button" (click)="close()" data-testid="cancel-button"> Cancel </ion-button> </ion-buttons> <ion-buttons slot="end"> <ion-button [strong]="true" [disabled]="!editorForm.valid" (click)="save()" data-testid="save-button" >{{ buttonLabel }}</ion-button > </ion-buttons> </ion-toolbar> </ion-header> <ion-content> <form [formGroup]="editorForm"> <ion-item> <ion-input id="brand-input" name="brand" label="Brand" label-placement="floating" formControlName="brand" data-testid="brand-input" ></ion-input> </ion-item> <ion-item> <ion-input id="name-input" name="name" label="Name" label-placement="floating" formControlName="name" data-testid="name-input" ></ion-input> </ion-item> <ion-item> <ion-select name="tea-type-select" label="Type" formControlName="teaCategoryId" data-testid="tea-type-select"> <ion-select-option *ngFor="let t of teaCategories$ | async" [value]="t.id">{{ t.name }}</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Rating</ion-label> <app-rating id="rating-input" name="rating" formControlName="rating" data-testid="rating"></app-rating> </ion-item> <ion-item> <ion-textarea id="notes-textbox" name="notes" label="Notes" label-placement="floating" formControlName="notes" rows="5" data-testid="notes-input" ></ion-textarea> </ion-item> </form> </ion-content> ``` #### `src/app/tasting-notes/tasting-note-editor/tasting-note-editor.component.ts` There are two TODOs in the following code. Copy the rest of the code in to your TypeScript file, then fill in the TODOs. ```typescript import { CommonModule } from '@angular/common'; import { Component, Input, OnInit } from '@angular/core'; import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; import { TastingNotesService, TeaService } from '@app/core'; import { TastingNote, Tea } from '@app/models'; import { RatingComponent } from '@app/shared'; import { IonicModule, ModalController } from '@ionic/angular'; import { Observable, of, tap } from 'rxjs'; @Component({ selector: 'app-tasting-note-editor', templateUrl: './tasting-note-editor.component.html', styleUrls: ['./tasting-note-editor.component.scss'], standalone: true, imports: [CommonModule, IonicModule, RatingComponent, ReactiveFormsModule], }) export class TastingNoteEditorComponent implements OnInit { @Input() note: TastingNote | undefined; editorForm = this.fb.group({ brand: ['', Validators.required], name: ['', Validators.required], teaCategoryId: new FormControl<number | undefined>(undefined, { validators: [Validators.required] }), rating: [0, Validators.required], notes: ['', Validators.required], }); buttonLabel: string = ''; title: string = ''; teaCategories$: Observable<Array<Tea>> = of([]); constructor( private fb: FormBuilder, private modalController: ModalController, private tastingNotes: TastingNotesService, private tea: TeaService ) {} close() { this.modalController.dismiss(); } async save() { const note: TastingNote = { // TODO: Figure out how to set this based on the test we just wrote. As an example, here is // how to set the brand: // brand: this.editorForm.controls.brand.value as string, // // Fill this in below brand: '', name: '', notes: '', rating: 0, teaCategoryId: 0, }; if (this.note?.id) { note.id = this.note?.id; } this.tastingNotes .save(note) .pipe(tap(() => this.modalController.dismiss())) .subscribe(); } ngOnInit() { this.teaCategories$ = this.tea.getAll(); if (this.note) { // TODO: Figure out what needs to be done here if a `note` is passed via property // // HINT: this.editorForm.controls.brand.setValue(this.note.brand); // ... // this.buttonLabel = 'Update' // ... } else { // TODO: Only the buttonLabel and title need to get set here. } } } ``` ### List the Notes #### `src/app/tasting-notes/tasting-notes.page.html` ```html <ion-header [translucent]="true"> <ion-toolbar> <ion-title>Tasting Notes</ion-title> </ion-toolbar> </ion-header> <ion-content [fullscreen]="true"> <ion-header collapse="condense"> <ion-toolbar> <ion-title size="large">Tasting Notes</ion-title> </ion-toolbar> </ion-header> <ion-list> <ion-item *ngFor="let note of notes$ | async"> <ion-label> <div>{{ note.brand }}</div> <div>{{ note.name }}</div> </ion-label> </ion-item> </ion-list> </ion-content> ``` #### `src/app/tasting-notes/tasting-notes.page.spec.ts` ```typescript import { fakeAsync, tick, waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { TastingNotesService } from '@app/core'; import { createTastingNotesServiceMock } from '@app/core/testing'; import { TastingNote } from '@app/models'; import { IonicModule } from '@ionic/angular'; import { of } from 'rxjs'; import { TastingNotesPage } from './tasting-notes.page'; describe('TastingNotesPage', () => { let component: TastingNotesPage; let fixture: ComponentFixture<TastingNotesPage>; let modal: HTMLIonModalElement; let testData: Array<TastingNote>; const mockRouterOutlet = { nativeEl: {}, }; beforeEach(waitForAsync(() => { initializeTestData(); TestBed.configureTestingModule({ imports: [TastingNotesPage], }) .overrideProvider(TastingNotesService, { useFactory: createTastingNotesServiceMock }) .compileComponents(); const tastingNotes = TestBed.inject(TastingNotesService); (tastingNotes.getAll as jasmine.Spy).and.returnValue(of(testData)); fixture = TestBed.createComponent(TastingNotesPage); component = fixture.componentInstance; })); it('should create', () => { expect(component).toBeTruthy(); }); it('displays the notes', () => { fixture.detectChanges(); const items = fixture.debugElement.queryAll(By.css('ion-item')); expect(items.length).toEqual(2); expect(items[0].nativeElement.textContent.trim()).toContain('Bentley'); expect(items[1].nativeElement.textContent.trim()).toContain('Lipton'); }); const click = (button: HTMLElement) => { const event = new Event('click'); button.dispatchEvent(event); fixture.detectChanges(); }; const initializeTestData = () => { testData = [ { id: 73, brand: 'Bentley', name: 'Brown Label', notes: 'Essentially OK', rating: 3, teaCategoryId: 2, }, { id: 42, brand: 'Lipton', name: 'Yellow Label', notes: 'Overly acidic, highly tannic flavor', rating: 1, teaCategoryId: 3, }, ]; }; }); ``` #### `src/app/tasting-notes/tasting-notes.page.ts` ```typescript import { CommonModule } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { TastingNotesService } from '@app/core'; import { TastingNote } from '@app/models'; import { IonicModule } from '@ionic/angular'; import { EMPTY, Observable } from 'rxjs'; @Component({ selector: 'app-tasting-notes', templateUrl: './tasting-notes.page.html', styleUrls: ['./tasting-notes.page.scss'], standalone: true, imports: [CommonModule, FormsModule, IonicModule], }) export class TastingNotesPage implements OnInit { notes$: Observable<Array<TastingNote>> = EMPTY; constructor(private tastingNotes: TastingNotesService) {} ngOnInit() { this.notes$ = this.tastingNotes.getAll(); } } ``` ## Using the Notes Editor Now we are getting into the new stuff. Back to the usual format. 🤓 We are going to use the Notes Editor in a modal in order to accomplish two different tasks: - adding a new note - updating an existing note With that in mind, let's update the test and the view model so we can inject the items that we will require. **Note:** adding the proper `import` statements is left as an exercise for the reader. In `src/app/tasting-notes/tasting-notes.page.spec.ts`, update the `TestBed` configuration to provide the `ModalController` and the `IonRouterOutlet`. The full `beforeEach` should look something like the following. **Do not** copy past this in. Instead just add the parts you don't have, using the auto-complete and auto-import features of your editor to get the proper `import` statements added for you. Here is a synopsis of the changes: - create a mock for the modal element - provide mocks for the `IonRouterOutlet` and `ModalController` ```typescript let modal: HTMLIonModalElement; let modalController: ModalController; let testData: Array<TastingNote>; const mockRouterOutlet = { nativeEl: {}, }; beforeEach(waitForAsync(() => { initializeTestData(); modal = createOverlayElementMock('Modal'); modalController = createOverlayControllerMock('ModalController', modal); TestBed.configureTestingModule({ imports: [TastingNotesPage], }) .overrideProvider(ModalController, { useValue: modalController }) .overrideProvider(IonRouterOutlet, { useValue: mockRouterOutlet }) .overrideProvider(TastingNotesService, { useFactory: createTastingNotesServiceMock }) .compileComponents(); const tastingNotes = TestBed.inject(TastingNotesService); (tastingNotes.getAll as jasmine.Spy).and.returnValue(of(testData)); fixture = TestBed.createComponent(TastingNotesPage); component = fixture.componentInstance; })); ``` In `src/app/tasting-notes/tasting-notes.page.ts`, add the `TastingNoteEditorComponent` to the `imports` list and inject the same items that we just set up providers for: ```typescript @Component({ selector: 'app-tasting-notes', templateUrl: './tasting-notes.page.html', styleUrls: ['./tasting-notes.page.scss'], standalone: true, imports: [CommonModule, FormsModule, IonicModule, TastingNoteEditorComponent], }) ... constructor( private modalController: ModalController, private routerOutlet: IonRouterOutlet, private tastingNotes: TastingNotesService, ) {} ``` ### Add a New Note Adding a new node will be handled via a <a href="https://ionicframework.com/docs/api/fab" target="_blank">floating action button</a>. Add the following markup to the tasting notes page HTML within the `ion-content`: ```html <ion-fab vertical="bottom" horizontal="end" slot="fixed"> <ion-fab-button data-testid="add-new-button" (click)="newNote()"> <ion-icon name="add"></ion-icon> </ion-fab-button> </ion-fab> ``` In our test, we will verify that the modal is properly opened: ```typescript describe('add new note', () => { beforeEach(() => { fixture.detectChanges(); }); it('creates the editor modal', () => { const button = fixture.debugElement.query(By.css('[data-testid="add-new-button"]')).nativeElement; click(button); expect(modalController.create).toHaveBeenCalledTimes(1); expect(modalController.create).toHaveBeenCalledWith({ component: TastingNoteEditorComponent, backdropDismiss: false, presentingElement: mockRouterOutlet.nativeEl as any, }); }); it('displays the editor modal', fakeAsync(() => { const button = fixture.debugElement.query(By.css('[data-testid="add-new-button"]')).nativeElement; click(button); tick(); expect(modal.present).toHaveBeenCalledTimes(1); })); }); ``` The code required to perform this action is: ```typescript async newNote(): Promise<void> { const modal = await this.modalController.create({ component: TastingNoteEditorComponent, backdropDismiss: false, presentingElement: this.routerOutlet.nativeEl, }); modal.present(); } ``` When you click on the FAB button, you should be able to add a tasting note. Check that out to determine if it works. Note that for now you will need to refresh your page to see the newly added note. ### Edit an Existing Note The modal editor component handles editing an existing note by binding the `note` property to the note to be edited when the modal is created. Let's change the code to support that. Find the `ion-item` that displays each note in the list and add the following event binding: ```html <ion-item (click)="updateNote(note)" ...> ... </ion-item> ``` Now we can add a set of tests: ```typescript describe('update an existing note', () => { beforeEach(() => { fixture.detectChanges(); }); it('creates the editor modal', () => { const item = fixture.debugElement.query(By.css('ion-item')).nativeElement; click(item); expect(modalController.create).toHaveBeenCalledTimes(1); expect(modalController.create).toHaveBeenCalledWith({ component: TastingNoteEditorComponent, backdropDismiss: false, presentingElement: mockRouterOutlet.nativeEl as any, componentProps: { note: testData[0] }, }); }); it('displays the editor modal', fakeAsync(() => { const item = fixture.debugElement.query(By.css('ion-item')).nativeElement; click(item); tick(); expect(modal.present).toHaveBeenCalledTimes(1); })); }); ``` The quick and dirty way to get this test to pass is to copy the `newNote()` method and add the note property binding to it as such: ```typescript async updateNote(note: TastingNote): Promise<void> { const modal = await this.modalController.create({ component: TastingNoteEditorComponent, backdropDismiss: false, presentingElement: this.routerOutlet.nativeEl, componentProps: { note }, }); modal.present(); } ``` But that is a lot of repeated code with just a one line difference. Let's refactor that a bit: ```typescript newNote(): Promise<void> { return this.displayEditor(); } updateNote(note: TastingNote): Promise<void> { return this.displayEditor(note); } private async displayEditor(note?: TastingNote): Promise<void> { // Filling in this code is left as an exercise for you. // You may want to start with setting up the options based on whether you have a note or not: // const opt: ModalOptions = { ... } } ``` Try clicking on an existing note to make sure that you can properly update it. ## Delete a Note The final feature we will add is the ability to delete a note. We will keep this one simple and make it somewhat hidden so that it isn't too easy for a user to delete a note. We will use a construct called <a ref="https://ionicframework.com/docs/api/item-sliding" target="_blank">item sliding</a> to essentially "hide" the delete button behind the item. That way the user has to slide the item over in order to expose the button and do a delete. Doing this results in a little bit of rework in how the item is rendered and bound on the `TastingNotesPage`: ```html <ion-item-sliding *ngFor="let note of notes$ | async"> <ion-item (click)="updateNote(note)"> <ion-label> <div>{{ note.brand }}</div> <div>{{ note.name }}</div> </ion-label> </ion-item> <ion-item-options> <ion-item-option color="danger" (click)="deleteNote(note)"> Delete </ion-item-option> </ion-item-options> </ion-item-sliding> ``` And the code for the delete is pretty straight forward: ```typescript deleteNote(note: TastingNote): void { this.tastingNotes.delete(note.id as number).subscribe(); } ``` ## Refreshing This is mostly working. Mostly. One problem we have, though, is that as we add, update, or remove tasting notes, the list does not update. We can fix that by using a `BehaviorSubject` to refresh the data. All of the following changes are in the `src/app/tasting-notes/tasting-notes.page.ts` file. First, create the `BehaviorSubject`: ```typescript private refresh = new BehaviorSubject<void>(undefined); ``` Then update the main observable pipeline that is feeding the data to our page: ```typescript ngOnInit() { this.notes$ = this.refresh.pipe(mergeMap(() => this.tastingNotes.getAll())); } ``` At this point, we just need to know when to call `next()` on the `BehaviorSubject`. Logically we will need to do this after the modal is closed and as part of the `delete` pipeline. ```typescript // NOTE: Your code may differ slightly... private async displayEditor(note?: TastingNote): Promise<void> { let opt: ModalOptions = { component: TastingNoteEditorComponent, backdropDismiss: false, presentingElement: this.routerOutlet.nativeEl, }; if (note) { opt.componentProps = { note }; } const modal = await this.modalController.create(opt); modal.present(); await modal.onDidDismiss(); this.refresh.next(); } ``` ```typescript async deleteNote(note: TastingNote) { this.tastingNotes .delete(note.id as number) .pipe(tap(() => this.refresh.next())) .subscribe(); } ``` This will ensure that the data is refreshed after each change. **Note:** The `getAll()` does not currently guarantee a consistent sort order on the notes, which may be jarring for the users. Fixing that is left as an exercise for the reader. ## Extra Credit Items **Extra Credit #1:** Normally, we would write the tests first and then the code. For the deleting of a note we did not do that. That is because I wanted to give you some practice crafting your own tests. **Extra Credit #2:** You could also use an alert to ask the user if they _really_ want to delete the note. Extra extra credit if you want to implement that logic. ## Conclusion Congratulations. You have used what we have learned to this point to add a whole new feature to your app. Along the way, you also exercised a few Framework components you had not used before. We are almost done with this app.
Shell
UTF-8
715
3.03125
3
[]
no_license
#!/usr/bin/zsh while read name mark junk do email=$( dcu-email-address $name) print $name $mark $email { cat <<EOF Your CA116 lab exam 3 mark is $mark. This mark is out of 100. This mark constitutes a third of your continuous assessment mark for the module, which itself constitutes 60% of your mark overall. Overall, the marks for this lab exam were weaker than I would have hoped for. Therefore, I reviewed all of the incorrect uploads and awarded attempt marks where merited. I have yet to review the uploads for issues related to academic integrity, and reserve the right to pursue such matters as required. EOF } | mail -s "2021/CA116, lab exam 3 mark for $name" $email sleep 5 done
JavaScript
UTF-8
6,376
2.578125
3
[]
no_license
import React from 'react'; import axios from 'axios'; class Stock extends React.Component { constructor(props) { super(props) this.onChangeBuyingStock = this.onChangeBuyingStock.bind(this); this.onSubmit = this.onSubmit.bind(this); this.onAmountChange = this.onAmountChange.bind(this); this.state = { buyables: [], buying_stock: '', buying_amount: 0, username: '', amount: 0, storedAmt: 0, data: [] } } async componentDidMount() { await axios.get('https://currency-trade.herokuapp.com/stocks/').then((res) => { this.setState({ buyables: res.data.stocks.map(stoc => stoc.stock), username: res.data.username }) }) .catch((err) => { console.error(err); }) await axios.get('https://currency-trade.herokuapp.com/stocks/getall').then((res) => { ////console.log(res.data[11].username+" "+res.data[11].currency) console.log(res.data.length) let arr = [] for (let i = 0; i < res.data.length; i++) { const element = res.data[i]; //console.log(element) arr.push(element) } this.setState({ data: arr }) console.log(this.state.data[1]) }) .catch((e) => { }) } async onAmountChange(e) { this.setState({ buying_amount: e.target.value }) } async onChangeBuyingStock(e) { const code = { code: e.target.value } this.setState({ buying_stock: e.target.value }) await axios.post('https://currency-trade.herokuapp.com/stocks/getRates', code).then((res) => { this.setState({ amount: res.data.rate, storedAmt: res.data.amount }) }) } async onSubmit(e) { e.preventDefault(); const code = { buying_stock: this.state.buying_stock, buying_amount: this.state.buying_amount, username: this.state.username } await axios.post('https://currency-trade.herokuapp.com/stocks/buyStock', code).then((res) => { if (res.data === "Trans complete") { alert('Transaction Completed!!\nYou bought ' + this.state.buying_amount + ' ' + this.state.buying_stock); } }) } renderTableData() { return this.state.data.map((data, index) => { const { username, stock, amount, status } = data //destructuring if (status === 'buy') { return ( <tr style={{ backgroundColor: "#ffcccb" }} key={username}> <td>{username}</td> <td>{amount}</td> <td>{stock}</td> <td>{status}</td> </tr> ) } else { return ( <tr style={{ backgroundColor: "lightgreen" }} key={username}> <td>{username}</td> <td>{amount}</td> <td>{stock}</td> <td>{status}</td> </tr> ) } }) } render() { return ( <div className="container-fluid"> <div className="row"> <div className="col-md-3 col-sm-3 col-xs-1"></div> <div className="col-md-6 col-sm-6 col-xs-10 borderDiv"> <div className="headingContent">Stock Buy</div> <form onSubmit={this.onSubmit}> <div className="form-group"> <label htmlFor="StockName">Stock Name</label> <select className="form-control" id="StockName" required onChange={this.onChangeBuyingStock}> <option disabled defaultValue value="p">---Please select one---</option> <option value="AAPL">Apple</option> <option value="GOOGL">Google</option> <option value="MSFT">Microsoft</option> <option value="AMZN">Amazon</option> <option value="FB">Facebook</option> <option value="WMT">Walmart</option> </select> </div> <div className="form-group"> <label htmlFor="StockRate">Stock Rate</label> <input type="text" className="form-control" id="StockRate" value={this.state.amount} placeholder="Stock Rate" readOnly /> </div> <div className="form-group"> <label htmlFor="AmountBuy">Amount Buy</label> <input type="text" className="form-control" id="AmountBuy" onChange={this.onAmountChange} placeholder="Please enter buy amount" /> </div> <button type="button" className="btn btn-warning btn-md" onClick={this.onSubmit}>Buy</button> </form> </div> </div> <br /> <div className="row"> <table class="table"> <thead> <tr> <th>Username</th> <th>Amount</th> <th>Stocks</th> <th>Status</th> </tr> </thead> <tbody> {this.renderTableData()} </tbody> </table> </div> <br /><br /><br /> </div> ); } } export default Stock;
Markdown
UTF-8
2,031
2.9375
3
[]
no_license
# Hilfsfunktionen für Contao ## Entwickler ## **Frank Hoppe** ## Simple PHP Cache für Contao ### Information ### Die Cache-Klasse ist eine Anpassung für Contao. Sie basiert auf [Simple PHP Cache](https://github.com/cosenary/Simple-PHP-Cache). ### Installation ### Falls die Klasse in einer Erweiterung angewendet wird, so muß ggfs. ein Eintrag in der autoload.ini der Erweiterung erfolgen: ```php <?php requires[] = "cache" ?> ``` ### Anwendung ### ```php <?php // Standardcache aktivieren, das Standardverzeichnis ist system/cache/schachbulle // Die Schlüssel werden in der Standardcachedatei "default" abgelegt, wenn kein Parameter // (hier 'Name') angegeben wird $cache = new \Schachbulle\ContaoHelperBundle\Classes\Cache('Name'); // String erstellen, es sind aber beliebige Datentypen möglich - auch Objekte und Arrays $result = "Hallo"; // String im Cache mit dem Schlüssel "ablage" speichern, Cachelebenszeit 3600s = 1h $cache->store('ablage', $result, 3600); // Cache mit dem Schlüssel "ablage" laden $daten = $cache->retrieve('ablage'); // Cache mit allen Schlüsseln laden $daten = $cache->retrieveAll(); // Cache mit allen Schlüsseln und Metadaten laden $daten = $cache->retrieveAll(true); // Cache mit dem Schlüssel "ablage" löschen $cache->erase('ablage'); // Cache mit allen Schlüsseln löschen $cache->eraseAll(); // Cache mit den abgelaufenen Schlüsseln löschen $cache->eraseExpired(); // Cache mit Schlüssel "ablage" auf Existenz prüfen und wenn vorhanden in Variable $result laden if($cache->isCached('ablage')) { $result = $cache->retrieve('ablage'); } // Cache mit einem neuen Dateinamen 'Test' generieren // Die Schlüssel werden jetzt in dieser Datei verwaltet. $cache2 = new \Schachbulle\ContaoHelperBundle\Classes\Cache('Test'); // Möglich ist der Wechsel des Cachenamens auch so, ohne ein neues Objekt anzulegen $cache->setCache('Test'); ?> ```
Java
UTF-8
2,010
3.546875
4
[]
no_license
package amm; public class BST implements BinarySearchTree { static class Node implements BinarySearchTree.Node { private int value; private Node left, right; Node(int value) { this.value = value; left = right = null; } @Override public int getValue() { return value; } @Override public void setValue(int value) { this.value = value; } @Override public Node getLeft() { return left; } @Override public void setLeft(Node left) { this.left = left; } @Override public Node getRight() { return right; } @Override public void setRight(Node right) { this.right = right; } } private Node root; public BST() { root = null; } @Override public Node getRoot() { return root; } @Override public void insert(int value) { root = insertRec(root, value); } Node insertRec(Node root, int value) { if (root == null) { root = new Node(value); return root; } if (value < root.getValue()) root.setLeft(insertRec(root.getLeft(), value)); else if (value > root.getValue()) root.setRight(insertRec(root.getRight(), value)); return root; } @Override public void print() { printRec(root); } void printRec(Node root) { if (root != null) { printRec(root.getLeft()); System.out.println(root.getValue()); printRec(root.getRight()); } } public Node search(Node root, int value) { if (root == null || root.getValue() == value) return root; if (root.getValue() < value) return search(root.getRight(), value); return search(root.getLeft(), value); } }
C#
UTF-8
501
3.21875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace System { public static partial class Extensions { public static bool IsBetween(this DateTime @this, DateTime minValue, DateTime maxValue) { return minValue.CompareTo(@this)==-1&&@this.CompareTo(maxValue)==-1; } public static Boolean IsInRange(this DateTime @this, DateTime startDate, DateTime endDate) { return @this.Date>=startDate.Date&&@this.Date<=endDate.Date; } } }
Python
UTF-8
1,563
2.609375
3
[]
no_license
import matplotlib.pyplot as plt from matplotlib import style import numpy as np import pandas as pd style.use('ggplot') # x,y = np.loadtxt('fitbitodu-export.csv',unpack=True,delimiter=',') #plt.plot(x,y) #plt.bar(x,y) #plt.show() df = pd.read_csv('a_data1.csv') df["|"] = df["|"].apply(lambda x: x.split()[0]) print(df.columns) df_1 = df[["|","|__acc"]] df_5 = df[["|","|__gyro"]] # df_2 = df[["|","|__acc-x"]] # df_3 = df[["|","|__acc-y"]] # df_4 = df[["|","|__acc-z"]] # # df_6 = df[["|","|__gyro-x"]] # df_7 = df[["|","|__gyro-y"]] # df_8 = df[["|","|__gyro-z"]] df_1=df_1.dropna() df_5=df_5.dropna() # df_2=df_2.dropna() # df_3=df_3.dropna() # df_4=df_4.dropna() # # df_6=df_6.dropna() # df_7=df_7.dropna() # df_8=df_8.dropna() df_1 = df_1.groupby("|").mean() df_5 = df_5.groupby("|").mean() # df_2 = df_2.groupby("|").mean() # df_3 = df_3.groupby("|").mean() # df_4 = df_4.groupby("|").mean() # df_6 = df_6.groupby("|").mean() # df_7 = df_7.groupby("|").mean() # df_8 = df_8.groupby("|").mean() print(df_1) print(df_5) # print(df_2) # print(df_3) # print(df_4) # print(df_6) # print(df_7) # print(df_8) df = pd.concat([df_1,df_5], axis=1) print(df) df.fillna(df.mean(), inplace=True) # from sklearn.preprocessing import StandardScaler # sc = StandardScaler() # X_train = sc.fit_transform(df_1) # X_test = sc.transform(df_2) # print(X_train) # print(X_test) df.to_csv(r'C:\Users\Gang\Desktop\new_data\a_data1.csv') # df.plot() # df_2.plot() # plt.show()
C#
UTF-8
3,169
2.78125
3
[]
no_license
using Riafco.Entity.Dataflex.Pro.Ressources; using Riafco.Service.Dataflex.Pro.Ressources.Data; using System.Collections.Generic; using System.Linq; namespace Riafco.Service.Dataflex.Pro.Ressources.Assembler { /// <summary> /// The PublicationTheme assembler class. /// </summary> public static class PublicationThemeAssembler { #region TO PIVOT /// <summary> /// From PublicationTheme To PublicationTheme Pivot. /// </summary> /// <param name="publicationTheme">publicationTheme TO ASSEMBLE</param> /// <returns>PublicationThemePivot result.</returns> public static PublicationThemePivot ToPivot(this PublicationTheme publicationTheme) { if (publicationTheme == null) { return null; } return new PublicationThemePivot { PublicationThemeId = publicationTheme.PublicationThemeId, Publication = publicationTheme.Publication?.ToPivot(), PublicationId = publicationTheme.PublicationId, Theme = publicationTheme.Theme?.ToPivot(), ThemeId = publicationTheme.ThemeId }; } /// <summary> /// From PublicationTheme list to PublicationTheme pivot list. /// </summary> /// <param name="publicationThemeList">publicationThemeList to assemble.</param> /// <returns>list of PublicationThemePivot result.</returns> public static List<PublicationThemePivot> ToPivotList(this List<PublicationTheme> publicationThemeList) { return publicationThemeList?.Select(x => x.ToPivot()).ToList(); } #endregion #region TO ENTITY /// <summary> /// From PublicationThemePivot to PublicationTheme. /// </summary> /// <param name="publicationThemePivot">publicationThemePivot to assemble.</param> /// <returns>PublicationTheme result.</returns> public static PublicationTheme ToEntity(this PublicationThemePivot publicationThemePivot) { if (publicationThemePivot == null) { return null; } return new PublicationTheme { PublicationThemeId = publicationThemePivot.PublicationThemeId, Publication = publicationThemePivot.Publication.ToEntity(), PublicationId = publicationThemePivot.PublicationId, Theme = publicationThemePivot.Theme.ToEntity(), ThemeId = publicationThemePivot.ThemeId }; } /// <summary> /// From PublicationThemePivotList to PublicationThemeList . /// </summary> /// <param name="publicationThemePivotList">PublicationThemePivotList to assemble.</param> /// <returns> list of PublicationTheme result.</returns> public static List<PublicationTheme> ToEntityList(this List<PublicationThemePivot> publicationThemePivotList) { return publicationThemePivotList?.Select(x => x.ToEntity()).ToList(); } #endregion } }
C#
UTF-8
3,870
3.296875
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Collections.Generic; namespace ZeroLevel.HNSW.Services { /// <summary> /// Min element always on top /// </summary> public class MinHeap : IEnumerable<(int, float)> { private readonly List<(int, float)> _elements; public MinHeap(int size = -1) { if (size > 0) _elements = new List<(int, float)>(size); else _elements = new List<(int, float)>(); } private int GetLeftChildIndex(int elementIndex) => 2 * elementIndex + 1; private int GetRightChildIndex(int elementIndex) => 2 * elementIndex + 2; private int GetParentIndex(int elementIndex) => (elementIndex - 1) / 2; private bool HasLeftChild(int elementIndex) => GetLeftChildIndex(elementIndex) < _elements.Count; private bool HasRightChild(int elementIndex) => GetRightChildIndex(elementIndex) < _elements.Count; private bool IsRoot(int elementIndex) => elementIndex == 0; private (int, float) GetLeftChild(int elementIndex) => _elements[GetLeftChildIndex(elementIndex)]; private (int, float) GetRightChild(int elementIndex) => _elements[GetRightChildIndex(elementIndex)]; private (int, float) GetParent(int elementIndex) => _elements[GetParentIndex(elementIndex)]; public int Count => _elements.Count; public void Clear() { _elements.Clear(); } private void Swap(int firstIndex, int secondIndex) { var temp = _elements[firstIndex]; _elements[firstIndex] = _elements[secondIndex]; _elements[secondIndex] = temp; } public bool IsEmpty() { return _elements.Count == 0; } public bool TryPeek(out int id, out float value) { if (_elements.Count == 0) { id = -1; value = 0; return false; } id = _elements[0].Item1; value = _elements[0].Item2; return true; } public (int, float) Pop() { if (_elements.Count == 0) throw new IndexOutOfRangeException(); var result = _elements[0]; _elements[0] = _elements[_elements.Count - 1]; _elements.RemoveAt(_elements.Count - 1); ReCalculateDown(); return result; } public void Push((int, float) element) { _elements.Add(element); ReCalculateUp(); } private void ReCalculateDown() { int index = 0; while (HasLeftChild(index)) { var smallerIndex = GetLeftChildIndex(index); if (HasRightChild(index) && GetRightChild(index).Item2 < GetLeftChild(index).Item2) { smallerIndex = GetRightChildIndex(index); } if (_elements[smallerIndex].Item2 >= _elements[index].Item2) { break; } Swap(smallerIndex, index); index = smallerIndex; } } private void ReCalculateUp() { var index = _elements.Count - 1; while (!IsRoot(index) && _elements[index].Item2 < GetParent(index).Item2) { var parentIndex = GetParentIndex(index); Swap(parentIndex, index); index = parentIndex; } } public IEnumerator<(int, float)> GetEnumerator() { return _elements.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _elements.GetEnumerator(); } } }
Python
UTF-8
63
3.046875
3
[]
no_license
myStr = "hello world" #print(dir(myStr)) print(myStr.title())
Java
UTF-8
568
2.984375
3
[]
no_license
package com.xzw.shuai.patterns.type.create.factory.abstractfactory; /** * @author DELL */ public class Client { public static void main(String[] args) { // 创建意大利风味甜品工厂 ItalyDessertFactory factory = new ItalyDessertFactory(); AmericanDessertFactory americanDessertFactory = new AmericanDessertFactory(); Coffee coffee = americanDessertFactory.createCoffee(); Dessert dessert = americanDessertFactory.createDessert(); System.out.println(coffee.getName()); dessert.show(); } }
Java
UTF-8
4,178
2.90625
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause" ]
permissive
package nl.tno.stormcv.batcher; import java.util.ArrayList; import java.util.List; import java.util.Map; import nl.tno.stormcv.bolt.BatchInputBolt.History; import nl.tno.stormcv.model.CVParticle; /** * A {@link IBatcher} implementation that partitions a set of {@link CVParticle} * items into zero or more non overlapping batches of the specified size. The * windowSize and sequenceDelta are used to determine if the provided list with * items contains any valid bathes. If the Batcher was created with a windowSize * of 3 and sequenceDelta of 10 the input <i>with sequenceNr's</i> [20, 30, 40, * 50, 60, 70, 90, 100, 110] will result in two 'windows': [20, 30, 40] and [50, * 60, 70]. Note that [90, 100, 110] is not a valid batch because of the missing * item (80). All items from a batch will be removed from the history which will * trigger an ACK for all of them. * * This Batcher starts to be greedy when the number of input items it gets * exceeds 5 * windowSize. In this case it will skip the first item in the list * and try to make a valid batch out of the next items. It keeps skipping until * a valid batch can be created of the end of the input is reached. Hence if * windowSize is 2 and sequenceDelta is 10 the set [0, 20, 30, 40, 50, 60, 70, * 80, 90, 100, 110] will result in one batch containing [20, 30] (matches the * criteria but skips the first element). This method avoid a bottleneck in the * topology in case an expected item never appears (might have been lost in * preceding bolts). * * @author Corne Versloot * */ public class DiscreteWindowBatcher implements IBatcher { private static final long serialVersionUID = 789734984349506398L; private int windowSize; private int sequenceDelta; public DiscreteWindowBatcher(int windowSize, int sequenceDelta) { this.windowSize = windowSize; this.sequenceDelta = sequenceDelta; } @SuppressWarnings("rawtypes") @Override public void prepare(Map stormConf) throws Exception { } @Override public List<List<CVParticle>> partition(History history, List<CVParticle> currentSet) { List<List<CVParticle>> result = new ArrayList<>(); if (currentSet.size() < windowSize) { return result; } int offset = 0; while (true) { if (offset + result.size() * windowSize + windowSize > currentSet.size()) { break; } List<CVParticle> window = new ArrayList<>(); window.addAll(currentSet.subList(offset + result.size() * windowSize, result.size() * windowSize + windowSize + offset)); // add window to the results if it is valid if (assessWindow(window)) { result.add(window); } else { // if the current set is large enough start a greedy approach by using the offset if (currentSet.size() - result.size() * windowSize > 5 * windowSize) { offset++; } else { break; } } if (result.size() > 0 && offset > 0) { break; } } // remove the items in the selected windows from the history for (List<CVParticle> window : result) { for (CVParticle window1 : window) { history.removeFromHistory(window1); } } return result; } /** * Checks if the provided window fits the required windowSize and * sequenceDelta criteria * * @param window * @return */ private boolean assessWindow(List<CVParticle> window) { if (window.size() != windowSize) { return false; } long previous = window.get(0).getSequenceNr(); for (int i = 1; i < window.size(); i++) { if (window.get(i).getSequenceNr() - previous != sequenceDelta) { return false; } previous = window.get(i).getSequenceNr(); } return true; } }
Shell
UTF-8
730
3.46875
3
[]
no_license
#!/bin/bash # Author: Rajat Sachdeva # Date Created: 22/06/2019 # Description: This script will add system inventory to database file # Date Modified: 22/06/2019 clear echo echo printing database cat database echo echo Please enter host-name: read host echo # quietly grep grep -q $host ./database if [ $? -eq 0 ] then echo ERROR -- Hostname $host already exists echo exit 0 fi echo Please enter IP address : read IP echo grep -q $IP ./database if [ $? -eq 0 ] then echo ERROR -- IP $IP already exists echo exit 0 fi echo Please enter Description: read description echo echo $host $IP $description >> ./database echo The provided record has been added echo echo printing database cat database echo
Java
UTF-8
280
2.34375
2
[]
no_license
package Example1; // Интерфейс DisplayElement содержит всего один метод display(), // который вызывается для отображения визуального элемента public interface DisplayElement { void display(); }
Java
UTF-8
386
2.109375
2
[]
no_license
package dbg.electronics.robodrv.mcu; public enum AdcChannel implements CodifierAware { POWER_VOLTAGE(0), POWER_CURRENT(1), MCU_VOLTAGE(2), POSITION(3); AdcChannel(int code) { this.code = code; } public int getCode() { return code; } private int code; @Override public int toCode() { return getCode(); } }
Python
UTF-8
8,663
3.140625
3
[]
no_license
import csv import numpy import scipy import matplotlib.pyplot as plt import seaborn from sklearn import preprocessing from sklearn import neighbors from sklearn.cross_validation import train_test_split from sklearn import metrics import knnplots from sklearn.naive_bayes import GaussianNB from sklearn import cross_validation from sklearn.grid_search import GridSearchCV print "Good to go, all packages installed ok, ready to code." fileName = "wdbc.csv" fileOpen = open(fileName, "rU") csvData = csv.reader(fileOpen) # read in the CSV file dataList = list(csvData) # convert to a list # print dataList[0:2] # print first two rows of data dataArray = numpy.array(dataList) # convert to numpy array # print dataArray X = dataArray[:,2:32].astype(float) # select features as data from full dataArray and convert to floats y = dataArray[:,1] # set labels to second column (B/M) - the diagnosis print "X dimensions: ", X.shape print "y dimensions: ", y.shape yFreq = scipy.stats.itemfreq(y) print yFreq # plot bar chart of frequencies #plt.bar(left = 0, height = int(yFreq[0][1]), color = 'red') #plt.bar(left = 1, height = int(yFreq[1][1])) #plt.show() # convert the M/B labels to 1 and 0 for later use le = preprocessing.LabelEncoder() #Fit numerical values to the categorical data. le.fit(y) #Transform the labels into numerical correspondents. yTransformed = le.transform(y) # print the original and transformed arrays to check print y print yTransformed # construct a correlation matrix between columns of X (rowvar=0) correlationMatrix = numpy.corrcoef(X, rowvar=0) # plot a heat map of the correlations #fig, ax = plt.subplots() #heatmap = ax.pcolor(correlationMatrix, cmap = plt.cm.RdBu) #plt.show() # plot a scatter plot of the first two columns (features) - tumor radius and perimeter # colour (c) according to y labels (B and M) #plt.scatter(x = X[:,0], y = X[:,1], c=y) #plt.show() # plot matrix of scatter plots for features - histograms for self/self def scatter_plot(X,y): # set the figure size (scales by the size of the X input array and a constant) plt.figure(figsize = (2*X.shape[1],2*X.shape[1])) # loop over every pair of columns for i in range(X.shape[1]): for j in range(X.shape[1]): # create a subplot for the current pair plt.subplot(X.shape[1],X.shape[1],i+1+j*X.shape[1]) # if self/self (i==j) plot two histograms according to y classification (B or M) # and colour accordingly if i == j: plt.hist(X[:, i][y=="M"], alpha = 0.4, color = 'm', bins = numpy.linspace(min(X[:, i]),max(X[:, i]),30)) plt.hist(X[:, i][y=="B"], alpha = 0.4, color = 'b', bins = numpy.linspace(min(X[:, i]),max(X[:, i]),30)) plt.xlabel(i) # otherwise plot a scatter plot as before to look at correlation else: plt.gca().scatter(X[:, i], X[:, j],c=y, alpha = 0.4) plt.xlabel(i) plt.ylabel(j) plt.gca().set_xticks([]) plt.gca().set_yticks([]) plt.tight_layout() plt.show() # pass in a limited slice of the X array - all rows and just first 5 columns (features) # y is the classification array (B/M) - why not use yTransformed? scatter_plot(X[:, :5], y) # KNN algorithm # TESTING nbrs = neighbors.NearestNeighbors(n_neighbors=3, algorithm="ball_tree").fit(X) #nbrs = neighbors.NearestNeighbors(n_neighbors=3, algorithm="kd_tree").fit(X) distances, indices = nbrs.kneighbors(X) print indices[:5] print distances[:5] # Applying to breast cancer data # using the transformed label array (0 = B, 1 = M) # Predict/classify using the 3 nearest neighbors # (weighting is uniform/default) knnK3 = neighbors.KNeighborsClassifier(n_neighbors=3) knnK3 = knnK3.fit(X, yTransformed) predictedK3 = knnK3.predict(X) # Predict/classify using the 15 nearest neighbors # (weighting is uniform/default) knnK15 = neighbors.KNeighborsClassifier(n_neighbors=15) knnK15 = knnK15.fit(X, yTransformed) predictedK15 = knnK15.predict(X) # Check to see how many points are classified differently using different n_neighbors nonAgreement = len(predictedK3[predictedK3 != predictedK15]) print "Number of discrepancies (3 vs 15 nearest neighbours): ", nonAgreement # weight using the 'distance' method - ascribes more importance to neighbours that are very close # Predict/classify using the 3 nearest neighbors # (weighting is distance) knnWD = neighbors.KNeighborsClassifier(n_neighbors=3, weights='distance') knnWD = knnWD.fit(X, yTransformed) predictedWD = knnWD.predict(X) # Check to see how many points are classified differently using the uniform weighting above nonAgreement = len(predictedK3[predictedK3 != predictedWD]) print "Number of discrepancies (uniform vs distance weights): ", nonAgreement # Now need to split data into training and test sets so we can judge the accuracy of the predictions # By default, 25% of the data goes in the test set XTrain, XTest, yTrain, yTest = train_test_split(X, yTransformed) print "XTrain dimensions: ", XTrain.shape print "yTrain dimensions: ", yTrain.shape print "XTest dimensions: ", XTest.shape print "yTest dimensions: ", yTest.shape # Apply the nearest neighbours classifier to the training set (XTrain) to train a predictor # yTrain contains the correct labels knn = neighbors.KNeighborsClassifier(n_neighbors=3) knn.fit(XTrain,yTrain) # Apply this fit to predict the classification of the test set (XTest) predicted = knn.predict(XTest) # Construct the confusion matrix by comparing the prediction to the correct labels in yTest # this is tp, fn # fp, fn mat = metrics.confusion_matrix(yTest, predicted) print mat # Print some validation metrics print metrics.classification_report(yTest, predicted) print "accuracy: ", metrics.accuracy_score(yTest, predicted) # Plot the accuracy score for a range (1-310?) of n_neighbors using both uniform and distance weights # knnplots has been given to us - look at how it works! #knnplots.plotaccuracy(XTrain, yTrain, XTest, yTest, 310) # Plot the decision boundaries for different models #knnplots.decisionplot(XTrain, yTrain, n_neighbors=3, weights="uniform") #knnplots.decisionplot(XTrain, yTrain, n_neighbors=15, weights="uniform") #knnplots.decisionplot(XTrain, yTrain, n_neighbors=3, weights="distance") #knnplots.decisionplot(XTrain, yTrain, n_neighbors=15, weights="distance") # Cross validate result using k-fold method # This splits the training data in XTrain 5 times, the validation scores are then given as the mean # n_neighbors = 3 knn3scores = cross_validation.cross_val_score(knnK3, XTrain, yTrain, cv = 5) print knn3scores print "Mean of scores KNN3", knn3scores.mean() print "SD of scores KNN3", knn3scores.std() # n_neighbors = 15 knn15scores = cross_validation.cross_val_score(knnK15, XTrain, yTrain, cv = 5) print knn15scores print "Mean of scores KNN15", knn15scores.mean() print "SD of scores KNN15", knn15scores.std() # looking how accuracy means and standard deviations vary with number of folds, k # lists to hold results meansKNNK3 = [] sdsKNNK3 = [] meansKNNK15 = [] sdsKNNK15 = [] # consider 2 to 20 folds ks = range(2,21) # calculate validation scores for each ks for k in ks: knn3scores = cross_validation.cross_val_score(knnK3, XTrain, yTrain, cv = k) knn15scores = cross_validation.cross_val_score(knnK15, XTrain, yTrain, cv = k) # append results to lists meansKNNK3.append(knn3scores.mean()) sdsKNNK3.append(knn3scores.std()) meansKNNK15.append(knn3scores.mean()) sdsKNNK15.append(knn3scores.std()) # plot the mean accuracy for KNN3 and KNN15 as number of folds varies #plt.plot(ks, meansKNNK3, label="KNN3 mean accuracy", color="purple") #plt.plot(ks, meansKNNK15, label="KNN15 mean accuracy", color="yellow") #plt.legend(loc=3) #plt.ylim(0.5, 1) #plt.title("Accuracy means with increasing number of folds K") #plt.show() # plot the standard deviation... # plot the results #plt.plot(ks, sdsKNNK3, label="KNN3 sd accuracy", color="purple") #plt.plot(ks, sdsKNNK15, label="KNN15 sd accuracy", color="yellow") #plt.legend(loc=3) #plt.ylim(0, 0.1) #plt.title("Accuracy standard deviations with increasing number of folds K") #plt.show() # Tuning parameters (number of neighbors and weight method) using a grid search parameters = [{'n_neighbors':[1,3,5,10,50,100], 'weights':['uniform','distance']}] clf = GridSearchCV(neighbors.KNeighborsClassifier(), parameters, cv=10, scoring="f1") clf.fit(XTrain, yTrain) # print best parameter set print "Best parameter set found: " print clf.best_estimator_
Java
UTF-8
2,470
2.921875
3
[]
no_license
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class Lottery { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for (int k = 0; k < t; k++) { String expr = in.readLine(); ArrayList<Integer> aslocs = new ArrayList<>(); ArrayList<Integer> mlocs = new ArrayList<>(); int n = expr.length(); for (int i = 0; i < n; i++) { char temp = expr.charAt(i); if ((temp < '0' || temp > '9') && temp != ' ') { if (temp == 'X') mlocs.add(i); else aslocs.add(i); } } ArrayList<Integer> oins = new ArrayList<>(); ArrayList<Integer> cins = new ArrayList<>(); int e = aslocs.isEmpty() ? n : aslocs.get(0); for (int i = 0; i < mlocs.size()-1 && mlocs.get(i) < e; i++) { oins.add(0); cins.add(Math.min(mlocs.get(i+1), e)-1); } int m = aslocs.size(); for (int i = 0; i < m; i++) { if (i != 0) { oins.add(0); cins.add(aslocs.get(i) - 1); } int fin = i == m-1 ? n+1 : aslocs.get(i+1); for (int j = aslocs.get(i)+1; j < fin-1; j++) { if (expr.charAt(j) == 'X') { int index = mlocs.indexOf(j); oins.add(aslocs.get(i)+2); cins.add(index != mlocs.size() - 1 && mlocs.get(index+1) < fin ? mlocs.get(index+1)-1 : fin-1); } } } ArrayList<Character> ans = new ArrayList<>(); for (int i = 0; i < n; i++) ans.add(expr.charAt(i)); int[] displacement = new int[1000]; for (int i = 0; i < oins.size(); i++) { ans.add(oins.get(i) + displacement[oins.get(i)], '('); for (int j = oins.get(i); j < ans.size(); j++) displacement[j]++; ans.add(cins.get(i) + displacement[cins.get(i)], ')'); for (int j = cins.get(i); j < ans.size(); j++) displacement[j]++; } for (char i : ans ) System.out.print(i); System.out.println(); } } }
JavaScript
UTF-8
3,794
3.140625
3
[]
no_license
/* --- SETUP VIEW --- This view fills the content section of the page with setup-related fields. Once the user starts the game, it will create a gametype object (currently only one exists) and attempt to start it. If it succeeds, this view creates a game-view and then destroys itself. If not, an error is displayed. FUNCTIONS start() - attempts to start a game with whatever settings the user has selected */ define(['jquery', 'backbone', 'js/models/game.js', 'js/views/game/game-view.js', 'js/helpers/gametypes.js', 'text!templates/setup.html'], function ($, Backbone, Game, GameView, gametypes, setupTemplate) { return Backbone.View.extend({ tagName: 'div', id: 'setup', initialize: function (options) { //get link back to mainView variable from the initialization options this.mainView = options.mainView; }, events: { 'change #playerList li': 'changePlayer', 'click button[name=start]': 'start' }, render: function () { //render sets these values to defaults. call once. this.$el.html(setupTemplate); }, changePlayer: function (event) { //add or remove a player-name input field var $target = $(event.target); if ($target.attr('value') !== '') { if ($('#playerList li:last input').attr('value') !== '') { $('#playerList').append('<li><input type="text" value="" /></li>'); } } else if (!$target.is('#playerList li:last')) { $target.parent().remove(); } }, start: function () { //reads values from the page and creates a new gametype-model with them //can be called several times if earlier start-attempts fail //get boardsize from page var boardSize = parseInt($('#boardSize').attr('value'), 10), i, name, playerNames = [], game, view, result, options; //get players from page for (i = $('#playerList li').length; i--;) { //extract a name name = $('#playerList li:eq(' + i + ') input').attr('value'); if (typeof name === 'string' && name !== '') { //if not an empty field, add a new player with this name playerNames.push(name); } } //create object to pass to game constructor options = { playerNames: playerNames, boardSize: boardSize }; //check validity of options by passing to gametype function directly //creation of Game object is unnecessary result = gametypes['default'].type.validateStart(options); //check if validation was succesfull if (result !== true) this.mainView.postMessage(result); else { //create new game game = new Game({}, { type: gametypes['default'].type }); //try to start result = game.start(options); //the same validation is performed, so this should be true if (result === true) { view = new GameView({ model: game, type: gametypes['default'].view, mainView: this.mainView }); //hand over content area to new view this.mainView.changeContentView(view); } else { throw new Error("Setup View: Start validations not in agreement"); } } } }); });
Java
UTF-8
669
1.71875
2
[]
no_license
package com.czz.hwy.dao.mission.impl.app; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.czz.hwy.base.BaseDaoImpl; import com.czz.hwy.bean.mission.app.ReportDutyApp; import com.czz.hwy.dao.mission.app.ReportDutyAppDao; /** * 监察举报考核项目责任人的dao接口实现类,用于app接口 * 功能描述 * @author 张咏雪 * @createDate 2016-12-22 */ @Repository public class ReportDutyDaoImpl extends BaseDaoImpl<ReportDutyApp> implements ReportDutyAppDao { @Autowired private SqlSessionTemplate sqlSessionTemplate; }
Markdown
UTF-8
751
2.59375
3
[ "MIT" ]
permissive
## Difference between PFN and PFN-nested In PFN-nested, we use two RE units for head-to-head and tail-to-tail prediction. There is only one RE unit in PFN model and it's for head-to-head prediction. ## Design Choice The head-to-head RE unit takes relation feature as the main feature, shared feature as auxiliary feature. The tail-to-tail RE unit takes shared feature as the main feature, relation feature as auxiliary feature. ## Justification Shared feature act as a mutual section for NER and RE. By **sharing** NER information (head-to-tail) and head-to-head RE information, we should be able to get the tail-to-tail RE information. This sharing mechanism is achieved by using shared feature as the main feature in the tail-to-tail RE unit.
Python
UTF-8
858
3.90625
4
[]
no_license
# Say you have an array for which the ith element is the price of a given stock on day i. # # If you were only permitted to complete at most one transaction (i.e., buy one and sell one share # of the stock), design an algorithm to find the maximum profit. # # Note that you cannot sell a stock before you buy one. import sys class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ min_price_so_far = sys.maxsize max_profit = 0 for price in prices: min_price_so_far = min(price, min_price_so_far) max_profit = max(max_profit, (price - min_price_so_far)) return max_profit my_sol = Solution() nums = [7,1,5,3,6,4] print(my_sol.maxProfit(nums)) nums = [7,6,4,3,1] print(my_sol.maxProfit(nums))
Java
UTF-8
1,190
2.328125
2
[]
no_license
package com.tangshengbo.service; /** * Created by Tangshengbo on 2017/10/30. * 全局异常处理,捕获所有Controller中抛出的异常 */ import com.tangshengbo.core.ResponseGenerator; import com.tangshengbo.core.ResponseMessage; import com.tangshengbo.exception.ServiceException; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); //处理自定义的异常 @ExceptionHandler(ServiceException.class) public ResponseMessage customHandler(ServiceException e) { return ResponseGenerator.genFailResult(e.getMessage()); } //其他未处理的异常 @ExceptionHandler(Exception.class) public ResponseMessage exceptionHandler(Exception e) { logger.error("{}", ExceptionUtils.getStackTrace(e)); return ResponseGenerator.genServerErrorResult(ExceptionUtils.getMessage(e)); } }
C
UTF-8
837
4.3125
4
[]
no_license
/* Takes an integer input and outputs the number in binary form. Only meant to convert positive integers. */ #include <stdio.h> void printBinary(int decimalNum); void clearKeyboardBuffer(void); int main(int argc, char *argv[]) { int decimalNum; printf("Enter an integer: "); scanf("%d", &decimalNum); clearKeyboardBuffer(); printf("\n"); if (decimalNum == 0) { printf("%d", decimalNum); } else { printf("%d In binary: ", decimalNum); printBinary(decimalNum); } printf("\n"); return 0; } void clearKeyboardBuffer(void) { char ch; scanf("%c", &ch); while (ch != '\n' && ch != '\0') { scanf("%c", &ch); } } void printBinary(int decimalNum) { if (decimalNum > 0) { printBinary(decimalNum / 2); printf("%d", decimalNum % 2); return; } }
Python
UTF-8
568
2.859375
3
[]
no_license
from api.database.db_helper import DBHelper class BaseDao: __db = None def __init__(self): self.__db = DBHelper() def get_users(self): return self.__db.execute_query('SELECT * FROM users') def get_user_by_id(self, id): return self.__db.execute_query(f'SELECT * FROM users WHERE id = {id}') def delete_user_by_id(self, id): return self.__db.execute_without_response(f'DELETE FROM users WHERE id = {id}') if __name__ == "__main__": dao = BaseDao() a = dao.get_users() for i in a: print(i)
Markdown
UTF-8
3,541
3.25
3
[]
no_license
# Fillactive-Community-App Build a community that reaches out and encourages teenage girls aged 12-17 to change their mindset about physical activity and be able to better their health by staying active and healthy as a long term goal with the help of technology and joining Fillactive ## Fillactive Community App guidelines To login: - By default the first page you see will be the login page - To login, you'll have to use one of the following credentials (since this is a prototype, we've not implemented extensive authentication or security controls; we've focused on presentational aspects) username: (one of the following, based on which role you want to access the site as) - student@test.com - teacher@test.com password: any value is acceptable (not implemented yet) Once you've logged in, you'll be taken to the 'Feed' page. ### Website architecture: Login | |------- Feed |------- Events |------- Wellness Hub |------- Manage (not implemented yet) ### Access The actions and features that are visible or available to you will depend on which role (`user_role`) you've logged in with. Teachers and Fillactive ambassadors will have additional authority and access in most cases, like to add an event, or manage their groups. ### Layout **Feed** - Feed page will display primarily three types of posts - commons posts, recognition posts and challenges - Eventually, we planned to provide a view where the user can switch between the types of post they want to view at any given time - Privacy can be managed by using *tags* which the author of the post can add while creating the post to manage who the post will be visible to (ex: friends, entire group, entire school etc.) - Ability to like the posts is present, but without any number count, since the purpose is to recognize not compete **Events** - Displays a list of upcoming events - User has the ability to interact and provide vital information like whether they are going or not, or haven't made a decision yet - Ability for the users to add events from the platform directly to their Google calendar - Ability for the user to provide feedback on why they might not go **Wellness Hub** - Wellness and mindfulness relates content curated by Fillactive partner teachers and ambassadors - Ability for the user to subscribe to receive updates on new posts related to wellness and mindfulness **Manage** (not implements yet) - Page to manage user profile settings (update name, email, password, etc.) - For teachers - additional ability to manage their group(s) and students ### Technical details **stack:** - Run environment: Nodejs - Web framework: Express - View engine: EJS - Languages: JavaScript (ES6), HTML/EJS, CSS **Project code structure:** We've followed the Express app project guidelines to structure our code in a modular and efficient way. parent directory | |----------- public | |------ images | |------ stylesheets |----------- data | |------ (all data files) |----------- routes | |------ index.js (primary routes) | |------ users.js (user/access management routes) |----------- views | |------ (all project view files) | |----------- Other files (config files required for development) ### Team members (creators) Evan Freayh, Carina Tam, JiaQi Zhao, Tyler Watson, Pranav Kural, Robert Joseph George, Tanyaradzwa Gozhora **Morgan Stanley Mentor**: Pascal Forget
Python
UTF-8
5,861
2.515625
3
[]
no_license
""" Versioning deployment. Installs the versioning into your (python) project. """ import os, sys import click from flowtool.style import colors, echo, debug from flowtool.files import find_parent_containing, find_subdirs_containing, check_file, append_to_file, make_executable from flowtool.files import cd from flowtool.ui import ask_choice, abort import filecmp DEFAULT_VERSION_CONFIG = ''' [versioning] source_versionfile={detected_location} #build_versionfile={guessed_location} tag_prefix={tag_prefix} ''' INIT_PY_SNIPPET = ''' from ._version import get_version __version__ = get_version() ''' GITATTRIBUTES_ADDON = ''' # creates a pseudo-version if exported via 'git archive' {} export-subst ''' @click.command() @click.argument('path', type=click.Path(), default=os.getcwd()) @click.option('-n', '--noop', is_flag=True, help='Do not do anything. Mainly for testing purposes.') @click.option( '-y', '--yes', is_flag=True, default=False, help="Update all components without asking." ) def init_versioning(path=os.getcwd(), yes=None, noop=None): """Initialize or update versioning.""" git_dir = find_parent_containing('.git', path, check='isdir') if git_dir: debug.white('git root is', git_dir) else: abort('%s is not under git version control.' % path) setup_dir = find_parent_containing('setup.py', path, check='isfile') echo.white('setup.py found:', colors.cyan(str(setup_dir))) if not setup_dir: abort(' '.join([ 'Please navigate or point me to a directory containing a', colors.white('setup.py'), colors.yellow('file.'), ])) with cd(path): from flowtool_versioning.dropins.version import __file__ as versionfile_source if versionfile_source.endswith('.pyc'): versionfile_source = versionfile_source[:-1] # deploy _version.py versionfile = None modules = find_subdirs_containing('__init__.py', setup_dir) if modules: if (yes and len(modules) == 1) or noop: chosen = modules[0] else: modules.append(None) chosen = ask_choice( heading='Searched for __init__.py:', choices=modules, question='Include _version.py into which module?', ) versionfile = None if chosen is not None: versionfile = os.path.join(chosen, '_version.py') init_py = os.path.join(chosen, '__init__.py') if not check_file(init_py, '__version__') and click.confirm('Update __init__.py?', default=True): noop or append_to_file(init_py, INIT_PY_SNIPPET) if versionfile is None and click.confirm('Enter versionfile manually?', default=True): versionfile = click.prompt('Deploy versionfile to') if versionfile is not None: if os.path.isfile(versionfile) and filecmp.cmp(versionfile, versionfile_source): echo.green('%s is up to date.' % os.path.basename(versionfile)) else: echo.bold('Updating: %s' % versionfile) with open(versionfile_source, 'r') as src, open(versionfile, 'w') as dest: noop or dest.write(src.read()) # deploy .gitattributes gitattributes = os.path.join(setup_dir, '.gitattributes') rel_path = versionfile[len(setup_dir)+1:] if not check_file(gitattributes, rel_path + ' export-subst'): noop or append_to_file(gitattributes, GITATTRIBUTES_ADDON.format(rel_path)) # setup.cfg (needed for cmdclass import!) setup_cfg = os.path.join(setup_dir, 'setup.cfg') echo.white('setup.cfg:', colors.cyan(setup_cfg)) if check_file(setup_cfg, '[versioning]'): echo.green('Versioning config detected in setup.cfg.') else: echo.cyan('There seems to be no versioning config in setup.cfg') if yes or click.confirm( colors.bold('Shall I add a default [versioning] section to setup.cfg?'), default=True): version_config = DEFAULT_VERSION_CONFIG if versionfile: source_versionfile = versionfile[len(setup_dir)+1:] if versionfile.startswith('src/'): build_versionfile = source_versionfile[4:] else: build_versionfile = source_versionfile version_config = version_config.format( detected_location=source_versionfile, guessed_location=build_versionfile, tag_prefix=click.prompt('Use which tag prefix?'), ) noop or append_to_file(setup_cfg, version_config) with cd(path): from flowtool_versioning.dropins.cmdclass import __file__ as setupextension_source if setupextension_source.endswith('.pyc'): setupextension_source = setupextension_source[:-1] # deploy versioning.py setup_extension = os.path.join(setup_dir, 'versioning.py') if os.path.isfile(setup_extension) and filecmp.cmp(setup_extension, setupextension_source): echo.green('%s is up to date.' % os.path.basename(setup_extension)) else: echo.bold('Updating: %s' % setup_extension) with open(setupextension_source, 'r') as src, open(setup_extension, 'w') as dest: noop or dest.write(src.read()) noop or make_executable(setup_extension) echo.green('Installation / Update complete.') echo.cyan('If this is the initial installation, you can now go ahead and add something like:') echo.white(''' from versioning import get_cmdclass, get_version if __name__ == '__main__': setup( ... version=get_version(), cmdclass=get_cmdclass(), ... ) ''') echo.cyan("to your setup.py, and don't forget to edit setup.cfg also.") echo.magenta('Enjoy a beautiful day.')
Python
UTF-8
498
3.25
3
[]
no_license
#!/usr/bin/env python from collections import Counter class SummableDict(dict): def __iadd__(self, other): for key, value in other.items(): if key in self: self[key] += value else: self[key] = value return self with open("input") as fd: seen = SummableDict() for line in fd: uid = line.strip() counts = {k: 1 for k in Counter(uid).values()} seen += counts print(seen[2] * seen[3])
Python
UTF-8
630
2.5625
3
[]
no_license
from django.db import models # Create your models here. # class Menu(models.Model): # Nonveg = models.CharField(max_length=30) # Veg = models.CharField(max_length=30) # pickles = models.CharField(max_length=35) # price = models.CharField(max_length=5, default="") class NonVeg(models.Model): item = models.CharField(max_length=20) quantity = models.CharField(max_length=5) price = models.CharField(max_length=5) def __str__(self): return self.item +'-'+ self.price class Veg(models.Model): item = models.CharField(max_length=20) quantity = models.CharField(max_length=5) price = models.CharField(max_length=5)
C#
UTF-8
2,306
2.96875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model.Models; using Model.Models.Exceptions; namespace Persistencia.Persistence { public class RepositorioTriagem { private static List<Triagem> listaTriagens; static RepositorioTriagem() { listaTriagens = new List<Triagem>(); } public Triagem Adicionar(Triagem triagem) { try { triagem.IdTriagem = listaTriagens.Count + 1; listaTriagens.Add(triagem); return triagem; } catch (Exception e) { throw new PersistenciaException("Não foi possivél completar a ação", e); } } public void Editar(Triagem triagem) { try { int posicao = listaTriagens.FindIndex(e => e.IdTriagem == triagem.IdTriagem); listaTriagens[posicao] = triagem; } catch (Exception e) { throw new PersistenciaException("Não foi possivél completar a ação", e); } } public void Remover(Triagem triagem) { try { int posicao = listaTriagens.FindIndex(e => e.IdTriagem == triagem.IdTriagem); listaTriagens.RemoveAt(posicao); } catch (Exception e) { throw new PersistenciaException("Não foi possivél completar a ação", e); } } public Triagem Obter(Func<Triagem, bool> where) { try { return listaTriagens.Where(where).FirstOrDefault(); } catch (Exception e) { throw new PersistenciaException("Não foi possivél completar a ação", e); } } public List<Triagem> ObterTodos() { try { return listaTriagens; } catch (Exception e) { throw new PersistenciaException("Não foi possivél completar a ação", e); } } } }
C++
UTF-8
1,021
3.03125
3
[]
no_license
#ifndef __BINNINGHELPER_C__ #define __BINNINGHELPER_C__ #include "../../meta/stl.C" struct binningstep { double fMaximum; double fBinsize; }; class binninghelper { public: binninghelper() = default; binninghelper(double minimum, std::vector<binningstep> steps) : fMinimum(minimum), fSteps(steps) {} ~binninghelper() = default; void SetMinimum(double minimum) { fMinimum = minimum; } void AddStep(double maximum, double stepsize) { fSteps.push_back({maximum, stepsize}); } std::vector<double> CreateCombinedBinning() const { std::vector<double> binning; double current = fMinimum; binning.emplace_back(current); for(const auto [max, stepsize] : fSteps ) { while(current < max) { current += stepsize; binning.emplace_back(current); } } return binning; } public: double fMinimum; std::vector<binningstep> fSteps; }; #endif //__BINNINGHELPER_C__
TypeScript
UTF-8
1,634
2.703125
3
[]
no_license
import { isString, cloneDeep, merge } from 'lodash'; import DC from 'src/types'; import { getConfig } from '../../../config'; export /** * 获取在配置中自定义的图表配置,并支持返回的数据中携带图表配置 * * @param {DC.StaticData} data * @param {DC.ChartConfig} config * @returns {object} */ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions const getCustomOption = (data: DC.StaticData = {} as DC.StaticData, config: DC.ChartConfig = {}): object => { // 优先级:customOptionFn > option let customOption; let { optionFn: customOptionFn } = config; const { option } = config; if (customOptionFn) { if (isString(customOptionFn)) { // 取之前注册好的 customOptionFn customOptionFn = getConfig(['chartOptionFn', customOptionFn]) as DC.OptionFn; // 未注册 if (!customOptionFn) { customOptionFn = (d: any) => d; // eslint-disable-next-line no-console console.warn(`optionFn \`${customOptionFn}\` not registered yet`); } } customOption = customOptionFn(data, config.optionExtra); } else if (option) { customOption = option; if (isString(customOption)) { customOption = getConfig(['chartOption', customOption]); if (!customOption) { customOption = {}; // eslint-disable-next-line no-console console.warn(`customOption \`${customOption}\` not registered yet`); } } customOption = cloneDeep(customOption) as any; } if (data.extraOption) { customOption = merge(customOption, data.extraOption); } return customOption || {}; };