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
Java
UTF-8
1,097
3.25
3
[]
no_license
package CS2110Final; public class Village { public static int VILLAGE_ID_SETTER = 1; public int id; public String name; public LinkedList<Gnome> allGnomes; public LinkedList<Village> adj_villages; public Village() { // TODO Auto-generated constructor stub this.id = this.VILLAGE_ID_SETTER++; this.name = ""; this.allGnomes = new LinkedList<Gnome>(); this.adj_villages = new LinkedList<Village>(); } public Village(String name) { this.id = this.VILLAGE_ID_SETTER++; this.name = name; this.allGnomes = new LinkedList<Gnome>(); this.adj_villages = new LinkedList<Village>(); } public void addGnomes(Gnome g) { this.allGnomes.join(g); } public Gnome deleteGnome(Gnome g) { Gnome temp = this.allGnomes.delete(g); return temp; } public void addAdjVillage(Village adj) { this.adj_villages.join(adj); } public void printGnomes() { Node<Gnome> temp = this.allGnomes.head; while (temp != null) { System.out.println(temp.getData()); temp = temp.getNext(); } } public String toString() { return "Name: " + this.name + " Id: " + this.id; } }
JavaScript
UTF-8
461
3.328125
3
[]
no_license
Array.prototype.removeItem = function(value){ var removePos = []; console.log(this); for(var i in this){ if(this[i] === value) { removePos.unshift(i); } } for(var i = 0; i < removePos.length; i++) { this.splice(parseInt(removePos[i]), 1); } console.log(this); } var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, '1']; arr.removeItem(1); var arr = ['hi', 'bye', 'hello' ]; arr.removeItem('bye');
Java
UTF-8
1,482
3.640625
4
[]
no_license
import java.util.Date; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; /** * Exmaple based on https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html * @author graham * */ public class LambdaOracleExample { /** * Print persons older than <code>age</code>. * @param roster * @param age */ static void printPersonsOlderThan(List<Person> roster, int age) { for (Person p : roster) { if (p.getAge() >= age) { p.printPerson(); } } } static void processPersonsPreJava8( List<Person> roster, Predicate<Person> tester, Consumer<Person> block) { for (Person p : roster) { if (tester.test(p)) { block.accept(p); } } } /* * * processPersons( roster, p -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25, p -> p.printPerson() ); */ /** * Using the stream API. * @param persons * @param action * @param predicate */ static void processPersons(List<Person> persons, Consumer<Person> action, Predicate<Person> predicate) { persons.stream().filter(predicate).forEach(action); } } class Person { public enum Sex { MALE, FEMALE } int age; String name; Date birthday; Sex gender; String emailAddress; public int getAge() { return age; } public void printPerson() { System.out.println(name); } }
Python
UTF-8
228
2.625
3
[]
no_license
from Solution import * if __name__ == '__main__': solution = Solution() print solution.combinationSum3(2, 9) print solution.combinationSum3(3, 7) print solution.combinationSum3(3, 9) # print solution.combinationSum3(8, 36)
Python
UTF-8
1,307
3.5625
4
[]
no_license
# ============================================================================= # ============================================================================= # # ##### Scope and user-defined functions # # # # # # # Global vs Local Scope # # def square(value): # # """Returns the square of a number""" # # new_val = value ** 2 # # return new_val # # # # print(square(3)) # # # # # print(new_val) # # # Throws error because can't var isn't global scope # # # # # # # # # Global vs Local Scope(2) # # new_vals = 10 # # # # def squares(values): # # """Returns the square of a number""" # # new_vals = values ** 2 # # return new_vals # # # # print(squares(3)) # prints 9 because applying within fxn vars # # # # print(new_vals) # prints 10 because we defined new_vals in global scope # # # # # # # Global vs Local Scope(3) # # new_valss = 10 # # # # def squaress(valuess): # # """Returns the square of a number""" # # global new_valss # # new_valss = new_valss ** 2 # # return new_valss # # # # print(squaress(3)) # # # # print(new_valss) # Responds to global new_valss iINSIDE fxn # ============================================================================= # # =============================================================================
Java
UTF-8
961
2.375
2
[]
no_license
package com.example.demo.service; import com.example.demo.eneities.Student; import org.springframework.stereotype.Service; import java.util.List; @Service public interface StudentService { // 通过用户id来判断数据库中是否存在该用户 public boolean checkUser(String userID); // 通过用户id来查询该用户的所有信息 public Student getSerialNum(String userID); // 更新用户的刷题序号 public boolean updateSerialNum(Student student); // 根据用户id更新其刷题总量 public boolean updateAnswerSum(Student student); // 根据用户id更新其总的正确题量 public boolean updateAnsRiSum(Student student); // 根据用户id更新quesserialA。quesserialB,quesserialC public boolean updateQuesserial(Student student); // 更新全部用信息 public boolean updUser(Student student); //获取所有用户信息 public List<Student> getAll(); }
Ruby
UTF-8
962
2.625
3
[]
no_license
module User::Base ALL_ATTRIBUTES = User::Update::ATTRIBUTES | User::Create::ATTRIBUTES def self.included(base) base.include ActiveModel::Model base.attr_accessor :user, :success base.attr_accessor *base::ATTRIBUTES base.validates_presence_of base::ATTRIBUTES base.include InstanceMethods end module InstanceMethods def initialize(attributes, user = User.new) self.user = user super(attributes.slice(*self.class::ATTRIBUTES)) end def save # Valid will setup the Form object errors if valid? persist! self.success = true else self.success = false end rescue ActiveRecord::RecordInvalid => e self.errors.add(:base, e.message) self.success = false end private def persist! user.update!(record_attributes) end def record_attributes self.class::ATTRIBUTES.map { |attr| [attr, send(attr)] }.to_h end end end
Markdown
UTF-8
1,227
2.828125
3
[ "MIT" ]
permissive
The approach of training sequence models using supervised learning and next-step prediction suffers from known failure modes. For example, it is notoriously diffi- cult to ensure multi-step generated sequences have coherent global structure. We propose a novel sequence-learning approach in which we use a pre-trained Recurrent Neural Network (RNN) to supply part of the reward value in a Reinforcement Learning (RL) model. Thus, we can refine a sequence predictor by optimizing for some imposed reward functions, while maintaining good predictive properties learned from data. We propose efficient ways to solve this by augmenting deep Q-learning with a cross-entropy reward and deriving novel off-policy methods for RNNs from KL control. We explore the usefulness of our approach in the context of music generation. An LSTM is trained on a large corpus of songs to predict the next note in a musical sequence. This Note-RNN is then refined using our method and rules of music theory. We show that by combining maximum likelihood (ML) and RL in this way, we can not only produce more pleasing melodies, but significantly reduce unwanted behaviors and failure modes of the RNN, while maintaining information learned from data.
C
UTF-8
4,052
3.125
3
[ "MIT" ]
permissive
/** * Terminal display control. */ #include <stddef.h> #include <stdint.h> #include "terminal.h" #include "vga.h" #include "../common/string.h" #include "../common/port.h" #include "../common/debug.h" static uint16_t * const VGA_MEMORY = (uint16_t *) 0xB8000; static const size_t VGA_WIDTH = 80; static const size_t VGA_HEIGHT = 25; /** * Default to black background + light grey foreground. * Foreground color can be customized with '*_color' functions. */ const vga_color_t TERMINAL_DEFAULT_COLOR_BG = VGA_COLOR_BLACK; const vga_color_t TERMINAL_DEFAULT_COLOR_FG = VGA_COLOR_LIGHT_GREY; static uint16_t *terminal_buf; static size_t terminal_row; /** Records current logical cursor pos. */ static size_t terminal_col; /** Enable physical cursor and set thickness to 2. */ static void _enable_cursor() { outb(0x3D4, 0x0A); outb(0x3D5, (inb(0x3D5) & 0xC0) | 14); /** Start at scanline 14. */ outb(0x3D4, 0x0B); outb(0x3D5, (inb(0x3D5) & 0xE0) | 15); /** End at scanline 15. */ } /** Update the actual cursor position on screen. */ static void _update_cursor() { size_t idx = terminal_row * VGA_WIDTH + terminal_col; outb(0x3D4, 0x0F); outb(0x3D5, (uint8_t) (idx & 0xFF)); outb(0x3D4, 0x0E); outb(0x3D5, (uint8_t) ((idx >> 8) & 0xFF)); } /** * Scroll one line up, by replacing line 0-23 with the line below, and clear * the last line. */ static void _scroll_line() { for (size_t y = 0; y < VGA_HEIGHT; ++y) { for (size_t x = 0; x < VGA_WIDTH; ++x) { size_t idx = y * VGA_WIDTH + x; if (y < VGA_HEIGHT - 1) terminal_buf[idx] = terminal_buf[idx + VGA_WIDTH]; else /** Clear the last line. */ terminal_buf[idx] = vga_entry(TERMINAL_DEFAULT_COLOR_BG, TERMINAL_DEFAULT_COLOR_FG, ' '); } } } /** * Put a character at current cursor position with specified foreground color, * then update the logical cursor position. Should consider special symbols. */ static void _putchar_color(char c, vga_color_t fg) { switch (c) { case '\b': /** Backspace. */ if (terminal_col > 0) terminal_col--; break; case '\t': /** Horizontal tab. */ terminal_col += 4; terminal_col -= terminal_col % 4; if (terminal_col == VGA_WIDTH) terminal_col -= 4; break; case '\n': /** Newline (w/ carriage return). */ terminal_row++; terminal_col = 0; break; case '\r': /** Carriage return. */ terminal_col = 0; break; default: ; /** Displayable character. */ size_t idx = terminal_row * VGA_WIDTH + terminal_col; terminal_buf[idx] = vga_entry(TERMINAL_DEFAULT_COLOR_BG, fg, c); if (++terminal_col == VGA_WIDTH) { terminal_row++; terminal_col = 0; } } /** When going beyond the bottom line, scroll up one line. */ if (terminal_row == VGA_HEIGHT) { _scroll_line(); terminal_row--; } } /** Initialize terminal display. */ void terminal_init(void) { terminal_buf = VGA_MEMORY; terminal_row = 0; terminal_col = 0; terminal_clear(); _enable_cursor(); } /** Write a sequence of data. */ void terminal_write(const char *data, size_t size) { terminal_write_color(data, size, TERMINAL_DEFAULT_COLOR_FG); } /** Write a sequence of data with specified foreground color. */ void terminal_write_color(const char *data, size_t size, vga_color_t fg) { for (size_t i = 0; i < size; ++i) _putchar_color(data[i], fg); _update_cursor(); } /** Clear the terminal window by flushing spaces. */ void terminal_clear(void) { for (size_t y = 0; y < VGA_HEIGHT; ++y) { for (size_t x = 0; x < VGA_WIDTH; ++x) { size_t idx = y * VGA_WIDTH + x; terminal_buf[idx] = vga_entry(TERMINAL_DEFAULT_COLOR_BG, TERMINAL_DEFAULT_COLOR_FG, ' '); } } }
Swift
UTF-8
2,270
2.6875
3
[]
no_license
// // ChatTableViewCell+.swift // SocketIODogeChat // // Created by 박성민 on 2021/05/07. // import UIKit extension ChatTableViewCell { override func layoutSubviews() { super.layoutSubviews() if isJoinMessage() { layoutForJoinMessage() } else { messageLabel.font = UIFont(name: "Helvetica", size: 17) messageLabel.textColor = .white let size = messageLabel.sizeThatFits(CGSize(width: 2 * (bounds.size.width / 3), height: .greatestFiniteMagnitude)) messageLabel.frame = CGRect(x: 0, y: 0, width: size.width + 32, height: size.height + 16) if messageSender == .ourself { nameLabel.isHidden = true messageLabel.center = CGPoint(x: bounds.size.width - messageLabel.bounds.size.width/2.0 - 16, y: bounds.size.height/2.0) messageLabel.backgroundColor = UIColor(red: 24 / 255, green: 180 / 255, blue: 128 / 255, alpha: 1.0) } else { nameLabel.isHidden = false nameLabel.sizeToFit() nameLabel.center = CGPoint(x: nameLabel.bounds.size.width / 2.0 + 16 + 4, y: nameLabel.bounds.size.height/2.0 + 4) messageLabel.center = CGPoint(x: messageLabel.bounds.size.width / 2.0 + 16, y: messageLabel.bounds.size.height/2.0 + nameLabel.bounds.size.height + 8) messageLabel.backgroundColor = .lightGray } } messageLabel.layer.cornerRadius = min(messageLabel.bounds.size.height / 2.0, 20) } func layoutForJoinMessage() { messageLabel.font = UIFont.systemFont(ofSize: 10) messageLabel.textColor = .lightGray messageLabel.backgroundColor = UIColor(red: 247 / 255, green: 247 / 255, blue: 247 / 255, alpha: 1.0) let size = messageLabel.sizeThatFits(CGSize(width: 2 * (bounds.size.width / 3), height: .greatestFiniteMagnitude)) messageLabel.frame = CGRect(x: 0, y: 0, width: size.width + 32, height: size.height + 16) messageLabel.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2.0) } func isJoinMessage() -> Bool { if let words = messageLabel.text?.components(separatedBy: " ") { if words.count >= 2 && words[words.count - 2] == "has" && words[words.count - 1] == "joined" { return true } } return false } }
Python
UTF-8
664
2.515625
3
[]
no_license
# 네이버 Datalab 실시간 검색어 기반으로 한 사용자 사전 구성 # crontab - 12시간 간격으로 실행할 것 import requests from bs4 import BeautifulSoup # 로봇방지 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} url = 'https://datalab.naver.com/keyword/realtimeList.naver?age=all&where=main' res = requests.get(url, headers = headers) soup = BeautifulSoup(res.content, 'html.parser') words = soup.findAll('span','item_title') f = open('user_dictionary.txt', 'a') for word in words : f.write(word.get_text()+'\t'+'NNP'+'\n') f.close()
Java
UTF-8
1,231
3.640625
4
[]
no_license
/* https://leetcode.com/problems/iterator-for-combination/ */ class CombinationIterator { private String chars; private int k; private Deque<String> q; public CombinationIterator(String characters, int combinationLength) { chars = characters; k = combinationLength; // precompute q = new ArrayDeque<>(); int n = chars.length(); for (int bitmask = 0; bitmask < (1 << n); bitmask++) { if (Integer.bitCount(bitmask) != k) { continue; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if ((bitmask & (1 << n - i - 1)) != 0) { sb.append(chars.charAt(i)); } } q.offerFirst(sb.toString()); } } public String next() { return q.pollFirst(); } public boolean hasNext() { return !q.isEmpty(); } } /** * Your CombinationIterator object will be instantiated and called as such: * CombinationIterator obj = new CombinationIterator(characters, combinationLength); * String param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
Markdown
UTF-8
832
3.25
3
[]
no_license
# Lesson 4.9 Lesson 1 Checkup So far, we've covered new ways to declare variables using let and const, how to write template literals for easier string interpolation, destructuring arrays and objects, and some shorthand ways for initializng objects. At this point, we hope you're starting to see how these improvements to the JavaScript language will impact the way you write code moving forward. The remainder of this lesson will focus on the addition of the - for... of loop, - the rest parameter, - and the spread operator. Iteration is a new mechanism for looping through data in ES6. Understanding what iteration is and how it works will be importatn for completing the rest of this lesson. - - - Next up: [Iteration](ND024_Part3_Lesson04_10.md) or return to [Table Of Contents](./ND024_TableOfContents.md)
Swift
UTF-8
757
2.828125
3
[ "MIT" ]
permissive
// // CollectionLabelCell.swift // InterviewTest // // Created by Umair Aamir on 3/15/16. // Copyright © 2016 MyWorkout AS. All rights reserved. // import UIKit class CollectionLabelCell: UICollectionViewCell { @IBOutlet weak var lblTitle: UILabel! let kLabelHorizontalInsets: CGFloat = 8.0 // In layoutSubViews, need set preferredMaxLayoutWidth for multiple lines label override func layoutSubviews() { super.layoutSubviews() // Set what preferredMaxLayoutWidth you want lblTitle.preferredMaxLayoutWidth = self.bounds.width - 2 * kLabelHorizontalInsets } func configCell(title: String) { lblTitle.text = title self.setNeedsLayout() self.layoutIfNeeded() } }
Python
UTF-8
730
3.234375
3
[]
no_license
t = str ( input('Enter the no of terms')) count = 0 if t == t[::-1]: print("its palindrome") else: print("it's not a palindrome") i = 0 j = len(t)-1 for i in range( len(t)): print(t[i]) if t[i::] == t[j::-1]: print (" its palindrome") else: temp = j for k in range(temp,i,-1): print('temp ',t[k],str(k)) if t[i] == t[k]: if t[i:k+1:] == t[k:i-1:-1]: print("palindrome") print(t[i:k+1:]) break ##if t <= 100 and t >= 1: # s = str( input('Enter the string ')) # if len(s) <= 1000 and len(s) >= 1: # sus = s # res = s[::-1] # s.in
Markdown
UTF-8
1,906
3.46875
3
[]
no_license
# `(中等)` [430.flatten-a-multilevel-doubly-linked-list 扁平化多级双向链表](https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/) ### 题目描述 <p>您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。</p> <p>扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。</p> <p>&nbsp;</p> <p><strong>示例:</strong></p> <pre><strong>输入:</strong> 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL <strong>输出:</strong> 1-2-3-7-8-11-12-9-10-4-5-6-NULL </pre> <p>&nbsp;</p> <p><strong>以上示例的说明:</strong></p> <p>给出以下多级双向链表:</p> <pre><img style="width: 640px;" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/multilevellinkedlist.png"></pre> <p>&nbsp;</p> <p>我们应该返回如下所示的扁平双向链表:</p> <pre><img style="width: 1100px;" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/multilevellinkedlistflattened.png"></pre> --- ### 思路 ``` ``` [题解](https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/solution/bian-ping-hua-duo-ji-shuang-xiang-lian-biao-zheng-/) ### 答题 ``` C++ Node* flatten(Node* head) { Node *pNode = head; while (pNode != NULL) { if (pNode->child != NULL) { Node *pNext = pNode->next; pNode->next = pNode->child; pNode->next->prev = pNode; pNode->child = NULL; flatten(pNode); while (pNode != NULL && pNode->next != NULL) pNode = pNode->next; pNode->next = pNext; if (pNext != NULL) pNext->prev = pNode; } pNode = pNode->next; } return head; } ```
C++
UTF-8
611
3.234375
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; bool cmp(string left, string right) { if (left.length() == right.length()) return left < right; else return left.length() < right.length(); } int main(){ int n; cin >> n; vector<string> unsorted(n); for(int unsorted_i = 0; unsorted_i < n; unsorted_i++) { cin >> unsorted[unsorted_i]; } sort(unsorted.begin(), unsorted.end(), cmp); for(int sorted_i = 0; sorted_i < n; sorted_i++) { cout << unsorted[sorted_i] << "\n"; } return 0; }
C
UTF-8
240
3.21875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main(void) { int i,n,x=0,y=1; scanf("%d",&n); printf("%d %d ",x,y); int p = x+y; for (i=1; i<=n; i++) { printf("%d ",p); x = y; y = p; p = x + y; } return EXIT_SUCCESS; }
SQL
UTF-8
4,866
4.125
4
[]
no_license
-- -- This SQL script builds a monopoly database, deleting any pre-existing version. -- Edited by: Valeria Martinez -- 10-19-2018 -- CS 262 -- @author kvlinden -- @version Summer, 2015 -- -- Drop previous versions of the tables if they they exist, in reverse order of foreign keys. DROP TABLE IF EXISTS propertyPlayerGame; DROP TABLE IF EXISTS PlayerGame; DROP TABLE IF EXISTS Game; DROP TABLE IF EXISTS Player; DROP TABLE IF EXISTS properties; -- Create the schema. CREATE TABLE Game ( ID integer PRIMARY KEY, time timestamp ); CREATE TABLE Player ( ID integer PRIMARY KEY, emailAddress varchar(50) NOT NULL, name varchar(50) ); CREATE TABLE PlayerGame ( gameID integer REFERENCES Game(ID), playerID integer REFERENCES Player(ID), score integer, playerCash money, playerLocation integer ); CREATE TABLE properties ( ID integer PRIMARY KEY, name varchar(100) ); CREATE TABLE propertyPlayerGame ( ID integer PRIMARY KEY, gameID integer REFERENCES Game(ID), playerID integer REFERENCES Player(ID), propertiesID integer REFERENCES properties(ID), hotels boolean, houses integer ); -- Allow users to select data from the tables. GRANT SELECT ON Game TO PUBLIC; GRANT SELECT ON Player TO PUBLIC; GRANT SELECT ON PlayerGame TO PUBLIC; GRANT SELECT ON propertyPlayerGame TO PUBLIC; GRANT SELECT ON properties TO PUBLIC; -- Game(ID, time) INSERT INTO Game VALUES (1, '2006-06-27 08:00:00'); INSERT INTO Game VALUES (2, '2006-06-28 13:20:00'); INSERT INTO Game VALUES (3, '2006-06-29 18:41:00'); INSERT INTO Game VALUES (4, '2018-10-18 18:41:00'); INSERT INTO Game VALUES (5, '2018-10-14 18:41:00'); -- Player(ID, emailAddress,name) INSERT INTO Player(ID, emailAddress) VALUES (1, 'me@calvin.edu'); INSERT INTO Player VALUES (2, 'king@gmail.edu', 'The King'); INSERT INTO Player VALUES (3, 'dog@gmail.edu', 'Dogbreath'); -- PlayerGame (gameID,playerID,score,playerCash, playerLocation) INSERT INTO PlayerGame VALUES (1, 1, 0.00, 5.00,1); INSERT INTO PlayerGame VALUES (1, 2, 0.00,8.25,25); INSERT INTO PlayerGame VALUES (1, 3, 2350.00,14,22); INSERT INTO PlayerGame VALUES (2, 1, 10000.00,40,16); INSERT INTO PlayerGame VALUES (2, 2, 10.00,33,46); INSERT INTO PlayerGame VALUES (2, 3, 500.00,25,11); INSERT INTO PlayerGame VALUES (3, 2, 450.00,20,12); INSERT INTO PlayerGame VALUES (3, 3, 5500.00,13,33); -- properties(ID, name) INSERT INTO properties VALUES (1, 'Boston'); INSERT INTO properties VALUES (2, 'Virginia Avenue'); INSERT INTO properties VALUES (3, 'States Avenue'); -- propertyPlayerGame(ID,gameID,playerID, propertiesID, hotels, houses) INSERT INTO propertyPlayerGame VALUES (1, 1,1,1,FALSE,5); INSERT INTO propertyPlayerGame VALUES (2, 2,2,2,TRUE,45); SELECT * FROM PlayerGame; SELECT * FROM propertyPlayerGame; SELECT * FROM properties; ------------------------------------------------------------- ----- LAB 08 ----- Valeria Martinez (vam6) ----- CS 262 ----- 10-26-18 -------------------------------------------------------------- -- EXERCISE 8.1 --- a. List of all games, ordered by date starting from the most recent SELECT * FROM GAME ORDER BY time ASC; --- b. Retrieve all the games that occurred in the past week --SELECT * FROM GAME SELECT * FROM GAME WHERE time >= '2018-10-14 00:00:00' ORDER BY time DESC; --- c. Retrieve a list of players who have a (non-NULL) names SELECT * FROM PLAYER WHERE name <> NULL; --- d. Retrieve a list of IDs of players who have some score larger than 2000 SELECT playerID FROM PlayerGame where score > 2000; ----- e. Retrieve a list of players who have a GMAIL account SELECT * FROM Player where emailAddress LIKE '%gmail%'; ----- EXERCISE 8.2 --- MULTIPLE-TABLE QUERIES -- a. Retrieve all "The King"'s game scores in decreasing order SELECT score FROM Player, PlayerGame WHERE Player.ID = PlayerGame.playerID AND Player.name = 'The King' ORDER BY score DESC; --- b. Retrieve the name of the winner of the game played on 2006-06-28 13:20:00 SELECT name FROM Game, Player, PlayerGame WHERE Game.time = '2006-06-28 13:20:00' AND Game.ID = PlayerGame.GameID AND PlayerGame.playerID = player.ID ORDER BY score DESC LIMIT 1; ---- c.So what does that P1.ID < P2.ID clause do in the last example query? ---- If the players share the same name, then it(p1.id <p2.id) makes sure that the p1 and the p2 don't have the same ID ----- and it also checks if one id is greater than the other one ------- d. The query that joined the Player table to itself seems rather contrived. Can you think of a realistic situation in which you’d want to join a table to itself? --------- We would like to join a table to itself when we want to compare how often an event happens involving the same part of a table. For example, if I want to know how --------- many time player1 won over player2, we would use the query SELECT P1.name, FROM Player AS P1, Player AS P2 ...
C#
UTF-8
2,215
3.421875
3
[]
no_license
using System; namespace Priority_Queue { // ReSharper disable once InconsistentNaming public class FibonacciWrapper<BaseType> { public BaseType Value { get; set; } public FibonacciWrapper<BaseType> FirstChild { get; set; } public FibonacciWrapper<BaseType> Parent { get; set; } public FibonacciWrapper<BaseType> LeftSibling { get; set; } public FibonacciWrapper<BaseType> RightSibling { get; set; } public int Degree { get; set; } public bool Marked { get; set; } private readonly Func<BaseType, BaseType, int> _compare; internal bool InfinitelyNegative { get; set; } public FibonacciWrapper(BaseType value, Func<BaseType, BaseType, int> compare = null) { Value = value; Degree = 0; FirstChild = null; Marked = false; Parent = null; LeftSibling = RightSibling = this; InfinitelyNegative = false; _compare = compare; } public static implicit operator FibonacciWrapper<BaseType>(BaseType value) { return new FibonacciWrapper<BaseType>(value); } public static implicit operator BaseType(FibonacciWrapper<BaseType> value) { return value.Value; } public int CompareTo(object obj) { var otherWrapper = obj as FibonacciWrapper<BaseType>; if (otherWrapper == null) { throw new ArgumentException("Comparing FibonacciWrapper with incompatible type"); } // Infinitely negative values are always smaller than other values if (InfinitelyNegative) { return -1; } if (otherWrapper.InfinitelyNegative) { return 1; } if (_compare != null) { return _compare(Value, otherWrapper.Value); } var cmpThis = Value as IComparable; var cmpOther = otherWrapper.Value as IComparable; if (cmpThis == null || cmpOther == null) { throw new InvalidOperationException("No comparison function and Attrs are not IComparable"); } return cmpThis.CompareTo(cmpOther); } public override string ToString() { return "[" + Value.ToString() + "]"; } public int Index { get; set; } } }
Java
UTF-8
1,556
2.015625
2
[]
no_license
package com.feelfreetocode.findbestinstituteSQL.models; import android.util.Log; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.simpledb.AmazonSimpleDBClient; import com.amazonaws.services.simpledb.model.Attribute; import com.amazonaws.services.simpledb.model.CreateDomainRequest; import com.amazonaws.services.simpledb.model.DeleteAttributesRequest; import com.amazonaws.services.simpledb.model.Item; import com.amazonaws.services.simpledb.model.PutAttributesRequest; import com.amazonaws.services.simpledb.model.ReplaceableAttribute; import com.amazonaws.services.simpledb.model.SelectRequest; import com.amazonaws.services.simpledb.model.SelectResult; import com.feelfreetocode.findbestinstituteSQL.constants.API; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Enquiry implements Serializable { String enquiryId; Course course; Student student; public Enquiry() { } public void setEnquiryId(String enquiryId) { this.enquiryId = enquiryId; } public void setCourse(Course course) { this.course = course; } public void setStudent(Student student) { this.student = student; } public String getEnquiryId() { return enquiryId; } public Course getCourse() { return course; } public Student getStudent() { return student; } private String generateCode(){ return student.getEmail()+course.getCourseId(); } }
Java
UTF-8
639
2.5625
3
[]
no_license
package shop4j.enums; /** * @Author: weixuedong * @Date: 2018/5/2 16:13 * @Description:商品图片类型 */ public enum ProductImageTypeEnum { SPU(1,"SPU图"), SKU(2,"SKU图"), Detail(3,"详情页图") ; private int type; private String name; ProductImageTypeEnum(int type, String name) { this.type = type; this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Python
UTF-8
308
2.765625
3
[]
no_license
import unittest from day_oopConcept.Student_1 import Student_1 class StudentTest(unittest.TestCase): def test_get_student_info(self): student = Student_1("vinny", "veerareddy", "1234","computer science"); self.assertAlmostEqual(student.getStudentInfo(), "vinny veerareddy 1234 computer science")
Markdown
UTF-8
1,704
2.734375
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
This is a ui component to the IDAES project. The FlowsheetSerializer module will serialize a flowsheet into a .idaes.vis file which this extension will render in JupyterLab. ## This will only work in JupyterLab. It will NOT work in a Jupyter Notebook. ## Install Activate the environment that you have idaes installed in. Run the following commands from the top of your git clone. ``` conda install -c conda-forge nodejs jupyterlab cd ui/modelvis/idaes-model-vis npm install npm run build jupyter labextension link . ``` ## Running This can be run from any directory. NOTE: JupyterLab will use your current working directory as your home directory. `jupyter lab` ## To use Launch a Jupyter notebook or a python file from inside of Jupyter Lab. First create your model then run the following commands to serialize your model. ``` from idaes.dmf.ui.flowsheet_serializer import FlowsheetSerializer flowsheet_serializer = FlowsheetSerializer() flowsheet_serializer.save(flowsheet, "file_prefix") ``` This will create a file called file_prefix.idaes.vis in the directory that you are in in Jupyter Lab. Double click the created file in the file tree. This should open the file and you will be able to drag and drop elements. Anytime your mouse leaves the graph area the layout will be saved. NOTE: If you call flowsheet_serializer.save again, it will not re-save the file unless you specify `overwrite=True`. This is done in an effort to preserve the layout that was saved in the idaes vis tab. If you specify `overwrite=True` then the layout will be lost and the model will be rendered using the default layout. Example: `flowsheet_serializer.save(flowsheet, "file_prefix", overwrite=True)`
Java
UTF-8
772
2.40625
2
[]
no_license
package com.pengembangsebelah.stmmappxo.utils; public class TimeParse { String yu; public TimeParse(String me){ this.yu=me; } public Integer getSecond(){ return Integer.valueOf(yu.substring(12,14)); } public Integer getMinuite(){ return Integer.valueOf(yu.substring(10,12)); } public Integer getHour(){ return Integer.valueOf(yu.substring(8,10)); } public Integer getYear(){ return Integer.valueOf(yu.substring(0,4)); } public Integer getMonth(){ return Integer.valueOf(yu.substring(4,6)); } public Integer getDay(){ return Integer.valueOf(yu.substring(6,8)); } public Integer getDateCal(){ return Integer.valueOf(yu.substring(0,8)); } }
JavaScript
UTF-8
2,104
2.828125
3
[ "MIT" ]
permissive
(function () { const app = angular.module('app'); function TaskTableView(taskId, taskContent) { this.taskId = taskId, this.taskContent = taskContent, this.editorTaskContent = taskContent // valid editor states are: // 'initial' : indicates loaded from the database // 'confirmDelete' : indicates that user is about to delete it // 'deleted' : indicates passed the confirmDelete state // 'editing' : indicates that the task is in inline-editing mode this.editorState = 'initial', /////////////////////////////// // // // state change functions // // // ////////////////////////////// this.setInitialState = function () { this.editorTaskContent = this.taskContent; this.editorState = 'initial'; }, this.setConfirmDeleteState = function () { this.editorState = 'confirmDelete'; }, this.setDeletedState = function () { this.editorState = 'deleted'; }, this.setEditingState = function () { this.editorState = 'editing'; } } app.factory('TaskTableViewFactory', function () { return { buildFromJson(jsonObj) { const id = jsonObj.TaskId || -1; const content = jsonObj.TaskContent || ''; return new TaskTableView(id, content); }, buildFromJsonCollection(jsonObjCollection) { const retVal = [] for (let i = 0; i < jsonObjCollection.length; i++) { const task = this.buildFromJson(jsonObjCollection[i]); retVal.push(task); } return retVal; }, updateFromJson(jsonObj, task) { const id = jsonObj.TaskId || -1; const content = jsonObj.TaskContent || ''; task.taskId = id; task.taskContent = content; } } }); }());
Java
UTF-8
383
1.992188
2
[]
no_license
package com.example.springmongo.repository; import com.example.springmongo.entities.Post; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PostRepository extends MongoRepository<Post,String> { List<Post> findByTitleContainingIgnoraingCase(String text); }
C++
UTF-8
316
2.65625
3
[]
no_license
#pragma once /*Item class will be base for branches, rocks and diamod*/ #include "cObject.h" class Item : public cObject { public: /*default constructor*/ Item(); /*this method returns type of an item -> item types can be found in utilities file (enum class)*/ ITEM GetType() const; public: ITEM m_type; };
Java
UTF-8
1,024
2.5625
3
[]
no_license
package com.Rest; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin public class testController { Student student=new Student((long) 1,"huanyu"); @RequestMapping("/test") public Student test(){ return student; // return "Hello world, JWT"; } } class Student{ private Long id; private String name; @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } public Student(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
C#
UTF-8
1,136
2.859375
3
[]
no_license
namespace Castle.Facilities.TypedFactory { using System; public class FactoryEntry { private String _id; private Type _factoryInterface; private String _creationMethod; private String _destructionMethod; public FactoryEntry(String id, Type factoryInterface, String creationMethod, String destructionMethod) { if (id == null || id.Length == 0) throw new ArgumentNullException("id"); if (factoryInterface == null) throw new ArgumentNullException("factoryInterface"); if (!factoryInterface.IsInterface) throw new ArgumentException("factoryInterface must be an interface"); if (creationMethod == null || creationMethod.Length == 0) throw new ArgumentNullException("creationMethod"); _id = id; _factoryInterface = factoryInterface; _creationMethod = creationMethod; _destructionMethod = destructionMethod; } public String Id { get { return _id; } } public Type FactoryInterface { get { return _factoryInterface; } } public String CreationMethod { get { return _creationMethod; } } public String DestructionMethod { get { return _destructionMethod; } } } }
Python
UTF-8
1,760
4.25
4
[]
no_license
""" Euler Project 35 ================================================================ The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ from time import time from math import sqrt def isPrime(n): # function to check if a number is a prime if(n != 2 and n%2 == 0): # even numbers are not prime return False else: prime = True for i in xrange(3,int(sqrt(n))+1,2): # check if n is divisible if (n%i == 0): prime = False break return prime def primesUpTo(N): # find all primes up to N sum_of_prime = set() for i in xrange(2,N): if(isPrime(i)): # contains all the prime numbers up to N sum_of_prime.add(i) return sum_of_prime def rotateNumbers(s): # rotate a string to the right by n places rotated_s = set([s]) s = str(s) # rotate each character to the right for i in range(len(s)-1,0,-1): rotated_s.add(int(s[i:] + s[:i])) return rotated_s start = time() primes = primesUpTo(10**6) circular_primes = set() # begin finding circular primes for i in primes: # skip over known circular primes if i not in circular_primes: # check if current prime is a circular prime # make use of sets, where order does not matter if rotateNumbers(i).issubset(primes): # if so, combine it circular_primes = circular_primes.union(rotateNumbers(i)) end = time() print len(circular_primes) print 'Elapsed', end-start
Python
UTF-8
149
3.265625
3
[]
no_license
#!/usr/bin/python #_*_coding:utf-8_*_ #函数:最大公约数 def gcd(a, b): m = min(a, b) while a % m != 0 and b % m != 0: m -= 1 return m
JavaScript
UTF-8
1,018
2.640625
3
[]
no_license
var http = require('http'); var url = require('url'); var port = process.argv[2]; var server = http.createServer(function(req, res){ var url_parsed = url.parse(req.url, true); if (req.method === 'GET' && ('iso' in url_parsed.query)){ if (url_parsed.pathname == '/api/parsetime'){ var date = new Date(url_parsed.query.iso); var data_response = { 'hour': date.getHours(), 'minute': date.getMinutes(), 'second': date.getSeconds() }; json_response = JSON.stringify(data_response); } if (url_parsed.pathname == '/api/unixtime'){ var data_response = { 'unixtime': Date.parse(url_parsed.query.iso) }; json_response = JSON.stringify(data_response); } req.on('data', function(data){ }); req.on('end', function(){ res.writeHead(200, { 'Content-Type': 'application/json' }); console.log(json_response); res.end(json_response); }); } else{ res.writeHead(404); res.end(); } }) .listen(Number(port), function(){ console.log('Listening on port ' + port); });
Java
UTF-8
7,984
2.421875
2
[]
no_license
/* * Copyright (C) 2007 TopCoder Inc., All Rights Reserved. */ package com.topcoder.timetracker.client; import com.topcoder.search.builder.filter.Filter; import com.topcoder.timetracker.project.Project; import com.topcoder.util.sql.databaseabstraction.CustomResultSet; /** * <p> * This interface specifies the contract for implementations of a Client DAOs. A ClientDAO is responsible for accessing * the database. * </p> * * <p> * <b>Thread Safety:</b> Implementations of this interface should be thread safe. * </p> * * @author TCSDESIGNER, TCSDEVELOPER * @version 3.2 */ public interface ClientDAO { /** * <p> * Add the given Client. * </p> * * @param client non null client to be added * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if the client is null * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void addClient(Client client, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Add the given Clients into the database. * </p> * * @param clients non null, possible empty array containing non null contact to be added * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if the array is null or containing null client * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void addClients(Client[] clients, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Retrieve the given Client. * </p> * * @param id the id of the Client * * @return the Client with given id, null if not found * * @throws IllegalArgumentException if the id not positive * @throws ClientPersistenceException if any exception occurs */ public Client retrieveClient(long id) throws ClientPersistenceException; /** * <p> * Retrieve the Clients with given ids. * </p> * * @param ids non null, possible empty array containing id of client to be removed * * @return non null, possible empty array containing possible null clients * * @throws IllegalArgumentException if the array is null or any id is not positive * @throws ClientPersistenceException if any exception occurs */ public Client[] retrieveClients(long[] ids) throws ClientPersistenceException; /** * <p> * Remove the Client with given id. * </p> * * @param id the id of the Client * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if the id not positive * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void removeClient(long id, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Remove the Clients with given ids. * </p> * * @param ids non null, possible empty array containing id of client to be removed * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if the array is null or any not positive * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void removeClients(long[] ids, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Update the given Client. * </p> * * @param client non null client to be updated * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if the client is null * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void updateClient(Client client, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Update the given Clients. * </p> * * @param clients non null, possible empty array containing non null contact * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if the array is null or containing null client * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void updateClients(Client[] clients, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Retrieve all the Clients. * </p> * * @return non null, possible empty array containing all the clients * * @throws ClientPersistenceException if any exception occurs */ public Client[] getAllClients() throws ClientPersistenceException; /** * <p> * Search the Clients with the given Filter and Depth. * </p> * * @param filter non null filter * @param depth non null depth * * @return non null result set * * @throws ClientPersistenceException if any exception occurs * @throws IllegalArgumentException if filter or depth is null */ public CustomResultSet searchClient(Filter filter, Depth depth) throws ClientPersistenceException; /** * <p> * Add the project to the Client. * </p> * * @param client the id of the Client * @param project the non null project * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if project is null or the clientId not positive * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void addProjectToClient(Client client, Project project, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Remove the project from the Client. * </p> * * @param client the id of client * @param projectId the id of project * @param audit whether an audit should be performed. * * @throws IllegalArgumentException if any id not positive of instance null * @throws ClientPersistenceException if any exception occurs * @throws ClientAuditException if any error when audit */ public void removeProjectFromClient(Client client, long projectId, boolean audit) throws ClientPersistenceException, ClientAuditException; /** * <p> * Get all ids of projects of the Client. * </p> * * @param clientId the id of the client * * @return the non null, possible empty array containing all project ids of the client * * @throws IllegalArgumentException if client id not positive * @throws ClientPersistenceException if any exception occurs */ public long[] getAllProjectIDsOfClient(long clientId) throws ClientPersistenceException; /** * Gets all projects for the client specified by ID. Only the IDs/Names of the resulting * projects will be retrieved. * * @return the non null, possibly empty array containing all projects of the client. * @param clientId * the ID of the client. * @throws IllegalArgumentException * if client ID not positive. * @throws ClientPersistenceException * if any exception occurs. */ public Project[] getProjectIDsNamesForClient(long clientId) throws ClientPersistenceException; }
C#
UTF-8
995
2.65625
3
[]
no_license
using UnityEngine; using System.Collections; using System.Collections.Generic; public class ArrowPool : MonoBehaviour { public GameObject PooledObjectPrefab; public bool WillGrow; public List<GameObject> Pool; protected virtual void Awake() { Pool = new List<GameObject>(); } public GameObject GetPooledObject() { for (int i = 0; i < Pool.Count; i++) { if (Pool[i] == null) { GameObject obj = (GameObject)Instantiate(PooledObjectPrefab); obj.transform.localPosition = Vector3.up * -3f; Pool[i] = obj; return Pool[i]; } if (!Pool[i].activeInHierarchy) { return Pool[i]; } } if (WillGrow) { GameObject obj = (GameObject)Instantiate(PooledObjectPrefab); Pool.Add(obj); return obj; } return null; } }
Markdown
UTF-8
880
2.65625
3
[ "Apache-2.0" ]
permissive
--- name: Shermin Voshmgir id: shermin-voshmgir company: "BlockchainHub" position: "Founder" location: "Berlin, Germany" talk_id: digital-human-rights featured: true intro: > Shermin is the Founder of BlockchainHub and working on Identity Startup Jolocom. She was on the advisory board of the Estonian e-residency program, a curator of theDAO. links: - text: "@sherminvo" url: "https://twitter.com/sherminvo" - text: "LinkedIn" url: "https://www.linkedin.com/in/sherminvoshmgir" --- Shermin did her PhD in IT-Management at the Vienna University of Economics, where she used to work as an assistant professor and currently lectures blockchain related topics. Furthermore she studied film and drama in Madrid. Her past work experience ranges from internet start-ups, IT consulting & filmmaking. Among others her films have screened in Cannes and at dOCUMENTA.
Java
UTF-8
4,758
2.359375
2
[]
no_license
package com.chbtc.springboot.controller; import com.chbtc.springboot.model.User; import com.chbtc.springboot.service.IUserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by chbtc on 2017/5/16. */ @Controller @RequestMapping("/user") public class FirstController { private static final Logger logger = LoggerFactory.getLogger(FirstController.class); @Autowired private IUserService userService; @RequestMapping("/{id}") @ResponseBody public User testSpringBoot(@PathVariable("id") Integer id) { User user=null; user=userService.getUserById(id); System.out.println(user); return user; } @RequestMapping(value="/login",method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping(value="/login",method = RequestMethod.POST) public String login(String name,String password) { UsernamePasswordToken token=new UsernamePasswordToken(name,password); Subject currentUser = SecurityUtils.getSubject(); try { //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 //每个Realm都能在必要时对提交的AuthenticationTokens作出反应 //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 logger.info("对用户[" + name + "]进行登录验证..验证开始"); currentUser.login(token); logger.info("对用户[" + name + "]进行登录验证..验证通过"); }catch(UnknownAccountException uae){ logger.info("对用户[" + name + "]进行登录验证..验证未通过,未知账户"); // redirectAttributes.addFlashAttribute("message", "未知账户"); }catch(IncorrectCredentialsException ice){ logger.info("对用户[" + name + "]进行登录验证..验证未通过,错误的凭证"); //redirectAttributes.addFlashAttribute("message", "密码不正确"); }catch(LockedAccountException lae){ logger.info("对用户[" + name + "]进行登录验证..验证未通过,账户已锁定"); //redirectAttributes.addFlashAttribute("message", "账户已锁定"); }catch(ExcessiveAttemptsException eae){ logger.info("对用户[" + name + "]进行登录验证..验证未通过,错误次数过多"); //redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多"); }catch(AuthenticationException ae){ //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景 logger.info("对用户[" + name + "]进行登录验证..验证未通过,堆栈轨迹如下"); ae.printStackTrace(); // redirectAttributes.addFlashAttribute("message", "用户名或密码不正确"); } //验证是否登录成功 if(currentUser.isAuthenticated()){ Session session = SecurityUtils.getSubject().getSession(); //session.setAttribute("loginType",LoginEnum.ADMIN.toString()); logger.info("用户[" + name + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)"); //String ip = IpUtil.getIpAddr(request); // logService.insertLoginLog(username, ip, request.getContextPath()); return "redirect:/hello"; }else{ token.clear(); return "redirect:/login"; } } @RequestMapping("/add/{name}") @ResponseBody public User add(@PathVariable("name") String name) { User user=new User(); user.setUsername(name); user.setPassword("123456"); userService.insert(user); // user.setPassword("ggsss"); System.out.println(user); return user; } @RequestMapping("/hello") public String hello(ModelMap map) { map.addAttribute("name","cgls"); map.addAttribute("names","cgl1"); return "hello"; } }
JavaScript
WINDOWS-1251
14,453
2.515625
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ // : var colors_tab_2 = ['#FFD100', '#FF7140', '#ACF53D', '#65E17B', '#5DCEC6', '#92B6E9', '#717BD8', '#896ED7', '#A768D5', '#DB63C4']; //, / ( ) var canEdit_tab_2 = true; // /*var stepTxt_tab_2 = ['1. , " ". / .', '2. , " "', '3. ! " ".', '! ! , " " .', ' , 1.' ];*/ var stepTxt_tab_2 = []; //console.log (stepTxt_tab_2); function drawAreas (map_id){ ymaps.ready(function () { $('#angerro_yadelivery_tab2_hint').html(stepTxt_tab_2[0]); // var area_titles = []; // id = map myMap = new ymaps.Map(map_id, { center: [59.9296,30.3186], zoom: 12, behaviors: ["default", "scrollZoom"], controls: ["searchControl", "zoomControl"] }); // //myMap.controls.add('searchControl').add('scaleLine').add('zoomControl'); // : var onClick = function (e) { if(canEdit_tab_2==true){ alert(stepTxt_tab_2[5]); // , : areas_count = 1; myMap.geoObjects.each(function (geoObject) { areas_count++; }); var shape = new ymaps.Polygon([], {hintContent: stepTxt_tab_2[6]+" "+areas_count}, {fillColor: colors_tab_2[areas_count-1], opacity: 0.5}); myMap.geoObjects.add(shape); shape.editor.startDrawing(); // : / (canEdit_tab_2=true) shape.events.add('click', function (){ if(canEdit_tab_2==true){ // , , if ((shape.editor.state.get('editing')==true)&&(shape.editor.state.get('drawing')==false)){ shape.editor.stopEditing(); } else{ shape.editor.startEditing(); } //console.log (shape.editor.state.get('drawing')); } else{ alert(stepTxt_tab_2[4]); } }); } else{ alert(stepTxt_tab_2[4]); } }; myMap.events.add('click', onClick); // : $( "#angerro_yadelivery_tab2_send" ).click(function() { var iterator = 0; var data = []; var data_areas = []; // var area_coordinates = []; myMap.geoObjects.each(function (geoObject) { area_coordinates[iterator] = geoObject.geometry.getCoordinates(); iterator++; }); /* * : * -area_coordinates ( ) * -settings (. : , .) */ for (var i=0; i < area_coordinates.length; i++){ data_areas.push({area_coordinates: area_coordinates[i], settings: {title: area_titles[i], color: colors_tab_2[i]} }); } // : var map_center = myMap.getCenter(); var map_zoom = myMap.getZoom(); data.push({map: {zoom: map_zoom, center: map_center, map_id: $('#angerro_yadelivery_tab2_delivery_map_name').val()}, delivery_areas: data_areas}); /* * : * [ { "map":{ "zoom":12, "center":[ 59.928971911376344, 30.30770241405099 ], "map_id":"delivery_spb" }, "delivery_areas":[ { "area_coordinates":[ [ [ 59.918397455124335, 30.283581079101552 ], [ 59.93149543984123, 30.307613671874975 ], [ 59.91753556370916, 30.31036025390622 ], [ 59.918397455124335, 30.283581079101552 ] ] ], "settings":{ "title":" 1", "color":"#FFD100" } } ] } ] */ // json: var json = JSON.stringify(data); $.ajax({ type: "POST", url: "/bitrix/components/angerro/angerro.yadelivery/classes/save_map.php", data: "map_data="+json+"&map_name="+$('#angerro_yadelivery_tab2_delivery_map_name').val()+"&sessid="+$('#sessid').val(), success: function(result){ if (result=='OK'){ $('#angerro_yadelivery_tab2_hint').html(stepTxt_tab_2[3]); //$( "<br><a href='/comp_map/view/?map_type="+$('#angerro_yadelivery_tab2_delivery_map_name').val()+"' target='_blank'> ( )</a>" ).insertAfter( "#angerro_yadelivery_tab2_hint" ); //$( "<a href='/comp_map/draw/'> </a>" ).insertAfter( "#angerro_yadelivery_tab2_hint" ); $('.angerro_yadelivery_tab2_map_name_block').hide(); $('#angerro_yadelivery_tab2_send').hide(); $('#angerro_yadelivery_tab2_back_on_step_2').hide(); } } }); }); // : $( "#angerro_yadelivery_tab2_create_description" ).click(function() { canEdit_tab_2 = false; //fix: , , , : myMap.geoObjects.each(function (geoObject) { var obj_length = geoObject.geometry.getCoordinates().length; if (obj_length==0){ myMap.geoObjects.remove(geoObject); }else{ if (obj_length==1){ if(geoObject.geometry.getCoordinates()[0].length<4){ myMap.geoObjects.remove(geoObject); } } } }); // : areas_count = 0; myMap.geoObjects.each(function (geoObject) { areas_count++; }); // : $(this).hide(); $('#angerro_yadelivery_tab2_save_description').show(); $('#angerro_yadelivery_tab2_back_on_step_1').show(); $('#angerro_yadelivery_tab2_delivery_description').show('slow'); $('#angerro_yadelivery_tab2_hint').html(stepTxt_tab_2[1]); // : // $('#angerro_yadelivery_tab2_delivery_description').html(''); // $('#angerro_yadelivery_tab2_delivery_description').append('<div class="angerro_yadelivery_tab2_header">'+stepTxt_tab_2[7]+'</div><div class="angerro_yadelivery_tab2_header">'+stepTxt_tab_2[8]+'</div><div class="angerro_yadelivery_tab2_clear"></div>'); for (var i = 0; i < areas_count; i++){ var table_tr ='<div class="angerro_yadelivery_tab2_content angerro_yadelivery_tab2_color"><input type="color" class="angerro_yadelivery_tab2_select_color" value="'+colors_tab_2[i]+'"></div><div class="angerro_yadelivery_tab2_content angerro_yadelivery_tab2_margin_10"><input type="text" class="form-control angerro_yadelivery_tab2_input_name" value="'+stepTxt_tab_2[6]+' '+(i+1)+'"></div><div class="angerro_yadelivery_tab2_clear"></div>'; $('#angerro_yadelivery_tab2_delivery_description').append(table_tr); } // : myMap.geoObjects.each(function (geoObject) { geoObject.editor.stopDrawing(); geoObject.editor.stopEditing(); }); }); $( "#angerro_yadelivery_tab2_save_description" ).click(function(){ // : area_titles = []; // : $( ".angerro_yadelivery_tab2_input_name" ).each(function( index ) { area_titles.push($(this).val()); }); // : $( ".angerro_yadelivery_tab2_select_color" ).each(function( index ) { colors_tab_2[index] = $(this).val(); }); // : var iterator = 0; myMap.geoObjects.each(function (geoObject) { geoObject.properties.set({hintContent:area_titles[iterator]}); geoObject.options.set({fillColor:colors_tab_2[iterator]}); iterator++; }); // $('#angerro_yadelivery_tab2_delivery_description').hide('slow'); $('#angerro_yadelivery_tab2_save_description').hide(); $('#angerro_yadelivery_tab2_back_on_step_1').hide(); $('#angerro_yadelivery_tab2_back_on_step_2').show(); $('#angerro_yadelivery_tab2_send').show(); $('#angerro_yadelivery_tab2_hint').html(stepTxt_tab_2[2]); $('.angerro_yadelivery_tab2_map_name_block').show(); }); $( "#angerro_yadelivery_tab2_back_on_step_1" ).click(function(){ canEdit_tab_2 = true; $('#angerro_yadelivery_tab2_delivery_description').hide('slow'); $('#angerro_yadelivery_tab2_save_description').hide(); $('#angerro_yadelivery_tab2_back_on_step_1').hide(); $('#angerro_yadelivery_tab2_create_description').show(); $('#angerro_yadelivery_tab2_hint').html(stepTxt_tab_2[0]); // : myMap.geoObjects.each(function (geoObject) { geoObject.editor.startEditing(); }); }); $( "#angerro_yadelivery_tab2_back_on_step_2" ).click(function(){ $('#angerro_yadelivery_tab2_back_on_step_2').hide(); $('#angerro_yadelivery_tab2_send').hide(); $('#angerro_yadelivery_tab2_delivery_description').show('slow'); $('#angerro_yadelivery_tab2_back_on_step_1').show(); $('#angerro_yadelivery_tab2_save_description').show(); $('#angerro_yadelivery_tab2_hint').html(stepTxt_tab_2[1]); $('.angerro_yadelivery_tab2_map_name_block').hide(); }); $( "#go_to_mainpage" ).click(function(){ window.location.replace('/comp_map/'); }); }); } $( document ).ready(function() { $.each($('.angerro_yadelivery_text_info_tab2'), function( index, value ) { stepTxt_tab_2.push( $(this).html() ); }); drawAreas('angerro_yadelivery_tab2_map_preview'); });
C
UTF-8
372
3.15625
3
[]
no_license
#include <stdio.h> #include <signal.h> #include <unistd.h> int flag = 1; // global flag void alarm_handler(int signum) { flag = 0; } int main() { signal(SIGALRM, alarm_handler); // Register signal handler alarm(5); printf("Looping forever...\n"); while(flag){ pause(); }; printf("This line should be executed.\n"); return 0; }
Python
UTF-8
1,094
2.65625
3
[]
no_license
import smtplib import argparse parser = argparse.ArgumentParser() parser.add_argument("-t", '--target', help='Target') parser.add_argument("-f", '--file', help='Password File') args = parser.parse_args() stop = False if args.target and args.file: stop = True print 'Dark Code\'s Gmail Password Cracker' passwordfile = open(args.file, 'r') counter = 0 flag = False for line in passwordfile: counter += 1 if flag == False and line.strip() == 'blood13': flag = True if flag == False: continue print 'Counter %s : Attempting Password:' % counter, line server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() try: server.login(args.target, line) print '[!] Account Cracked, Password', line a = raw_input() exit() except smtplib.SMTPAuthenticationError: pass if '__main__' == __name__: if stop == False: print "The corrent syntex is python script.py -t <target> -f <passfile>"
Java
UTF-8
340
2.109375
2
[]
no_license
package com.ruby.cfg; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.ruby.bean.Student; @Configuration public class AppContext { AppContext(){ } @Bean(name="student") public Student getStudent() { Student stu=new Student(); return stu; } }
C#
UTF-8
1,072
2.9375
3
[ "MIT" ]
permissive
using System; namespace AllOverIt.Assertion { /// <summary>Provides a number of extensions that enable method pre-condition checking.</summary> public static partial class Guard { private static void ThrowArgumentNullException(string name, string errorMessage) { ThrowArgumentNullException<string>(name, errorMessage); } private static void ThrowArgumentNullException<TType>(string name, string errorMessage) { if (errorMessage == default) { throw new ArgumentNullException(name); } throw new ArgumentNullException(name, errorMessage); } private static void ThrowInvalidOperationException(string name, string errorMessage) { ThrowInvalidOperationException<string>(name, errorMessage); } private static void ThrowInvalidOperationException<TType>(string name, string errorMessage) { throw new InvalidOperationException($"{errorMessage} ({name})"); } } }
C
ISO-8859-1
1,429
3.59375
4
[]
no_license
// need to think #include<iostream> #include<vector> #include<stack> using namespace std; void reverseStack2(stack<int> s, int n) { if(n == 2) { int a = s.top(); s.pop(); int b = s.top(); s.pop(); s.push(b); s.push(a); } else { int topData = s.top(); s.pop(); reverseStack2(s, n - 1); } } void addToStackBottom(stack<int>& s, int top) { if(s.empty()) { cout << "the top is:" << top << endl; s.push(top); } else { int tmp = s.top(); s.pop(); //addToStackBottom(s,tmp); addToStackBottom(s, top); s.push(tmp); cout << "the tmp is:" << tmp << endl; } } void reverseStack(stack<int>& s) { if(!s.empty()) { int top = s.top(); s.pop(); reverseStack(s); addToStackBottom(s, top); } } int main() { stack<int> s; for(int i = 1; i <= 5; i++) s.push(i); cout<<"the stack top "; for(int i = 5; i >= 1; i--) cout << i << ends; cout<<" the stack tail" << endl; reverseStack(s); cout<<"the stack top "; while(!s.empty()) { int top = s.top(); s.pop(); cout << top <<ends; } cout << " the stack tail" << endl; return 0; }
Java
UTF-8
1,695
3.171875
3
[]
no_license
package cs5643.rigidbody; import java.awt.Color; import javax.media.opengl.GL2; import javax.vecmath.*; /** * A class representing a node in a bounding volume hierarchy. */ public class BVHNode { public final Point2d minBound, maxBound; public final BVHNode child[]; /** The index of the first block contained in this node */ public int blockIndexStart; /** The index of the surface next to the last block under this node. */ public int blockIndexEnd; /** Constructor */ public BVHNode(Point2d minBound, Point2d maxBound, BVHNode leftChild, BVHNode rightChild, int start, int end) { this.minBound = new Point2d(); this.minBound.set(minBound); this.maxBound = new Point2d(); this.maxBound.set(maxBound); this.child = new BVHNode[2]; this.child[0] = leftChild; this.child[1] = rightChild; this.blockIndexStart = start; this.blockIndexEnd = end; } public boolean isLeaf() { return child[0] == null && child[1] == null; } public boolean intersects(RigidBody body) { return body.getMinBound().x <= maxBound.x && body.getMaxBound().x >= minBound.x && body.getMinBound().y <= maxBound.y && body.getMaxBound().y >= minBound.y; } public void draw(GL2 gl, int layerLevel) { if (isLeaf()) { Color3f fillColor = new Color3f(Color.RED); gl.glColor4f(fillColor.x,fillColor.y,fillColor.z,.8f); gl.glBegin(GL2.GL_QUADS); gl.glVertex2d(minBound.x,minBound.y); gl.glVertex2d(maxBound.x,minBound.y); gl.glVertex2d(maxBound.x,maxBound.y); gl.glVertex2d(minBound.x,maxBound.y); gl.glEnd(); } if (child[0] != null) child[0].draw(gl, layerLevel+1); if (child[1] != null) child[1].draw(gl, layerLevel+1); } }
Java
UTF-8
2,087
1.929688
2
[ "Apache-2.0" ]
permissive
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.enums; /** * * @author Honza Brázdil &lt;jbrazdil@redhat.com&gt; * @deprecated use pnc-api */ @Deprecated public enum ArtifactQuality { // TODO mark all deprecated /** * The artifact has not yet been verified or tested. */ NEW, /** * The artifact has been verified by an automated process, but has not yet been tested against a complete product or * other large set of components. */ VERIFIED, /** * The artifact has passed integration testing. */ TESTED, /** * The artifact should no longer be used due to lack of support and/or a better alternative being available. */ DEPRECATED, /** * The artifact contains a severe defect, possibly a functional or security issue. */ BLACKLISTED, /** * Artifact with DELETED quality is used to show BuildRecord dependencies although the artifact itself was deleted * OR can identify artifacts, which are were removed from repository manager (e.g. due to conflicts), but the * metadata were kept for archival purposes. */ DELETED, /** * The artifact is built as temporary and it is planned to remove it later. The artifact cannot be used for product * releases. */ TEMPORARY, /** * The artifact was not built inhouse and was imported from outside world. */ IMPORTED }
Markdown
UTF-8
6,354
2.890625
3
[]
no_license
title: 'Biking Around Taiwan: Taipei to Kaoshiung' date: 29 MARCH 2014 tags: [Travel] --- With a friend I just finished my first long-distance bike trip down the west coast of Taiwan. I’d planned to make a full loop of the island, but I’m headed to Sri Lanka in a few weeks and wanted to spend some more time in Taipei before I leave, so I hopped a train when I got to the end of the tracks in the south and came back to Taipei. When I come back to Taiwan I’ll rent a bike again and go down the east coast, which’ll probably be sometime this summer. <!-- more --> ![taiwan_bike](/images/taiwan_bike_blfxsl.jpg)] One of the first temples we came across. Before leaving on the trip I found it terribly hard to find any information online in English about biking around Taiwan, so here it is. ### Renting a Bike Giant Bikes has a half famous but at the same time still half unknown bike rental program for long distance trips. It’s famous in the sense that everyone in Taiwan seems to know about it, but half unknown in the sense that nobody can tell you the details. I had someone who spoke Chinese call Giant for me and here’s the deal: You rent a Giant bike from any of the company-owned (versus franchised) Giant outlets in Taiwan, preferably a week in advanced. The bikes will have little luggage bags on them and basically come with everything you’d ever need for your trip, and you can return them to any company owned Giant outlet. You’ll also be able to grab a coffee and wash up at any company-owned outlet you come across; this almost sold us on renting from Giant, but we ended up renting from an independent bike shop and any time we stopped in a Giant (or Merida) shop for directions, they were still super nice and occasionally offered us a coffee anyway. I can’t remember the exact price for the Giant rental program because we ended up going with another option, which was much cheaper: [http://bluepuffy1990.pixnet.net/blog/post/13754737](http://bluepuffy1990.pixnet.net/blog/post/13754737). This is a small shop owned by an old man in Damsui. He only speaks Chinese, but if you can speak with him he’ll rent you the same bike as Giant would have with all the same gear at $2,000 for 15 days and $100/day after that (Taiwan dollars). He stocked us up with free bottles of water before we left, tore the tags off a brand new bike to rent to my friend, and I brought the bike back one day over the 15 days for which he refused to take my $100NT. Nice guy, we did a lot of research before we rented and that’s who you’d probably want to go with. If you can’t rent from him and don’t want to rent from Giant, just take the MRT up to Damsui. When you get off you’ll be surrounded by bike shops and they’ll all be happy to rent to you, I don’t think you’d even need to call ahead. ![taiwan<em>bike</em>2](/images/taiwan_bike_2_j74hdg.jpg) Red dirt overlooking Taichung city. ### Where to Sleep If you’ve got a hotel budget of a few hundred US dollars for your trip, you can just sleep in hostels in the big cities and hotels in the small cities along the way. A hotel room in these small cities were between $1000-$1500 Taiwan dollars per night, and we never had an issue rolling into town and finding a room on the spot. Except in Douliu where a teenage ice skating competition of all things had rented out almost all the rooms…but even there we found one for a few hundred Taiwan Dollars more than normal. This is also Taiwan, where everyone helps everyone else, so amazingly enough if you want to sleep for free the whole way that’s cool too. Head to any temple and ask to speak with the priest, and ask his/her permission to sleep in their rest room. These are rooms for travellers who don’t have anywhere to stay, not every temple has them but enough of them do that after 2-3 temples you should find one. We didn’t end up staying in one, but we were told repeatedly that they’d be more than happy to have us. On the east coast we were told that police stations also have rest rooms, and that they might be fine with having you sleep there as well. Lastly, just sleep outside in a sleeping bag – nobody will mind. ### What Route to Take Honestly, still no idea. We Just figured it out as we went along, and no matter what road we took we always saw other bikers on the road (road biking is crazy popular in Taiwan). In general we found the small highways/small roads way better than the major highways, but for safety it’s worth noting that just about every road we were on had a bike lane and most of the major highways had bike trails carved out beside them, particularly where this meant avoiding a dangerous piece of the highway. Again, biking is popular. ### How Long Does It Take We heard someone in the giant tour tell us they take experienced bikers around the island in 9 days. Judging by the distances they said they covered every day (about 100km), this’d probably mean they stick to major highways so in my opinion I’d say you give it more time. To go to Kaoshiung from Taipei we made a point of going as slowly as possible, we’ve lived in Taiwan long enough to have friends in most of these cities, so we spent up to 5 days each hanging out in Taichong, Tainan, and Kaoshiung once we got there. It took us two weeks to go to Kaoshiung, but again that was intentionally slow, and if you didn’t spend a lot of time in each city two weeks would probably get you around the island comfortably, maybe 2.5 weeks if you wanted some breathing room. ![taiwan<em>bike</em>3](/images/taiwan_bike_3_dvxgnu.jpg)] Taken while standing inside a giant Buddha. I’m headed to Sri Lanka to learn to surf, then I’m coming back to Taiwan and going down the east coast. If you’ve ever thought about biking Taiwan but were intimidated by the lack of English information, don’t be. Just get an MRT to Damsui, rent a bike and go.<script type="text/javascript">/* * * CONFIGURATION VARIABLES * * */ var disqus_shortname = 'nick-budden'; /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();</script>
C++
UTF-8
803
2.859375
3
[]
no_license
#include <computation/geometry/transform.h> TranslateTransform:: TranslateTransform(const float &dx, const float &dy, const float &dz){ float d[4][4]={ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, dx , dy , dz , 1.0f }; Modify(d); } ScaleTransform:: ScaleTransform(const float &sx, const float &sy, const float &sz){ float d[4][4]={ sx , 0.0f, 0.0f, 0.0f, 0.0f, sy , 0.0f, 0.0f, 0.0f, 0.0f, sz , 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; Modify(d); } RotationTransform:: RotationTransform(const Vector& a, const float &theta){ Normal v1 = a.x() < 0?(a % Vector(1.0f, 0.0f, 0.0f)):(a % Vector(-1.0f, 0.0f, 0.0f)); Normal v2 = a % v1; // a, v1, v2 are othonormal // TO DO }
Python
UTF-8
595
2.828125
3
[]
no_license
import time from url_thread import UrlThread import urllib class LinkParser: def __init__(self, url, mode): self.links = [] self.url = url self.mode = mode self.url_thread = UrlThread(url) self.url_thread.start() def grab(self): splits = self.url_thread.get().split("href=\"") for i in range(0, len(splits)-1): if splits[i][0] == "/": self.links.append(self.url + splits[i].split("\"")[0]) elif splits[i][0] == "h": self.links.append(splits[i].split("\"")[0]) return self.links def is_done(self): return self.url_thread.get() != "" or self.url_thread.ran
C++
UTF-8
3,055
2.75
3
[ "MIT" ]
permissive
/* * Author: @Genozen 01/03/2021 * This is the arduino code for controlling motorized prosthetic hand using servos */ //servo #include <Servo.h> Servo serv1; //Thumb Servo serv2; //Index Finger Servo serv3; //Middle Finger Servo serv4; //Ring Finger Servo serv5; //Pinky Finger //offset initial servo angles to keep string in tension int serv1_ang = 0; int serv2_ang = 0; int serv3_ang = 0; int serv4_ang = 0; int serv5_ang = 60; int incomingByte = 0; // for incoming serial data //map key press using ASCII input from serial monitor int key = 0; int key1on = 49; int key2on = 50; int key3on = 51; int key4on = 52; int key5on = 53; int key6on = 54; //Flex all fingers int key1off = 113; //q int key2off = 119; //w int key3off = 101; //e int key4off = 114; //r int key5off = 116; //t void setup() { Serial.begin(9600); serv1.attach(2); //attach Thumb to A02 serv2.attach(3); //attach Index Finger to A03 serv3.attach(4); //attach Middle Finger to A04 serv4.attach(5); //attach Ring Finger to A05 serv5.attach(6); //attach Pinky to A06 // myservoX.attach(9); // attaches the servo on pin 9 to the servo object // myservoY.attach(8); delay(10); initializeAllFinger(); } void loop() { key = serialRead(); Serial.println(key); moveFinger(key); key = 0; delay(1000); } //to keep wires in tension void initializeAllFinger(){ serv1.write(serv1_ang); serv2.write(serv2_ang); serv3.write(serv3_ang); serv4.write(serv4_ang); serv5.write(serv5_ang); } //serious of movements for the fingers void moveFinger(int n){ //if input is 0, do nothing if(n == 0){ serv1.write(serv1_ang); serv2.write(serv2_ang); serv3.write(serv3_ang); serv4.write(serv4_ang); serv5.write(serv5_ang); } if(n == 1){ serv1.write(150); } if(n == 2){ serv2.write(140); } if(n == 3){ serv3.write(180); } if(n == 4){ serv4.write(180); } if(n == 5){ serv5.write(360); } if(n == 6){ serv1.write(150); // delay(1000); // initializeAllFinger(); serv2.write(140); // delay(1000); // initializeAllFinger(); serv3.write(180); // delay(1000); // initializeAllFinger(); serv4.write(180); // delay(1000); // initializeAllFinger(); serv5.write(360); // delay(1000); // initializeAllFinger(); } } //helper function to read which key is pressed int serialRead(){ // send data only when you receive data: if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); //print which finger is on or off if(incomingByte == key1on){ key = 1; } if(incomingByte == key2on){ key = 2; } if(incomingByte == key3on){ key = 3; } if(incomingByte == key4on){ key = 4; } if(incomingByte == key5on){ key = 5; } if(incomingByte == key6on){ key = 6; } } return key; }
Java
UTF-8
704
2.15625
2
[]
no_license
package dolphin.service; import dolphin.entity.Script; import java.util.List; public interface ScriptService { List<Script> findAll(); void save(Script script); /** * @param id id * @return 脚本对象 */ Script findById(Long id); /** * 查询历史脚本 * * @param id id * @return 脚本 */ Script findHisTory(Long id); /** * 更新一个脚本: * 1、将已有的脚本设置为已过期 * 2、新加入一条脚本数据,状态为最新,parentId为上一个脚本的id,状态为最新 * * @param script 脚本 */ void update(Script script); Script findByName(String name); }
C++
UTF-8
1,086
3.390625
3
[]
no_license
#include "Node.h" #include <iostream> #include <string> Node::Node() {} void Node::setData(int d) { data = d; //std::cout << "data now set to " << data << std::endl; } void Node::setColour(Colour c) { colour = c; } void Node::setParent(Node* p) { parent = p; } void Node::setLeft(Node* l) { left = l; } void Node::setRight(Node* r) { right = r; } int Node::getData() { return data; } std::string Node::getColourName() { if (colour == BLACK) { return "black"; } return "red"; } Node* Node::getParent() { return parent; } Node* Node::getGrandparent() { return parent->getParent(); } Node* Node::getSibling() { if (parent->getLeft() == this) { return parent->getRight(); } else { return parent->getLeft(); } } Node* Node::getUncle() { if (getGrandparent() != nullptr) { if (parent == getGrandparent()->getLeft()) { return getGrandparent()->getRight(); } else { return getGrandparent()->getLeft(); } } return nullptr; } Node* Node::getLeft() { return left; } Node* Node::getRight() { return right; }
Ruby
UTF-8
2,495
2.671875
3
[]
no_license
module TeamHelper #separates the file into the necessary elements to create a new user def self.upload_teams(file, assignment_id, options,logger) unknown = Array.new while (rline = file.gets) split_line = rline.split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/) if options[:has_column_names] == "true" name = split_line[0] pos = 1 else name = generate_team_name() pos = 0 end teams = Team.find(:all, :conditions => ["name =? and assignment_id =?",name,assignment_id]) currTeam = teams.first if currTeam != nil && options[:handle_dups] == "rename" name = generate_team_name() currTeam = nil end if options[:handle_dups] == "replace" && teams.first != nil for teamsuser in TeamsUser.find(:all, :conditions => ["team_id =?", currTeam.id]) teamsuser.destroy end currTeam.destroy currTeam = nil end if teams.length == 0 || currTeam == nil currTeam = Team.new currTeam.name = name currTeam.assignment_id = assignment_id currTeam.save end logger.info "#{split_line.length}" logger.info "#{split_line}" while(pos < split_line.length) user = User.find_by_name(split_line[pos].strip) if user && !(options[:handle_dups] == "ignore" && teams.length > 0) teamusers = TeamsUser.find(:all, :conditions => ["team_id =? and user_id =?", currTeam.id,user.id]) currUser = teamusers.first if teamusers.length == 0 || currUser == nil currUser = TeamsUser.new currUser.team_id = currTeam.id currUser.user_id = user.id currUser.save Participant.create(:assignment_id => assignment_id, :user_id => user.id, :permission_granted => true) end else unknown << split_line[pos] end pos = pos+1 end end return unknown end def self.generate_team_name() counter = 0 while (true) temp = "Team #{counter}" if (!Team.find_by_name(temp)) return temp end counter=counter+1 end end end
Markdown
UTF-8
13,616
4.15625
4
[]
no_license
title: Generator函数 author: 乔丁 tags: - 前端 categories: - web date: 2018-04-27 15:48:00 --- ## 简介 >1、Generator函数是ES6提供的一种异步编程方案 >2、从语法上,首先可以把它理解成一个状态机,封装了多个内部状态 >3、Generator函数还是一个遍历器对象生成函数,返回遍历器对象 >4、Generator函数有两个特征:1、function命令与函数名之间有一个星号;2、函数体内部使用yield语句定义不同的内部状态(“yield”在英语里的意思是“产出”) ```javascript function* helloWorldGenerator(){ yield 'hello'; yield 'world'; return 'ending'; } var hw = helloWorldGenerator(); ``` 定义了一个Generator函数——helloWorldGenerator,它内部有两个yield语句“hello”和“world”,即该函数有三个状态:hello、world和return语句(结束执行) 在调用Generator函数后,**该函数并不执行**,**返回的也不是函数运行结果,而是一个指向内部状态的指针对象,也就是遍历器对象**。 下一步必须调用遍历器对象的next方法,使得指针移向下一个状态。也就是说,每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个状态。也就是说,每次调用next方法,内部指针就从函数头部或从函数上一次停下来的地方开始执行,直到遇到下一条yield语句(或return语句)为止。换言之,**Generator函数是分段执行的,yield语句是暂停执行的标记,而next方法可以恢复执行** ```javascript hw.next() // {value: 'hello', done: false } hw.next() // {value: 'world', done: false } hw.next() // {value: 'ending', done: true } hw.next() // {value: undefined, done: true } ``` ES6没有规定function关键字与函数名之间的星号必须在哪 ### yield语句 由于Generator函数返回的遍历器对象只有调用next方法才会遍历下一个内部状态,所以其实提供了一种可以暂停执行的函数。yield语句就是暂停标志。 遍历器对象的next方法的运行逻辑如下: >1、遇到yield语句就暂停执行后面的操作,并将紧跟在yield后的表达式的值作为返回的对象的value属性值 >2、下一次调用next方法时才会继续执行,直到遇到下一个yield语句。 >3、如果没有再遇到新的yield语句,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值作为返回的对象的value属性值。 >4、如果该函数没有return语句,则返回的对象的value属性值为undefined。 要注意的是,yield语句后面的表达式,只有当调用next方法、内部指针指向该语句时才会执行,因此等于为JS提供了手动的“惰性求值”的语法功能。 ```javascript function* gen(){ yield 123+456; } ``` 上面的代码中,yield后面的表达式123+456不会立即求值,只会在next方法将指针移到这一语句时才求值 Generator函数可以不用yield语句,这时就变成了一个单纯的暂缓执行函数。 ```javascript function* f(){ console.log('执行了'); } var generator = f(); setTimeout(function(){ generator.next(); }, 2000); ``` 如果f只是普通函数,在为变量generator赋值时就会执行。但是函数f是一个Generator函数,于是就变成只有调用next方法时才会执行。 要注意yield语句不能再普通函数中,yield语句在表达式中,必须放在括号里 ## next方法 next方法可以携带一个参数: ```javascript function* f(){ for(var i=0; true; i++){ var reset = yield i; if(reset) {i = -1}; } } var g = f(); g.next() // {value: 0, done: false} g.next() // {value: 1, done: false} g.next(true) // {value: 0, done: false} ``` 定义了一个可以无限循环的Generator函数f,如果next方法没有参数,每次运行到yield语句,变量reset就会被重置为这个参数,因而i会等于-1,下一轮循环就从-1开始递增。 Generator函数从暂停到恢复运行,其上下文状态是不变的。通过next方法的参数就有办法在Generator函数开始运行后继续向函数提内部注入值。也就是说,可以在Generator函数运行的不同阶段,从外部向内部注入不同的值,从而调整函数行为。 ```javascript function* foo(x){ var y = 2 * (yield(x + 1)); var z = yield( y / 3 ); return (x + y + z); } var a = foo(5); a.next()//Object{value:6, done:false} a.next()//Object{value:NaN, done:false} a.next()//Object{value:NaN, done:false} var b = foo(5); b.next()//Object{value:6, done:false} b.next(12)//Object{value:8, done:false} b.next(13)//Object{value:42, done:false} ``` 如果next中没有参数,yield就返回undefined。所以在a第二次调next是y=2\*undefined,所以结果为NaN。 在实例b中,第一次yield返回6。第二次传入12,所以第二次返回的值为2\*12再除以3,所以结果为8.第三次同理 next参数就是上一条yield的返回值,所以第一次yield时不能带有参数。V8引擎会忽略第一次next时的参数,只从第二次使用next方法开始参数才是有效的。从语义上讲,第一个next方法用来启动遍历器对象,所以不用带有参数。如果想要第一次next带有参数,需要在Generator函数外再包一层。 ```javascript function wrapper(generatorFunction){ return function(...args){ let generatorObject = generatorFunction(...args); generatorObject.next(); return generatorObject; }; } const wrapped = wrapper(function* () { console.log('First input: ${yield}'); return 'DONE'; }); wrapped().next('hello!'); ``` 如果Generator函数不用wrapper先包一层,是无法第一次调用next方法就输入参数的。 ## for...of **for...of循环可以自动遍历Generator函数,且此时不再需要调用next方法。** ```javascript function *foo(){ yield 1; yield 2; yield 3; yield 4; yield 5; return 6; } for(let v of foo(){ console.log(v); }) //1 2 3 4 5 ``` for...of遇到done属性为true就会终止,且不包含该返回对象。所以return的6就不包括在for...of中 ## Generator与协程 协程是一种程序运行的方式,可以理解成“协作的线程”或“协作的函数”。协程可以用单线程实现,也可以用多线程实现;前者是一种特殊的子线程,后者是一种特殊的线程。 #### 协程与子例程的差异 传统的“子例程”采用堆栈式“先进后出”的概念实现,只有当调用的子函数完全执行完毕,才会结束执行父函数。协程与其不同,多个线程可以并行执行,但只有一个线程处于正在运行状态,其他线程都处于暂停态,线程之间可以交换执行权。也就是说,一个线程执行到一半,可以暂停执行,将执行权交给另一个线程,等到稍后回收执行权时再恢复执行。这种可以并行执行,将执行权交给另一个线程,等到稍后收回执行权时再恢复执行。这种可以并行执行、交换执行权的线程,就成为协程。 从实现上看,在内存中子例程只使用一个栈,而协程是同时存在多个栈,但只有一个栈是在运行态。也就是说,协程是以多占用内存为代价实现多任务的并行运行。 #### 协程与普通线程的差异 不难看出,协程适用于多任务运行的环境。在这个意义上,它与普通的线程很相似,都有自己执行的上下文,可以分享全局变量。他们不同之处在于,同一时间可以有多个线程是抢占式的,到底哪个线程优先得到资源,必须由运行环境决定,但是协程是合作式的,执行权由协程自己分配。 ECMAScript是单线程语言,只能保持一个调用栈。引入协程以后,每个任务可以保持自己的调用栈。这样做的最大好处,就是抛出错误时可以找到原始的调用栈,不至于像异步操作的回调函数那样,一旦出错原始的调用栈早已结束。 Generator函数是ES6对协程的实现,但属于不完全实现。Generator函数被称为“半协程”,意思是只有Generator函数的调用者才能将程序的执行权还给Generator函数。如果是完全实现的协程,任何函数都可以让暂停的协程继续执行。 如果将Generator函数当作协程,完全可以将多个需要互相协作的任务写成Generator函数,它们之间使用yield语句交换控制权。 ## 应用 Generator可以暂停函数执行,返回任意表达式的值。这种特点使得Generator有多种应用场景。 #### 1、异步操作的同步化表达 Generator函数的暂停执行效果,意味着可以把异步操作卸载yield语句里面,等到调用next方法时再执行。所以,Generator函数的一个重要实际意义就是用于**处理异步操作,改写回调函数** ```javascript function* loadUI () { showLoadingScreen(); yield loadUIDataAsynchronously(); hideLoadingScreen(); } var loader = loadUI(); //加载UI loader.next(); //卸载UI loader.next(); ``` 上面的代码表示,第一次调用loadUI函数时,该函数不会执行,仅返回一个遍历器。下一次对该遍历器调用next方法,**则会显示加载界面,并且异步加载数据**。等到数据加载完成,再一次使用next方法,则会隐藏加载界面。可以看到,这种写法的好处是所有加载界面的逻辑都被封装在一个函数中,按部就班非常清晰。 Ajax是典型的异步操作,通过Generator函数部署Ajax操作,可以用同步的方式表达。 ```javascript function* main(){ var result = yield request("http://xxoo"); var resp = JSON.parse(result); console.log(resp.value); } function request(url){ makeAjaxCall(url, function(response){ it.next(response); }); } var it = main(); it.next(); ``` 上面的main函数就是通过AJAX操作获取数据。可以看到,除了多了一个yield,它几乎与同步操作的写法一模一样。注意,makeAjaxCall函数中的next方法必须加上response参数,因为yield语句构成的表达式本身是没有值的,总是等于undefined。 通过Generator实现的逐行读取文本文件。 ```javascript function* numbers(){ let file = new FileReader("numbers.txt"); try{ while(!file.eof){ yield parseInt(file.readLine(), 10); } }finally{ file.close(); } } ``` 上面代码可以使用yield手动逐行读取文件 #### 2、控制流管理 如果有一个多步操作非常耗时,采用回调函数可能会写成这样。。 ```javascript step1(function(value1){ step2(value1, function(value2){ step3(value2, function(value3){ step4(value3, function(value4){ // Do something with value4 }) }) }) }); ``` 采用Promise改写上面的代码如下 ```javascript Q.fcall(step1) .then(step2) .then(step3) .then(step4) .then(function(value4){ //Do something with value4 }, function (error) { // Handle any error from step1 through step4 }) .done(); ``` 上面代码把回调函数改成了直线执行的形式,但是加入了大量Promise的语法 Generator函数可以进一步改善代码运行流程 ```javascript function* longRunningTask(){ try { var value1 = yield step1(); var value2 = yield step2(value1); var value3 = yield step2(value2); var value4 = yield step2(value3); // do something with value4 }catch(e){ // handle any err } } ``` 然后使用一个函数按次序自动执行所有步骤 ```javascript scheduler(longRunningTask()); function scheduler(task){ setTimeout(function(){ var taskObj = task.next(task.value); // 如果Generator函数未结束,就继续调用 if(!taskObj.done){ task.value = taskObj.value scheduler(task); } }, 0); } ``` yield语句是同步运行,不是异步运行(否则失去取代回调函数的设计目的) 多个任务按顺序一个接一个执行时,yield语句可以按顺序排列。多个任务需要并列执行时(比如只有当任务A和任务B都执行完时才能执行C),可以采用数组的写法。 ```javascript function* parallelDownloads(){ let [ text1, text2 ] = yield [ taskA(); taskB(); ]; console.log(text1, text2); } ``` 上面的代码中,yield语句的参数是一个数组,成员就是两个任务——taskA和taskB,只有等这两个任务都完成,才会接着执行下面的语句 #### 3、部署Iterator接口 利用Generator函数可以在任意对象上部署Iterator接口。 ```javascript function* iterEntries(obj){ let keys = Object.keys(obj); for(let i=0; i<keys.length; i++){ let key = key[i]; yield [key, obj[key]]; } } let myObj = {foo: 3, bar: 7}; for(let [key, value] of iterEntries(myObj)){ console.log(key, value); } // foo 3 bar 7 ``` 代码中,myObj是一个普通对象,通过iterEntries函数就有了Iterator接口。也就是说,可以在任意对象上部署next方法。 #### 4、作为数据结构 Generator可以看作数据结构,因为Generator函数可以返回一系列的值,这意味着它可以对任意表达式提供类似数组的接口。 ```javascript function *doStuff(){ yield fs.readFile.bind(null, 'xx.txt'); yield fs.readFile.bind(null, 'oo.txt'); yield fs.readFile.bind(null, 'zz.txt'); } ``` 上面代码一次返回三个函数,但是由于使用了Generator函数,导致可以像处理数组那样处理这三个返回的函数 ```javascript for(task of doStuff()){ //task是一个函数,可以像回调函数那样使用它 } ``` Generator使得数据或者操作具备了类似数组的接口
C#
UTF-8
833
2.53125
3
[]
no_license
namespace Dahlia.Domain.AggregateRootNotCreatedExceptionSpecs { using Machine.Specifications; public class when_initializing_a_AggregateRootNotCreatedException { Establish context =()=> aggregateRoot = new TestAggregateRoot(); Because of =()=> exception = new AggregateRootNotCreatedException(aggregateRoot); It should_have_a_useful_message =()=> exception.Message.ShouldEqual("The " + aggregateRoot.GetType() + " was not created"); It should_say_what_type_of_aggregate_root_was_involved =()=> exception.AggregateRoot.ShouldEqual(aggregateRoot.GetType()); static TestAggregateRoot aggregateRoot; static AggregateRootNotCreatedException exception; private class TestAggregateRoot : Dahlia.Domain.AggregateRoot { } } }
Java
UTF-8
3,391
2.390625
2
[]
no_license
package com.tje.model; import java.util.Date; public class DetailBoardFree_View { private int board_id; // 게시판 아이디 private int topic; // sql data의 board info 의 넘버링 private int category; // 관심사 private String title; // 제목 private String content; // 게시글 private String image; // 이미지 추가 private int comment_cnt; // 댓글 숫자 private String member_id; // 멤버 아이디 private String nickname; // 닉네임 private int view_cnt; // 게시글 읽음 카운트 private int like_cnt; // 좋아요 수 private int dislike_cnt; // 싫어요 수 private Date write_date; // 작성날자 public DetailBoardFree_View() { // TODO Auto-generated constructor stub } public DetailBoardFree_View(int board_id, int topic, int category, String title, String content, String image, int comment_cnt, String member_id, String nickname, int view_cnt, int like_cnt, int dislike_cnt, Date write_date) { super(); this.board_id = board_id; this.topic = topic; this.category = category; this.title = title; this.content = content; this.image = image; this.comment_cnt = comment_cnt; this.member_id = member_id; this.nickname = nickname; this.view_cnt = view_cnt; this.like_cnt = like_cnt; this.dislike_cnt = dislike_cnt; this.write_date = write_date; } public int getBoard_id() { return board_id; } public void setBoard_id(int board_id) { this.board_id = board_id; } public int getTopic() { return topic; } public void setTopic(int topic) { this.topic = topic; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getComment_cnt() { return comment_cnt; } public void setComment_cnt(int comment_cnt) { this.comment_cnt = comment_cnt; } public String getMember_id() { return member_id; } public void setMember_id(String member_id) { this.member_id = member_id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getView_cnt() { return view_cnt; } public void setView_cnt(int view_cnt) { this.view_cnt = view_cnt; } public int getLike_cnt() { return like_cnt; } public void setLike_cnt(int like_cnt) { this.like_cnt = like_cnt; } public int getDislike_cnt() { return dislike_cnt; } public void setDislike_cnt(int dislike_cnt) { this.dislike_cnt = dislike_cnt; } public Date getWrite_date() { return write_date; } public void setWrite_date(Date write_date) { this.write_date = write_date; } public String getCategoryString() { if (category == 1) { return "전체 게시글"; } else if (category == 2) { return "우리동네 운동부"; } else if (category == 3) { return "건강한 식생활"; } else if (category == 4) { return "나만의 운동법"; } else if (category == 5) { return "초보자를 위한 운동 추천"; } else { return "컴플랙스 극복"; } } }
Java
UTF-8
1,213
1.585938
2
[]
no_license
package org.nodeclipse.ui.preferences; /** * Constant definitions for plug-in preferences * * @author Tomoyuki Inagaki * @author Paul Verest */ public class PreferenceConstants { public static final String NODE_PATH = "node_path"; public static final String NODE_SOURCES_LIB_PATH = "node_sources_lib_path"; public static final String NODE_DEBUG_NO_BREAK = "node_debug_no_break"; public static final String NODE_DEBUG_PORT = "node_debug_port"; public static final String NODE_MONITOR_PATH = "node_monitor_path"; public static final String EXPRESS_PATH = "express_pass"; public static final String EXPRESS_VERSION = "express_version"; public static final String COFFEE_PATH = "coffee_pass"; public static final String COFFEE_COMPILE_OPTIONS = "coffee_compile_options"; public static final String COFFEE_COMPILE_OUTPUT_FOLDER = "coffee_compile_output_folder"; public static final String TYPESCRIPT_COMPILER_PATH = "typescript_compiler_path"; public static final String TYPESCRIPT_COMPILER_OPTIONS = "typescript_compiler_options"; public static final String COMPLETIONS_JSON_PATH = "completionsjson_path"; public static final String PREFERENCES_PAGE = "org.nodeclipse.ui.preferences.NodePreferencePage"; }
Markdown
UTF-8
3,059
2.578125
3
[ "MIT" ]
permissive
## Cityzen Clients - multiple client endpoints expected in future - client might be: a js widget that shows on any site, wp plugin, mobile app, any other client that can access an API - currently a vue based webapp is in development for the Fledge - external styles should match with [thefledge.com](https://thefledge.com) website style - accept task and track without sign-in (user token/id?) some tracking is needed for reporting - task acceptance should be allowed without login? - should entry of a valid user token be a form of authentication? ie: no 'unauthenticated' user actions, just configure what is needed to be 'authenticated' ### [Client User Stories](#user-stories) ### Vue webclient user stories #### unauthenticated users ##### when unauthenticated actions are allowed - [able to see available volunteer tasks](vue-client-user-stories/unauthenticated-list-available-tasks.md) - [accept task with user_code, username, or email](vue-client-user-stories/unauthenticated-accept-task.md) - [mark task complete with a user code](vue-client-user-stories/unauthenticated-mark-task-complete.md) ##### when configured for authenticated users only - [register for an account](vue-client-user-stories/register-new-user-account.md) - [authenticate internally to client on local network](vue-client-user-stories/authenticate-on-local-network.md) - [users should be able to authenticate from the internet, when configured](vue-client-user-stories/authenticate-from-internet.md) #### authenticated users definition of authenticated could be site/implementation specific (vue-client-user-stories/full login, user code/email, token, etc) - [authenticated user should be able to accept a task](vue-client-user-stories/authenticated-user-accept-task.md) - [authenticated user should be able to mark accepted task complete](vue-client-user-stories/authenticated-user-mark-accepted-task-complete.md) - [authenticated user should be able to list accepted/completed tasks](vue-client-user-stories/authenticated-user-list-accepted-complete-tasks.md) #### admin users - [admin user should be able to list users](vue-client-user-stories/admin-user-list-users.md) - [admin user should be able to edit notes for a valid user](vue-client-user-stories/admin-user-edit-notes-on-user.md) - [admin user should be able to list tasks for a specific user](vue-client-user-stories/admin-user-list-tasks-single-user.md) - [admin user should be able to mark completed task approved for a user](vue-client-user-stories/admin-user-marks-completed-task-approved.md) - [admin user should be able to make notes on completed user task](vue-client-user-stories/admin-user-make-completed-task-notes.md) - [admin user gets a list of users with accepted/completed tasks](vue-client-user-stories/admin-get-all-users-all-tasks-report) - [admin user gets a list of a specific user's accepted/completed tasks in a specified time period](vue-client-user-stories/admin-user-get-user-tasks-time-block.md) - [admin user add a task](vue-client-user-stories/admin-user-manually-add-task.md)
JavaScript
UTF-8
18,194
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "AFL-2.1", "EPL-1.0", "Apache-1.1", "MPL-1.1", "LicenseRef-scancode-generic-export-compliance", "Apache-2.0", "CPL-1.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "MIT", "AFL-3.0" ]
permissive
/* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ define(function(require, exports, module) { var strings = {}; /** * Add a CommonJS module to the list of places in which we look for * localizations. Before calling this function, it's important to make a call * to require(modulePath) to ensure that the dependency system (either require * or dryice) knows to make the module ready. * @param modulePath A CommonJS module (as used in calls to require). Don't * add the 'i18n!' prefix used by requirejs. * @see unregisterStringsSource() */ exports.registerStringsSource = function(modulePath) { // Bug 683844: Should be require('i18n!' + module); var additions = require(modulePath).root; Object.keys(additions).forEach(function(key) { if (strings[key]) { console.error('Key \'' + key + '\' (loaded from ' + modulePath + ') ' + 'already exists. Ignoring.'); return; } strings[key] = additions[key]; }, this); }; /** * Undo the effects of registerStringsSource(). * @param modulePath A CommonJS module (as used in calls to require). * @see registerStringsSource() */ exports.unregisterStringsSource = function(modulePath) { // Bug 683844: Should be require('i18n!' + module); var additions = require(modulePath).root; Object.keys(additions).forEach(function(key) { delete strings[key]; }, this); }; /** * Finds the preferred locales of the user as an array of RFC 4646 strings * (e.g. 'pt-br'). * . There is considerable confusion as to the correct value * since there are a number of places the information can be stored: * - In the OS (IE:navigator.userLanguage, IE:navigator.systemLanguage) * - In the browser (navigator.language, IE:navigator.browserLanguage) * - By GEO-IP * - By website specific settings * This implementation uses navigator.language || navigator.userLanguage as * this is compatible with requirejs. * See http://tools.ietf.org/html/rfc4646 * See http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference * See http://msdn.microsoft.com/en-us/library/ms534713.aspx * @return The current locale as an RFC 4646 string */ exports.getPreferredLocales = function() { var language = (navigator.language || navigator.userLanguage).toLowerCase(); var parts = language.split('-'); var reply = parts.map(function(part, index) { return parts.slice(0, parts.length - index).join('-'); }); reply.push('root'); return reply; }; /** * Lookup a key in our strings file using localized versions if possible, * throwing an error if that string does not exist. * @param key The string to lookup * This should generally be in the general form 'filenameExportIssue' where * filename is the name of the module (all lowercase without underscores) and * export is the name of a top level thing in which the message is used and * issue is a short string indicating the issue. * The point of a 'standard' like this is to keep strings fairly short whilst * still allowing users to have an idea where they come from, and preventing * name clashes. * @return The string resolved from the correct locale */ exports.lookup = function(key) { var str = strings[key]; if (!str) { throw new Error('No i18n key: ' + key); } return str; }; /** * An alternative to lookup(). * <tt>l10n.lookup('x') === l10n.propertyLookup.x</tt> * We should go easy on this method until we are sure that we don't have too * many 'old-browser' problems. However this works particularly well with the * templater because you can pass this in to a template that does not do * <tt>{ allowEval: true }</tt> */ if (typeof Proxy !== 'undefined') { exports.propertyLookup = Proxy.create({ get: function(rcvr, name) { return exports.lookup(name); } }); } /** * Helper function to process swaps. * For example: * swap('the {subject} {verb} {preposition} the {object}', { * subject: 'cat', verb: 'sat', preposition: 'on', object: 'mat' * }); * Returns 'the cat sat on the mat'. * @param str The string containing parts delimited by { and } to be replaced * @param swaps Lookup map containing the replacement strings */ function swap(str, swaps) { return str.replace(/\{[^}]*\}/g, function(name) { name = name.slice(1, -1); if (swaps == null) { console.log('Missing swaps while looking up \'' + name + '\''); return ''; } var replacement = swaps[name]; if (replacement == null) { console.log('Can\'t find \'' + name + '\' in ' + JSON.stringify(swaps)); replacement = ''; } return replacement; }); } /** * Lookup a key in our strings file using localized versions if possible, * and perform string interpolation to inject runtime values into the string. * l10n lookup is required for user visible strings, but not required for * console messages and throw strings. * lookupSwap() is virtually identical in function to lookupFormat(), except * that lookupSwap() is easier to use, however lookupFormat() is required if * your code is to work with Mozilla's i10n system. * @param key The string to lookup * This should generally be in the general form 'filename_export_issue' where * filename is the name of the module (all lowercase without underscores) and * export is the name of a top level thing in which the message is used and * issue is a short string indicating the issue. * The point of a 'standard' like this is to keep strings fairly short whilst * still allowing users to have an idea where they come from, and preventing * name clashes. * The value looked up may contain {variables} to be exchanged using swaps * @param swaps A map of variable values to be swapped. * @return A looked-up and interpolated message for display to the user. * @see lookupFormat() */ exports.lookupSwap = function(key, swaps) { var str = exports.lookup(key); return swap(str, swaps); }; /** * Perform the string swapping required by format(). * @see format() for details of the swaps performed. */ function format(str, swaps) { // First replace the %S strings var index = 0; str = str.replace(/%S/g, function() { return swaps[index++]; }); // Then %n$S style strings str = str.replace(/%([0-9])\$S/g, function(match, idx) { return swaps[idx - 1]; }); return str; } /** * Lookup a key in our strings file using localized versions if possible, * and perform string interpolation to inject runtime values into the string. * l10n lookup is required for user visible strings, but not required for * console messages and throw strings. * lookupFormat() is virtually identical in function to lookupSwap(), except * that lookupFormat() works with strings held in the mozilla repo in addition * to files held outside. * @param key Looks up the format string for the given key in the string bundle * and returns a formatted copy where each occurrence of %S (uppercase) is * replaced by each successive element in the supplied array. * Alternatively, numbered indices of the format %n$S (e.g. %1$S, %2$S, etc.) * can be used to specify the position of the corresponding parameter * explicitly. * The mozilla version performs more advances formatting than these simple * cases, however these cases are not supported so far, mostly because they are * not well documented. * @param swaps An array of strings to be swapped. * @return A looked-up and interpolated message for display to the user. * @see https://developer.mozilla.org/en/XUL/Method/getFormattedString */ exports.lookupFormat = function(key, swaps) { var str = exports.lookup(key); return format(str, swaps); }; /** * Lookup the correct pluralization of a word/string. * The first ``key`` and ``swaps`` parameters of lookupPlural() are the same * as for lookupSwap(), however there is an extra ``ord`` parameter which indicates * the plural ordinal to use. * For example, in looking up the string '39 steps', the ordinal would be 39. * * More detailed example: * French has 2 plural forms: the first for 0 and 1, the second for everything * else. English also has 2, but the first only covers 1. Zero is lumped into * the 'everything else' category. Vietnamese has only 1 plural form - so it * uses the same noun form however many of them there are. * The following localization strings describe how to pluralize the phrase * '1 minute': * 'en-us': { demo_plural_time: [ '{ord} minute', '{ord} minutes' ] }, * 'fr-fr': { demo_plural_time: [ '{ord} minute', '{ord} minutes' ] }, * 'vi-vn': { demo_plural_time: [ '{ord} phut' ] }, * * l10n.lookupPlural('demo_plural_time', 0); // '0 minutes' in 'en-us' * l10n.lookupPlural('demo_plural_time', 1); // '1 minute' in 'en-us' * l10n.lookupPlural('demo_plural_time', 9); // '9 minutes' in 'en-us' * * l10n.lookupPlural('demo_plural_time', 0); // '0 minute' in 'fr-fr' * l10n.lookupPlural('demo_plural_time', 1); // '1 minute' in 'fr-fr' * l10n.lookupPlural('demo_plural_time', 9); // '9 minutes' in 'fr-fr' * * l10n.lookupPlural('demo_plural_time', 0); // '0 phut' in 'vi-vn' * l10n.lookupPlural('demo_plural_time', 1); // '1 phut' in 'vi-vn' * l10n.lookupPlural('demo_plural_time', 9); // '9 phut' in 'vi-vn' * * The * Note that the localization strings are (correctly) the same (since both * the English and the French words have the same etymology) * @param key The string to lookup in gcli/nls/strings.js * @param ord The number to use in plural lookup * @param swaps A map of variable values to be swapped. */ exports.lookupPlural = function(key, ord, swaps) { var index = getPluralRule().get(ord); var words = exports.lookup(key); var str = words[index]; swaps = swaps || {}; swaps.ord = ord; return swap(str, swaps); }; /** * Find the correct plural rule for the current locale * @return a plural rule with a 'get()' function */ function getPluralRule() { if (!pluralRule) { var lang = navigator.language || navigator.userLanguage; // Convert lang to a rule index pluralRules.some(function(rule) { if (rule.locales.indexOf(lang) !== -1) { pluralRule = rule; return true; } return false; }); // Use rule 0 by default, which is no plural forms at all if (!pluralRule) { console.error('Failed to find plural rule for ' + lang); pluralRule = pluralRules[0]; } } return pluralRule; } /** * A plural form is a way to pluralize a noun. There are 2 simple plural forms * in English, with (s) and without - e.g. tree and trees. There are many other * ways to pluralize (e.g. witches, ladies, teeth, oxen, axes, data, alumini) * However they all follow the rule that 1 is 'singular' while everything * else is 'plural' (words without a plural form like sheep can be seen as * following this rule where the singular and plural forms are the same) * <p>Non-English languages have different pluralization rules, for example * French uses singular for 0 as well as 1. Japanese has no plurals while * Arabic and Russian are very complex. * * See https://developer.mozilla.org/en/Localization_and_Plurals * See https://secure.wikimedia.org/wikipedia/en/wiki/List_of_ISO_639-1_codes * * Contains code inspired by Mozilla L10n code originally developed by * Edward Lee <edward.lee@engineering.uiuc.edu> */ var pluralRules = [ /** * Index 0 - Only one form for all * Asian family: Japanese, Vietnamese, Korean */ { locales: [ 'fa', 'fa-ir', 'id', 'ja', 'ja-jp-mac', 'ka', 'ko', 'ko-kr', 'th', 'th-th', 'tr', 'tr-tr', 'zh', 'zh-tw', 'zh-cn' ], numForms: 1, get: function(n) { return 0; } }, /** * Index 1 - Two forms, singular used for one only * Germanic family: English, German, Dutch, Swedish, Danish, Norwegian, * Faroese * Romanic family: Spanish, Portuguese, Italian, Bulgarian * Latin/Greek family: Greek * Finno-Ugric family: Finnish, Estonian * Semitic family: Hebrew * Artificial: Esperanto * Finno-Ugric family: Hungarian * Turkic/Altaic family: Turkish */ { locales: [ 'af', 'af-za', 'as', 'ast', 'bg', 'br', 'bs', 'bs-ba', 'ca', 'cy', 'cy-gb', 'da', 'de', 'de-de', 'de-ch', 'en', 'en-gb', 'en-us', 'en-za', 'el', 'el-gr', 'eo', 'es', 'es-es', 'es-ar', 'es-cl', 'es-mx', 'et', 'et-ee', 'eu', 'fi', 'fi-fi', 'fy', 'fy-nl', 'gl', 'gl-gl', 'he', // 'hi-in', Without an unqualified language, looks dodgy 'hu', 'hu-hu', 'hy', 'hy-am', 'it', 'it-it', 'kk', 'ku', 'lg', 'mai', // 'mk', 'mk-mk', Should be 14? 'ml', 'ml-in', 'mn', 'nb', 'nb-no', 'no', 'no-no', 'nl', 'nn', 'nn-no', 'no', 'no-no', 'nb', 'nb-no', 'nso', 'nso-za', 'pa', 'pa-in', 'pt', 'pt-pt', 'rm', 'rm-ch', // 'ro', 'ro-ro', Should be 5? 'si', 'si-lk', // 'sl', Should be 10? 'son', 'son-ml', 'sq', 'sq-al', 'sv', 'sv-se', 'vi', 'vi-vn', 'zu', 'zu-za' ], numForms: 2, get: function(n) { return n != 1 ? 1 : 0; } }, /** * Index 2 - Two forms, singular used for zero and one * Romanic family: Brazilian Portuguese, French */ { locales: [ 'ak', 'ak-gh', 'bn', 'bn-in', 'bn-bd', 'fr', 'fr-fr', 'gu', 'gu-in', 'kn', 'kn-in', 'mr', 'mr-in', 'oc', 'oc-oc', 'or', 'or-in', 'pt-br', 'ta', 'ta-in', 'ta-lk', 'te', 'te-in' ], numForms: 2, get: function(n) { return n > 1 ? 1 : 0; } }, /** * Index 3 - Three forms, special case for zero * Latvian */ { locales: [ 'lv' ], numForms: 3, get: function(n) { return n % 10 == 1 && n % 100 != 11 ? 1 : n != 0 ? 2 : 0; } }, /** * Index 4 - * Scottish Gaelic */ { locales: [ 'gd', 'gd-gb' ], numForms: 4, get: function(n) { return n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 0 && n < 20 ? 2 : 3; } }, /** * Index 5 - Three forms, special case for numbers ending in 00 or [2-9][0-9] * Romanian */ { locales: [ 'ro', 'ro-ro' ], numForms: 3, get: function(n) { return n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2; } }, /** * Index 6 - Three forms, special case for numbers ending in 1[2-9] * Lithuanian */ { locales: [ 'lt' ], numForms: 3, get: function(n) { return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 2 : 1; } }, /** * Index 7 - Three forms, special cases for numbers ending in 1 and * 2, 3, 4, except those ending in 1[1-4] * Slavic family: Russian, Ukrainian, Serbian, Croatian */ { locales: [ 'be', 'be-by', 'hr', 'hr-hr', 'ru', 'ru-ru', 'sr', 'sr-rs', 'sr-cs', 'uk' ], numForms: 3, get: function(n) { return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; } }, /** * Index 8 - Three forms, special cases for 1 and 2, 3, 4 * Slavic family: Czech, Slovak */ { locales: [ 'cs', 'sk' ], numForms: 3, get: function(n) { return n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2; } }, /** * Index 9 - Three forms, special case for one and some numbers ending in * 2, 3, or 4 * Polish */ { locales: [ 'pl' ], numForms: 3, get: function(n) { return n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; } }, /** * Index 10 - Four forms, special case for one and all numbers ending in * 02, 03, or 04 * Slovenian */ { locales: [ 'sl' ], numForms: 4, get: function(n) { return n % 100 == 1 ? 0 : n % 100 == 2 ? 1 : n % 100 == 3 || n % 100 == 4 ? 2 : 3; } }, /** * Index 11 - * Irish Gaeilge */ { locales: [ 'ga-ie', 'ga-ie', 'ga', 'en-ie' ], numForms: 5, get: function(n) { return n == 1 ? 0 : n == 2 ? 1 : n >= 3 && n <= 6 ? 2 : n >= 7 && n <= 10 ? 3 : 4; } }, /** * Index 12 - * Arabic */ { locales: [ 'ar' ], numForms: 6, get: function(n) { return n == 0 ? 5 : n == 1 ? 0 : n == 2 ? 1 : n % 100 >= 3 && n % 100 <= 10 ? 2 : n % 100 >= 11 && n % 100 <= 99 ? 3 : 4; } }, /** * Index 13 - * Maltese */ { locales: [ 'mt' ], numForms: 4, get: function(n) { return n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 <= 10 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3; } }, /** * Index 14 - * Macedonian */ { locales: [ 'mk', 'mk-mk' ], numForms: 3, get: function(n) { return n % 10 == 1 ? 0 : n % 10 == 2 ? 1 : 2; } }, /** * Index 15 - * Icelandic */ { locales: [ 'is' ], numForms: 2, get: function(n) { return n % 10 == 1 && n % 100 != 11 ? 0 : 1; } } /* // Known locales without a known plural rule 'km', 'ms', 'ne-np', 'ne-np', 'ne', 'nr', 'nr-za', 'rw', 'ss', 'ss-za', 'st', 'st-za', 'tn', 'tn-za', 'ts', 'ts-za', 've', 've-za', 'xh', 'xh-za' */ ]; /** * The cached plural rule */ var pluralRule; });
Markdown
UTF-8
2,102
2.828125
3
[]
no_license
## ARVSM Absence Request and Vacation Schedule Management ## Case An ordinary way for any employee to request an approval to leave for some hours/days off the office is to send an email to the HR department and his Reporting manager. Then both parties approve or deny the request, resulting in an overload of communications over emails, messengers etc. ## Solution This application allows every employee, no matter his position, to place an absense request through a centralised web interface. Then another employee with the **manager** role may approve or deny requests assigned to him. ### Features for Requesters - Requesters could submit a absense request of type Full, Partial and Sickness. - For Full and Sickness type Requesters could specify Starting and Ending date , and days of leave - For Partial type Requesters specify Date and time interval - In addition they should provide a comment - After submiting their request they could view their past requests in tabular form along with their statuses - After request gets approved or denied from the assigned manager, request changes status and requesters can view their status and an additional comment from the manager - Requesters receive an email when their request gets approved or denied ### Features for Managers - Managers can view incoming requests in a tabular view - Managers can optionally include a response to the requester - Managers can approve or deny a request - Managers receive email when a new request assigned to them arrives ### Screenshots ![Imgur](http://i.imgur.com/KxO0YUs.png) ![Imgur](http://i.imgur.com/DhFaaWf.png) ###Instructions In order to run the application - `bundle install` Install required gems - `db:setup` Setup and seed the database - `rails s` Run embedded rails server ### Demo crendentials #### Employee - **email:** alonzo@gmail.com **password:** demo - **email:** james@gmail.com **password:** demo #### Manager - **email:** sherman@gmail.com **password:** demo - **email:** darin@gmail.com **password:** demo ###Specifications - Ruby on Rails v4.2.x - PostgreSQL 9.x - Semantic UI 2.1.8
C
UTF-8
3,924
2.84375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <unistd.h> #include <getopt.h> #include <mocalib.h> static int reset = 0; // -r option static char *chipId = NULL; // -i option static int persistent = 0; // -M option static char *beaconpwr = NULL; GCAP_GEN static void showUsage() { printf("Usage: DCAP.103 <PWR> [-M] [-r] [-h]\n\ Set or report beacon power of the node\n\ Note that resetting SoC is required for configuration to take affect.\n\ \n\ Options:\n\ <PWR> Amount of power reduction for Beacons in dB (rounded down to a multiple of 3)\n\ -M Make configuration changes permanent\n\ -r Reset SoC to make configuration changes effective\n\ -h Display this help and exit\n"); } GCAP_GEN int DCAP_103_main(int argc, char **argv) { int ret = 0; void *ctx; uint32_t getpwr =0; uint32_t pwr = 0; chipId = NULL; beaconpwr = NULL; persistent=0; reset=0; #if defined(STANDALONE) int i; #endif // ----------- Parse parameters if (argc < 2) { getpwr = 1; } else { beaconpwr = argv[1]; #if defined(STANDALONE) for (i=1; i < argc; i++) { if (strcmp(argv[i], "-i") == 0) { i++; chipId = argv[i]; } else if (strcmp(argv[i], "-M") == 0) { persistent = 1; } else if (strcmp(argv[i], "-r") == 0) { reset = 1; } else if (strcmp(argv[i], "?") == 0) { printf( "Error! Invalid option - %s\n", argv[i]); return(-1); } else if (strcmp(argv[i], "-h") == 0) { showUsage(); return(0); } } #else opterr = 0; while((ret = getopt(argc, argv, "Mrhi:")) != -1) { switch(ret) { case 'i': chipId = optarg; break; case 'M': persistent = 1; break; case 'r': reset = 1; break; case '?': printf( "Error! Invalid option - %c\n", optopt); return(-1); break; case 'h': default: showUsage(); return(0); } } #endif } // ----------- Initialize ctx = moca_open(chipId); if (!ctx) { printf( "Error! Unable to connect to moca instance\n"); return(-2); } if (getpwr) { ret = moca_get_beacon_pwr_reduction(ctx, &pwr); if (ret != MOCA_API_SUCCESS) { moca_close(ctx); printf( "Error! Internal-1\n"); return(-3); } printf("Beacon power reduction: %d dB\n", pwr*3); moca_close(ctx); return(0); } pwr = atol(beaconpwr); pwr /= 3; if ( pwr > MOCA_BEACON_PWR_REDUCTION_MAX ) { printf( "Error! Invalid value %d, beacon power must be between 0 and %d\n", pwr, MOCA_BEACON_PWR_REDUCTION_MAX*3); moca_close(ctx); return(-4); } ret = moca_set_beacon_pwr_reduction(ctx, pwr); if (ret != MOCA_API_SUCCESS) { moca_close(ctx); printf( "Error! Internal\n"); return(-2); } if (reset) { ret = moca_set_restart(ctx); if (ret != MOCA_API_SUCCESS) { moca_close(ctx); printf( "Error! Reinitialize\n"); return(-3); } } if (persistent) { ret = moca_set_persistent(ctx); if (ret != MOCA_API_SUCCESS) { moca_close(ctx); printf( "Error! Unable to save persistent parameters\n"); return(-8); } } moca_close(ctx); return(0); }
Java
UTF-8
524
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clinicpms.model; import clinicpms.store.CSVStore; import clinicpms.store.exceptions.StoreException; import java.util.ArrayList; /** * * @author colin */ public class Patients { public ArrayList<Patient> getPatients() throws StoreException{ return CSVStore.getInstance().readPatients(); } }
Java
UTF-8
353
2.328125
2
[]
no_license
package main.java.diet.nutella.hekibot.model; import java.util.Date; import java.util.TimerTask; public class DatabaseReconnecter extends TimerTask { private UserDAO dao; public DatabaseReconnecter(UserDAO dao) { this.dao = dao; } public void run() { this.dao.connect(); System.out.println("Reconnecting to DB at " + new Date()); } }
TypeScript
UTF-8
222
2.65625
3
[]
no_license
/* * @Author: linxiaozhou.com * @LastEditors: linxiaozhou.com * @Description: file content */ const welcome = (name: string): string => { return `Hello ${name}`; } console.log(welcome.toString()) console.log(welcome("linxiaozhou"))
Python
UTF-8
365
3.234375
3
[]
no_license
# https://www.acmicpc.net/problem/3052 # Solved Date: 20.04.05. import sys read = sys.stdin.readline NUM = 10 MOD = 42 def main(): # set을 쓰거나 in연산자와 list를 사용할 수 있다. remainder = set() for _ in range(NUM): remainder.add(int(read().strip()) % MOD) print(len(remainder)) if __name__ == '__main__': main()
C#
UTF-8
2,835
2.90625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; public class InstanceGenerator : MonoBehaviour { //PROPERTIES //---------------------- private List<GameObject> instances = new List<GameObject>(); private GameObject lastInstanceSpawned; private Vector3 pos = Vector3.zero; private Quaternion rot = Quaternion.identity; public int instanceCount { get { return instances.Count; } set { } } //EVENTS //---------------------- #pragma warning disable CS0649 public UnityEvent OnInstanceSpawned; public UnityEvent OnAllInstancesRemoved; #pragma warning restore CS0649 //METHODS //---------------------- /// <summary> /// Instantiate an object and store in the generator instance /// </summary> /// <param name="objectToSpawn"></param> public virtual void SpawnInstance(GameObject objectToSpawn) { _SpawnInstance(objectToSpawn, pos, rot); } /// <summary> /// Instantiate an object and store in the generator instance /// </summary> /// <param name="objectToSpawn"></param> /// <param name="position"></param> public virtual void SpawnInstance(GameObject objectToSpawn, Vector3 position) { _SpawnInstance(objectToSpawn, position, rot); } /// <summary> /// Instantiate an object and store in the generator instance /// </summary> /// <param name="objectToSpawn"></param> /// <param name="position"></param> /// <param name="rotation"></param> public virtual void SpawnInstance(GameObject objectToSpawn, Vector3 position, Quaternion rotation) { _SpawnInstance(objectToSpawn, position, rotation); } /// <summary> /// Internal method to handle spawning the instance once the public method has been called /// </summary> /// <param name="objectToSpawn"></param> /// <param name="position"></param> /// <param name="rotation"></param> protected virtual void _SpawnInstance(GameObject objectToSpawn, Vector3 position, Quaternion rotation) { if (!objectToSpawn) return; lastInstanceSpawned = Instantiate(objectToSpawn, position, rotation); instances.Add(lastInstanceSpawned); OnInstanceSpawned.Invoke(); } /// <summary> /// Remove all the instances managed by this generator /// </summary> public virtual void RemoveAllInstances() { foreach(GameObject obj in instances) { Destroy(obj); } OnAllInstancesRemoved.Invoke(); } /// <summary> /// Return the very last instance spawned. /// </summary> /// <returns></returns> public virtual GameObject GetLastInstance() { return lastInstanceSpawned; } }
Java
UTF-8
1,351
2.828125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Joueur; /** * * @author isoyturk */ public class Joueur { private int idJoueur; private int tourCourrant = 1; private final int nbToursMax = 30; private int score; private int nbOuvriersPlateau = 0; private int nbOuvriersExterieur = 8; private int materiels = 8; private int energie = 16; private int batimentSurPlateau=0; public Joueur(int idJoueur, int score) { this.idJoueur = idJoueur; this.score = score; } public void tourSuivant() { if (tourCourrant < nbToursMax) { tourCourrant++; } } public int recupererTourCourrant() { return tourCourrant; } public int recupererMateriel() { return materiels; } public int recupererEnergie() { return energie; } public int recupererScore() { score=(1*materiels)+(1*energie)+(2*nbOuvriersExterieur)+(4*nbOuvriersPlateau)+(8*batimentSurPlateau); return score; } public int recupererOuvrierPlateau() { return nbOuvriersPlateau; } public int recupererOuvrierExterieur() { return nbOuvriersExterieur; } }
C++
UTF-8
2,141
3.21875
3
[]
no_license
// // 1dtb_02.cpp // // // Created by Disha Kuzhively on 24/03/19. // #include <iostream> #include <algorithm> #include <fstream> #include <cmath> #include <cstdio> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_sort_vector.h> static const double t = 1; static const double pi = acos(-1); static const int N = 1000; //N has to be larger than 2, kDelta is defined that way using namespace std; int kDelta(int, int); double Lorentzian(double, double, double); int main(void){ gsl_matrix * H = gsl_matrix_alloc (N, N); // Hamiltonian matrix for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { gsl_matrix_set (H, i-1, j-1, - 1 * (kDelta(i,j-1) + kDelta(i,j+1))*t); } } // Display Hamiltonian matrix // for (int i = 0; i < N; i ++) { // for (int j = 0; j < N; j++) { // cout << gsl_matrix_get (H, i, j) << " \t " ; // } // cout << endl ; // } gsl_vector * eig_val = gsl_vector_alloc (N); gsl_eigen_symm_workspace * w = gsl_eigen_symm_alloc (N); gsl_eigen_symm(H, eig_val, w); gsl_eigen_symm_free (w); gsl_sort_vector(eig_val); // for (int i = 0; i < N; i++) { // cout << gsl_vector_get(eig_val,i) << endl; // } double en_min = gsl_vector_get(eig_val,0); double en_max = gsl_vector_get(eig_val, N-1); double gamma = ( en_max - en_min )/N; ofstream outfile; outfile.open( "1dtb02.dat" ); double E = en_min; for (int i = 0; i <= 50; i ++) { double dos = 0; for (int j = 0; j < N; j ++) { dos += Lorentzian(E, gsl_vector_get(eig_val,j), gamma); } E += (en_max - en_min)/50; outfile << E << " \t " << dos << " \t " <<endl; } outfile.close(); gsl_vector_free (eig_val); gsl_matrix_free (H); return 0; } int kDelta(int a, int b) { if (a%N == b%N) { return 1; } else { return 0; } } double Lorentzian(double E, double E0 , double gamma) { return gamma / ( 2*pi*( pow((E-E0),2) + pow((gamma/2),2) ) ); }
Ruby
UTF-8
263
2.671875
3
[]
no_license
module TrackIdentity::PointDistanceToPoint module_function def get(point_a, point_b) distance( point_a.map(&:to_f), point_b.map(&:to_f), ) end def distance(pa, pb) Math.sqrt((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2) end end
Java
UTF-8
3,095
2.765625
3
[]
no_license
package com.franklin.test; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.List; import java.awt.Panel; import java.awt.Toolkit; import java.util.ArrayList; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JPanel; import com.franklin.domain.Position; import com.franklin.snake.item.equipment.gun.bullet.BiasBullet; import com.franklin.snake.item.equipment.gun.bullet.RailBullet; import com.franklin.utils.KeyBoard; import com.franklin.utils.settings.EnemySettings; import com.franklin.utils.settings.SnakeSettings; /** *@author : 叶俊晖 *@date : 2019年4月27日上午9:28:14 */ public class TanA extends JFrame{ MyPanel2 mp=null; public static void main(String[] args) { new TanA(); } public TanA(){ RailBullet railBullet = new RailBullet(); // BiasBullet biasBullet = new BiasBullet(KeyBoard.UP, 10); Thread thread = new Thread(railBullet); thread.start(); // BiasBullet biasBullet2 = new BiasBullet(KeyBoard.UP, -10); // Thread thread2 = new Thread(biasBullet2); // thread2.start(); mp=new MyPanel2(); // mp.biasBullet=biasBullet; // mp.biasBullet2=biasBullet2; mp.railBullet=railBullet; this.add(mp); this.setSize(1280,720); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); while (true) { mp.repaint(); } } } class MyPanel extends JPanel{ @Override public void paint(Graphics g) { super.paint(g); /* g.drawImage(SnakeSettings.BODY_IMAGE, body.getNow().getX(), body.getNow().getY(), SnakeSettings.size,SnakeSettings.size,this); */ int angle = 45; int x0 =400; int y0 =400; double tanA = Math.tan(getAngle()); Vector<Position> list = new Vector<>(); int b = (int) (x0 - y0/tanA);//b = y0/tan(pi+b/2)+x0 // x = tanA*y + b for (int y = 0; y < y0; y+=SnakeSettings.size) { Position position = new Position((int) (tanA*y)+b, y); list.add(position); } tanA = -tanA;//b2 = x0 - y0/tan(b/2) x = int b2 = (int) (x0 - y0/tanA); for (int y = 0; y < y0; y+=SnakeSettings.size) { Position position = new Position((int) (tanA*y)+b2,y); list.add(position); } for (Position position : list) { g.drawImage(SnakeSettings.BODY_IMAGE, position.getX(), position.getY(), SnakeSettings.size,SnakeSettings.size,this); } } public static double getAngle(){ return Math.PI*(EnemySettings.VISION_ANGLE/360.0); } } class MyPanel2 extends JPanel{ BiasBullet biasBullet; BiasBullet biasBullet2; RailBullet railBullet; public MyPanel2() { } @Override public void paint(Graphics g) { super.paint(g); Position position = railBullet.getBody().getNow(); // g.drawImage(SnakeSettings.BODY_IMAGE, position.getX(), position.getY(), SnakeSettings.size,SnakeSettings.size,this); // position = biasBullet2.getBody().getNow(); // g.drawImage(SnakeSettings.BODY_IMAGE, position.getX(), position.getY(), SnakeSettings.size,SnakeSettings.size,this); g.drawImage(railBullet.image, position.getX(), position.getY(), railBullet.width,railBullet.height,this); } }
Java
UTF-8
2,137
3.34375
3
[]
no_license
package generators; import model.Cell; import model.Field; import model.State; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; public class FieldGenerator { private static CellHelper cellHelper = new CellHelper(); public static Field generateRandomField(int m, int n) { Random random = new Random(); Cell[][] cells = new Cell[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int chance = random.nextInt(10); if (chance == State.ALIVE.ordinal()) { cells[i][j] = new Cell(State.ALIVE); } else { cells[i][j] = new Cell(State.DEAD); } } } cellHelper.setNeighbors(cells); return new Field(m, n, cells); } public static Field generateFieldFromFile(File file) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(file))) { List<String> lines = new ArrayList<>(); while (br.ready()) { lines.add(br.readLine()); } br.close(); int m = lines.size(); int n = lines.get(0).split(" ").length; Cell[][] cells = new Cell[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { String[] line = lines.get(i).split(" "); int state = Integer.parseInt(line[j]); if (state == 0) { cells[i][j] = new Cell(State.DEAD); } else if (state == 1) { cells[i][j] = new Cell(State.ALIVE); } else { throw new IOException("Wrong data in file!"); } } } cellHelper.setNeighbors(cells); return new Field(m, n, cells); } } }
Java
UTF-8
579
3.0625
3
[]
no_license
package basic.chapter19.it; /** * @author xiangdotzhaoAtwoqutechcommacom * @date 2020/4/27 */ public class Leaf extends AbstractComponent { public Leaf(String name) { super(name); } @Override protected void add(AbstractComponent component) { System.out.println("Cannot add to a leaf"); } @Override protected void remove(AbstractComponent component) { System.out.println("Cannot remove from a leaf"); } @Override protected void display(int depth) { System.out.println(name + " : " + depth); } }
Ruby
UTF-8
403
3.875
4
[]
no_license
#!/usr/bin/ruby class Point attr_accessor :x, :y protected :x=, :y= def initialize(x = 0.0, y = 0.0) @x, @y = x, y end def swap(other) @x, other.x = other.x, @x @y, other.y = other.y, @y return self end end p0 = Point.new p1 = Point.new(1.0, 2.0) p [p0.x, p0.y] p [ p1.x, p1.y ] p0.swap(p1) p [ p0.x, p0.y ] p [ p1.x, p1.y ] a, b = 1, 2 p [a, b] a, b = b, a p [a, b]
Java
UTF-8
1,537
2.25
2
[]
no_license
package de.linnk.streaming; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; import com.thoughtworks.xstream.io.xml.SaxWriter; import de.linnk.domain.Document; public class SaxDocumentStreamer extends XStreamDocumentStreamer { public final OutputFormat outputformat ; public SaxDocumentStreamer() { super(); this.outputformat = new OutputFormat("XML","UTF-8",true); // encoding works ! (?) this.outputformat.setIndent(1); this.outputformat.setIndenting(true); // TODO Auto-generated constructor stub } @Override public Document readFromStream(InputStream stream) { throw new RuntimeException("not yet supported"); //return null; } @Override public boolean writeToStream(OutputStream stream, Document document) { final XMLSerializer serializer = new XMLSerializer(stream,this.outputformat); final SaxWriter writer = new SaxWriter(); try { writer.setContentHandler(serializer.asContentHandler()); this.addNodesBeforeDocument(writer); this.xstream.marshal(document, writer); this.addNodesAfterDocument(writer); return true; } catch (final IOException e) { de.mxro.utils.log.UserError.singelton.log(e); de.mxro.utils.log.UserError.singelton.log("Error while trying to write Document to stream: "+document.getFilename().toString()); return false; } } }
C
UTF-8
1,426
2.53125
3
[]
no_license
/* ============================================================================ Name : MDangeloParc1LaboV2.c Author : mdangelo Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "utn_mdangelo_test/EntitiesTest.h" #include "utn_mdangelo_business/VeterinaryBusiness.h" #define TEST_MODE 1 int main(void) { Veterinary veterinary; vtBsns_initializeAllVeterinary(&veterinary,TEST_MODE); if(!TEST_MODE) vtnBsn_startVeterinary(&veterinary); else{ //entTst_petCreationTest(&veterinary); //ok //entTst_updateABreedTest(&veterinary); //ok //entTst_deleteAPetTest(&veterinary); //ok //entTst_updateAPetTest(&veterinary); //ok //entTst_updateOwnerTest(&veterinary); //ok //entTst_createOwnerTest(&veterinary); //ok //entTst_deleteOwner(&veterinary); //ok //entTst_sortPetsByTypeAndShowAll(&veterinary); //ok //entTst_showOwnerWithPets(&veterinary); //ok //entTst_showPetsMoreThan3YearsAndHisOwner(&veterinary); //ok //entTst_showPetsByType(&veterinary); //ok //entTst_sortOwnerByPetsNumberAndOwnerName(&veterinary); //ok //entTst_calculateAndShowAllInfo(&veterinary);//ok entTst_sortOwnerByLocIdAndOwnerName(&veterinary);//preg 21 } printf("============END==================\n"); return EXIT_SUCCESS; }
Java
UTF-8
9,548
2.59375
3
[]
no_license
package sample; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.util.ArrayList; import java.util.List; public class Main extends Application { private List<Good> goodsInShop = new ArrayList<>(); @Override public void start(Stage purchase) { purchase.setX(100); purchase.setY(10); purchase.setTitle("ПОКУПКА ТОВАРОВ В МАГАЗИНЕ"); ScrollPane mainPane = new ScrollPane(); mainPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); GridPane gridPane = new GridPane(); gridPane.add(new Label(" Наименование "), 0, 0); gridPane.add(new Label(" Цена, $"), 1, 0); gridPane.add(new Label(" Кол-во в\nмагазине "), 2, 0); gridPane.add(new Label(" Кол-во в\nкорзине "), 4, 0); gridPane.add(new Label(" Стоимость "), 5, 0); Controller service = new Controller(); goodsInShop = service.getAll(); int countOfGoods = goodsInShop.size(); gridPane.getCellBounds(5, countOfGoods + 3); Label totalCost = new Label(); Label totalCount = new Label(); gridPane.add(totalCount, 4, countOfGoods + 2); gridPane.add(totalCost, 5, countOfGoods + 2); gridPane.add(new Label("КОЛ-ВО"), 4, countOfGoods + 1); gridPane.add(new Label("СУММА"), 5, countOfGoods + 1); Button butBuy = new Button(); butBuy.setText("ОПЛАТА"); butBuy.setMinWidth(65); Label[] name = new Label[countOfGoods]; Label[] price = new Label[countOfGoods]; Label[] countInShop = new Label[countOfGoods]; Button[] butPlus = new Button[countOfGoods]; Button[] butMinus = new Button[countOfGoods]; Label[] countInCart = new Label[countOfGoods]; Label[] cost = new Label[countOfGoods]; for (int i = 0; i < countOfGoods; i++) { int row = i + 1; name[i] = new Label(goodsInShop.get(i).name); price[i] = new Label(String.valueOf(goodsInShop.get(i).price)); countInShop[i] = new Label(); countInCart[i] = new Label(); cost[i] = new Label(); gridPane.add(name[i], 0, row); gridPane.add(price[i], 1, row); gridPane.add(countInShop[i], 2, row); gridPane.add(countInCart[i], 4, row); gridPane.add(cost[i], 5, row); butPlus[i] = new Button(); butPlus[i].setText("+"); butPlus[i].setMinWidth(65); butMinus[i] = new Button(); butMinus[i].setText("-"); butMinus[i].setMinWidth(65); VBox boxButton = new VBox(); boxButton.getChildren().addAll(butPlus[i], butMinus[i]); gridPane.add(boxButton, 3, row); } goodsCounter(goodsInShop, countInShop); gridPane.add(butBuy, 3, countOfGoods + 2); mainPane.setContent(gridPane); purchase.setScene(new Scene(mainPane)); purchase.show(); for (int i = 0; i < countOfGoods; i++) { int index = i; butPlus[i].setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { if (Integer.parseInt(countInCart[index].getText()) < Integer.parseInt(countInShop[index].getText())) { int numInCart = 0; if (!countInCart[index].getText().isEmpty()) { numInCart = Integer.parseInt(countInCart[index].getText()); } numInCart++; countInCart[index].setText(String.valueOf(numInCart)); int currentPrice = Integer.parseInt(price[index].getText()); cost[index].setText(String.valueOf(numInCart * currentPrice)); totalCount.setText(sum(countInCart)); totalCost.setText(sum(cost)); } else { showAlert("Количество товара в магазине меньше нуля!"); } } }); butMinus[i].setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { int numInCart; if (!countInCart[index].getText().isEmpty()) { numInCart = Integer.parseInt(countInCart[index].getText()); if (numInCart > 0) { numInCart--; countInCart[index].setText(String.valueOf(numInCart)); int currentPrice = Integer.parseInt(price[index].getText()); cost[index].setText(String.valueOf(numInCart * currentPrice)); totalCount.setText(sum(countInCart)); totalCost.setText(sum(cost)); } if (numInCart == 0) { countInCart[index].setText(""); cost[index].setText(""); } } else { showAlert("Данный товар в корзине отсутствует!"); } } }); } butBuy.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { ArrayList<Good> buyList = new ArrayList<>(); for (int iD = 0; iD < countOfGoods; iD++) { if (!countInCart[iD].getText().isEmpty()) { int count = Integer.parseInt(countInCart[iD].getText()); buyList.add(goodsInShop.get(iD)); buyList.get(buyList.size() - 1).count = count; countInCart[iD].setText(""); cost[iD].setText(""); } } service.buy(buyList); totalCount.setText(""); totalCost.setText(""); goodsInShop = service.getAll(); goodsCounter(goodsInShop, countInShop); } }); Stage addingGoodsWindow = new Stage(); addingGoodsWindow.setX(500); addingGoodsWindow.setY(10); addingGoodsWindow.setHeight(70); addingGoodsWindow.setWidth(580); addingGoodsWindow.setTitle("ДОБАВЛЕНИЕ ТОВАРОВ В МАГАЗИН"); TextField nameOfGood = new TextField(); TextField priceOfGood = new TextField(); TextField countOfGood = new TextField(); Button inputGood = new Button("Добавить товар"); FlowPane flowPane = new FlowPane(); flowPane.getChildren().addAll(nameOfGood, priceOfGood, countOfGood, inputGood); Scene scene = new Scene(flowPane, 10, 10); addingGoodsWindow.setScene(scene); addingGoodsWindow.show(); inputGood.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { String name = nameOfGood.getText(); int price = Integer.parseInt(priceOfGood.getText()); int count = Integer.parseInt(countOfGood.getText()); Good newGood = new Good(); newGood.name = name; newGood.price = price; newGood.count = count; String result = service.addGood(newGood); showResultOfAdding(result); } }); } public static void main(String[] args) { launch(args); } private static String sum(Label[] cost) { int result = 0; for (Label index : cost) { if (!(index.getText().isEmpty())) { result += Integer.parseInt(index.getText()); } } return String.valueOf(result); } private static void goodsCounter(List<Good> goods, Label[] count) { for (int i = 0; i < goods.size(); i++) { count[i].setText(String.valueOf(goods.get(i).count)); } } private void showAlert(String information) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle(""); alert.setHeaderText("ВНИМАНИЕ!"); alert.setContentText(information); alert.showAndWait(); } private void showResultOfAdding(String information) { if (information.equals("Добавление товара НЕ получилось!")) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle(""); alert.setHeaderText("ПРОВАЛ !!!"); alert.setContentText(information); alert.showAndWait(); } else { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle(""); alert.setHeaderText("УСПЕШНО !!!"); alert.setContentText(information); alert.showAndWait(); } } }
C#
UTF-8
1,997
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Scholarship { class Program { static void Main(string[] args) { double incomeMoney = double.Parse(Console.ReadLine()); double advancement = double.Parse(Console.ReadLine()); double minIncomeSalary = double.Parse(Console.ReadLine()); double socialScholarShip = 0; double gradeScholarShip = 0; if (incomeMoney > minIncomeSalary) { if (advancement < 5.50) { Console.WriteLine("You cannot get a scholarship!"); } else if (advancement >= 5.50) { gradeScholarShip = advancement * 25; Console.WriteLine($"You get a scholarship for excellent results {gradeScholarShip} BGN"); } } else if (incomeMoney<=minIncomeSalary) { if (advancement < 5.50) { socialScholarShip = 0.35 * minIncomeSalary; Console.WriteLine($"You get a Social scholarship {socialScholarShip} BGN"); } else if (advancement >= 5.50) { gradeScholarShip = Math.Floor(advancement * 25); socialScholarShip = Math.Floor(0.35 * minIncomeSalary); if (gradeScholarShip>=socialScholarShip) { Console.WriteLine($"You get a scholarship for excellent results {gradeScholarShip} BGN"); } else if (socialScholarShip>gradeScholarShip) { Console.WriteLine($"You get a Social scholarship {socialScholarShip} BGN"); } } } } } }
Java
UTF-8
1,245
2.40625
2
[]
no_license
package nl.saxion.site.Provider; import nl.saxion.site.Administration.Administration; import nl.saxion.site.model.Accessory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * @author Onyebuchi Iheuwadinachi Eleazu */ @Service public class AccessoryProvider { public List<Accessory> getAccessories(String username) { List<Accessory> accessories = new ArrayList<>(); for (Accessory accessory : Administration.accessories) { if (accessory == null) { continue; } if (username.equals("admin")) { accessories.add(accessory); } else { if (accessory.getUsername().equals(username)) { accessories.add(accessory); } } } return accessories; } public void removeAccessory(int id) { Administration.accessories.set(id, null); } public void newAccessory(String name, int stock, int price, String category, String description, String username) { int id = Administration.accessories.size(); Administration.accessories.add(new Accessory(id, name, stock, price, category, description, username)); } }
Java
UTF-8
566
1.984375
2
[]
no_license
package cn.com.clubank.weihang.manage.product.service; import cn.com.clubank.weihang.manage.product.pojo.ProductReadLog; /** * 产品浏览记录管理 * @author Liangwl * */ public interface IProductReadLogService { /** * 保存浏览记录 * @param record * @return */ String insertReadLog(ProductReadLog record); /** * 查询浏览记录并分页 * @param customerId 客户ID * @param pageIndex 页码下标 * @param pageSize 每页行数 * @return */ String selectReadLog(String customerId,Integer pageIndex,Integer pageSize); }
Java
UTF-8
11,977
2.265625
2
[]
no_license
package com.config; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import com.enc.Blowfish; import com.topking.ftp.bean.UserInfoBean; import com.topking.ftp.bean.ConfigBean; /** * 配置文件生成 * * @author root input: Panel output: Config.txt */ public class ParseConfig implements Runnable { // TestConfig tc; //测试配置面板 private String desDir; private UserInfoBean uib; private ConfigBean cfb; public boolean isFinish = false; public ParseConfig(String desDir, UserInfoBean uibean, ConfigBean cfbean) { this.desDir = desDir + ".txt"; this.uib = uibean; this.cfb = cfbean; } public void run() { File file = new File(desDir); if (!file.getParentFile().exists()) { file.mkdir(); } if (uib == null || cfb == null) { return; } try { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter output = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(output); { bw.write("# 配置文件,自动生成,请勿修改!!"); bw.newLine(); bw.write("# 注意请不要修改格式!"); bw.newLine(); bw.write("#每个参数间用“;”隔开"); bw.newLine(); bw.write("#"); bw.newLine(); bw.newLine(); } { String ftpupdir = uib.getUserID(); // System.out.println("ftpupdir:"+ftpupdir); bw.write("<个人用户名>"); bw.newLine(); if ((ftpupdir == null) || (ftpupdir.equals(""))) { bw.write("/;"); } else { bw.write("/" + ftpupdir + ";"); } bw.newLine(); bw.write("</个人用户名>"); bw.newLine(); bw.newLine(); } { boolean unInstall = cfb.getUnInstall(); bw.write("<卸载程序>");// 选中则卸载木马 bw.newLine(); if (unInstall) { bw.write("true" + ";"); } else { bw.write("false" + ";"); } System.out.println("Uninstall:" + unInstall); bw.newLine(); bw.write("</卸载程序>"); bw.newLine(); bw.newLine(); } { bw.write("<屏幕截图存放路径>"); bw.newLine(); if (true) { // bw.write("/private/var/root/Library/Caches/com.apple.ScreenSaver;"); bw.write("/;"); } bw.newLine(); bw.write("</屏幕截图存放路径>"); bw.newLine(); bw.newLine(); } { boolean closeScreen = cfb.getScreenCapture(); bw.write("<屏幕截图开关>");// 这个木马端没有 bw.newLine(); if (closeScreen) { bw.write("true" + ";"); } else { bw.write("false" + ";"); } System.out.println("OpenScreenCapture:" + closeScreen); bw.newLine(); bw.write("</屏幕截图开关>"); bw.newLine(); bw.newLine(); } { boolean closeScreenTime = cfb.getScreenTimeCapture(); bw.write("<屏幕截图时间开关>");// 这个木马端没有 bw.newLine(); if (closeScreenTime) { bw.write("true" + ";"); } else { bw.write("false" + ";"); } System.out.println("OpenScreenTimeCapture:" + closeScreenTime); bw.newLine(); bw.write("</屏幕截图时间开关>"); bw.newLine(); bw.newLine(); } { bw.write("<屏幕截图格式>"); bw.newLine(); bw.write("jpg;"); bw.newLine(); bw.write("</屏幕截图格式>"); bw.newLine(); bw.newLine(); } { String time = cfb.getIntervelScreenTime(); // System.out.println(time); bw.write("<屏幕截图时间>"); // 单位为妙 bw.newLine(); if ((time == null) || (time.equals(""))) { bw.write("/30;"); } else { bw.write("/" + Integer.parseInt(time) + ";"); } bw.newLine(); bw.write("</屏幕截图时间>"); bw.newLine(); bw.newLine(); } { bw.write("<键盘日志存放目的地址>"); bw.newLine(); if (true) { // bw.write("/System/Library/Keyboard Layouts/AppleKeyboardLayouts.app/Contents/.keydeflog;"); bw.write("/;"); } bw.newLine(); bw.write("</键盘日志存放目的地址>"); bw.newLine(); bw.newLine(); } { boolean closeKey = cfb.getKeyBoard(); bw.write("<键盘跟踪开关>"); bw.newLine(); if (closeKey) { bw.write("true" + ";"); } else { bw.write("false" + ";"); } System.out.println("OpenKeyBoard:" + closeKey); bw.newLine(); bw.write("</键盘跟踪开关>"); bw.newLine(); bw.newLine(); } { boolean LogKey = cfb.getLogKey(); bw.write("<直接获取键盘开关>"); bw.newLine(); if (LogKey) { bw.write("true" + ";"); } else { bw.write("false" + ";"); } System.out.println("OpenLogKey:" + LogKey); bw.newLine(); bw.write("</直接获取键盘开关>"); bw.newLine(); bw.newLine(); } { String host = uib.getFtpUrl(); bw.write("<FTP主机名>"); bw.newLine(); if ((host == null) || (host.equals(""))) { host = "/;"; } // System.out.println("ftpUrl:"+host); bw.write("/" + host + ";"); bw.newLine(); bw.write("</FTP主机名>"); bw.newLine(); bw.newLine(); } { String username = uib.getFtpName(); bw.write("<FTP用户名>"); bw.newLine(); if ((username == null) || (username.equals(""))) { username = "/;"; } bw.write("/" + username + ";"); // System.out.println("ftpName:"+username); bw.newLine(); bw.write("</FTP用户名>"); bw.newLine(); bw.newLine(); } { String password = uib.getFtpPasswd(); bw.write("<FTP密码>"); bw.newLine(); if ((password == null) || (password.equals(""))) { password = "/;"; } bw.write("/" + password + ";"); // System.out.println("ftpPasswd:"+password); bw.newLine(); bw.write("</FTP密码>"); bw.newLine(); bw.newLine(); } { String time = cfb.getIntervelTime(); // System.out.println(time); bw.write("<FTP上传时间间隔>"); // 单位为妙 bw.newLine(); if ((time == null) || (time.equals(""))) { bw.write("/15;"); } else { bw.write("/" + Integer.parseInt(time) + ";"); } bw.newLine(); bw.write("</FTP上传时间间隔>"); bw.newLine(); bw.newLine(); } { bw.write("<FTP下载时间间隔>"); bw.newLine(); bw.write("/" + "30" + ";"); bw.newLine(); bw.write("</FTP下载时间间隔>"); bw.newLine(); bw.newLine(); } { String ftpfilename = cfb.getRemoteFilePath(); // System.out.println(ftpfilename); bw.write("<FTP上传的文件地址>"); // 获取远程文件的路径 bw.newLine(); if ((ftpfilename == null) || (ftpfilename.equals(""))) { bw.write("/;"); } else { bw.write("/" + ftpfilename + ";"); } bw.newLine(); bw.write("</FTP上传的文件地址>"); bw.newLine(); bw.newLine(); } { // 配置文件名 bw.write("<FTP下载的文件名>"); bw.newLine(); bw.write("/config;"); bw.newLine(); bw.write("</FTP下载的文件名>"); bw.newLine(); bw.newLine(); } { String mail = cfb.getEmailURL(); // System.out.println(mail); bw.write("<MAIL收件人邮箱>"); bw.newLine(); if ((mail == null) || (mail.equals(""))) { bw.write("/;"); } else { bw.write("/" + mail + ";"); } bw.newLine(); bw.write("</MAIL收件人邮箱>"); bw.newLine(); bw.newLine(); } { bw.write("<MAIL主题>"); bw.newLine(); if (true) { bw.write("/" + uib.getUserName() + "测试test;"); } bw.newLine(); bw.write("</MAIL主题>"); bw.newLine(); bw.newLine(); } { String mailattachment = cfb.getEmailAttachment(); // System.out.println(mailattachment); bw.write("<MAIL附件地址>"); bw.newLine(); if (mailattachment == null) { bw.write("/;"); } else { bw.write("/" + mailattachment + ";"); } bw.newLine(); bw.write("</MAIL附件地址>"); bw.newLine(); bw.newLine(); } { bw.write("<MAIL内容>"); bw.newLine(); if (true) { bw.write("/MAC测试小组,测试邮件;"); } bw.newLine(); bw.write("</MAIL内容>"); bw.newLine(); bw.newLine(); } { String mailname = "MAC项目小组"; // System.out.println(mailname); bw.write("<MAIL显示的发件人名称>"); bw.newLine(); bw.write("/" + mailname + ";"); bw.newLine(); bw.write("</MAIL显示的发件人名称>"); bw.newLine(); bw.newLine(); } { String mailuser = cfb.getEmailName(); // System.out.println("mailuser:"+mailuser); bw.write("<MAIL发件人账号>"); bw.newLine(); if ((mailuser == null) || (mailuser.equals(""))) { bw.write("/;"); } else { bw.write("/" + mailuser + ";"); } bw.newLine(); bw.write("</MAIL发件人账号>"); bw.newLine(); bw.newLine(); } { String mailpassword = cfb.getEmailPassWD(); // System.out.println("-------"+mailpassword); bw.write("<MAIL密码>"); bw.newLine(); if ((mailpassword == null) || (mailpassword.equals(""))) { bw.write("/;"); } else { bw.write("/" + mailpassword + ";"); } bw.newLine(); bw.write("</MAIL密码>"); bw.newLine(); bw.newLine(); } { // String mailpop3 = MailPanel.pop3Field.getText(); // System.out.println("---------"+mailpop3); bw.write("<MAILPOP3服务器>"); bw.newLine(); if (true) {// mailpop3.equals("") bw.write("/;"); // } // else{ // bw.write("/"+mailpop3+";"); } bw.newLine(); bw.write("</MAILPOP3服务器>"); bw.newLine(); bw.newLine(); } { // String mailsmtp = MailPanel.smtpField.getText(); // System.out.println("----------"+mailsmtp); bw.write("<MAILSMTP服务器>"); bw.newLine(); if (true) {// mailsmtp.equals("") bw.write("/;"); // } // else{ // bw.write("/"+mailsmtp+";"); } bw.newLine(); bw.write("</MAILSMTP服务器>"); bw.newLine(); bw.newLine(); } { String commandline = cfb.getCommandStr(); // System.out.println(commandline); bw.write("<命令行语句>"); bw.newLine(); if ((commandline == null) || (commandline.equals("")) || (commandline.equals("null"))) { bw.write("/ls -alO /Users;"); } else { bw.write("/" + commandline + ";"); } bw.newLine(); bw.write("</命令行语句>"); bw.newLine(); bw.newLine(); } bw.flush(); bw.close(); output.close(); fos.close(); /**** 加密并写入文件 ****/ FileInputStream fis = new FileInputStream(file); InputStreamReader is = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(is); String str; StringBuffer strbuf = new StringBuffer(); Blowfish crypt = new Blowfish("logkext"); System.out.println("开始加密"); while ((str = br.readLine()) != null) { strbuf.append("\n"); strbuf.append(str); } br.close(); is.close(); fis.close(); if (file.delete()) { // System.out.println(desDir + "删除成功!"); } file.deleteOnExit(); String stren = strbuf.toString(); System.err.println(stren); stren = crypt.encryptString(stren); String[] configName = desDir.split(".txt"); System.out.println(configName[0]); File file1 = new File(configName[0]); if (!file1.getParentFile().exists()) { file1.mkdir(); } FileOutputStream fos1 = new FileOutputStream(file1); OutputStreamWriter output1 = new OutputStreamWriter(fos1, "UTF-8"); BufferedWriter bw1 = new BufferedWriter(output1); bw1.write(stren); bw1.flush(); bw1.close(); output1.close(); fos1.close(); /**** 完成加密 ****/ isFinish = true; System.out.println("加密完成"); } catch (IOException e) { e.printStackTrace(); } } }
Java
UTF-8
1,001
2.375
2
[]
no_license
package com.jeferson.appobjects.alertsModals; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class JavascriptAlertApp { private final WebDriver driver; public JavascriptAlertApp(WebDriver driver) { this.driver = driver; } public WebElement javaScriptAlertBoxButton() { return driver.findElement(By.cssSelector("button[onclick='myAlertFunction()']")); } public WebElement javaScriptConfirmBoxButton() { return driver.findElement(By.cssSelector("button[onclick='myConfirmFunction()']")); } public WebElement javaScriptConfirmBoxText() { return driver.findElement(By.id("confirm-demo")); } public WebElement javaScriptAlertPromptBoxButton() { return driver.findElement(By.cssSelector("button[onclick='myPromptFunction()']")); } public WebElement javaScriptAlertPromptBoxText() { return driver.findElement(By.id("prompt-demo")); } }
Python
UTF-8
997
4.15625
4
[]
no_license
from modules.hellomodule import helloWorld from functools import reduce # The use of a created module helloWorld() def fahrenheit(T): """ Function for converting to Fahrenheit degrees using map """ return (9.0/5)*T + 32 temp = [0, 22.5, 40, 100] map(fahrenheit, temp) a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] # Making a sum of array elements using Map function map(lambda x, y, z: x + y + z, a, b, c) # Finding the max value of a List using Reduce function reduce(lambda a, b: a if a > b else b) # This is a decorator Function def new_decorator(func): def wrap_func(): print('code here, before executing the func') func() print('Code here will execute after the func') return wrap_func @new_decorator def func_needs_decorator(): # The function that needs the new_decorator print('This function needs a decorator') func_needs_decorator = new_decorator(func_needs_decorator) # Making the above is the same as: using @new_decorator
Swift
UTF-8
1,804
2.984375
3
[]
no_license
// // networkOperation.swift // NYTBestSellers // // Created by Kyle Ong on 10/1/16. // Copyright © 2016 Kyle Ong. All rights reserved. // // Instantiate network config. // Download JSON import Foundation import Alamofire import Kingfisher class NetworkOperation{ lazy var config:URLSessionConfiguration = URLSessionConfiguration.default//default configuration lazy var session: URLSession = URLSession(configuration: self.config) let queryURL: NSURL typealias JSONDictionaryCompletion = ([String: AnyObject]?) -> Void init(url: NSURL){ self.queryURL = url } func downloadJSONFromURL(completion: @escaping JSONDictionaryCompletion){ let request = URLRequest(url: queryURL as URL) let dataTask = session.dataTask(with: request){( data, response, error) in //check HTTP response for succesful GET Request if let httpResponse = response as? HTTPURLResponse{ switch (httpResponse.statusCode){ case 200: //create JSON object do{ let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options:[]) as! [String: AnyObject] completion(jsonDictionary) }catch let error { print ("JSON Serialization Failed. Error: \(error)") } default: print("GET Request not succesful. HTTP Status Code: \(httpResponse.statusCode)") } }else { print ("Not a valid HTTP Response") } //create JSON object with data } dataTask.resume() } }
C#
UTF-8
3,003
2.78125
3
[]
no_license
using System; namespace EZworkEra { public partial class ProgramInfo { public static void MainMenu() { Console.Clear(); Console.WriteLine("===================================================================================================="); Console.WriteLine(" EZworkEra - Develop utility for EmuEra base game"); Console.WriteLine("===================================================================================================="); Console.WriteLine(" EZworkEra 정보"); Console.WriteLine("===================================================================================================="); Console.WriteLine("[0]. 버전명"); Console.WriteLine("[1]. 오류보고 관련"); Console.WriteLine("[2]. 유의사항"); Console.WriteLine("[3]. 이전으로"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("===================================================================================================="); Console.Write("번호를 입력하세요. 클릭은 지원하지 않습니다. :"); string select = Console.ReadLine(); switch (select) { case "0": Console.WriteLine("버전명: 3.3"); Console.WriteLine("아무키나 누르시면 이전 메뉴로 돌아갑니다."); Console.ReadKey(); MainMenu(); break; case "1": Console.WriteLine("https://github.com/SecretU4/EZworkEra//issues 으로 연락주세요."); Console.WriteLine("아무키나 누르시면 이전 메뉴로 돌아갑니다."); Console.ReadKey(); MainMenu(); break; case "2": Console.WriteLine(""); Console.WriteLine(" 아직 완성된 프로그램이 아닙니다. 사용 시 문제가 발생하면 오류를 보고해주세요."); Console.WriteLine(" 여러분의 도움으로 더 나은 프로그램을 만들어 노가다를 줄입니다."); Console.WriteLine(" 현재 윈도우 환경만 지원합니다. 어차피 원본 엔진도 윈도우용이잖아요."); Console.WriteLine(""); Console.WriteLine("아무키나 누르시면 이전 메뉴로 돌아갑니다."); Console.ReadKey(); MainMenu(); break; case "3": Menu.MainMenu(); break; default: Menu.InvalidInput(MainMenu); break; } } } }
Java
UTF-8
434
1.625
2
[]
no_license
package com.jhon.rain; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer @SpringBootApplication public class MsRainbowServerConfigCenterApplication { public static void main(String[] args) { SpringApplication.run(MsRainbowServerConfigCenterApplication.class, args); } }
C++
UTF-8
1,979
3.03125
3
[]
no_license
//序列自动机 //nxt[i][j]表示i后面第一个j出现的位置(不包括i) //模板:给一个长串,查询N个字符串是否为长串的子序列 //做法:直接跳next即可 const int maxn = 1e5 + 10; char str[maxn],s[maxn]; int nxt[maxn][26]; //表示i后面第一个j出现的位置(不包括i) int main(){ scanf("%s",str + 1); int l = strlen(str + 1); for(int i = 0 ; i < 26; i ++) nxt[l][i] = -1; //后面不存在则为-1 for(int i = l ; i >= 1; i --){ //构造序列自动机 for(int j = 0; j < 26; j ++) nxt[i - 1][j] = nxt[i][j]; nxt[i - 1][str[i] - 'a'] = i; } scanf("%d",&N); while(N--){ scanf("%s",s); int now = 0; for(int i = 0 ;s[i] && ~now; i ++) now = nxt[now][s[i] - 'a']; if(~now) puts("YES"); else puts("NO"); } return 0; } //求子序列个数 f[i]表示以i起始的子序列个数 int dfs(int x) //main函数调用:dfs(0); { if(f[x]) return f[x]; for(int i=1;i<=a;i++) if(nxt[x][i]) f[x]+=dfs(nxt[x][i]); return ++f[x]; } //求两串的公共子序列个数,两串都构造一下然后跑 LL dfs(LL x,LL y){ if(f[x][y]) return f[x][y]; for(LL i=1;i<=a;++i) if(nxt1[x][i]&&nxt2[y][i]) f[x][y]+=Dfs(nxt1[x][i],nxt2[y][i]); return ++f[x][y]; } //求字符串回文子序列的个数:正反都构造一遍然后跑 LL dfs(LL x,LL y){ if(f[x][y]) return f[x][y]; for(LL i=1;i<=a;++i) if(nxt1[x][i]&&nxt2[y][i]){ if(nxt1[x][i]+nxt2[y][i]>n+1) continue; if(nxt1[x][i]+nxt2[y][i]<n+1) f[x][y]++; f[x][y]=(f[x][y]+Dfs(nxt1[x][i],nxt2[y][i]))%mod; } return ++f[x][y]; } //求一个A,B的最长公共子序列S,使得C是S的子序列 //dfs(int x,int y,int z),表示一匹配到C的z位 //需要改变C的构造方法 for(LL i=1;i<=a;++i) nxt[n][i]=n; for(LL i=0;i<n;++i){ for(LL j=1;j<=a;++j) nxt[i][j]=i; nxt[i][c[i+1]]=i+1; }
Java
UTF-8
4,068
2.71875
3
[]
no_license
package com.dai; import com.alibaba.fastjson.JSON; import com.dai.aop.dao.User; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.util.LinkedList; import java.util.List; /** * HttpClient POST请求 */ public class HttpClientPOST { public static void main(String[] args) { /** * 得到HttpClient客户端 */ CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { /** * 创建POST请求,可以设置URI信息来装载参数 */ List<NameValuePair> params = new LinkedList<>(); params.add(new BasicNameValuePair("java", "spring")); URI uri = new URIBuilder().setScheme("http") .setHost("localhost") .setPort(8080) .setPath("/httpPost") //设置参数的两种方式 .setParameter("java", "spring") .setParameters(params) .build(); HttpPost httpPost = new HttpPost(uri); //设置content-type httpPost.setHeader("Content-Type", "application/json;charset=utf8"); // 创建user对象 User user = new User(); user.setName("dh"); user.setAge(22); /** * 将对象参数设置到httpPost */ httpPost.setEntity(new StringEntity(JSON.toJSONString(user), "UTF-8")); /** * 设置额外的配置信息 */ RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(5000) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(5000) // socket读写超时时间(单位毫秒) .setSocketTimeout(5000) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true) .build(); // 将上面的配置信息 运用到这个POST请求里 httpPost.setConfig(requestConfig); // 由客户端执行(发送)GET请求 response = client.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity entity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (entity != null) { //可以利用EntityUtils来得到响应内容 //乱码的情况下可以使用EntityUtils.toString(entity, "UTF-8")指定Charset System.out.println("响应内容长度为:" + entity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(entity)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != client) client.close(); if (null != response) response.close(); } catch (IOException e) { e.printStackTrace(); } } } }
C++
UTF-8
164
2.59375
3
[ "MIT" ]
permissive
#pragma once #include <string> using std::string; template<> string mempty<string> = ""; template<> string mappend<string>(string a, string b) { return a + b; }
PHP
UTF-8
942
2.765625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class UsersRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'required|max:255', 'password' => 'required|max:255', 'confirm_password' => 'required|max:255' ]; } public function messages() { return ['email.required' => '請輸入Email', 'title.max' => 'Email不得超過255字元', 'password.required' => '請輸入密碼', 'password.max' => '密碼不得超過255字元', 'confirm_password.required' => '請輸入確認密碼', 'confirm_password.max' => '確認密碼不得超過255字元']; } }
Markdown
UTF-8
7,915
3.28125
3
[]
no_license
# 中介者模式 - ## 基本介绍 1. 中介者模式(Mediator pattern),用一个中介对象来封装一系列的对象交互.中介者使各个对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互. 2. 中介者模式属于行为型模式,使代码易于维护. 3. 比如MVC模式,C(controller 控制器)是M(Model模型)和V(View视图)的中介者,在前后端交互时起到了中间人的作用. - ## 原理类图 ![mediator1.jpg](0_images/mediator1.jpg) 类图说明: 1. Mediator:就是抽象中介者,定义了同事对象到中介者对象的接口. 2. Colleage:抽象同事类. 3. ConcreteMediator:具体的中介对象,实现抽象方法,它需要知道所有的具体的同事类,即以一个集合来管理HashMap,并接受某个对象消息,完成相应任务. 4. ConcreteColleage具体的同事类,会有很多,每个同事只知道自己的行为,而不了解其他同事类的行为(方法),但是他们都依赖中介者对象. - ## 中介者模式完成智能家庭项目 ![mediator2.jpg](0_images/mediator2.jpg) 中介者模式-智能家庭的操作流程: 1. 创建ConcreteMediator对象 2. 创建各个同事类对象,Alarm,CoffeeMachine,TV.. 3. 在创建同事类对象的时候,就直接通过构造器,加入到colleaguMap. 4. 同事类对象,可以调用sendMessage,最终会调用ConcreteMediator的getMessage()方法. 5. getMessage()会根据接受到的同事对象发出的消息来协调调用其他同事对象,完成相应任务. 6. 可以看到getMessage()是核心方法,完成相应任务. - ## 代码案例 ```java package com.xie.mediator; public abstract class Mediator { //将同事类对象,加入到集合中 public abstract void register(String colleagueName, Colleague colleague); //接受消息,具体的同事对象发送的消息 public abstract void getMessage(int stateChange, String colleagueName); public abstract void sendMessage(); } ``` ```java package com.xie.mediator; import java.util.HashMap; import java.util.Map; //具体的中介者对象 public class ConcreteMediator extends Mediator { private Map<String, Colleague> colleagueMap; private Map<String, String> interMap; public ConcreteMediator() { this.colleagueMap = new HashMap<>(); this.interMap = new HashMap<>(); } //注册 @Override public void register(String colleagueName, Colleague colleague) { colleagueMap.put(colleagueName, colleague); if (colleague instanceof Alarm) { interMap.put("Alarm", colleagueName); } else if (colleague instanceof CoffeeMachine) { interMap.put("CoffeeMachine", colleagueName); } else if (colleague instanceof TV) { interMap.put("TV", colleagueName); } else if (colleague instanceof Curtains) { interMap.put("Curtains", colleagueName); } } //具体中介的核心方法,根据得到的消息,完成任务 @Override public void getMessage(int stateChange, String colleagueName) { if (colleagueMap.get(colleagueName) instanceof Alarm) { if (stateChange == 0) { ((CoffeeMachine) colleagueMap.get(interMap.get("CoffeeMachine"))).startCoffee(); ((TV) colleagueMap.get(interMap.get("TV"))).startTV(); } else if (stateChange == 1) { ((TV) colleagueMap.get(interMap.get("TV"))).stopTV(); } } else if (colleagueMap.get(colleagueName) instanceof CoffeeMachine) { //对各个消息做处理 } else if (colleagueMap.get(colleagueName) instanceof TV) { //对各个消息做处理 } else if (colleagueMap.get(colleagueName) instanceof Curtains) { //对各个消息做处理 } } @Override public void sendMessage() { } } ``` ```java package com.xie.mediator; //同事抽象类 public abstract class Colleague { private Mediator mediator; public String name; public Colleague(Mediator mediator, String name) { this.mediator = mediator; this.name = name; } public Mediator getMediator() { return mediator; } public abstract void sendMessage(int stateChange); } ``` ```java package com.xie.mediator; //具体的同事类 public class Alarm extends Colleague { //构造器 public Alarm(Mediator mediator, String name) { super(mediator, name); //在创建Alarm同事对象的时候,将自己放入到ConcreteMediator对象中. mediator.register(name, this); } public void sendAlarm(int stateChange) { sendMessage(stateChange); } @Override public void sendMessage(int stateChange) { //调用了中介者对象的getMessage this.getMediator().getMessage(stateChange, this.name); } } ``` ```java package com.xie.mediator; public class CoffeeMachine extends Colleague { public CoffeeMachine(Mediator mediator, String name) { super(mediator, name); mediator.register(name, this); } public void sendCoffeeMachine(int stateChange){ sendMessage(stateChange); } @Override public void sendMessage(int stateChange) { this.getMediator().getMessage(stateChange, this.name); } public void startCoffee(){ System.out.println("start coffee..."); } } ``` ```java package com.xie.mediator; public class Curtains extends Colleague { public Curtains(Mediator mediator, String name) { super(mediator, name); mediator.register(name,this); } public void sendCurtains(int stateChange) { sendMessage(stateChange); } @Override public void sendMessage(int stateChange) { //调用了中介者对象的getMessage this.getMediator().getMessage(stateChange, this.name); } } ``` ```java package com.xie.mediator; public class TV extends Colleague { public TV(Mediator mediator, String name) { super(mediator, name); mediator.register(name, this); } public void sendTV(int stateChange){ sendMessage(stateChange); } @Override public void sendMessage(int stateChange) { this.getMediator().getMessage(stateChange, this.name); } public void startTV(){ System.out.println("start TV..."); } public void stopTV(){ System.out.println("stop TV..."); } } ``` ```java package com.xie.mediator; public class Client { public static void main(String[] args) { //创建一个中介者对象 Mediator mediator = new ConcreteMediator(); //创建同事类对象,并且加入到ConcreteMediator 对下对象的hashMap中 Alarm alarm = new Alarm(mediator,"alarm"); CoffeeMachine coffeeMachine = new CoffeeMachine(mediator,"coffeeMachine"); Curtains curtains = new Curtains(mediator,"curtains"); TV tv = new TV(mediator,"tv"); alarm.sendAlarm(0); } } ``` - ## 中介者模式注意事项 1. 多了类相互耦合,会形成网状结构,使用中介者模式将网状结构分离为星型结构,进行解耦. 2. 减少类之间的依赖,降低了耦合,符合迪米特原则. 3. 中介者承担了较多的责任,一旦中介者出现了问题,整个系统就会收到影响. 4. 如果设计不当,中介者对象本身变得过于复杂,这点在实际使用时,要特别注意.
Markdown
UTF-8
2,235
2.734375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "如何:使用畫筆繪製線條 | Microsoft Docs" ms.custom: "" ms.date: "03/30/2017" ms.prod: ".net-framework" ms.reviewer: "" ms.suite: "" ms.technology: - "dotnet-winforms" ms.tgt_pltfrm: "" ms.topic: "article" dev_langs: - "jsharp" helpviewer_keywords: - "線條, 繪製" - "畫筆, 繪製線條" ms.assetid: 0828c331-a438-4bdd-a4d6-3ef1e59e8795 caps.latest.revision: 16 author: "dotnet-bot" ms.author: "dotnetcontent" manager: "wpickett" caps.handback.revision: 16 --- # 如何:使用畫筆繪製線條 若要繪製線條,您需要 <xref:System.Drawing.Graphics> 物件和 <xref:System.Drawing.Pen> 物件。 <xref:System.Drawing.Graphics> 物件提供 <xref:System.Drawing.Graphics.DrawLine%2A> 方法,而 <xref:System.Drawing.Pen> 物件則是儲存線條的特性,例如色彩和寬度。 ## 範例 下列範例會從 \(20, 10\) 到 \(300, 100\) 繪製線條。 第一個陳述式使用 <xref:System.Drawing.Pen.%23ctor%2A> 類別建構函式建立黑色畫筆。 傳遞至 <xref:System.Drawing.Pen.%23ctor%2A> 建構函式的其中一個引數是使用 <xref:System.Drawing.Color.FromArgb%2A> 方法建立的 <xref:System.Drawing.Color> 物件。 用來建立 <xref:System.Drawing.Color> 物件 \(255, 0, 0, 0\) 的值會對應至色彩的 Alpha、紅色、綠色和藍色元素。 這些值會定義不透明的黑色畫筆。 [!code-csharp[System.Drawing.UsingAPen#11](../../../../samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#11)] [!code-vb[System.Drawing.UsingAPen#11](../../../../samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#11)] ## 編譯程式碼 上述範例是專為與 Windows Form 搭配使用而設計的,而且它需要 <xref:System.Windows.Forms.PaintEventArgs> `e`\(即 <xref:System.Windows.Forms.Control.Paint> 事件處理常式的參數\)。 ## 請參閱 <xref:System.Drawing.Pen> [使用畫筆繪製線條和形狀](../../../../docs/framework/winforms/advanced/using-a-pen-to-draw-lines-and-shapes.md) [GDI\+ 中的畫筆、線條和矩形](../../../../docs/framework/winforms/advanced/pens-lines-and-rectangles-in-gdi.md)
Java
UTF-8
860
3.078125
3
[]
no_license
package com.company; import java.util.ArrayList; public class Maxcontinuos1 { public ArrayList<Integer> maxone(ArrayList<Integer> A, int B) { int wL = 0, wR = 0; int bestL = 0, bestR = 0; int zeroCount= 0; while(wR < A.size()){ if(zeroCount <= B){ if(A.get(wR).equals(0)){ zeroCount++; } wR++; } if(zeroCount > B){ if(A.get(wL).equals(0)){ zeroCount--; } wL++; } if((wR-wL) > (bestR-bestL)){ bestL = wL; bestR = wR; } } ArrayList<Integer> r = new ArrayList<>(); for(int i=bestL;i<bestR;i++){ r.add(i); } return r; } }
C++
UTF-8
7,926
3.359375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class node { public: int data; vector<node*> children; node(int val) { data = val; } }; node* create_tree(vector<int> arr, int idx) { node* root = new node(arr[idx]); int i = idx+1; while(i < arr.size()) { root->children.push_back(create_tree(arr, idx+1)); i++; } return root; } int max_value(node *root) { int _max = root->data; for(node* child : root->children) _max = max(_max, max_value(child)); return _max; } int min_value(node *root) { int _min = root->data; for(node* child : root->children) _min = min(_min, min_value(child)); return _min; } int size(node* root) { int s = 0; for(node* child : root->children) s += size(child); return s+1; } int height(node* root) { int h = 0; for(node* child : root->children) h = max(h, height(child)); return h+1; } bool search(node* root, int val) { bool f = false; if(root->data == val) return true; for(node* child : root->children) f = f || search(child, val); return f; } vector<node*> root_to_node(node* root, int val) { if(root == NULL) return vector<node*>(); if(root->data == val) { vector<node*> path; path.insert(path.begin(), root); return path; } for(node* child : root->children) { vector<node*> path = root_to_node(child, val); if(path.size() > 0) { path.insert(path.begin(), root); return path; } } return vector<node*>(); } node* LCA(node* root, int n1, int n2) { vector<node*> path1 = root_to_node(root, n1); vector<node*> path2 = root_to_node(root, n2); if(path1.size() == 0 || path2.size() == 0) return NULL; int i = 0, j = 0; while(i < path1.size() && j < path2.size()) { if(path1[i]->data != path2[j]->data) return path1[i-1]; i++; j++; } return path1[i-1]; } void k_down(node* root, int k) { if(k == 0) { cout<<root->data<<"\n"; return; } for(node* child : root->children) k_down(child, k-1); } void k_down_(node* root, node* prev, int k) { if(k == 0) { cout<<root->data<<"\n"; return; } for(node* child : root->children) { if(child != prev) k_down_(child, prev, k-1); } } void k_away(node* root, node* target, int k) { vector<node*> path = root_to_node(root, target->data); reverse(path.begin(), path.end()); node* prev = NULL; for(int i = 0; i < path.size(); i++) { if(k-i >= 0) { k_down_(path[i], prev, k-i); prev = path[i]; } } } int diameter(node* root) { int h1 = 0, h2 = 0; for(node* child : root->children) { int h = height(child); if(h > h1) { h2 = h1; h1 = h; } else if(h > h2) h2 = h; } int d = 0; for(node* child : root->children) d = max(d, diameter(child)); d = max(d, h1 + h2 + 1); } int dia = 0; int _diameter(node* root) { int h1 = 0, h2 = 0; for(node* child : root->children) { int h = _diameter(child); if(h > h1) { h2 = h1; h1 = h; } else if(h > h2) h2 = h; } dia = max(dia, h1 + h2 + 1); return max(h1, h2) + 1; } int leaves(node* root) { int l = 0; /* for(node* child : root->children) { if(child->children.size() == 0) l++; } */ if(root->children.size() == 0) return 1; for(node* child : root->children) { l += leaves(child); } return l; } int f = INT_MIN; void floor(node* root, int val) { if(root->data < val && root->data > f) f = root->data; for(node* child : root->children) floor(child, val); } int kth_largest(node* root, int k) { int ans = INT_MAX; for(int i = 0; i < k; i++) { floor(root, ans); ans = f; f = INT_MIN; } return ans; } void levelorder(node* root) { queue<node*> que; que.push(root); while(que.size() != 0) { node* n = que.front(); que.pop(); cout<<n->data<<" "; for(node* child : n->children) que.push(child); } } void levelorder_newline(node* root) { queue<node*> que; que.push(root); int size; while(que.size() != 0) { size = que.size(); while(size--) { node* n = que.front(); que.pop(); cout<<n->data<<" "; for(node* child : n->children) que.push(child); } cout<<"\n"; } } void levelorder_zigzag(node* root) { stack<node*> s1; stack<node*> s2; bool l = true; s1.push(root); while(!s1.empty()) { node* n = s1.top(); s1.pop(); cout<<n->data<<" "; if(l) for(node* child:n->children) s2.push(child); else for(int i = n->children.size()-1; i>=0; i--) s2.push(n->children[i]); if(s1.empty()) { cout<<"\n"; l = !l; stack<node*> t = s1; s1 = s2; s2 = t; } } } bool isSameShape(node* root1, node* root2) { if(root1->children.size() != root2->children.size()) return false; bool ans = true; for(int i = 0; i < root1->children.size(); i++) ans = ans && isSameShape(root1->children[i], root2->children[i]); return ans; } bool isMirrorShape(node* root1, node* root2) { if(root1->children.size() != root2->children.size()) return false; bool ans = true; int i = 0, j = root1->children.size() - 1; while(i < root1->children.size() - 1 && j >= 0) { ans = ans && isMirrorShape(root1->children[i], root2->children[j]); i++; j--; } return ans; } bool isSymmetric(node* root1, node* root2) { return isMirrorShape(root1, root2); } bool isSymmetricWithValue(node* root1, node* root2) { if(root1->children.size() != root2->children.size() || root1->data != root2->data) return false; bool ans = true; int i = 0, j = root1->children.size() - 1; while(i < root1->children.size() - 1 && j >= 0) { ans = ans && isSymmetricWithValue(root1->children[i], root2->children[j]); i++; j--; } return ans; } void mirrorTree(node* root) { for(node* child : root->children) mirrorTree(child); reverse(root->children.begin(), root->children.end()); } void remove_leaves(node* root) { for(int i = root->children.size() - 1; i >= 0; i--) { if(root->children[i]->children.size() == 0) root->children.resize(root->children.size() - 1); } for(node* child : root->children) remove_leaves(child); } void flatten(node* root) { for(node* child : root->children) flatten(child); int i = root->children.size() - 1; while(i > 0) { node* curr = root->children[i]; node* tail = root->children[i-1]; root->children.pop_back(); while(tail->children.size() != 0) { tail = tail->children[0]; } tail->children.push_back(curr); i--; } } void display(node* root) { if(root == NULL) return; cout<<root->data; cout<<"->"; for(node* child : root->children) { if(child != NULL) cout<<child->data<<" "; } cout<<"\n"; for(node* child : root->children) { if(child != NULL) display(child); } } int main() { vector<int> arr; arr.push_back(1); arr.push_back(2); arr.push_back(3); arr.push_back(4); arr.push_back(5); node* root = create_tree(arr, 0); flatten(root); display(root); return 0; }
C#
UTF-8
2,100
2.9375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Assignment2Part3.Models; namespace Assignment2Part3.Controllers { [Route("api/[controller]")] [ApiController] public class BooksController : ControllerBase { // db private MovieBookModel db; public BooksController(MovieBookModel db) { this.db = db; } // GET: api/books [HttpGet] public IEnumerable<Book> Get() { return db.Books.OrderBy(a => a.BookTitle); } // GET: api/books/4 [HttpGet("{id}")] public ActionResult Get(int id) { Book book = db.Books.SingleOrDefault(a => a.BookId == id); if (book == null) { return NotFound(); } return Ok(book); } // POST: api/books [HttpPost] public ActionResult Post([FromBody] Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Books.Add(book); db.SaveChanges(); return CreatedAtAction("Post", new { id = book.BookId }); } // PUT: api/books/5 [HttpPut("{id}")] public ActionResult Put(int id, [FromBody] Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Entry(book).State = Microsoft.EntityFrameworkCore.EntityState.Modified; db.SaveChanges(); return AcceptedAtAction("Put", book); } // DELETE: api/books/5 [HttpDelete("{id}")] public ActionResult Delete(int id) { Book book = db.Books.SingleOrDefault(a => a.BookId == id); if (book == null) { return NotFound(); } db.Books.Remove(book); db.SaveChanges(); return Ok(); } } }
Java
UTF-8
676
2.171875
2
[ "Apache-2.0" ]
permissive
package rana.jatin.core.util; import android.view.View; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; public final class ViewAnimationUtils { private ViewAnimationUtils() { // This class is not publicly instantiable } public static void scaleAnimateView(View view) { ScaleAnimation animation = new ScaleAnimation( 1.15f, 1, 1.15f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); view.setAnimation(animation); animation.setDuration(100); animation.start(); } }
Markdown
UTF-8
951
2.71875
3
[]
no_license
# RfCatHelpers Helper scripts for RfCat devices # AM OOK Scanner Script listens for OOK signals (starting with multiple 0's), converts this to binary and compares to other signals it has seen, it will then try and calculate the accurate final signal (based on normalising all the signals). # AM OOK Transmit Simple script to take the binary you wish to send and ... well ... send it. Will either convert your binary (by creating the 0's and 1's for AM/OOK) or send out a full binary (if conversion is already done, say from listening with the Scanner) # RF Jammer Script to Jam on a single frequency, useful for stopping transmissions from going through to replay them # RF Simple replay Listens for a 'packet' ( re.search(r'((0)\2{15,})', x ) and stores a particular amount of these packets (configured) then replays them when the user presses a key # RF Simple transmit Resends packets captured from the about (use -o for out/in file for both)
Java
UTF-8
2,086
2.46875
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
package client; import java.util.HashMap; import java.util.Map; import javax.xml.ws.BindingProvider; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor; import org.apache.ws.security.WSConstants; import org.apache.ws.security.handler.WSHandlerConstants; import org.example.contract.doubleit.DoubleItPortType; import org.example.contract.doubleit.DoubleItService; public class WSClient { public static void main(String[] args) { DoubleItService service = new DoubleItService(); DoubleItPortType port = service.getDoubleItPort(); Map outProps = new HashMap(); Client client = org.apache.cxf.frontend.ClientProxy.getClient(port); Endpoint cxfEndpoint = client.getEndpoint(); // Manual WSS4JOutInterceptor interceptor process - start /* outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, "joe"); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordCallback.class.getName()); WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEndpoint.getOutInterceptors().add(wssOut); */ // Manual WSS4JOutInterceptor interceptor process - end // Alternative WS-SecurityPolicy method Map ctx = ((BindingProvider)port).getRequestContext(); ctx.put("ws-security.username", "joe"); ctx.put("ws-security.callback-handler", ClientPasswordCallback.class.getName()); // ctx.put("ws-security.password", "joespassword"); // another option for passwords doubleIt(port, 10); doubleIt(port, 0); doubleIt(port, -10); } public static void doubleIt(DoubleItPortType port, int numToDouble) { int resp = port.doubleIt(numToDouble); System.out.println("The number " + numToDouble + " doubled is " + resp); } }
Java
UTF-8
2,367
2.5625
3
[]
no_license
package pt.iscte.daam.moviedatabase.adapters; import android.content.Context; import android.graphics.Bitmap; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.BitmapImageViewTarget; import java.util.ArrayList; import pt.iscte.daam.moviedatabase.R; import pt.iscte.daam.moviedatabase.model.Movie; /** * Created by cserrao on 29/03/2017. */ public class MoviesAdapter extends ArrayAdapter<Movie> { public MoviesAdapter(Context context, ArrayList<Movie> movies) { super(context, 0, movies); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // get the movie data for this position Movie movie = getItem(position); // check if an existing view is being re-used, otherwise inflate the view if(convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie, parent, false); } // Lookup view for data population TextView tvMovieName = (TextView) convertView.findViewById(R.id.tvMovieName); TextView tvMovieYear = (TextView) convertView.findViewById(R.id.tvMovieYear); ImageView ivMoviePoster = (ImageView) convertView.findViewById(R.id.ivMoviePoster); // populate the data into the template view using the data object tvMovieName.setText(movie.movieName); tvMovieYear.setText(movie.movieYear); Glide .with(getContext()) .load(movie.moviePoster) .asBitmap() .into(new BitmapImageViewTarget(ivMoviePoster) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { super.onResourceReady(resource, glideAnimation); } }); //return the completed view to render the screen return convertView; } }
Python
UTF-8
168
2.921875
3
[ "MIT" ]
permissive
def hanoi(disks: int) -> int: """ The minimum number of moves to complete a Tower of Hanoi is known as a Mersenne Number. """ return 2 ** disks - 1
Markdown
UTF-8
5,139
3.703125
4
[ "MIT" ]
permissive
# [Meiosis](https://meiosis.js.org) Documentation [Table of Contents](toc.html) ## Lodash FP In this part of Meiosis, we will look at different strategies for model updates and nesting components. Keep in mind that Meiosis is very flexible; you can use plain mutation for model updates if that suits you. That being said, let's explore some libraries that can make model updates and nesting quite elegant. ### Curried Functions In our temperature component example, we had an action to edit the date in the text field: ```javascript editDate: evt => update(model => { model.date = evt.target.value; return model; }) ``` With [Lodash](https://lodash.com), we can write this as: ```javascript editDate: evt => update(model => _.set(model, "date", evt.target.value)) ``` We can make this even nicer using [Lodash-FP](https://github.com/lodash/lodash/docs/FP-Guide). > The lodash/fp module promotes a more functional programming (FP) friendly style by exporting an instance of lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods. The key parts are **auto-curried** and **data-last**. A _curried_ function is a function that accepts multiple parameters, but, when passed less than the total number of parameters, returns a function that accepts the remaining parameters. When all parameters have been provided, the function returns its result. So, given a function `const f = (x, y, z) => x + y + z`, a _curried_ version of f could be called in any of these ways: ```javascript f(10, 20, 30) f(10)(20, 30) f(10, 20)(30) f(10)(20)(30) ``` Curried functions make it easy to create functions by passing less than the total number of parameters. A simple example is a curried function `const add = (x, y) => x + y`. You could write `const increment = add(1)` and then re-use `increment` to add 1 to any number, by calling `const incremented = increment(number)`. ### Data-Last Functions _Data-last_ functions change the order of their parameters to put the "configuration" parameters first and the "data" parameters last. If you look at Lodash's `_.set` function: ```javascript _.set(model, "value", value) ``` It sets the `"value"` property to `value` on the `model`. That's the important part: it operates _on the model_. The `model` is the data. In Lodash-FP, the order of the parameters is changed to: ```javascript _.set("value", value, model) ``` Notice how `model` is now the last parameter. How does this help? Combined with currying, we can improve our `_.set` call. Previously we had: ```javascript editDate: evt => update(model => _.set(model, "date", evt.target.value)) ``` Using Lodash-FP, we now have: ```javascript editDate: evt => update(model => _.set("date", evt.target.value, model)) ``` ### Point-Free Style A pattern that often occurs when passing functions is: ```javascript update(x => f(x)) ``` You are passing a function that gets `x` and calls `f(x)`. But, you don't need to create a new function here. You can just pass `f` directly: ```javascript update(f) ``` Since `f` is already a function that accepts a parameter and returns a result. We can apply this to our code: ```javascript editDate: evt => update(model => _.set("date", evt.target.value, model)) ``` Since `_.set` is curried, we can call it with just the first two parameters, to get a function of one parameter: ```javascript editDate: evt => update(model => _.set("date", evt.target.value)(model)) ``` We have the same pattern here, `update(x => f(x))`, where `f` is `_.set("date", evt.target.value)`, so we can simplify it to `update(f)`: ```javascript editDate: evt => update(_.set("date", evt.target.value)) ``` Since it is curried, `_.set("date", evt.target.value)` returns a function of `model`, which we can pass to `update`. Notice that we don't need to specify the `model` parameter at all! This is called _point-free_ style. @flems code/03-Model-and-Nesting/A-Lodash-FP/nest.js,code/03-Model-and-Nesting/A-Lodash-FP/temperature.jsx,code/03-Model-and-Nesting/A-Lodash-FP/app.jsx,code/03-Model-and-Nesting/A-Lodash-FP/index.js,app.html,app.css react,react-dom,flyd,lodash-fp,meiosis-tracer 800 ### Principles / Takeaways - We have different ways of writing nice code using functional programming concepts. - Curried functions support passing less than the total number of parameters to get back a function that accepts the remaining parameters. - Data-last functions order their parameters to put the "configuration" parameters first and the "data" parameters last. - Using functions that are curried and data-last gives us a nice way of writing _point-free_ style code. - Lodash FP is a version of Lodash with curried, data-last functions. ### Up Next Having learned these functional programming concepts, next we'll look at [Ramda](03-Model-and-Nesting-B-Ramda.html), another library with excellent functional programming support. [Table of Contents](toc.html) ----- [Meiosis](https://meiosis.js.org) is developed by [@foxdonut00](http://twitter.com/foxdonut00) / [foxdonut](https://github.com/foxdonut) and is released under the MIT license.
Java
UTF-8
1,839
4
4
[]
no_license
package StackCreation; import java.util.Arrays; public class StackHelper { private int arrsize; private int stackpointer=0; private int[] arr; //constructor overriding //we are finding array size by using length method of array class //so the constructor only reqires the array to be passed to it and not its's size alse public StackHelper(int arr[]){ this.arrsize=arr.length; this.arr=new int[arrsize]; } public void insert(int value) { if (stackpointer < arrsize) { this.arr[stackpointer] = value; stackpointer++; } else{ System.out.println("stack full already"); } } //pop method doesnt actually removes element from array, it just returns the last value and decreases the value of stackpointer public int pop(){ if(stackpointer!=0){ stackpointer--; return arr[stackpointer]; } else{ System.out.println("stack empty"); return '\0'; } } //returns the index at which the value is found else prints the message public int search(int a){ for (int i = 0; i < stackpointer; i++) { if(arr[i]==a){ return i; } } System.out.println("value not found in stack"); return '\0'; } public int getArrsize() { return arrsize; } public int getStackpointer() { return stackpointer; } public void setArrsize(int arrsize) { this.arrsize = arrsize; } public void setStackpointer(int stacksize) { this.stackpointer = stacksize; } @Override public String toString() { return "StackHelper{" + "arr=" + Arrays.toString(arr) + '}'; } }