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
Markdown
UTF-8
2,648
3.421875
3
[]
no_license
## 什麼是 DOM? ### 全名是 document object model ,簡單來說他將 HTML Document中的標籤和文字內容都轉換成物件 ,形成一個樹狀結構。javascript 可以拿到樹狀裡的 html 節點去改變畫面上的東西,而瀏覽器提供 DOM 這個規則,成為 javascript 和 html 溝通的橋樑。 ### DOM 中的節點有四種類型:Document(指這份文件)、 Element(指 html 標籤)、 Text(指文字內容)和 Attribute(指標籤內的 class id 等屬性) Image:https://i.imgur.com/quZtbSB.jpg ### 改變不同節點的常用語法如下: ### (1) 改變 element: ### document.getElementById(‘idName’)或 GetElementByClassName(‘className') ### (2) 改變 text: ### document.querySelector('selector’).innerText:抓到標籤內的實際內容 ### document.querySelector('selector’).innerHTML:會抓到指定的標籤中的標籤 ### (3)改變 attribute: ### document.querySelector('selector’) 或 document.querySelectorAll('selector’) ## 事件傳遞機制的順序是什麼;什麼是冒泡,什麼又是捕獲? ### 事件在 DOM 裡面傳遞的順序,事件傳遞的意思是,因為 html 一個區塊中包含其他子元素,像是 table 底下會有 tr 和 td ,但如果在兩個元素都加上監聽器 event listener ,此時事件的執行順序,會從 DOM 樹狀結構最高層往下執行。 ### 點擊一個 target 事件後,事件傳遞的順序會從根節點 window 開始向下傳遞到 target,接著事件會傳遞到 target 本身,觸發事件監聽器後,接著一路逆向回傳到根節點,因此向下傳遞即為捕獲階段,往上回傳的過程即是冒泡階段。記得一個口訣:先捕獲再冒泡 ## 什麼是 event delegation,為什麼我們需要它? ### 事件代理指的是由父節點代為處理子節點的事件,假設有一個 ul,底下有數個 li,比起在每一個 li 都加上 event listener,可由 ul 作為加上 event listener 的總代理,全部的監聽只會用一個event listener。常使用的原因是可以節省資源,不用一一指定相同 event listener,也時常應用在處理動態新增元件的情境。 ## event.preventDefault() 跟 event.stopPropagation() 差在哪裡,可以舉個範例嗎? ### event.stepPropagation 可以中斷事件傳遞,不會再繼續往下執行,下一層節點的 listener 都不會再被觸發,不過同節點上的其他 listener 仍會被觸發完畢。 ### event.preventDefault 指取消瀏覽器的預設行為,例如點擊超連結不會新增分頁連出去,而加上這一行後事件還是會繼續往下傳遞。
Java
UTF-8
13,094
2.140625
2
[ "MIT" ]
permissive
package io.cucumber.core.runtime; import io.cucumber.core.eventbus.IncrementingUuidGenerator; import io.cucumber.core.eventbus.Options; import io.cucumber.core.eventbus.RandomUuidGenerator; import io.cucumber.core.eventbus.UuidGenerator; import io.cucumber.core.exception.CucumberException; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import java.util.UUID; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; /** * # Testcases for `UuidGeneratorServiceLoader` * <p> * <!-- @formatter:off --> * | # | uuid-generator property | Available services | Result | * |-----|---------------------------|-------------------------------------------------------------------------------------|----------------------------------------------------------------------------------| * | 1 | undefined | none | exception, no generators available | * | 2 | undefined | RandomUuidGenerator, IncrementingUuidGenerator | RandomUuidGenerator used | * | 3 | RandomUuidGenerator | RandomUuidGenerator, IncrementingUuidGenerator | RandomUuidGenerator used | * | 4 | undefined | RandomUuidGenerator, IncrementingUuidGenerator, OtherGenerator | OtherGenerator used | * | 5 | RandomUuidGenerator | RandomUuidGenerator, IncrementingUuidGenerator, OtherGenerator | RandomUuidGenerator used | * | 6 | undefined | RandomUuidGenerator, IncrementingUuidGenerator, OtherGenerator, YetAnotherGenerator | exception, cucumber couldn't decide multiple (non default) generators available | * | 7 | OtherGenerator | RandomUuidGenerator, IncrementingUuidGenerator, OtherGenerator, YetAnotherGenerator | OtherGenerator used | * | 8 | IncrementingUuidGenerator | RandomUuidGenerator, IncrementingUuidGenerator, OtherGenerator, YetAnotherGenerator | IncrementingUuidGenerator used | * | 9 | IncrementingUuidGenerator | RandomUuidGenerator, IncrementingUuidGenerator | IncrementingUuidGenerator used | * | 10 | OtherGenerator | none | exception, generator OtherGenerator not available | * | 11 | undefined | OtherGenerator | OtherGenerator used | * | 12 | undefined | IncrementingUuidGenerator, OtherGenerator | OtherGenerator used | * | 13 | undefined | IncrementingUuidGenerator | IncrementingUuidGenerator used | * <!-- @formatter:on --> */ class UuidGeneratorServiceLoaderTest { /** * | 1 | undefined | none | exception, no generators available | */ @Test void test_case_1() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class), options); CucumberException exception = assertThrows(CucumberException.class, loader::loadUuidGenerator); assertThat(exception.getMessage(), is("" + "Could not find any UUID generator.\n" + "\n" + "Cucumber uses SPI to discover UUID generator implementations.\n" + "This typically happens when using shaded jars. Make sure\n" + "to merge all SPI definitions in META-INF/services correctly")); } /** * | 2 | undefined | RandomUuidGenerator, IncrementingUuidGenerator | * RandomUuidGenerator used | */ @Test void test_case_2() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( UuidGeneratorServiceLoaderTest.class::getClassLoader, options); assertThat(loader.loadUuidGenerator(), instanceOf(RandomUuidGenerator.class)); } /** * | 3 | RandomUuidGenerator | RandomUuidGenerator, * IncrementingUuidGenerator | RandomUuidGenerator used | */ @Test void test_case_3() { Options options = () -> RandomUuidGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( UuidGeneratorServiceLoaderTest.class::getClassLoader, options); assertThat(loader.loadUuidGenerator(), instanceOf(RandomUuidGenerator.class)); } /** * | 4 | undefined | RandomUuidGenerator, IncrementingUuidGenerator, * OtherGenerator | OtherGenerator used | */ @Test void test_case_4() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.class, OtherGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(OtherGenerator.class)); } /** * | 4bis | undefined | OtherGenerator, RandomUuidGenerator, * IncrementingUuidGenerator | OtherGenerator used | */ @Test void test_case_4_bis() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, OtherGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(OtherGenerator.class)); } /** * | 5 | RandomUuidGenerator | RandomUuidGenerator, * IncrementingUuidGenerator, OtherGenerator | RandomUuidGenerator used | */ @Test void test_case_5() { Options options = () -> RandomUuidGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.class, OtherGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(RandomUuidGenerator.class)); } /** * | 6 | undefined | RandomUuidGenerator, IncrementingUuidGenerator, * OtherGenerator, YetAnotherGenerator | exception, cucumber couldn't decide * multiple (non default) generators available | */ @Test void test_case_6() { // Given Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.class, OtherGenerator.class, YetAnotherGenerator.class), options); // When CucumberException cucumberException = assertThrows(CucumberException.class, loader::loadUuidGenerator); // Then assertThat(cucumberException.getMessage(), Matchers.containsString("More than one Cucumber UuidGenerator was found on the classpath")); } /** * | 7 | OtherGenerator | RandomUuidGenerator, IncrementingUuidGenerator, * OtherGenerator, YetAnotherGenerator | OtherGenerator used | */ @Test void test_case_7() { Options options = () -> OtherGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.class, OtherGenerator.class, YetAnotherGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(OtherGenerator.class)); } /** * | 8 | IncrementingUuidGenerator | RandomUuidGenerator, * IncrementingUuidGenerator, OtherGenerator, YetAnotherGenerator | * IncrementingUuidGenerator used | */ @Test void test_case_8() { Options options = () -> IncrementingUuidGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidGenerator.class, OtherGenerator.class, YetAnotherGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(IncrementingUuidGenerator.class)); } /** * | 9 | IncrementingUuidGenerator | RandomUuidGenerator, * IncrementingUuidGenerator | IncrementingUuidGenerator used | */ @Test void test_case_9() { Options options = () -> IncrementingUuidGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( UuidGeneratorServiceLoaderTest.class::getClassLoader, options); assertThat(loader.loadUuidGenerator(), instanceOf(IncrementingUuidGenerator.class)); } /** * | 10 | OtherGenerator | none | exception, generator OtherGenerator not * available | */ @Test void test_case_10() { Options options = () -> OtherGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class), options); CucumberException exception = assertThrows(CucumberException.class, loader::loadUuidGenerator); assertThat(exception.getMessage(), is("" + "Could not find UUID generator io.cucumber.core.runtime.UuidGeneratorServiceLoaderTest$OtherGenerator.\n" + "\n" + "Cucumber uses SPI to discover UUID generator implementations.\n" + "Has the class been registered with SPI and is it available on\n" + "the classpath?")); } /** * | 11 | undefined | OtherGenerator | OtherGenerator used | */ @Test void test_case_11() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, OtherGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(OtherGenerator.class)); } /** * | 12 | undefined | IncrementingUuidGenerator, OtherGenerator | * OtherGenerator used | */ @Test void test_case_12() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, IncrementingUuidGenerator.class, OtherGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(OtherGenerator.class)); } /** * | 13 | undefined | IncrementingUuidGenerator | IncrementingUuidGenerator * used | */ @Test void test_case_13() { Options options = () -> null; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, IncrementingUuidGenerator.class), options); assertThat(loader.loadUuidGenerator(), instanceOf(IncrementingUuidGenerator.class)); } public static class OtherGenerator implements UuidGenerator { @Override public UUID generateId() { return null; } } public static class YetAnotherGenerator implements UuidGenerator { @Override public UUID generateId() { return null; } } }
Java
UTF-8
1,922
2.28125
2
[]
no_license
package com.adp3.service.reports.impl; import com.adp3.entity.reports.StoreReports; import com.adp3.factory.reports.StoreReportFactory; import com.adp3.service.reports.StoreReportsService; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Set; @SpringBootTest @RunWith(SpringRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class StoreReportsServiceImplTest { @Autowired StoreReportsService storeReportsService; private StoreReports storeReports; @Before public void a_a(){ storeReports = StoreReportFactory.createStoreReports("Employee","Store","In"); storeReportsService.create(storeReports); } @Test public void d_getAll() { Set<StoreReports> storeReports = storeReportsService.getAll(); System.out.println("All StoreReports: " + storeReports); } @Test public void a_create() { StoreReports created = storeReportsService.create(storeReports); System.out.println("Created: "+ created); } @Test public void b_read() { StoreReports read = storeReportsService.read(storeReports.getStoreReportID()); System.out.println("Read: " + read); } @Test public void c_update() { StoreReports updated = new StoreReports.Builder().copy(storeReports).setEmpID("Employee") .setStoreID("Store").setRecID("Out").build(); updated = storeReportsService.update(updated); System.out.println("Updated: " + updated); } @Test public void e_delete() { storeReportsService.delete(storeReports.getStoreReportID()); } }
PHP
UTF-8
126
2.71875
3
[]
no_license
<?php class Message { public $body; public function __construct($body) { $this->body = $body; } }
SQL
UTF-8
4,051
2.96875
3
[]
no_license
INSERT INTO category(id, name, symbol_code) VALUES (1, 'Доски и лыжи', 'boards'), (2, 'Крепления', 'attachment'), (3, 'Ботинки', 'boots'), (4, 'Одежда', 'clothing'), (5, 'Инструменты', 'tools'), (6, 'Разное', 'other'); INSERT INTO user(id, registration_date, email, name, passwd, contact_info) VALUES (1, '2021-01-01', 'blablabla@mail.ru', 'Иван Иванов', '123456', '+7-495-666-66-66'), (2, '2020-12-20', 'hhhhhh@mail.ru', 'Сергей Сергеев', 'abcdef', '+7-495-777-77-77'), (3, '2020-11-15', 'uraaaaa@mail.ru', 'Андрей Андреев', 'gehlmnp', '+7-495-888-88-88'); INSERT INTO lot(id, date_creation, name, description, img_src, starter_price, expiration_date, bet_offset, author_id, winner_id, category_id) VALUES (1, '2021-02-10 14:25:10', '2014 Rossignol District Snowboard', 'Сноуборд', 'img/lot-1.jpg', 10999, '2021-2-28', 100, (SELECT id FROM user WHERE name = 'Андрей Андреев'), NULL, (SELECT id FROM category WHERE name = 'Доски и лыжи')), (2, '2021-02-10 14:25:10', 'DC Ply Mens 2016/2017 Snowboard', 'Сноуборд', 'img/lot-2.jpg', 159999, '2021-3-1', 100, (SELECT id FROM user WHERE name = 'Андрей Андреев'), NULL, (SELECT id FROM category WHERE name = 'Доски и лыжи')), (3, '2021-02-11 15:25:10', 'Крепления Union Contact Pro 2015 года размер L/XL', 'Крепления', 'img/lot-3.jpg', 8000, '2021-3-2', 200, (SELECT id FROM user WHERE name = 'Сергей Сергеев'), NULL, (SELECT id FROM category WHERE name = 'Крепления')), (4, '2021-02-11 16:25:10', 'Ботинки для сноуборда DC Mutiny Charocal', 'Ботинки', 'img/lot-4.jpg', 10999, '2021-3-3', 200, (SELECT id FROM user WHERE name = 'Сергей Сергеев'), NULL, (SELECT id FROM category WHERE name = 'Ботинки')), (5, '2021-02-12 17:25:10', 'Куртка для сноуборда DC Mutiny Charocal', 'Куртка', 'img/lot-5.jpg', 7500, '2021-3-4', 300, (SELECT id FROM user WHERE name = 'Иван Иванов'), NULL, (SELECT id FROM category WHERE name = 'Одежда')), (6, '2021-02-13 11:25:10', 'Маска Oakley Canopy', 'Маска', 'img/lot-6.jpg', 5400, '2021-3-4', 300, (SELECT id FROM user WHERE name = 'Иван Иванов'), NULL, (SELECT id FROM category WHERE name = 'Разное')); INSERT INTO bet(id, date_creation, price, user_id, lot_id) VALUES (1, '2021-02-13 12:25:10', 5700, (SELECT id FROM user WHERE name = 'Сергей Сергеев'), (SELECT id FROM lot WHERE name = 'Маска Oakley Canopy')), (2, '2021-02-13 12:30:10', 160099, (SELECT id FROM user WHERE name = 'Сергей Сергеев'), (SELECT id FROM lot WHERE name = 'DC Ply Mens 2016/2017 Snowboard')); /* получить все категории */ SELECT * FROM category; /* получить самые новые, открытые лоты. Каждый лот должен включать название, стартовую цену, ссылку на изображение, текущую цену, название категории; */ SELECT lot.name, lot.starter_price, lot.img_src, bet.price as current_price, category.name FROM lot LEFT OUTER JOIN bet ON bet.lot_id = lot.id JOIN category ON lot.category_id = category.id WHERE lot.winner_id is NULL AND lot.date_creation > '2021-02-11'; /* показать лот по его id. Получите также название категории, к которой принадлежит лот */ SELECT lot.*, category.name FROM lot JOIN category ON lot.category_id = category.id WHERE lot.id = 3 /* обновить название лота по его идентификатору; */ UPDATE lot SET name = 'New name' WHERE id = 1; /* получить список ставок для лота по его идентификатору с сортировкой по дате. */ SELECT * FROM bet WHERE lot_id = 6 ORDER BY date_creation DESC;
JavaScript
UTF-8
1,354
3.515625
4
[]
no_license
// Stampare tutti i numeri da 1 a 100 con le seguenti regole: // al posto dei multipli di 3 stampare "Fizz" // al posto dei multipli di 5 stampare "Buzz" // al posto dei multipli di 3 e 5 stampare "FizzBuzz" // nome repo: js-fizzbuzz // creazione var d'appoggio var list = '' // ciclo per creare numeri da 1 a 100 for (var i = 1; i < 101; i++) { var num = i; // il principio è quello di creare una stringa che contenga già al suo interno dei tag <li> per html // il tutto a braccetto con Bootstrap4 è una bomba a orologeria ==> SPETTACOLO PURO!!! if ((num % 3 == 0) && (num % 5 == 0)) { list = list + '<li class = "list-inline-item mx-3 mb-3 text-warning bg-primary rounded">' + 'FizzBuzz' + '</li>'; } else if (num % 3 == 0) { list = list + '<li class = "list-inline-item mx-3 mb-3 text-primary">' + 'Fizz' + '</li>'; } else if (num % 5 == 0) { list = list + '<li class = "list-inline-item mx-3 mb-3 text-warning">' + 'Buzz' + '</li>'; } else { list = list + '<li class = "list-inline-item mx-3 mb-3">' + num + '</li>'; } }; // qui si inserisce un tag padre <ul> var list_unordered = '<ul class = "list-unstyled text-left">' + list + '</ul>'; console.log(list_unordered); // inviamo tutto il pacchetto lista all'Html document.getElementById('fizzbuzztest').innerHTML = list_unordered;
C++
UTF-8
751
2.515625
3
[]
no_license
// // Created by Julian on 13.10.18. // #ifndef ROSBRIDGECLIENT_CSV_READER_H #define ROSBRIDGECLIENT_CSV_READER_H #include <vector> #include <string> #include <iostream> #include <unordered_map> #include <fstream> #include <boost/algorithm/string.hpp> namespace test { class CSVReader { public: CSVReader() = delete; CSVReader(const std::string filename, std::string delim = ","); ~CSVReader(); const std::unordered_map<std::string, std::vector<std::string>> &getData() const; private: void saveVec(const std::vector<std::string> &line); void processFile(); std::unordered_map<std::string, std::vector<std::string>> data; std::ifstream file; std::string delimiter; }; } // namespace test #endif //ROSBRIDGECLIENT_CSV_READER_H
Java
UTF-8
3,215
2.125
2
[]
no_license
package nju.trust.payloads.personalinfomation; import java.util.List; /** * @Author: 161250127 * @Description: * @Date: 2018/9/11 */ public class PersonalDetailInfomation { //学校分类 private String schoolClass; //专业情况 private String majorCondition; //受教育情况 private String educationBackground; //经济来源 private String financeSource; //学习成绩 private String studyRank; //挂科数 private Integer numNoPass; //奖学金 private List<String> scholarship; //科研竞赛获奖情况 private List<String> researchCompetition; //奖励情况 private List<String> awards; //惩罚情况 private List<String> punishment; //学费及住宿费缴纳状况 private Integer payment; //图书馆借阅还书情况 private Integer library; //考试作弊的信息 private Integer cheating; public String getSchoolClass() { return schoolClass; } public void setSchoolClass(String schoolClass) { this.schoolClass = schoolClass; } public String getMajorCondition() { return majorCondition; } public void setMajorCondition(String majorCondition) { this.majorCondition = majorCondition; } public String getEducationBackground() { return educationBackground; } public void setEducationBackground(String educationBackground) { this.educationBackground = educationBackground; } public String getFinanceSource() { return financeSource; } public void setFinanceSource(String financeSource) { this.financeSource = financeSource; } public String getStudyRank() { return studyRank; } public void setStudyRank(String studyRank) { this.studyRank = studyRank; } public Integer getNumNoPass() { return numNoPass; } public void setNumNoPass(Integer numNoPass) { this.numNoPass = numNoPass; } public List<String> getResearchCompetition() { return researchCompetition; } public void setResearchCompetition(List<String> researchCompetition) { this.researchCompetition = researchCompetition; } public List<String> getPunishment() { return punishment; } public void setPunishment(List<String> punishment) { this.punishment = punishment; } public Integer getPayment() { return payment; } public void setPayment(Integer payment) { this.payment = payment; } public Integer getLibrary() { return library; } public void setLibrary(Integer library) { this.library = library; } public Integer getCheating() { return cheating; } public void setCheating(Integer cheating) { this.cheating = cheating; } public List<String> getScholarship() { return scholarship; } public void setScholarship(List<String> scholarship) { this.scholarship = scholarship; } public List<String> getAwards() { return awards; } public void setAwards(List<String> awards) { this.awards = awards; } }
Java
UTF-8
1,779
2.3125
2
[]
no_license
package com.neekle.kunlunandroid.xmpp.data; import java.util.ArrayList; import com.neekle.kunlunandroid.xmpp.data.TypeEnum.HuddleState; public class HuddleInfo { // 群JID,是裸JID,主键,比如huddle@conference.openfire private String JID = ""; // 群的当前状态 private HuddleState State; // 群主题 private String Subject; // 群备注名称 private String RemarkName; //是否显示群昵称 private boolean isShowNickName; // 群成员列表 private ArrayList<HuddleMemberInfo> memberList; public HuddleInfo(String huddleJID) { JID = huddleJID; State = HuddleState.None; // Self = new HuddleMemberInfo(huddleJID, createrJID); Subject = null; RemarkName = null; memberList = new ArrayList<HuddleMemberInfo>(); } public HuddleInfo() { State = HuddleState.None; // Self = new HuddleMemberInfo(huddleJID, createrJID); Subject = null; RemarkName = null; memberList = new ArrayList<HuddleMemberInfo>(); } public String getJID() { return JID; } public void setJID(String jID) { JID = jID; } public HuddleState getState() { return State; } public void setState(HuddleState state) { State = state; } public String getSubject() { return Subject; } public void setSubject(String subject) { Subject = subject; } public String getRemarkName() { return RemarkName; } public void setRemarkName(String remarkName) { RemarkName = remarkName; } public ArrayList<HuddleMemberInfo> getMemberList() { return memberList; } public void setMemberList(ArrayList<HuddleMemberInfo> memberList) { this.memberList = memberList; } public boolean isShowNickName() { return isShowNickName; } public void setShowNickName(boolean isShowNickName) { this.isShowNickName = isShowNickName; } }
Python
UTF-8
256
3.09375
3
[]
no_license
n=int(input()) d={} for e in range(n): s=input().split(" ") name=s[0] m1=float(s[1]) m2=float(s[2]) m3=float(s[3]) d[name]=(m1,m2,m3) print(d) n=input("enter name") x=d.get(n) print(x) add=0 for e in x: add=add+e print(add/3)
Markdown
UTF-8
7,977
2.53125
3
[]
no_license
--- description: "Recipe: Quick Brad&amp;#39;s salmon roll ups with lemon dill cream sauce" title: "Recipe: Quick Brad&amp;#39;s salmon roll ups with lemon dill cream sauce" slug: 6342-recipe-quick-brad-and-39-s-salmon-roll-ups-with-lemon-dill-cream-sauce date: 2019-11-04T12:03:56.221Z image: https://img-global.cpcdn.com/recipes/c1f78f2623115eee/751x532cq70/brads-salmon-roll-ups-with-lemon-dill-cream-sauce-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/c1f78f2623115eee/751x532cq70/brads-salmon-roll-ups-with-lemon-dill-cream-sauce-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/c1f78f2623115eee/751x532cq70/brads-salmon-roll-ups-with-lemon-dill-cream-sauce-recipe-main-photo.jpg author: Randall Howell ratingvalue: 3 reviewcount: 11 recipeingredient: - 1 filet king salmon - 2 dungeness crab deshelled - 2 8 Oz pkg cream cheese room temperature - 14 cup chopped fresh basil - 12 LG onion chopped - 1 tbs garlic chopped - 14 cup white wine - For the sauce - 13 cup butter - 13 cup flour - 3 lemon juiced - 14 cup white wine - 1 qt heavy cream - 1 tsp granulated chicken bouillon - 23 Oz fresh dill chopped Reserve some for garnish - 9 drops yellow food coloring optional - 1 lemon cut into wedges for garnish recipeinstructions: - "Deshelled crab. Mix in a bowl with cream cheese, and fresh basil. Set aside." - "Saute onion in a small frying pan with a little butter. Cook for 3 to 4 minutes to sweat off. Add garlic and cook one more minute. Do not let brown. Add white wine. Let liquid reduce almost completely. When done fold into cream cheese mixture. Keep at room temperature." - "Next prepare the salmon fillet. Completely debone fish. Remove fins, and belly locks. Reserve for stock for risotto if desired. Remove pin bones with a pair of pliars." - "Remove skin and filet meat so that it is around a quarter inch thick. It is easier to do this if the fish is chilled. After this cut into chunks around 3 inches wide and as long as possible." - "Place pieces of meat on a board with the long side towards you. Spread crab mixture evenly on top. Roll up to the short side. You should have a long tube about 3 inches around. Using butchers twine, tie around the roll, starting at an inch from the end. Tie every two inches. Repeat this until all of the salmon is rolled and tied." - "Preheat oven to 400 degrees. Cut rolls of salmon in between the tied twine. Place in a baking dish. Bake for 15 minutes. After that change temp to 450 and bake another 5 minutes." - "Immediately start the sauce. Melt butter in a large frying pan. Add flour. Cook for 3 to 4 minutes to combine well. Do not let brown. Stir constantly. Add lemon juice first. Stir until incorporated. Next add wine. Do the same. Next add cream a half cup at a time stirring constantly. During this the bouillon and dill can be added and the food coloring if you prefer to use it. Add cream until you get a nice creamy gravy." - "When all is done, plate salmon roll ups. Drizzle with sauce. Garnish with fresh dill and lemon. Serve immediately. Enjoy" categories: - Resep tags: - brads - salmon - roll katakunci: brads salmon roll nutrition: 100 calories recipecuisine: Indonesian preptime: "PT17M" cooktime: "PT1H" recipeyield: "1" recipecategory: Dessert --- ![Brad&#39;s salmon roll ups with lemon dill cream sauce](https://img-global.cpcdn.com/recipes/c1f78f2623115eee/751x532cq70/brads-salmon-roll-ups-with-lemon-dill-cream-sauce-recipe-main-photo.jpg) Hello everybody, it's Drew, welcome to my recipe page. Today, I'm gonna show you how to make a distinctive dish, brad&#39;s salmon roll ups with lemon dill cream sauce. It is one of my favorites. This time, I am going to make it a bit unique. This will be really delicious. Brad&#39;s salmon roll ups with lemon dill cream sauce is only one of the most popular of current trending foods in the world. It's easy, it is quick, it tastes delicious. It's enjoyed by millions every day. They're nice and they look fantastic. Brad&#39;s salmon roll ups with lemon dill cream sauce is something which I've loved my entire life. Great recipe for Brad&#39;s salmon roll ups with lemon dill cream sauce. This recipe is not super tough. As well as nailing down the timing. To get started with this recipe, we must first prepare a few components. You can have brad&#39;s salmon roll ups with lemon dill cream sauce using 17 ingredients and 8 steps. Here is how you cook that. ##### The ingredients needed to make Brad&#39;s salmon roll ups with lemon dill cream sauce:: 1. Prepare 1 filet king salmon 1. Make ready 2 dungeness crab, deshelled 1. Take 2 (8 Oz) pkg cream cheese, room temperature 1. Prepare 1/4 cup chopped fresh basil 1. Prepare 1/2 LG onion, chopped 1. Prepare 1 tbs garlic, chopped 1. Make ready 1/4 cup white wine 1. Take For the sauce 1. Take 1/3 cup butter 1. Prepare 1/3 cup flour 1. Prepare 3 lemon, juiced 1. Get 1/4 cup white wine 1. Take 1 qt heavy cream 1. Make ready 1 tsp granulated chicken bouillon 1. Prepare 2/3 Oz fresh dill, chopped. Reserve some for garnish 1. Get 9 drops yellow food coloring, optional 1. Make ready 1 lemon cut into wedges for garnish Smoked Salmon Pinwheels Ambitious Kitchen. smoked salmon, spinach, chives, chopped fresh. Brad&#39;s salmon roll ups with lemon dill cream sauce. This recipe is not super tough. As well as nailing down the timing. ##### Steps to make Brad&#39;s salmon roll ups with lemon dill cream sauce: 1. Deshelled crab. Mix in a bowl with cream cheese, and fresh basil. Set aside. 1. Saute onion in a small frying pan with a little butter. Cook for 3 to 4 minutes to sweat off. Add garlic and cook one more minute. Do not let brown. Add white wine. Let liquid reduce almost completely. When done fold into cream cheese mixture. Keep at room temperature. 1. Next prepare the salmon fillet. Completely debone fish. Remove fins, and belly locks. Reserve for stock for risotto if desired. Remove pin bones with a pair of pliars. 1. Remove skin and filet meat so that it is around a quarter inch thick. It is easier to do this if the fish is chilled. After this cut into chunks around 3 inches wide and as long as possible. 1. Place pieces of meat on a board with the long side towards you. Spread crab mixture evenly on top. Roll up to the short side. You should have a long tube about 3 inches around. Using butchers twine, tie around the roll, starting at an inch from the end. Tie every two inches. Repeat this until all of the salmon is rolled and tied. 1. Preheat oven to 400 degrees. Cut rolls of salmon in between the tied twine. Place in a baking dish. Bake for 15 minutes. After that change temp to 450 and bake another 5 minutes. 1. Immediately start the sauce. Melt butter in a large frying pan. Add flour. Cook for 3 to 4 minutes to combine well. Do not let brown. Stir constantly. Add lemon juice first. Stir until incorporated. Next add wine. Do the same. Next add cream a half cup at a time stirring constantly. During this the bouillon and dill can be added and the food coloring if you prefer to use it. Add cream until you get a nice creamy gravy. 1. When all is done, plate salmon roll ups. Drizzle with sauce. Garnish with fresh dill and lemon. Serve immediately. Enjoy But this is a very flavorful dish. I served this dish with wild Chantrelle mushroom risotto. See great recipes for Brad&#39;s steak roll up&#39;s with heirloom tomato relish too! Take about a baseball sized handful of salmon mix and form into a thin patty. Place about a golf ball sized wad of shredded mozzarella in the middle. So that's going to wrap it up for this special food brad&#39;s salmon roll ups with lemon dill cream sauce recipe. Thank you very much for your time. I'm confident you will make this at home. There's gonna be more interesting food in home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking!
Markdown
UTF-8
3,026
2.953125
3
[]
no_license
借款单位:____(以下简称甲方) 贷款银行:______中国农业银行(以下简称乙方) 甲方用于:______ 所需外汇资金,于____年__月__日向乙方申请外汇贷款。乙方根据甲方填报的《外汇借款申请书》(编号:_____)和其它有关资料,经审查同意向甲方发放外汇流动资金贷款。为明确责任,恪守信用,特签订本合同并共同遵守。 第一条 甲方向乙方借(外币名称)_____万元(大写金额) 第二条 借款期限自第一笔用汇日起到还清全部本息日止,即从____年__月__日至____年__月__日,共__月。 第三条 在合同规定的借款期限内,贷款基准利率为按__月浮动,利息每季计收一次。 第四条 甲方愿遵守《中国农业银行外汇流动资金贷款暂行办法》和其它有关规定,按乙方的要求提供使用贷款的有关情况、财务资料及进行信贷管理工作的便利。 第五条 甲方在乙方开立外汇和人民币帐户,遵照国家外汇管理的有关规定用款。 第六条 本合同所附《用款计划表》和《还本付息计划表》是本合同的组成部分,与本合同具有同等法律效力。 乙方保证按《用款计划表》及时供应资金。如因乙方责任未按期提供贷款则乙方须向甲方支付____‰的违约金。 甲方因故不能按用款计划用款,必须提前一个月向乙方提出调整用款计划。否则,乙方对未用或超用部分按实际占用天数收取___‰的承担费。 第七条 甲方保证按《还本付息计划表》以所借同种外币还本付息(若以其它可自由兑换的外汇偿还,按还款时的外汇牌价折算成所借外币偿还)如因不可抗力事件,甲方不能在贷款期限终止日全部还清本息,应在到期日十五天前向乙方提出展期申请,经乙方同意,双方共同修改合同的原借款期限,并重新确定相应的贷款利率。未经乙方同意展期的贷款,乙方对逾期部分加收__%的逾期利息。 第八条 甲方保证本合同规定的用途使用贷款,如发生挪用,乙方除限期纠正外,对被挪用部分加收__%的罚息,并有权停止或收回全部或部分贷款。 第九条 本合同项下的借款本息由作为甲方的担保人,并由担保人按乙方的要求向乙方出具担保书。一旦甲方无力清偿贷款本息,应由担保人履行还贷款本息的责任。 第十条 本合同以外的其它事项,由甲、乙方双方共同按照《中华人民共和国经济 合同法 》和国务院《 借款合同 条例》的有关规定办理。 第十一条 本合同经甲、乙双方签章生效,至全部贷款本息收回后失效。本合同正本一式二份,甲、乙双方各执一份。 甲方: 乙方: 单位名称: (公章) 单位名称: (公章) 签约人: (签章) 签约人: (签章) 年 月 日签订于:
Java
UTF-8
1,234
2.484375
2
[]
no_license
package staff.backend.model; import javax.persistence.*; import java.sql.Time; import java.util.Date; @Entity @Table(name = "history") public class History { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) // IDENTITY as the example has flyway in it and fixed schema in src/main/resources/db/migration private long id; @Column(name = "Date", nullable = false) private Date date; @Column(name = "Time", nullable = false) private Time time; @Column(name = "status", nullable = false) private Boolean status; @ManyToOne @OrderBy("officer_id") private Officer officers; public History(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Time getTime() { return time; } public void setTime(Time time) { this.time = time; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } }
Python
UTF-8
1,263
3.3125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.cluster import KMeans # In[4]: data = pd.read_csv('3.01.+Country+clusters.csv') data # In[5]: data_mapped = data.copy() data_mapped['Language']=data_mapped['Language'].map({'English':0,'French':1,'German':2}) data_mapped # In[6]: x=data_mapped.iloc[:,1:4] x # In[9]: kmeans = KMeans(3) kmeans.fit(x) # In[10]: identified_clusters = kmeans.fit_predict(x) identified_clusters # In[11]: data_with_clusters = data_mapped.copy() data_with_clusters['Cluster'] = identified_clusters data_with_clusters # In[12]: plt.scatter(data_with_clusters['Longitude'],data_with_clusters['Latitude'],c=data_with_clusters['Cluster'],cmap='rainbow') plt.xlim(-180,180) plt.ylim(-90,90) plt.show() # ## WCSS # In[13]: kmeans.inertia_ # In[14]: wcss=[] for i in range(1,7): kmeans=KMeans(i) kmeans.fit(x) wcss_iter=kmeans.inertia_ wcss.append(wcss_iter) # In[15]: wcss # In[16]: number_clusters=range(1,7) plt.plot(number_clusters,wcss) plt.title('The Elbow Method') plt.xlabel('Number Of Clusters') plt.ylabel('Within-cluster Sum Of Squares') # In[ ]:
JavaScript
UTF-8
5,550
2.625
3
[]
no_license
//删除用户组 $(function () { $('.delete-role-btn').click(function (event) { event.preventDefault(); var role_id = $(this).attr('data-role-id'); zlalert.alertConfirm({ msg: '您确定要删除这个分组吗?', confirmCallback: function () { // 发送ajax zlajax.post({ url: '/cms/croles/delete/', data:{ 'role_id': role_id }, success: function (data) { if(data['code'] == 200){ setTimeout(function () { zlalert.alertSuccessToast('恭喜!CMS组删除成功!'); },200); setTimeout(function () { // 重新加载这个页面 window.location.reload(); },1400); }else{ setTimeout(function () { zlalert.alertInfoToast(data['message']); },200); } } }) } }); }); }); //修改 新增按钮切换 $(function () { $('#new-group-btn').click(function () { $("#edit-btn").css('display','none'); $("#submit-btn").css('display',''); }) }); // 添加用户组 $(function () { $("#submit-btn").click(function (event) { // 获取组名 var name = $("input[name='name']").val(); var desc = $("input[name='desc']").val(); var permission_inputs = $("input[name='permission']:checked"); var permissions = []; $.each(permission_inputs,function (idx,obj) { permissions.push($(obj).val()); }); var data = { name:name, desc:desc, permissions: permissions }; console.log(permissions); zlajax.post({ url: '/cms/croles/', data: data, success: function (data) { if(data['code']===200){ zlalert.alertSuccessToast('恭喜,CMS组添加成功!'); setTimeout(function () { // 跳转到组管理页面 window.location = '/cms/croles/'; },1200); }else{ zlalert.alertInfoToast(data['message']); } }, }); }); }); //模态框添加数据 $(function(){ $('.edit-role-btn').click(function(){ $("#submit-btn").css('display','none'); $("#edit-btn").css('display',''); var self = $(this); var role_id = $(this).attr('data-role-id'); var dialog = $("#role-dialog"); dialog.modal("show"); var tr = self.parent().parent(); var name = tr.attr('role-name'); var desc = tr.attr("role-desc"); var permissions = tr.attr("role.permissions"); var idInput = dialog.find("input[name='role-id']"); var nameInput = dialog.find("input[name='name']"); var descInput = dialog.find("input[name='desc']"); var permissionInputs = dialog.find("input[name='permission']"); idInput.val(role_id); nameInput.val(name); descInput.val(desc); var reg = /\{\d{1,3}\:/g; var arry1 = []; var arry2 = permissions.match(reg); for (let i=0;i<arry2.length;i++){ let reg = /\d{1,3}/; arry1.push(arry2[i].match(reg)[0]); } for(let i=0;i<arry1.length;i++){ for(let j=0;j<permissionInputs.length;j++){ if(permissionInputs[j].value === arry1[i]){ permissionInputs[j].checked = true; } } } }) }); //修改用户组数据 $(function () { $("#edit-btn").click(function () { var role_id = $("input[name='role-id']").val(); var name = $("input[name='name']").val(); var desc = $("input[name='desc']").val(); var permission_inputs = $("input[name='permission']:checked"); var permissions = []; $.each(permission_inputs,function (idx,obj) { permissions.push($(obj).val()); }); console.log(role_id); console.log(permissions); zlajax.post({ url: '/cms/roles/edit', data: { 'id': role_id, 'name':name, 'desc':desc, 'permissions': permissions }, success: function (data) { if(data['code']==200){ zlalert.alertSuccessToast('恭喜,CMS组修改成功!'); setTimeout(function () { // 跳转到组管理页面 window.location = '/cms/croles/'; },1200); }else{ zlalert.alertInfoToast(data['message']); } }, }); }) }); //关闭模态框清空input数据 $(function () { $('#role-dialog').on('hide.bs.modal', function () { var dialog = $("#role-dialog"); var nameInput = dialog.find("input[name='name']"); var descInput = dialog.find("input[name='desc']"); var permissionInputs = dialog.find("input[name='permission']"); nameInput.val(""); descInput.val(''); for(let i=0;i<permissionInputs.length;i++){ if(permissionInputs[i].checked === true){ permissionInputs[i].checked = false; } } }); });
C++
UTF-8
826
2.734375
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <vector> int main() { freopen("cycles.in", "r", stdin); freopen("cycles.out", "w", stdout); int n, m; scanf("%d%d", &n, &m); std::vector<int> a(m), b(m), deg(n); for (int i = 0; i < m; ++i) { scanf("%d%d", &a[i], &b[i]); deg[--a[i]]++; deg[--b[i]]++; } std::vector<std::vector<int>> edges(n); for (int i = 0; i < m; ++i) { if (deg[a[i]] < deg[b[i]] || (deg[a[i]] == deg[b[i]] && a[i] < b[i])) edges[a[i]].push_back(b[i]); else edges[b[i]].push_back(a[i]); } std::vector<bool> mark(n); int ret = 0; for (int u = 0; u < n; ++u) { for (auto &v: edges[u]) mark[v] = 1; for (auto &v: edges[u]) { for (auto &w: edges[v]) ret += mark[w]; } for (auto &v: edges[u]) mark[v] = 0; } printf("%d\n", ret); return 0; }
C++
UTF-8
9,102
2.765625
3
[]
no_license
#include "dataman.h" #include <exception> #ifdef __LOG_TEST__ #include "../Utils/logfile.h" static LogFile logFile("DataManager", "LogTest", true); #endif Field::Field() : m_position(0), m_type(Text), m_start(0), m_end(0) { //empty } Field::Field(int pos, FieldType type, unsigned int start, unsigned int end) : m_position(pos), m_type(type), m_start(start), m_end(end) { //empty } bool Field::atRange(unsigned int col) { return col >= m_start && col <= m_end; } template<typename _Iterator1, typename _Iterator2> inline size_t IncUtf8StringIterator(_Iterator1& it, const _Iterator2& last) { if(it == last) return 0; unsigned char c; size_t res = 1; for(++it; last != it; ++it, ++res) { c = *it; if(!(c&0x80) || ((c&0xC0) == 0xC0)) break; } return res; } inline size_t Utf8StringSize(const std::string& str) { size_t res = 0; std::string::const_iterator it = str.begin(); for(; it != str.end(); IncUtf8StringIterator(it, str.end())) res++; return res; } void Field::appendInfo(std::string c, unsigned int pos) { m_info.insert( (pos-m_start), c); //std::cout << "appendInfo --> String[" << c.c_str() << "] Size[" << c.size() << "]" << std::endl; m_end += Utf8StringSize(c); } void Field::appendChar(char c, unsigned int pos) { m_info.insert( (pos-m_start) , 1, c); m_end++; } void Field::removeAt(unsigned int pos) { m_info.erase( (pos-m_start), 1); m_end--; } void Field::shiftRight() { m_start++; m_end++; } void Field::shiftLeft() { m_start--; m_end--; } Field* Line::searchAtCol(unsigned int col) { for(auto d : m_fields) { if(d->atRange(col)) { return d; } } return nullptr; } std::string Line::dump() { std::string ret = ""; for( unsigned int i = 0; i < m_fields.size(); i++ ) { ret.append(m_fields[i]->m_info); ret.append(" "); } return ret; } LineManager::LineManager() { #ifdef __LOG_TEST__ logFile.write("[DataMananager] ctor"); #endif } LineManager::~LineManager() { if( m_lines.empty() == false ) { for( auto line : m_lines ) { delete line.second; } m_lines.clear(); } } unsigned int LineManager::lineCount() { return (unsigned int)m_lines.size(); } std::string LineManager::dumpLine(unsigned int line) { #ifdef __LOG_TEST__ logFile.write("[DataMananager] dumping line [%d]", line); #endif return m_lines.at(line)->dump(); } std::string LineManager::dumpLines() { std::string ret = std::string(""); for( auto line : m_lines ) { ret.append(line.second->dump() + "\n"); } return ret; } #ifdef __LOG_TEST__ void LineManager::dump() { logFile.write("[DataManager] Dumping all lines"); for( auto line : m_lines ) { logFile.write("\t>>>Line[%d] Text[ %s]", (line.second->m_number + 1), line.second->dump().c_str() ); } } #endif void LineManager::removeCharacter(unsigned int col, unsigned int line) { try { #ifdef __LOG_TEST__ logFile.write("[DataMananager] Removing character Line[%d] Column[%d]", line, col); #endif Line* ptr = m_lines.at(line); Field* type = ptr->searchAtCol(col); if( type != nullptr ) { type->removeAt(col - 1); for( unsigned int i = type->m_position + 1; i < ptr->m_fields.size(); i++ ) { Field* o = ptr->m_fields.at(i); o->shiftLeft(); } } } catch(std::out_of_range& ex) { #ifdef __LOG_TEST__ logFile.write("[DataMananager] Remove Character Error [%s]", ex.what()); #endif } catch(std::exception& ex) { throw ex; } } void LineManager::addTitle(const char* str, unsigned int col, unsigned int line) { Line* ptr = nullptr; try { #ifdef __LOG_TEST__ logFile.write("[DataMananager] Inserting title [%s] at Line[%d] in Column[%d]", str, line, col); #endif ptr = m_lines.at(line); } catch(std::out_of_range& /*ex*/) { ptr = new Line; ptr->m_number = line; m_lines.insert(std::make_pair(line, ptr)); #ifdef __LOG_TEST__ logFile.write("[DataMananager] Inserting a new line [%d]", line); #endif } Field* type = ptr->searchAtCol(col); if( type == nullptr ) { type = new Field((unsigned int)ptr->m_fields.size(), Title, col, col); type->appendInfo(str, col); #ifdef __LOG_TEST__ logFile.write("[DataMananager] Appending new string [%s] with size [%d] at [%d] in line [%d]", str, type->m_end, col, line); #endif ptr->m_fields.push_back(type); } } void LineManager::addName(const char* str, unsigned int col, unsigned int line) { Line* ptr = nullptr; try { #ifdef __LOG_TEST__ logFile.write("[DataMananager] Inserting name [%s] at Line[%d] in Column[%d]", str, line, col); #endif ptr = m_lines.at(line); } catch(std::out_of_range& /*ex*/) { ptr = new Line; ptr->m_number = line; m_lines.insert(std::make_pair(line, ptr)); #ifdef __LOG_TEST__ logFile.write("[DataMananager] Inserting a new line [%d]", line); #endif } Field* type = ptr->searchAtCol(col); if( type == nullptr ) { type = new Field((unsigned int)ptr->m_fields.size(), Name, col, col); type->appendInfo(str, col); #ifdef __LOG_TEST__ logFile.write("[DataMananager] Appending new string [%s] with size [%d] at [%d] in line [%d]", str, type->m_end, col, line); #endif ptr->m_fields.push_back(type); } } bool LineManager::isEditable(unsigned int col, unsigned int line) { if(m_lines.empty()) { return true; } try { std::cout << "m_lines.size() " << m_lines.size() << std::endl; Line* ptr = m_lines.at(line); Field* type = ptr->searchAtCol(col); if(type != nullptr) { if( type->m_type == Title ) return false; } return true; } catch(std::out_of_range& ex) { #ifdef __LOG_TEST__ logFile.write("[DataMananager][isEditable] Expected error at eventFilter [%s]", ex.what()); #endif return true; } } std::string LineManager::type(unsigned int col, unsigned int line) throw(std::exception) { if(m_lines.empty()) { return "Text"; } try { Line* ptr = m_lines.at(line); Field* type = ptr->searchAtCol(col); if(type != nullptr) { switch(type->m_type) { case Title: return "Title"; case Text: return "Text"; case Name: return "Name"; case Relation: return "Relation"; case None: case MaxFieldType: return "Error"; } } return "Text"; } catch(std::out_of_range& ex) { //logFile.write("[DataMananager][type] Expected error at eventFilter [%s]", ex.what()); return "Text"; } catch(std::exception& ex) { throw ex; } } bool LineManager::eventFilter(unsigned int col, unsigned int line, char character) { Line* ptr; int position = 0; try { ptr = m_lines.at(line); Field* type = ptr->searchAtCol(col); if( type != nullptr ) { if( type->m_type == Title) { return false; } #if __LOG_TEST__ logFile.write("[DataMananager] Appending new character [%c] at [%d] in line [%d]", character, col, line); #endif type->appendChar(character, col); for( unsigned int i = type->m_position + 1; i < ptr->m_fields.size(); i++ ) { Field* o = ptr->m_fields.at(i); o->shiftRight(); } return true; } else { position = (unsigned int)ptr->m_fields.size(); } } catch(std::out_of_range& /*ex*/) { #ifdef __LOG_TEST__ logFile.write("[DataMananager][Create new line] Inserting new line [%d]", line); #endif ptr = new Line; ptr->m_number = line; } Field* type = new Field(position, Text, col, col); #ifdef __LOG_TEST__ logFile.write("[DataMananager] Appending new character [%c] at [%d] in line [%d]", character, col, line); #endif type->appendChar(character, col); ptr->m_fields.push_back(type); m_lines.insert(std::make_pair(line, ptr)); return true; }
Python
UTF-8
3,895
4.09375
4
[]
no_license
''' implement as stack using doubly linked list ''' import gc class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class Stack: def __init__(self): self.size = 0 self.head = None self.tail = None self.pointer = self.head def push(self, data): ''' pushes to top of the stack O(1) ''' new_node = Node(data) # if empty, make new node as head if self.is_empty(): self.head = new_node self.tail = new_node else: # take current head, update head and pointers if self.size == 0: self.tail = new_node cur_head = self.head cur_head.prev = new_node new_node.next = cur_head self.head = new_node self.size += 1 def pop(self): ''' pops the head of the stack O(1) ''' # if empty, return if self.is_empty(): return if self.size == 1: self.tail = None # get head # get next node # make next node the head cur_head = self.head next_node = cur_head.next if next_node is not None: next_node.prev = None self.head = next_node cur_head = None self.size -= 1 def is_empty(self): ''' checks currents size of the stack O(1) ''' if self.size <= 0: return True return False def peek_head(self): ''' returns top of the stack O(1) ''' if self.is_empty(): print('empty stack') return return self.head.data def peek_tail(self): ''' returns bottom of the stack O(1) ''' if self.is_empty(): print('empty stack') return return self.tail.data def print_all_forward(self): ''' prints the entire stack O(N) ''' cur_node = self.head while cur_node is not None: print(cur_node.data, end=', ') cur_node = cur_node.next print('') def print_all_reverse(self): ''' iterates using link nodes backwards O(N) ''' # get tail, iterate backwards using link nodes cur_node = self.tail while cur_node is not None: print(cur_node.data, end=', ') cur_node = cur_node.prev print() if __name__ == '__main__': stack_obj = Stack() stack_obj.push(1) stack_obj.print_all_forward() stack_obj.push(2) stack_obj.print_all_forward() stack_obj.push(3) stack_obj.print_all_forward() stack_obj.push(4) stack_obj.print_all_forward() stack_obj.push(5) stack_obj.print_all_forward() stack_obj.pop() stack_obj.print_all_forward() stack_obj.push(0) stack_obj.print_all_forward() stack_obj.print_all_reverse() stack_obj.pop() stack_obj.print_all_forward() stack_obj.pop() stack_obj.print_all_forward() print('head', stack_obj.peek_head()) print('tail', stack_obj.peek_tail()) stack_obj.print_all_reverse() stack_obj.pop() stack_obj.print_all_forward() stack_obj.print_all_reverse() stack_obj.pop() stack_obj.print_all_forward() stack_obj.print_all_reverse() stack_obj.pop() stack_obj.print_all_forward() stack_obj.pop() stack_obj.print_all_reverse() stack_obj.print_all_forward() stack_obj.print_all_reverse() stack_obj.push(10) stack_obj.print_all_forward() print('head', stack_obj.peek_head()) print('tail', stack_obj.peek_tail()) stack_obj.push(9) stack_obj.print_all_forward() print('head', stack_obj.peek_head()) print('tail', stack_obj.peek_tail()) gc.collect()
Java
UTF-8
567
1.84375
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 foodiesquad.dao; import foodiesquad.entity.Deliver; import java.util.List; /** * * @author hmqhmq */ public interface DeliverDao { public boolean addDeliver(Deliver Deliver); public boolean delDeliver(int dId); public boolean updateDeliver(Deliver Deliver); public Deliver queryDeliverById(int dId); public Deliver queryDeliverBydName(String dName); }
C++
UTF-8
648
2.828125
3
[]
no_license
#include<vector> class Solution { public: int jump(std::vector<int>& nums) { if(nums.size() == 1){ return 0; } int step = 0; int lastIdx= 0; int fastIdx = nums[0]; while(true){ step++; if(fastIdx >= nums.size() -1){ return step; } int local = fastIdx; for(int i = lastIdx + 1; i <= fastIdx; i++){ if(i + nums[i] >= local){ local = i + nums[i]; } } lastIdx = fastIdx; fastIdx = local; } return 0; } };
Java
UTF-8
2,095
2.9375
3
[]
no_license
package gui; import javafx.scene.control.TextField; import javafx.util.Pair; import java.util.List; public class SmartTextField extends TextField { private List<Pair<Integer, Integer>> actualText; public SmartTextField(String s) { super(s); } String getTypedText() { String orig = getText(); StringBuilder text = new StringBuilder(); for (Pair<Integer, Integer> p : actualText) { text.append(orig.substring(p.getKey(), p.getValue())); } return text.toString(); } void edit(int index, int length, String oldText, String newText, boolean user) { } protected static class Rule { String regex; List<EditConstraint> textToModify; void apply(SmartTextField field) { if (field.getTypedText().matches(regex)) { for (EditConstraint e : textToModify){ int index = e.getIndex(); if (e.insert) { field.edit(index, e.getLength(), field.getTypedText(), e.getReplace(), false); } else { field.edit(index, e.getLength(), field.getTypedText(), "", false); } } } } } private static class EditConstraint { private boolean insert; private int index; private int length; private String replace; public int getIndex() { return index; } public boolean isInsert() { return insert; } public void setInsert(boolean insert) { this.insert = insert; } public void setIndex(int index) { this.index = index; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getReplace() { return replace; } public void setReplace(String replace) { this.replace = replace; } } }
Java
UTF-8
2,401
2.40625
2
[]
no_license
package com.costrella.android.first_android_game.game.object; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Movie; import android.graphics.Paint; import android.graphics.RectF; import android.util.Log; import com.costrella.android.first_android_game.R; import org.jbox2d.collision.CircleDef; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.World; public class Monster1{ public float x; public float y; private float radius; private boolean sensorInitial = true; private float xSensorInitial = 0; private float ySensorInitial = 0; private Body body; private Vec2 force = new Vec2(0, 0); private Vec2 point; private Vec2 pointOld = new Vec2(0, 0); private Movie mMovie; private long start; public void draw(Canvas canvas, Resources resources){ Paint mPaint = new Paint(); int duration; mPaint.setAntiAlias(true); mPaint.setColor(Color.GREEN); //canvas.drawCircle(x, y, radius, mPaint); // GIF animation part try{ if(mMovie == null){ mMovie = Movie.decodeStream(resources.openRawResource(R.drawable.kingusuraimu)); // mMovie = null; start = android.os.SystemClock.uptimeMillis(); Log.d("Game", "Movie success"); } duration = mMovie.duration(); if(duration == 0){ duration = 1000; } mMovie.setTime((int)(android.os.SystemClock.uptimeMillis() - start)%duration); mMovie.draw(canvas, x - mMovie.width()/2, y - mMovie.height()/2); }catch (Exception e) { Log.d("Game","Movie exception: "+e.toString()); } } public Monster1(float _x, float _y, float _radius, World _world){ x = _x; y = _y; radius = _radius; CircleDef shape = new CircleDef(); shape.density = 0.1f; shape.friction = 0.0f; shape.radius = radius; BodyDef bodyDef = new BodyDef(); bodyDef.position.set(x, y); body = _world.createDynamicBody(bodyDef); body.createShape(shape); body.setMassFromShapes(); } }
Java
UTF-8
1,618
2.546875
3
[ "Apache-2.0" ]
permissive
package cn.dyaoming.sync; import org.springframework.cache.Cache; import org.springframework.cache.support.AbstractCacheManager; import java.util.Collection; import java.util.Collections; /** * <p> * 缓存控制器 * </p> * * @author DYAOMING * @since 2020-04-25 * @version 0.0.4 */ public class DefaultSyncManager extends AbstractCacheManager { private String name = "default"; private long timeout = 300L; private boolean secret; private String database; /** * 分隔符 */ private final static String SEPARATOR = "#"; /** * <p> * 设置缓存名 * </p> * * @param name 缓存名称 */ public void setName(String name) { this.name = name; } public void setTimeout(long timeout) { this.timeout = timeout; } /** * <p> * 加密标识设置 * </p> * * @param secret String类型 加密标识 */ public void setSecret(String secret) { if ("true".equalsIgnoreCase(secret)) { this.secret = true; } else { this.secret = false; } } public void setDatabase(String database) { this.database = database; } private Collection<? extends Cache> caches = Collections.emptySet(); public void setCaches(Collection<? extends Cache> caches) { this.caches = caches; } @Override protected Collection<? extends Cache> loadCaches() { return this.caches; } }
C#
UTF-8
2,078
2.53125
3
[]
no_license
using DataLibrary; using NewsBookLN.GestUtilizadores; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccessLibrary { public class CategoriaData : ICategoriaData { private readonly ISQLDataAccess _dbCat; public CategoriaData(ISQLDataAccess db) { _dbCat = db; } public Task<List<Categoria>> GetCategorias() { string sql = "select * from dbo.Categoria"; return _dbCat.LoadData<Categoria, dynamic>(sql, new { }); } public Task<List<Categoria>> GetCategoria(int cat) { string sql = "select * from dbo.Categoria where IdCategoria = '" + cat + "'"; return _dbCat.LoadData<Categoria, dynamic>(sql, new { }); } public Task InsertUserCategorias(Utilizador person) { List <int> c = person.CategoriasFav; int cat = c[0]; string sql = @"insert into dbo.Utilizador_Categoria (UserName,IdCategoria) values "; for (int i = 0; i < c.Count()-1; i++) { sql = sql + "('" + person.UserName + "', '" + c[i] + "'), "; } sql = sql + "('" + person.UserName + "', '" + c[c.Count()-1] + "')"; return _dbCat.SaveData(sql, new { }); } public Task<List<Categoria>> GetCategoriaUser(string u) { string sql = "select * from dbo.Utilizador_Categoria where UserName = '" + u + "'"; return _dbCat.LoadData<Categoria, dynamic>(sql, new { }); } public Task deleteCategoriasFav(string username, List<int> idCats) { string sql = ""; foreach (int cat in idCats) sql += "delete from dbo.Utilizador_Categoria where IdCategoria='" + cat + "' and UserName ='" + username + "';"; return _dbCat.SaveData(sql, new { }); } } }
C++
UTF-8
450
2.71875
3
[]
no_license
// // Created by phillip.goellner on 19.02.2017. // #include "And.h" //Konstruktor mit zwei Subtermen als Übergabeparameter And::And(Term_Object* sub_left, Term_Object* sub_right) { subterm_left = sub_left; subterm_right = sub_right; } //Die logische Auswertung dieses Ausdrucks wird zurückgegeben bool And::evaluate(std::map<std::string, char>* vars) { return (subterm_left -> evaluate(vars)) && (subterm_right -> evaluate(vars)); }
Python
UTF-8
11,641
2.5625
3
[ "BSD-3-Clause" ]
permissive
''' Tool Dialogs ''' import os import pyglet import kytten from kytten.frame import Frame, SectionHeader, FoldingSection from kytten.dialog import Dialog from kytten.button import Button from kytten.layout import VerticalLayout, HorizontalLayout, GridLayout from kytten.widgets import Spacer, Label from kytten.text_input import Input from kytten.checkbox import Checkbox import widgets import dialogs from dialogs import genOkCancelLayout, theme, on_escape import appEngine.scenegraph as scenegraph class ToolDialog(object): ''' controls dialog that allows user to manipulate layers by dynamically while current type of layer is selected showing given controls for type of layer. ''' def __init__(self, editor): self.layouts = { "terrain" : self.terrainLayout, "aesthetic" : self.itemLayout, "object" : self.itemLayout } editor.push_handlers(self) self.controller = editor.controller self.dialog = None self.window = editor self.previousChoice = None self.selectedItemLabel = None def delete(self): if self.dialog is not None: self.dialog.teardown() self.dialog = None def on_layer_update(self): layer = self.controller.currentLayer if layer == None: self.delete() return if self.dialog != None: self.dialog.teardown() # create layout according to editor mode if layer.name == "terrain" or layer.name == "object": name = layer.name else: name = "aesthetic" self.layout = self.layouts[name]() self.dialog = Dialog(Frame(VerticalLayout([self.layout])), window=self.window, batch=self.window.dialogBatch, anchor=kytten.ANCHOR_TOP_LEFT, theme=theme) def on_tool_select(self, id): self.active_tool = id self.controller.setCurrentTool(id) # reset the selected item dialog if self.window.selectedItemDialog.dialog != None: self.window.selectedItemDialog.dialog.teardown() def on_item_select(self, item): self.selectedItemLabel.set_text(item) path = os.path.join("assets", self.controller.currentLayer.dir, item) self.selectedItemImage.setImage(pyglet.image.load(path)) self.controller.tools['placeitem'].setSelectedItem(path) def terrainLayout(self): ''' creates terrain layer manip dialog. syncing with current options ''' def on_snapmode_click(is_checked): self.controller.tools['plotline'].snapMode = is_checked def on_colour_select(choice): self.controller.graph.layers['terrain'].setLineColor(choice) toolSet = [] toolSet.append(('pan', pyglet.image.load( os.path.join('theme', 'tools', 'pan.png')))) toolSet.append(('plotline', pyglet.image.load( os.path.join('theme', 'tools', 'plotline.png')))) toolSet.append(('select',pyglet.image.load( os.path.join('theme', 'tools', 'select.png')))) # Create options from images to pass to Palette palette_options = [[]] palette_options.append([]) palette_options.append([]) for i, pair in enumerate(toolSet): option = widgets.PaletteOption(id=pair[0], image=pair[1], padding=4) # Build column down, 3 rows palette_options[i%2].append(option) toolSection = widgets.PaletteMenu(palette_options, on_select=self.on_tool_select) ''' sync dropdown colour selection ''' keys = self.controller.currentLayer.colors.items() for key in keys: if key[1] == self.controller.currentLayer.curColor: colour = key[0] break return VerticalLayout([ toolSection, SectionHeader("", align=kytten.HALIGN_LEFT), Label("Line Colour"), kytten.Dropdown(["White", "Black", "Blue", "Green", "Red"], selected=colour, on_select=on_colour_select), Checkbox("Point Snap", is_checked=self.controller.tools["plotline"].snapMode, on_click=on_snapmode_click), Checkbox("Grid Snap", id="snap_to", is_checked=True) ]) ''' ''' def itemLayout(self): def on_select_item(): SelectItemDialog(self.window, self.controller.currentLayer, self) toolSet = [] toolSet.append(('pan', pyglet.image.load( os.path.join('theme', 'tools', 'pan.png')))) toolSet.append(('placeitem', pyglet.image.load( os.path.join('theme', 'tools', 'object.png')))) toolSet.append(('select',pyglet.image.load( os.path.join('theme', 'tools', 'select.png')))) # Create options from images to pass to Palette palette_options = [[]] palette_options.append([]) palette_options.append([]) for i, pair in enumerate(toolSet): option = widgets.PaletteOption(id=pair[0], image=pair[1], padding=4) # Build column down, 3 rows palette_options[i%2].append(option) toolSection = widgets.PaletteMenu(palette_options, on_select=self.on_tool_select) ''' selected item display ''' self.selectedItemLabel = Label("") self.selectedItemImage = widgets.Image(None, maxWidth=128, maxHeight=164) return VerticalLayout([ Label(self.controller.currentLayer.name), toolSection, SectionHeader("Selected Item", align=kytten.HALIGN_LEFT), self.selectedItemLabel, self.selectedItemImage, SectionHeader("", align=kytten.HALIGN_LEFT), Checkbox("Grid Snap", id="snap_to", is_checked=True), Checkbox("Sticky Mode", id="sticky_mode", is_checked=True), SectionHeader("", align=kytten.HALIGN_LEFT), kytten.Button("Select Item", on_click=on_select_item) ]) class SelectItemDialog(Dialog): ''' allows user to select aesthetic or object item ''' def __init__(self, window, currentLayer, layerDialog): self.controller = window.controller self.layerDialog = layerDialog layout = self.createLayout(currentLayer) super(SelectItemDialog, self).__init__( Frame(layout), window=window, batch=window.dialogBatch, anchor=kytten.ANCHOR_CENTER, theme=theme, on_enter=self.on_enter, on_escape=on_escape) def createLayout(self, currentLayer): ''' build list of items with name and image ''' path = os.path.join("assets", currentLayer.dir) items = list() for (path, dirs, files) in os.walk(path): for file in files: if file.endswith(".png"): items.append([file, pyglet.image.load(os.path.join(path, file))]) if len(items) == 0: itemsMenu = Label("No Items Found") else: itemsMenu = kytten.Scrollable(widgets.ItemMenu(items, on_select=self.layerDialog.on_item_select), height=600) return VerticalLayout([ itemsMenu, SectionHeader("", align=kytten.HALIGN_LEFT), genOkCancelLayout(self.on_submit, self.on_cancel) ]) def on_cancel(self): on_escape(self) def on_submit(self): self.on_enter(self) def on_enter(self, dialog): on_escape(self) class SelectedItemDialog(object): ''' indicated currently selected and item and displays editable properties ''' currentItem = None def __init__(self, editor): self.dialog = None self.controller = editor.controller self.window = editor self.updateItem() def on_select_item(self): item = self.controller.tools["select"].selectedItem self.updateItem(item) def updateItem(self, item=None): if self.dialog != None: self.dialog.teardown() if item == None: self.currentItem = None else: self.currentItem = item if self.controller.currentLayer.name == "terrain": layout = self.lineLayout() elif self.controller.currentLayer.name == "object": layout = self.objectLayout() else: layout = self.visualLayout() self.dialog = kytten.Dialog( Frame(kytten.FoldingSection("Item",layout)), window=self.window, batch=self.window.dialogBatch, anchor=kytten.ANCHOR_BOTTOM_LEFT, theme=theme) def objectLayout(self): def x_input(text): self.currentItem.updatePosition(x=int(text)) self.controller.edited = True def y_input(text): self.currentItem.updatePosition(y=int(text)) self.controller.edited = True item = self.currentItem return GridLayout([ [Label("Name"), Input(text=item.name, abs_width=100, disabled=True)], [Label("X Pos"), Input(text=str(item.x), abs_width=50, max_length=4, on_input=x_input)], [Label("Y Pos"), Input(text=str(item.y), abs_width=50, max_length=4, on_input=y_input)], [Label("Width"), Input(text=str(item.x2-item.x), abs_width=50, max_length=4, disabled=True)], [Label("Height"), Input(text=str(item.y2-item.y), abs_width=50, max_length=4, disabled=True)]], padding=18) def visualLayout(self): def x_input(text): self.currentItem.updatePosition(x=int(text)) self.controller.edited = True def y_input(text): self.currentItem.updatePosition(y=int(text)) self.controller.edited = True item = self.currentItem return GridLayout([ [Label("Name"), Input(text=item.name, abs_width=100, disabled=True)], [Label("X Pos"), Input(text=str(item.x), abs_width=50, max_length=4, on_input=x_input)], [Label("Y Pos"), Input(text=str(item.y), abs_width=50, max_length=4, on_input=y_input)], [Label("Width"), Input(text=str(item.x2-item.x), abs_width=50, max_length=4, disabled=True)], [Label("Height"), Input(text=str(item.y2-item.y), abs_width=50, max_length=4, disabled=True)] ], padding=18) def lineLayout(self): item = self.currentItem def x1_input(text): item.updatePosition(x1=int(text)) self.controller.edited = True def y1_input(text): item.updatePosition(y1=int(text)) self.controller.edited = True def x2_input(text): item.updatePosition(x2=int(text)) self.controller.edited = True def y2_input(text): item.updatePosition(y2=int(text)) self.controller.edited = True return GridLayout([ [Label("X1 Pos"), Input("x1_pos", str(item.x1), abs_width=50, max_length=5)], [Label("Y1 Pos"), Input("y1_pos", str(item.y1), abs_width=50, max_length=5)], [Label("X2 Pos"), Input("x2_pos", str(item.x2), abs_width=50, max_length=5)], [Label("Y2 Pos"), Input("y2_pos", str(item.y2), abs_width=50, max_length=5)] ], padding=18)
Markdown
UTF-8
1,190
3.140625
3
[ "MIT" ]
permissive
# Chapter5 传输层 --- 考试说明 - TCP拥塞控制、TCP连接的建立与释放、TCP与UDP的对比、TCP数据段格式等是考试的重点 - TCP拥塞控制常考解答题 - 本章以客观题和解答题为主,但是题型相对固定,解题思路也明显 --- ## 知识结构 本章的知识结构图如下mermaid图所示 ```mermaid graph RL a(传输层) --> b1(传输层的功能) a --> b2(传输层的两种服务) b2 --> c1(可靠服务) b2 --> c2(不可靠服务) a --> b3(传输层的端口) b3 --> c3(端口的作用) b3 --> c4(端口的分类) b3 --> c5(套接字) a --> b4(UDP) b4 --> c6(UDP概述) b4 --> c7(UDP的部首格式) b4 --> c8(UDP校验) a --> b5(TCP) b5 --> c9(TCP概述) b5 --> c10(TCP报文段) b5 --> c11(建立TCP连接) b5 --> c12(释放TCP连接) a --> b6(TCP可靠传输和流量控制) b6 --> c13(面向字节的序号) b6 --> c14(确认机制) b6 --> c15(超时机制和自动重传机制) b6 --> c16(TCP流量控制的具体实现) b6 --> c17(TC可靠通信的具体实现) c17 --> d1(慢开始算法) c17 --> d2(拥塞避免算法) c17 --> d3(快重传算法) c17 --> d4(快恢复算法) ```
Python
UTF-8
516
3.5
4
[]
no_license
from typing import List def findAll(string: str, target: str) -> List[int]: """找到所有匹配的字符串起始位置""" start = 0 res = [] while True: pos = string.find(target, start) if pos == -1: break else: res.append(pos) start = pos + 1 return res if __name__ == '__main__': print(findAll('abcdefgabcabc', 'abc')) # https://www.quora.com/What-is-the-time-complexity-of-std-string-find-in-C++
Markdown
UTF-8
1,241
3.09375
3
[]
no_license
# ScraperSite A web app that lets users view and leave comments on the latest news. With the use of: express express-handlebars mongoose body-parser cheerio request to build a site where users can scrape articles from the New York Times. Then save articles of interest and add/delete notes on the articles. on first load of the site the user is present with ![alt text](screenshots/intl.png "intial launch for user. Will not see again once Db has scraped articles") from here the user can scrape articles that are displayed on the home route ![alt text](screenshots/articles.png "articles are listed below for user to look through and save.") once saved, the user can go to the saved articles tab and view all the articles they have saved. Articles can also be deleted from here. ![alt text](screenshots/saved.png "articles are listed below for user to look through their saved articles.") the user also has the ability to add notes to their saved articles ![alt text](screenshots/notes.png "articles are given a notes modal to add/delete notes.") lastly, the user can delete a note if they no longer want to save that info to the article ![alt text](screenshots/delete.jpg "click red 'x' ")
Java
UTF-8
869
2.203125
2
[]
no_license
package com.haier.demo.attach; import java.io.IOException; import com.sun.tools.attach.AgentInitializationException; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.VirtualMachine; public class AttachMain { public static void main(String args[]) { try { attachTargetVm("5886", "/Users/tangxqa/develop/code/java/demos/haier/target/haier-1.0-SNAPSHOT.jar"); } catch (AttachNotSupportedException | IOException | AgentLoadException | AgentInitializationException e) { e.printStackTrace(); } } private static void attachTargetVm(String pid, String agentPath) throws AttachNotSupportedException, IOException, AgentLoadException, AgentInitializationException { VirtualMachine vm = VirtualMachine.attach(pid); vm.loadAgent(agentPath, null); } }
C
UTF-8
2,095
2.65625
3
[]
no_license
#include "shared.h" GLfloat cubeVertex[] = { 0.0f, 1.0f, 0.0f, //0 1.0f, 1.0f, 0.0f, //1 1.0f, 1.0f, 1.0f, //2 0.0f, 1.0f, 1.0f, //3 0.0f, 0.0f, 0.0f, //4 1.0f, 0.0f, 0.0f, //5 1.0f, 0.0f, 1.0f, //6 0.0f, 0.0f, 1.0f, //7 }; GLushort cubeIndices[] = { 0, 1, 2, 2, 3, 0, //top 4, 5, 6, 6, 7, 4, //buttom 4, 5, 1, 1, 0, 4, //front 7, 6, 2, 2, 3, 7, //back 4, 0, 3, 3, 7, 4, //left 5, 1, 2, 2, 6, 5 //right }; #define CUBE_V_COUNT (sizeof(cubeVertex) / sizeof(GLfloat)) //24 #define CUBE_I_COUNT (sizeof(cubeIndices) / sizeof(GLshort)) //36 //#define OLD_GEN_METHOD void GenarateCubes(uint count, GLfloat **pVertex, uint *vertexCount, GLshort **pIndices, uint *indicesCount) { GLfloat *vertex = malloc(count * sizeof(cubeVertex)); GLshort *indices = malloc(count * sizeof(cubeIndices)); *vertexCount = CUBE_V_COUNT * count; *indicesCount = CUBE_I_COUNT * count; for (int i = 0; i < count; i++) { for (int j = 0; j < CUBE_V_COUNT; j++) { GLfloat t = cubeVertex[j] / count; switch (j % 3) { case 0: //x t = t + i * (1.0f / count); t -= 0.5f; break; case 1: //y t = cubeVertex[j]; break; case 2: //z t -= 0.5f / count; break; } if (j < CUBE_V_COUNT / 2) { //Gen Top vertex[j + CUBE_V_COUNT / 2 * i] = t; } else { //buttom vertex[j + CUBE_V_COUNT / 2 * i + CUBE_V_COUNT / 2 * (count - 1)] = t; } } for (int j = 0; j < CUBE_I_COUNT; j++) { GLushort t = cubeIndices[j]; if (t >= CUBE_V_COUNT / 3 / 2) { t += CUBE_V_COUNT / 3 / 2 * (count - 1); } indices[i * CUBE_I_COUNT + j] = t + CUBE_V_COUNT / 3 / 2 * i; } } *pVertex = vertex; *pIndices = indices; }
Ruby
UTF-8
1,988
4.03125
4
[]
no_license
# Read a varint128 from a deobfuscated hex string value. # Basically just keep reading bytes until one of them is less than 128 (so the 8th bit wouldn't be set). def varint128_read(value, offset=0, verbose=false) # use offset to start reading from a number of characters in from the string if verbose puts value # display the starting value we have been given end # read varint128 data = '' # build up a string of bytes from the hex string value we have been given offset = offset || 0 # keep track of our place as we read through the hex string # keep reading bytes until one of them doesn't have the 8th bit set. e.g. # b98276a2ec7700cbc2986ff9aed6825920aece14aa6f5382ca5580 # b9 = 10111001 XOR 10000000 (0x80) (128) # 82 = 10000010 XOR 10000000 # 76 = 1110110 XOR 10000000 <- 8th bit has not been set # # Basically just keep reading bytes until one of them is less than 128 (so the 8th bit wouldn't be set) loop do # split value in to bytes (2 hexadecimal characters) byte = value[offset..offset+1] binary = byte.to_i(16).to_s(2) # convert byte to a binary string (for debugging) check = byte.to_i(16) & 0b10000000 # check that the 8th bit is set by using bitwise AND 10000000 (0x80) # print results if verbose puts "#{byte} #{binary.rjust(8, " ")} AND (#{byte.to_i(16)})" puts " #{check.to_s(2).rjust(8, " ")} #{0b10000000.to_s(2)}" end # append this byte to the result data += byte # return the hexadecimal string of bytes and stop looking for more if the 8th bit isn't set for the current byte return data if check == 0 # move on to the next byte offset += 2 end end # Test # puts varint128_read("c49132a52f00700b18f2629ea0dc9514a09bd633dc0b47b8d180", 0, true) # c49132 # puts varint128_read("969460a7cf820700d957c2536c205e2483b635ce17b2e02036788d54", 0, true) # 969460 # puts varint128_read("c0842680ed5900a38f35518de4487c108e3810e6794fb68b189d8b", 0, true) # c08426
C#
UTF-8
2,510
3.453125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace 事件__订阅者方法超时的处理 { class Program { static void Main(string[] args) { Publisher pub = new Publisher(); Subscriber1 sub1 = new Subscriber1(); Subscriber2 sub2 = new Subscriber2(); Subscriber3 sub3 = new Subscriber3(); pub.MyEvent += new EventHandler(sub1.OnEvent); pub.MyEvent += new EventHandler(sub2.OnEvent); pub.MyEvent += new EventHandler(sub3.OnEvent); pub.DoSomething(); // 触发事件 Console.WriteLine("Control back to client!\n"); // 返回控制权 Console.WriteLine("Press any thing to exit..."); Console.ReadKey(); // 暂停客户程序,提供时间供订阅者完成方法 } // 触发某个事件,以列表形式返回所有方法的返回值 } public class Publisher { public event EventHandler MyEvent; public void DoSomething() { // 做某些其他的事情 Console.WriteLine("DoSomething invoked!"); if (MyEvent != null) { Delegate[] delArray = MyEvent.GetInvocationList(); foreach (Delegate del in delArray) { EventHandler method = (EventHandler)del; method.BeginInvoke(null, EventArgs.Empty, null, null); } } } } public class Subscriber1 { public void OnEvent(object sender, EventArgs e) { Thread.Sleep(TimeSpan.FromSeconds(3)); // 模拟耗时三秒才能完成方法 Console.WriteLine("Waited for 3 seconds, subscriber1 invoked!"); } } public class Subscriber2 { public void OnEvent(object sender, EventArgs e) { throw new Exception("Subsciber2 Failed"); // 即使抛出异常也不会影响到客户端 //Console.WriteLine("Subscriber2 immediately Invoked!"); } } public class Subscriber3 { public void OnEvent(object sender, EventArgs e) { Thread.Sleep(TimeSpan.FromSeconds(2)); // 模拟耗时两秒才能完成方法 Console.WriteLine("Waited for 2 seconds, subscriber3 invoked!"); } } }
C++
UTF-8
1,359
3.234375
3
[ "BSD-3-Clause" ]
permissive
/* * buffer.h * * Created on: Jun 9, 2020 * Author: Marcel Flottmann */ #ifndef BUFFER_H_ #define BUFFER_H_ #include <stddef.h> #include <stdint.h> namespace trail_detection { /** * Represents a buffer in memory that can be accessed by the hardware through the physical address */ class Buffer { private: /// size of buffer size_t size; /// physical address uint32_t physical_addr; /// virtual address void *virtual_addr; /** * Allocates buffer */ void allocate(); /** * Frees buffer */ void free(); public: /** * Create new Buffer of specified size * @param size */ Buffer(size_t size); /// destructor ~Buffer(); /// no copy constructor Buffer(const Buffer &) = delete; /// no assignment Buffer &operator=(const Buffer &) = delete; /** * Invalidate the cache so that the software can see the changes from the hardware. */ void invalidate(); /** * Flush the cache so that the hardware can see the changes from the software. */ void flush(); /** * Get virtual address of buffer * @return */ inline void *getVirtual() { return virtual_addr; } /** * Get physical address of buffer * @return address */ inline uint32_t getPhysical() const { return physical_addr; } }; } // end namespace trail_detection #endif /* BUFFER_H_ */
Java
UTF-8
836
3.28125
3
[]
no_license
import java.util.*; public class pattern16{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int sp = 2*n - 3; int st = 1; for(int i = 1;i<=n;i++){ int val = 1; for(int j = 1;j<=st;j++){ System.out.print(val + "\t"); val++; } for(int j = 1;j<=sp;j++){ System.out.print("\t"); } if(i == n){ st--; val--; } for(int j = 1;j<=st;j++){ val--; System.out.print(val + "\t"); } st++; sp-=2; System.out.println(); } } } /* input = 5; output : 1 1 1 2 2 1 1 2 3 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 4 3 2 1 */
C++
UTF-8
309
2.546875
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; cin>>n; while(n!=-1){ int j=0,x,y,total=0; for(int i=0;i<n;i++){ cin>>x>>y; total+=(y-j)*x; j=y; } cout<<total<<" miles"<<endl; cin>>n; } return 0; }
Java
UTF-8
224
1.984375
2
[]
no_license
package com.corgi.example.exception; public class QuerySyntaxException extends RuntimeException { public QuerySyntaxException() { } public QuerySyntaxException(Throwable cause) { super(cause); } }
Python
UTF-8
1,990
3.109375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import re import time import reg_titanic from reg_titanic import Surviving external_stylesheets = ['https://github.com/plotly/dash-app-stylesheets/blob/master/dash-uber-ride-demo.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([html.H1(children="Please input your name age sex and class(1,2,3)", id = "teext", style= {'vertical-align': 'middle', 'width': '49%', 'display': 'inline-block'}), dcc.Input( id="input", type= "text" ), # html.Button(id='submit-button', # type='submit', # children='Submit'), html.H1(id="result") ]) @app.callback(Output('result', 'children'), [Input('input', 'value')] ) def surv(input_value): pattern_num = r"\d+" pattern_name = r"[A-Z][a-z]+" pattern_sex = r"male|female" name = re.findall(pattern_name, str(input_value))[0] age = int(re.findall(pattern_num, str(input_value))[0]) sex= re.findall(pattern_sex, str(input_value))[0] class_p = int(re.findall(pattern_num, str(input_value))[1]) time.sleep(4) print(name,sex,age,class_p) survivor=Surviving(age, sex, int(class_p)) will_survive= int(survivor.will_survive()) print(will_survive) if will_survive==1: return f"Dear {name}, according to our estimations you will probably survive in titanic" else: return f"Dear {name}, according to our estimations you will probably not survive in titanic :(((((((" if __name__ == '__main__': app.run_server(debug=False)
Markdown
UTF-8
4,023
2.59375
3
[]
no_license
### [2014-03-22](/news/2014/03/22/index.md) # Post-civil war violence in Libya: The Libyan National Army fights with rebels occupying oil ports near Benghazi. ### Source: 1. [Reuters](http://www.reuters.com/article/2014/03/22/us-libya-oil-fighting-idUSBREA2L06020140322) ### Related: 1. [Post-civil war violence in Libya:: Nine people are killed in clashes between the Libyan Army and militias in the city of Benghazi. ](/news/2013/11/25/post-civil-war-violence-in-libya-nine-people-are-killed-in-clashes-between-the-libyan-army-and-militias-in-the-city-of-benghazi.md) _Context: Benghazi, Libyan National Army, Post-civil war violence in Libya_ 2. [Libyan Civil War (2014-present): Forces of the Libyan National Army claim to have captured one of the last remaining strongholds of Benghazi from Ansar al-Sharia. ](/news/2017/01/26/libyan-civil-war-2014-present-forces-of-the-libyan-national-army-claim-to-have-captured-one-of-the-last-remaining-strongholds-of-bengha.md) _Context: Benghazi, Libyan National Army_ 3. [Libyan Civil War (2014-present): Seven Libyan National Army soldiers are killed fighting ISIL militants in Benghazi. ](/news/2016/02/26/libyan-civil-war-2014-present-seven-libyan-national-army-soldiers-are-killed-fighting-isil-militants-in-benghazi.md) _Context: Benghazi, Libyan National Army_ 4. [Libyan Civil War (2014-present): Senior Libyan military officials say French special forces are on the ground in Benghazi helping Libyan National Army troops fight ISIL militants. They said that the French forces, along with American and British teams, are setting up an operations room inside Benina International Airport in Benina. The French defense ministry declined to comment, citing a policy not to comment on special forces' activities. ](/news/2016/02/24/libyan-civil-war-2014-present-senior-libyan-military-officials-say-french-special-forces-are-on-the-ground-in-benghazi-helping-libyan-n.md) _Context: Benghazi, Libyan National Army_ 5. [Libyan Civil War (2014-present): The Libyan National Army says it has taken control of the town of Ajdabiya and several areas of Benghazi following heavy clashes with Islamist militant groups. ](/news/2016/02/21/libyan-civil-war-2014-present-the-libyan-national-army-says-it-has-taken-control-of-the-town-of-ajdabiya-and-several-areas-of-benghazi.md) _Context: Benghazi, Libyan National Army_ 6. [Post-civil war violence in Libya: Islamist militias capture a special forces base in Benghazi. ](/news/2014/07/30/post-civil-war-violence-in-libya-islamist-militias-capture-a-special-forces-base-in-benghazi.md) _Context: Benghazi, Post-civil war violence in Libya_ 7. [Post-civil war violence in Libya:: Intense fighting in Benghazi between the Libyan Army and local Islamist militias leaves 38 dead, mostly soldiers. ](/news/2014/07/27/post-civil-war-violence-in-libya-intense-fighting-in-benghazi-between-the-libyan-army-and-local-islamist-militias-leaves-38-dead-mostly-s.md) _Context: Benghazi, Post-civil war violence in Libya_ 8. [Post-civil war violence in Libya:: At least 12 people are injured in a grenade attack on a school in Benghazi. ](/news/2014/02/5/post-civil-war-violence-in-libya-at-least-12-people-are-injured-in-a-grenade-attack-on-a-school-in-benghazi.md) _Context: Benghazi, Post-civil war violence in Libya_ 9. [Post-civil war violence in Libya: Libyan police found the bodies of seven Egyptian Christians shot dead execution-style on a beach near the city of Benghazi. ](/news/2014/02/24/post-civil-war-violence-in-libya-libyan-police-found-the-bodies-of-seven-egyptian-christians-shot-dead-execution-style-on-a-beach-near-the.md) _Context: Benghazi, Post-civil war violence in Libya_ 10. [Post-civil war violence in Libya:: Unidentified gunmen shoot and kill a U.S. teacher at an international school in Benghazi, Libya. ](/news/2013/12/5/post-civil-war-violence-in-libya-unidentified-gunmen-shoot-and-kill-a-u-s-teacher-at-an-international-school-in-benghazi-libya.md) _Context: Benghazi, Post-civil war violence in Libya_
C++
UTF-8
2,473
3.140625
3
[]
no_license
/* * ===================================================================================== * * Filename: Euler55.cpp * * Description: Solution to Project Euler, Problem 55 * * Version: 1.0 * Created: 9/2/2016 12:38:37 AM * Revision: none * Compiler: g++ * * Author: Andrew Epstein * Problem: If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. * Not all numbers produce palindromes so quickly. For example, * 349 + 943 = 1292, * 1292 + 2921 = 4213 * 4213 + 3124 = 7337 * That is, 349 took three iterations to arrive at a palindrome. * Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. * A number that never forms a palindrome through the reverse and add process is called a Lychrel number. * Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. * In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, * (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. * In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: * 4668731596684224866951378664 (53 iterations, 28-digits). * Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. * How many Lychrel numbers are there below ten-thousand? * Answer: 249 * ===================================================================================== */ #include "../helper.hpp" namespace euler55 { mpz_class reverseDecimal( mpz_class x ) { mpz_class result = 0; while( x != 0 ) { result *= 10; result += x % 10; x /= 10; } return result; } } // namespace euler55 int solve55() { int result = 10000; for( int i = 0; i < 10000; ++i ) { mpz_class num = i; for( int j = 0; j < 50; ++j ) { num += euler55::reverseDecimal( num ); if( num == euler55::reverseDecimal( num ) ) { result--; break; } } } return result; }
JavaScript
UTF-8
7,005
3.3125
3
[]
no_license
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); class Grid { constructor(width, height) { this.scale = 5; this.cellWidth = width / this.scale; this.cellHeight = height / this.scale; this.space = []; this.changed = []; this.generation = 0; this.init(); } init() { for (let i = 0; i < this.cellHeight; i++) { this.space.push([]); for (let j = 0; j < this.cellWidth; j++) { this.space[i].push(0); } } this.updateChanged(); } changeScale(newScale) { console.log(newScale); this.scale = +newScale; this.cellWidth = canvas.width / this.scale; this.cellHeight = canvas.height / this.scale; this.init(); this.clear(); } draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = 'black'; ctx.strokeRect(0, 0, canvas.width, canvas.height); let x = 0, y = 0; this.space.forEach((row, i) => { row.forEach((item, j) => { if (item === 0) { ctx.strokeStyle = 'silver'; ctx.strokeRect(x, y, this.scale, this.scale); } if (item === 1) { ctx.fillStyle = 'green'; ctx.fillRect(x, y, this.scale - 1, this.scale - 1); } x += this.scale; }); x = 0; y += this.scale; }); document.getElementById('gen').innerHTML = this.generation; } findNeighbors(item, rowIndex, cellIndex) { let row = rowIndex; let cell = cellIndex; let neighbors = []; for (let i = row - 1; i <= row + 1; i++) { for (let j = cell - 1; j <= cell + 1; j++) { if (i !== rowIndex || j !== cellIndex) { let x = i; let y = j; if (x < 0) x = this.space.length - 1; if (x > this.space.length - 1) x = 0; if (y < 0) y = this.space[0].length - 1; if (y > this.space[0].length - 1) y = 0; if (this.space[x][y] === 1) { neighbors.push(this.space[x][y]); } } } } return neighbors; } turn() { let neighbors = []; this.space.forEach((row, rowIndex) => { row.forEach((item, cellIndex) => { neighbors = this.findNeighbors(item, rowIndex, cellIndex); if (this.space[rowIndex][cellIndex] === 1 && neighbors.length < 2) { this.changed[rowIndex][cellIndex] = 0; } if (this.space[rowIndex][cellIndex] === 1 && neighbors.length > 3) { this.changed[rowIndex][cellIndex] = 0; } if (this.space[rowIndex][cellIndex] === 0 && neighbors.length == 3) { this.changed[rowIndex][cellIndex] = 1; } }); }); this.space = this.changed.slice().map(function (row) { return row.slice(); }); this.generation++; this.draw(); } random() { this.clear(); this.generation = 0; this.space.forEach((row, rowIndex) => { row.forEach((item, cellIndex) => { if (Math.random() > 0.7) { this.space[rowIndex][cellIndex] = 1; } }); }); this.updateChanged(); this.draw(); } createLifeCell(rowIndex, cellIndex) { if (this.space[rowIndex][cellIndex] == 0) { this.space[rowIndex][cellIndex] = 1; } else this.space[rowIndex][cellIndex] = 0; this.updateChanged(); this.draw(); } clear() { this.space.forEach((row, rowIndex) => { row.forEach((cell, cellIndex) => { this.space[rowIndex][cellIndex] = 0; }); }); this.changed = this.space.slice().map(function (row) { return row.slice(); }); this.generation = 0; this.draw(); } createFigure(str) { switch (str) { case 'glider': this.clear(); this.space[10][10] = 1; this.space[10][11] = 1; this.space[10][12] = 1; this.space[9][12] = 1; this.space[8][11] = 1; break case 'small exploder': this.clear(); this.space[15][27] = 1; this.space[15][28] = 1; this.space[15][29] = 1; this.space[14][28] = 1; this.space[16][27] = 1; this.space[16][29] = 1; this.space[17][28] = 1; break case 'exploder': this.clear(); this.space[15][27] = 1; this.space[16][27] = 1; this.space[17][27] = 1; this.space[18][27] = 1; this.space[19][27] = 1; this.space[15][31] = 1; this.space[16][31] = 1; this.space[17][31] = 1; this.space[18][31] = 1; this.space[19][31] = 1; this.space[15][29] = 1; this.space[19][29] = 1; break case 'cellrow': this.clear(); this.space[18][28] = 1; this.space[18][29] = 1; this.space[18][30] = 1; this.space[18][31] = 1; this.space[18][32] = 1; this.space[18][33] = 1; this.space[18][34] = 1; this.space[18][35] = 1; this.space[18][36] = 1; this.space[18][37] = 1; break case 'spaceship': this.clear(); this.space[18][30] = 1; this.space[18][31] = 1; this.space[18][32] = 1; this.space[18][33] = 1; this.space[19][29] = 1; this.space[21][29] = 1; this.space[21][32] = 1; this.space[19][33] = 1; this.space[20][33] = 1; break default: break } this.updateChanged(); this.draw(); } updateChanged() { this.changed = this.space.map((row)=> { return row.slice(); }); } } let grid = new Grid(canvas.width, canvas.height); grid.draw(); let pause = true; let globalId; const cont = document.getElementById('container'); cont.onclick = function (event) { let target = event.target; if (target.id === 'start' && pause === true) { pause = false; function repeat() { grid.turn(); globalId = requestAnimationFrame(repeat); } requestAnimationFrame(repeat); } if (target.id === 'stop' && pause === false) { cancelAnimationFrame(globalId); pause = true; } if (target.id === 'random' && pause === true) { grid.random(); } if (target.id === 'clear' && pause === true) { grid.clear(); } } function clickOnCell(event) { console.log(event.clientX, event.clientY); if (event.clientX !== undefined || event.clientY !== undefined) { let x = Math.floor((event.clientY - 10) / grid.scale); let y = Math.floor((event.clientX - 10) / grid.scale); grid.createLifeCell(x, y); } } canvas.addEventListener('click', clickOnCell); const sel = document.getElementById('sel'); sel.addEventListener('change', clickOnSel); function clickOnSel(event) { let target = event.target; console.log(target.options[target.selectedIndex].value); grid.createFigure(target.options[target.selectedIndex].value); } const size = document.getElementById('size'); size.addEventListener('change', (e)=> { grid.changeScale(e.target.options[e.target.selectedIndex].value); })
TypeScript
UTF-8
3,198
2.59375
3
[ "MIT" ]
permissive
'use strict'; import jwt = require('jsonwebtoken'); import _ = require('lodash'); /** * Create a new Policy * * @constructor * @param {object} options - ... * @param {string} [options.url] - Policy URL * @param {string} [options.method] - HTTP Method * @param {object} [options.queryFilter] - Request query filter allowances * @param {object} [options.postFilter] - Request post filter allowances * @param {boolean} [options.allowed] - Allow the policy */ class Policy { constructor(public options) { options = options || {}; this.url = options.url; this.method = options.method || 'GET'; this.queryFilter = options.queryFilter || {}; this.postFilter = options.postFilter || {}; this.allow = options.allow || true; } _.extend(Policy.prototype, { payload: function() { return { url: this.url, method: this.method, query_filter: this.queryFilter, post_filter: this.postFilter, allow: this.allow }; } }); /** * @constructor * @param {object} options - ... * @param {string} options.accountSid - account sid * @param {string} options.authToken - auth token * @param {string} options.workspaceSid - workspace sid * @param {string} options.channelId - taskrouter channel id * @param {string} [options.friendlyName] - friendly name for the jwt * @param {number} [options.ttl] - time to live * @param {string} [options.version] - taskrouter version */ class TaskRouterCapability { constructor(public options) { if (_.isUndefined(options)) { throw new Error('Required parameter "options" missing.'); } if (_.isUndefined(options.accountSid)) { throw new Error('Required parameter "options.accountSid" missing.'); } if (_.isUndefined(options.authToken)) { throw new Error('Required parameter "options.authToken" missing.'); } if (_.isUndefined(options.workspaceSid)) { throw new Error('Required parameter "options.workspaceSid" missing.'); } if (_.isUndefined(options.channelId)) { throw new Error('Required parameter "options.channelId" missing.'); } this.accountSid = options.accountSid; this.authToken = options.authToken; this.workspaceSid = options.workspaceSid; this.channelId = options.channelId; this.friendlyName = options.friendlyName; this.ttl = options.ttl || 3600; this.version = options.version || 'v1'; this.policies = []; } static Policy = Policy; _.extend(TaskRouterCapability.prototype, { addPolicy: function(policy) { this.policies.push(policy); }, toJwt: function() { var payload = { iss: this.accountSid, exp: (Math.floor(new Date() / 1000)) + this.ttl, version: this.version, friendly_name: this.friendlyName, account_sid: this.accountSid, channel: this.channelId, workspace_sid: this.workspaceSid, policies: _.map(this.policies, function(policy) { return policy.payload(); }) }; if (_.startsWith(this.channelId, 'WK')) { payload.worker_sid = this.channelId; } else if (_.startsWith(this.channelId, 'WQ')) { payload.taskqueue_sid = this.channelId; } return jwt.sign(payload, this.authToken); } }); } export = TaskRouterCapability;
SQL
UTF-8
2,225
4.53125
5
[]
no_license
-- List following details of employees: employee number, last name, first name, sex, and salary SELECT employees.emp_no, employees.last_name, employees.first_name, employees.sex, salaries.salary FROM employees JOIN salaries ON employees.emp_no = salaries.emp_no; --List FN, LN, and Hire date for employees hired in 1986 SELECT employees.first_name, employees.last_name, employees.hire_date FROM employees WHERE hire_date BETWEEN '1986-01-01' AND '1986-12-31'; --List manager of each dept with: dept_no, dept_name, emp_no, LN, FN SELECT departments.dept_no, departments.dept_name, dept_man.emp_no, employees.last_name, employees.first_name FROM departments INNER JOIN dept_man ON dept_man.dept_no = departments.dept_no INNER JOIN employees ON dept_man.emp_no = employees.emp_no; --List dept of each emp with: emp_no, LN, FN, dept_name SELECT dept_emp.emp_no, employees.last_name, employees.first_name, departments.dept_name FROM dept_emp JOIN employees ON dept_emp.emp_no = employees.emp_no JOIN departments ON departments.dept_no = dept_emp.dept_no; --List FN, LN, and sex for employees whose first name is "Hercules" and last name begins with B SELECT employees.first_name, employees.last_name, employees.sex FROM employees WHERE first_name = 'Hercules' AND last_name LIKE 'B%'; --List all employees in Sales with emp_no, LN, FN, and dept_name SELECT dept_emp.emp_no, employees.last_name, employees.first_name, departments.dept_name FROM dept_emp JOIN employees ON dept_emp.emp_no = employees.emp_no JOIN departments ON departments.dept_no = dept_emp.dept_no WHERE dept_name = 'Sales'; --List all employees in Sales and Development with emp_no, LN, FN, and dept_name SELECT dept_emp.emp_no, employees.last_name, employees.first_name, departments.dept_name FROM dept_emp JOIN employees ON dept_emp.emp_no = employees.emp_no JOIN departments ON departments.dept_no = dept_emp.dept_no WHERE dept_name = 'Sales' OR dept_name = 'Development'; --In descending order, list frequency count of employees LN SELECT last_name, COUNT(last_name) AS "last name count" FROM employees GROUP BY last_name ORDER BY "last name count" DESC; --EPILOGUE SELECT * FROM employees WHERE emp_no = '499942'
C#
UTF-8
3,229
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace Acceso { public class Conexion { private SqlConnection Conection; private const string CONNECTION_STRING = @"Data Source=DESKTOP-4EMC1D1;Initial Catalog=PrimerParcialLug;Integrated Security=True"; #region Abrir y Cerrar Conexion public bool OpenConexion() { if (Conection != null && Conection.State == System.Data.ConnectionState.Open) { return true; } try { Conection = new SqlConnection(); Conection.ConnectionString = CONNECTION_STRING; Conection.Open(); return true; } catch (SqlException) { return false; } } public void ClosedConexion() { Conection.Close(); Conection.Dispose(); GC.Collect(); } #endregion public bool CrearComando(string ProcedAlmacenado, List<IDbDataParameter> parametros = null) { using (var Comando = new SqlCommand(ProcedAlmacenado, Conection)) { Comando.CommandType = System.Data.CommandType.StoredProcedure; Comando.Parameters.AddRange(parametros.ToArray());//añado todos los parametros Comando.ExecuteNonQuery(); } return true; } public DataTable LeerBaseDeDatos(string procAlmacenado) { DataTable tabla = new DataTable(); SqlDataAdapter DA = new SqlDataAdapter(); DA.SelectCommand = new SqlCommand(procAlmacenado, Conection); //Le paso el procAlmacenado y la conexion al comando DA.Fill(tabla); //Ejecuto comando y le paso la tabla para rellenar return tabla; }//Leo todos los elementos public DataTable LeerBaseDeDatos(string procAlmacenado, int id) { DataTable tabla = new DataTable(); SqlCommand comando = new SqlCommand(procAlmacenado, Conection); comando.CommandType = System.Data.CommandType.StoredProcedure; comando.Parameters.AddWithValue("@id", id); SqlDataAdapter DA = new SqlDataAdapter(); DA.SelectCommand = comando; //Le paso el procAlmacenado y la conexion al comando DA.Fill(tabla); //Ejecuto comando y le paso la tabla para rellenar return tabla; }//Leo los elementos con cierto ID #region Creo Parametros public IDbDataParameter CrearParametro(string nom, string valor) { SqlParameter parametro = new SqlParameter(nom, valor); parametro.DbType = DbType.String; return parametro; } public IDbDataParameter CrearParametro(string nom, int valor) { SqlParameter parametro = new SqlParameter(nom, valor); parametro.DbType = DbType.Int32; return parametro; } #endregion } }
C#
UTF-8
6,940
2.5625
3
[]
no_license
//----------------------------------------------------------------------- // <copyright file="SystemText.cs"> // Copyright (c) Erik Bunnstad. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Chaos.Wedding.Models.Games { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.Common; using System.Linq; using System.Threading.Tasks; using Chaos.Movies.Model; using Chaos.Movies.Model.Base; using Chaos.Movies.Model.Exceptions; /// <inheritdoc cref="Readable{T, TDto}" /> /// <summary>A subject of a <see cref="Challenge"/> or <see cref="Question"/>.</summary> public sealed class SystemText : Typeable<SystemText, Contract.SystemText> { /// <summary>The database column for <see cref="TextKey"/>.</summary> private const string TextKeyColumn = "TextKey"; /// <summary>Prevents a default instance of the <see cref="SystemText"/> class from being created.</summary> private SystemText() { this.SchemaName = "game"; } /// <summary>Gets a reference to simulate static methods.</summary> public static SystemText Static { get; } = new SystemText(); /// <summary>Gets the image of the <see cref="Game"/>.</summary> public string TextKey { get; private set; } /// <summary>Gets the titles of the <see cref="SystemText"/>.</summary> public LanguageDescriptionCollection Titles { get; } = new LanguageDescriptionCollection(); /// <inheritdoc /> public override Contract.SystemText ToContract() { return new Contract.SystemText { Id = this.Id, TextKey = this.TextKey, Titles = this.Titles.ToContract() }; } /// <inheritdoc /> public override Contract.SystemText ToContract(string languageName) { return new Contract.SystemText { Id = this.Id, TextKey = this.TextKey, Titles = this.Titles.ToContract(languageName) }; } /// <inheritdoc /> public override SystemText FromContract(Contract.SystemText contract) { // ReSharper disable once ExceptionNotDocumented throw new NotSupportedException(); } /// <inheritdoc /> /// <exception cref="InvalidSaveCandidateException">The <see cref="SystemText"/> is not valid to be saved.</exception> public override void ValidateSaveCandidate() { this.Titles.ValidateSaveCandidate(); } /// <inheritdoc /> /// <exception cref="MissingColumnException">A required column is missing in the record.</exception> public override async Task<SystemText> NewFromRecordAsync(IDataRecord record) { var result = new SystemText(); await result.ReadFromRecordAsync(record); return result; } /// <inheritdoc /> /// <exception cref="MissingColumnException">A required column is missing in the record.</exception> public override Task ReadFromRecordAsync(IDataRecord record) { Persistent.ValidateRecord(record, new[] { IdColumn }); this.Id = (int)record[IdColumn]; this.TextKey = (string)record[TextKeyColumn]; return Task.CompletedTask; } /// <inheritdoc /> /// <exception cref="Exception">A delegate callback throws an exception.</exception> /// <exception cref="InvalidSaveCandidateException">The <see cref="SystemText"/> is not valid to be saved.</exception> public override async Task SaveAsync(UserSession session) { this.ValidateSaveCandidate(); await this.SaveToDatabaseAsync(this.GetSaveParameters(), this.ReadFromRecordAsync, session); } /// <inheritdoc /> /// <exception cref="PersistentObjectRequiredException">All items to get needs to be persisted.</exception> /// <exception cref="Exception">A delegate callback throws an exception.</exception> public override async Task<SystemText> GetAsync(UserSession session, int id) { return (await this.GetAsync(session, new[] { id })).First(); } /// <inheritdoc /> /// <exception cref="PersistentObjectRequiredException">All items to get needs to be persisted.</exception> /// <exception cref="Exception">A delegate callback throws an exception.</exception> public override async Task<IEnumerable<SystemText>> GetAsync(UserSession session, IEnumerable<int> idList) { return await this.GetFromDatabaseAsync(idList, this.ReadFromRecordsAsync, session); } /// <inheritdoc /> /// <exception cref="Exception">A delegate callback throws an exception.</exception> public override async Task<IEnumerable<SystemText>> GetAllAsync(UserSession session) { return await this.GetAllFromDatabaseAsync(this.ReadFromRecordsAsync, session); } /// <inheritdoc /> /// <exception cref="MissingColumnException">A required column is missing in the record.</exception> /// <exception cref="SqlResultSyncException">Two or more of the SQL results are out of sync with each other.</exception> public override async Task<IEnumerable<SystemText>> ReadFromRecordsAsync(DbDataReader reader) { var systemTexts = new List<SystemText>(); if (!reader.HasRows) { return systemTexts; } while (await reader.ReadAsync()) { systemTexts.Add(await this.NewFromRecordAsync(reader)); } if (!await reader.NextResultAsync() || !reader.HasRows) { return systemTexts; } while (await reader.ReadAsync()) { var systemText = (SystemText)this.GetFromResultsByIdInRecord(systemTexts, reader, IdColumn); systemText.Titles.Add(await LanguageDescription.Static.NewFromRecordAsync(reader)); } return systemTexts; } /// <inheritdoc /> protected override IReadOnlyDictionary<string, object> GetSaveParameters() { return new ReadOnlyDictionary<string, object>( new Dictionary<string, object> { { Persistent.ColumnToVariable(IdColumn), this.Id }, { Persistent.ColumnToVariable(TextKeyColumn), this.TextKey }, { Persistent.ColumnToVariable(LanguageTitleCollection.TitlesColumn), this.Titles.GetSaveTable } }); } } }
TypeScript
UTF-8
2,940
3
3
[]
no_license
import Helpers from "./Helpers"; import { M2 } from "./M2"; import { V2 } from "./V2"; export class M3 { public m00: number; public m01: number; public m02: number; public m10: number; public m11: number; public m12: number; public m20: number; public m21: number; public m22: number; // m00 m01 m02 // m10 m11 m12 // m11 m12 m13 public rightVector: V2; // <m00, m10> public upVector: V2; // <m01, m11> public position: V2; // <m02, m12> constructor(m2: M2) constructor(pos: V2, target: V2) constructor(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number) constructor(...args: any) { if (args[0] instanceof M2) { this.upVector = args[0].r1.add(args[0].r0.scale(-1)).unit(); this.position = args[0].r0; } else if (args[0] instanceof V2 && args[0] instanceof V2) { this.position = args[0]; this.upVector = args[1].add(args[0].scale(-1)).unit(); } else if (typeof args[0] === "number" && args.length === 9) { this.position = new V2(args[2], args[5]); this.upVector = new V2(args[1], args[4]); } else { throw new Error(); } this.m00 = this.upVector.y; this.m10 = -this.upVector.x; this.m20 = 0; this.m01 = this.upVector.x; this.m11 = this.upVector.y; this.m21 = 0; this.m02 = this.position.x; this.m12 = this.position.y; this.m22 = 1; this.rightVector = new V2(this.m00, this.m10); } translate(v2: V2): V2 { return new V2( this.m00*v2.x + this.m01*v2.y + this.m02, this.m10*v2.x + this.m11*v2.y + this.m12 ); } inverse(): M3 { return new M3( new M2(this.m11, this.m12, this.m21, this.m22).det(), new M2(this.m02, this.m01, this.m22, this.m21).det(), new M2(this.m01, this.m02, this.m11, this.m12).det(), new M2(this.m12, this.m10, this.m22, this.m20).det(), new M2(this.m00, this.m02, this.m20, this.m22).det(), new M2(this.m02, this.m00, this.m12, this.m10).det(), new M2(this.m10, this.m11, this.m20, this.m21).det(), new M2(this.m01, this.m00, this.m21, this.m20).det(), new M2(this.m00, this.m01, this.m10, this.m11).det() ); } toString(compact: boolean = false): string { if (compact) { return "M3[" + Helpers.round(this.m00) + "," + Helpers.round(this.m01) + "," + Helpers.round(this.m02) + "," + Helpers.round(this.m10) + "," + Helpers.round(this.m11) + "," + Helpers.round(this.m12) + "," + Helpers.round(this.m20) + "," + Helpers.round(this.m21) + "," + Helpers.round(this.m22) + "]"; } else { return "M3[" + Helpers.round(this.m00) + "," + Helpers.round(this.m01) + "," + Helpers.round(this.m02) + "]\n [" + Helpers.round(this.m10) + "," + Helpers.round(this.m11) + "," + Helpers.round(this.m12) + "]\n [" + this.m20 + "," + this.m21 + "," + this.m22 + "]"; } } }
Java
UTF-8
975
3.484375
3
[]
no_license
public class MultiDimen { public static void main(String[] args) { //float array with 3 rows, 2 columns float arr[][] = new float[3][2]; //double[][] barr = {{2.3,3.4},{4.6,6.5}}; arr[0][0] = 35.4f; arr[0][1] = 68.3f; arr[1][0] = 53.2f; arr[1][1] = 68.3f; arr[2][0] = (float)45.7;//Type Casting arr[2][1] = 78.3f; float total = 0, all_total = 0; System.out.println("Rows:"+ arr.length);//number of rows System.out.println("Cols:"+ arr[0].length);//number of columns for(int i=0;i<arr.length;i++)//to iterate thru rows { total = 0; System.out.print("Marks of student:"+i+" "); for(int j=0;j<arr[0].length;j++)//to iterate thru columns { System.out.print(arr[i][j]+" "); total = total + arr[i][j]; } all_total = all_total + total; System.out.println("Total marks:"+total); } System.out.println("Total of all Marks:"+all_total); } }
C++
UTF-8
4,060
3.609375
4
[]
no_license
//Design an algorithm and write code to find the first common ancester of two nodes in a binary tree. //Avoid stroing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. #include <iostream> #include <cstring> #include <vector> #include <list> #include <map> using namespace std; const int maxn = 100; int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; struct Node { int key; Node* parent; Node* lchild; Node* rchild; }; Node node[maxn]; int cnt = 0; void init() { memset(node, '\0', sizeof(node)); } //肯定是最中间的数做中点 树最矮 而这要用到递归 void create_minmal_binary_tree(int start, int end, int parent_id) { if(start > end) return; if(start == end) { node[cnt].key = a[start]; node[cnt].lchild = NULL; node[cnt].rchild = NULL; cout<<"Create node:"<<node[cnt].key<<" pos:"<<cnt<<" Parent:"<<node[parent_id].key<<endl; if(parent_id > 0) { node[cnt].parent = &node[parent_id]; if(node[parent_id].key > node[cnt].key) node[parent_id].lchild = &node[cnt]; else node[parent_id].rchild = &node[cnt]; } cnt++; return; } int mid = (start + end) / 2; int temp_key = a[mid]; int current_id = cnt; node[cnt].key = temp_key; cout<<"Create node:"<<temp_key<<" pos:"<<cnt<<" Parent:"<<node[parent_id].key<<endl; if(parent_id >= 0) { node[cnt].parent = &node[parent_id]; if(node[parent_id].key > temp_key) node[parent_id].lchild = &node[cnt]; else node[parent_id].rchild = &node[cnt]; } cnt++; create_minmal_binary_tree(start, mid - 1, current_id); create_minmal_binary_tree(mid + 1, end, current_id); } //最开始考虑,可以记录一个节点的祖先们和另一个节点的祖先们,比较留下最小的祖先 //但是本题目在数据结构中不允许额外的存储空间 Node* first_ancestor(Node *first, Node *second) { if(first == NULL || second == NULL) return NULL; map<Node*, bool> amap; while(first != NULL) { amap[first] = true; first = first->parent; } Node* res = NULL; while(second != NULL) { if(amap[second] == true) { //return second; res = second; } second = second->parent; } return res; } bool father(Node* n1, Node* n2) { if(n1 == NULL) return false; else if(n1 == n2) return true; else return father(n1->lchild, n2) || father(n1->rchild, n2); } Node* first_ancestor_1(Node* n1, Node* n2) { if(n1 == NULL || n2 == NULL) return NULL; while(n1) { if(father(n1, n2)) return n1; n1 = n1->parent; } return NULL; } void first_ancestor_2(Node* head, Node* n1, Node* n2, Node** ans) { if(head == NULL || n1 == NULL || n2 == NULL) return; if(head && father(head, n1) && father(head, n2)) { cout<<"Mutual ancestor: "<<head->key<<endl; *ans = head; first_ancestor_2(head->lchild, n1, n2, ans); first_ancestor_2(head->rchild, n1, n2, ans); } } //如果不允许额外的存储空间,那么只能一个一个试,对第一个节点的每一个祖先,都看是否是另一个节点的祖先 //如果数据结构里不允许有parent,那就只能从每一个parent开始找,看是否有这两个子孙节点。 int main() { init(); create_minmal_binary_tree(0, 8, -1); Node* a = first_ancestor(&node[6], &node[8]); if(a == NULL) { cout<<"No Ancestor!"<<endl; return 0; } cout<<"First Ancestor: "<<a->key<<endl; Node* b = first_ancestor_1(&node[6], &node[8]); if(b == NULL) { cout<<"No Ancestor!"<<endl; return 0; } cout<<"First Ancestor: "<<b->key<<endl; Node *c; first_ancestor_2(&node[0], &node[6], &node[8], &c); if(c == NULL) { cout<<"No Ancestor!"<<endl; return 0; } cout<<"First Ancestor: "<<c->key<<endl; return 0; }
Markdown
UTF-8
803
2.609375
3
[]
no_license
# reinforcement-learning-course Winter Semester 2018/2019 - Albert-Ludwigs-Universität Freiburg ## Introduction In this repository you will find different exercises for Reinforcement Learning, such as Markov Processes, Bellman Equations, Dynamic Programming or Model-free Prediction and Control. ## Glossary - Exercise 00: OpenAI Gym Tutorial - Exercise 01: Markov Decision Processes, Markov Properties and Bellman Equation - Exercise 02: Dynamic Programming - Exercise 03: Model-free Prediction (Monte-Carlo) - Exercise 04: Model-free Control (Off-Policy Monte-Carlo) and Q-Learning - Exercise 05: Q-Learning with Function Aproximation - Exercise 06: Advanced Policy Gradient Algorithms (REINFORCE) - Exercise 07: Advanced Policy Gradient Algorithms (PPO) - Exercise 08: UCB1 - Project: CartPole
C
UTF-8
619
2.609375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "diaryh.h" int main() { char name[100]; char pass[100]; printf("\n\t*************************************\n"); printf("\n\tWelcome to personal diary management system!\n"); printf("\n\t*************************************\n"); printf("Enter your name:\n"); fflush(stdin); scanf("%s",name); printf("Enter password:\n"); fflush(stdin); scanf("%s",pass); if (login(name,pass)==0) { printf("Login success\n"); ma_in(); } else { printf("Invalid password and username combination\n"); } return 0; }
Java
UTF-8
988
2.796875
3
[]
no_license
package se.liu.ida.oscth887oskth878.tddc69.project.simulation; import se.liu.ida.oscth887oskth878.tddc69.project.simulation.units.*; import se.liu.ida.oscth887oskth878.tddc69.project.util.Pointf; /** * A simple Factory for Units * * @author Oscar Thunberg (oscth887) * @author Oskar Therén (oskth878) * @version 1.0 * @since 30/09/2013 */ public class UnitFactory { public static enum UnitType { BASIC_UNIT, GOOMBA_UNIT, ADVANCED_UNIT, BASIC_FLYING } public static Unit getUnit(UnitType type, Player.Team team, Pointf pointf) { switch (type) { case BASIC_UNIT: return new BasicUnit(pointf, team); case GOOMBA_UNIT: return new GoombaUnit(pointf, team); case ADVANCED_UNIT: return new AdvancedUnit(pointf, team); case BASIC_FLYING: return new BasicFlying(pointf, team); } throw new RuntimeException(type + " is not spawnable"); } }
Java
UTF-8
13,259
2.03125
2
[ "Apache-2.0" ]
permissive
package org.folio.edge.sip2.domain.messages.requests; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static org.folio.edge.sip2.domain.messages.requests.Renew.builder; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.time.OffsetDateTime; import org.junit.jupiter.api.Test; class RenewTests { final Boolean thirdPartyAllowed = TRUE; final Boolean noBlock = TRUE; final OffsetDateTime transactionDate = OffsetDateTime.now(); final OffsetDateTime nbDueDate = transactionDate.plusDays(30); final String institutionId = "diku"; final String patronIdentifier = "1234567890"; final String patronPassword = "2112"; final String itemIdentifier = "8675309"; final String titleIdentifier = "5551212"; final String terminalPassword = "12345"; final String itemProperties = "The autographed copy"; final Boolean feeAcknowledged = TRUE; @Test void testGetThirdPartyAllowed() { final Renew r = builder().thirdPartyAllowed(thirdPartyAllowed).build(); assertEquals(thirdPartyAllowed, r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetNoBlock() { final Renew r = builder().noBlock(noBlock).build(); assertNull(r.getThirdPartyAllowed()); assertEquals(noBlock, r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetTransactionDate() { final Renew r = builder().transactionDate(transactionDate).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertEquals(transactionDate, r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetNbDueDate() { final Renew r = builder().nbDueDate(nbDueDate).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertEquals(nbDueDate, r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetInstitutionId() { final Renew r = builder().institutionId(institutionId).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertEquals(institutionId, r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetPatronIdentifier() { final Renew r = builder().patronIdentifier(patronIdentifier).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertEquals(patronIdentifier, r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetPatronPassword() { final Renew r = builder().patronPassword(patronPassword).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertEquals(patronPassword, r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetItemIdentifier() { final Renew r = builder().itemIdentifier(itemIdentifier).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertEquals(itemIdentifier, r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetTitleIdentifier() { final Renew r = builder().titleIdentifier(titleIdentifier).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertEquals(titleIdentifier, r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetTerminalPassword() { final Renew r = builder().terminalPassword(terminalPassword).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertEquals(terminalPassword, r.getTerminalPassword()); assertNull(r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetItemProperties() { final Renew r = builder().itemProperties(itemProperties).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertEquals(itemProperties, r.getItemProperties()); assertNull(r.getFeeAcknowledged()); } @Test void testGetFeeAcknowledged() { final Renew r = builder().feeAcknowledged(feeAcknowledged).build(); assertNull(r.getThirdPartyAllowed()); assertNull(r.getNoBlock()); assertNull(r.getTransactionDate()); assertNull(r.getNbDueDate()); assertNull(r.getInstitutionId()); assertNull(r.getPatronIdentifier()); assertNull(r.getPatronPassword()); assertNull(r.getItemIdentifier()); assertNull(r.getTitleIdentifier()); assertNull(r.getTerminalPassword()); assertNull(r.getItemProperties()); assertEquals(feeAcknowledged, r.getFeeAcknowledged()); } @Test void testCompleteRenew() { final Renew r = builder() .thirdPartyAllowed(thirdPartyAllowed) .noBlock(noBlock) .transactionDate(transactionDate) .nbDueDate(nbDueDate) .institutionId(institutionId) .patronIdentifier(patronIdentifier) .patronPassword(patronPassword) .itemIdentifier(itemIdentifier) .titleIdentifier(titleIdentifier) .terminalPassword(terminalPassword) .itemProperties(itemProperties) .feeAcknowledged(feeAcknowledged) .build(); assertAll("Renew", () -> assertEquals(thirdPartyAllowed, r.getThirdPartyAllowed()), () -> assertEquals(noBlock, r.getNoBlock()), () -> assertEquals(transactionDate, r.getTransactionDate()), () -> assertEquals(nbDueDate, r.getNbDueDate()), () -> assertEquals(institutionId, r.getInstitutionId()), () -> assertEquals(patronIdentifier, r.getPatronIdentifier()), () -> assertEquals(patronPassword, r.getPatronPassword()), () -> assertEquals(itemIdentifier, r.getItemIdentifier()), () -> assertEquals(titleIdentifier, r.getTitleIdentifier()), () -> assertEquals(terminalPassword, r.getTerminalPassword()), () -> assertEquals(itemProperties, r.getItemProperties()), () -> assertEquals(feeAcknowledged, r.getFeeAcknowledged()) ); } @Test void testEqualsObject() { final Renew r1 = builder() .thirdPartyAllowed(thirdPartyAllowed) .noBlock(noBlock) .transactionDate(transactionDate) .nbDueDate(nbDueDate) .institutionId(institutionId) .patronIdentifier(patronIdentifier) .patronPassword(patronPassword) .itemIdentifier(itemIdentifier) .titleIdentifier(titleIdentifier) .terminalPassword(terminalPassword) .itemProperties(itemProperties) .feeAcknowledged(feeAcknowledged) .build(); final Renew r2 = builder() .thirdPartyAllowed(thirdPartyAllowed) .noBlock(noBlock) .transactionDate(transactionDate) .nbDueDate(nbDueDate) .institutionId(institutionId) .patronIdentifier(patronIdentifier) .patronPassword(patronPassword) .itemIdentifier(itemIdentifier) .titleIdentifier(titleIdentifier) .terminalPassword(terminalPassword) .itemProperties(itemProperties) .feeAcknowledged(feeAcknowledged) .build(); assertEquals(r1, r2); } @Test void testNotEqualsObject() { final Renew r1 = builder() .thirdPartyAllowed(thirdPartyAllowed) .noBlock(noBlock) .transactionDate(transactionDate) .nbDueDate(nbDueDate) .institutionId(institutionId) .patronIdentifier(patronIdentifier) .patronPassword(patronPassword) .itemIdentifier(itemIdentifier) .titleIdentifier(titleIdentifier) .terminalPassword(terminalPassword) .itemProperties(itemProperties) .feeAcknowledged(feeAcknowledged) .build(); final Renew r2 = builder() .thirdPartyAllowed(FALSE) .noBlock(FALSE) .transactionDate(transactionDate.minusDays(100)) .nbDueDate(nbDueDate.minusDays(50)) .institutionId("xyzzy") .patronIdentifier("111111111") .patronPassword("0000000000") .itemIdentifier("222222222") .itemIdentifier("777777777") .terminalPassword("88888888") .itemProperties("Give me a book!") .feeAcknowledged(FALSE) .build(); assertNotEquals(r1, r2); } @Test void testToString() { final String expectedString = new StringBuilder() .append("Renew [thirdPartyAllowed=").append(thirdPartyAllowed) .append(", noBlock=").append(noBlock) .append(", transactionDate=").append(transactionDate) .append(", nbDueDate=").append(nbDueDate) .append(", institutionId=").append(institutionId) .append(", patronIdentifier=").append(patronIdentifier) .append(", patronPassword=").append(patronPassword) .append(", itemIdentifier=").append(itemIdentifier) .append(", titleIdentifier=").append(titleIdentifier) .append(", terminalPassword=").append(terminalPassword) .append(", itemProperties=").append(itemProperties) .append(", feeAcknowledged=").append(feeAcknowledged) .append(']').toString(); final Renew r = builder() .thirdPartyAllowed(thirdPartyAllowed) .noBlock(noBlock) .transactionDate(transactionDate) .nbDueDate(nbDueDate) .institutionId(institutionId) .patronIdentifier(patronIdentifier) .patronPassword(patronPassword) .itemIdentifier(itemIdentifier) .titleIdentifier(titleIdentifier) .terminalPassword(terminalPassword) .itemProperties(itemProperties) .feeAcknowledged(feeAcknowledged) .build(); assertEquals(expectedString, r.toString()); } }
TypeScript
UTF-8
3,119
2.9375
3
[]
no_license
import { PathLike } from 'fs' import fs from 'fs/promises' import path from 'path' type EnvConfigStruct = { srcDir: string destDir: string backupDir: string combinedLogsOutputDir: string errorLogsOutputdir: string debounceAmount: number rezAttempts: number rezCooldown: number } const defaultEnvConfig: EnvConfigStruct = { srcDir: '', destDir: '', backupDir: '', combinedLogsOutputDir: './logs/combined.log', errorLogsOutputdir: './logs/error.log', debounceAmount: 60000, rezAttempts: 3, rezCooldown: 10000, } function shouldDefault(val: number | string | undefined): boolean { if (typeof val === 'number') { return !val } else { return !val || !val.toString().length } } function getDefault(key: keyof EnvConfigStruct, val: number | string) { return shouldDefault(val) ? defaultEnvConfig[key] : val } function parseDefaults(config: EnvConfigStruct): EnvConfigStruct { return { srcDir: getDefault('srcDir', config.srcDir) as string, destDir: getDefault('destDir', config.destDir) as string, backupDir: getDefault('backupDir', config.backupDir) as string, combinedLogsOutputDir: getDefault( 'combinedLogsOutputDir', config.combinedLogsOutputDir ) as string, errorLogsOutputdir: getDefault( 'errorLogsOutputdir', config.errorLogsOutputdir ) as string, debounceAmount: getDefault('debounceAmount', 60000) as number, rezAttempts: getDefault('rezAttempts', 3) as number, rezCooldown: getDefault('rezCooldown', 10000) as number, } } class EnvConfig { private static _initialConfig: EnvConfigStruct private static _config: EnvConfigStruct static async init(): Promise<any> { return fs .readFile(path.resolve('./.config.json'), { encoding: 'utf-8', }) .then((contents) => { const config = JSON.parse(contents) as EnvConfigStruct EnvConfig._config = parseDefaults(config) if (!EnvConfig._initialConfig) { EnvConfig._initialConfig = parseDefaults(config) } }) } static get get(): EnvConfigStruct { return { ...defaultEnvConfig, ...EnvConfig._config } } private static _updateFuncs = { srcDir: (val: PathLike): void => EnvConfig._update('srcDir', val), destDir: (val: PathLike): void => EnvConfig._update('destDir', val), backupDir: (val: PathLike): void => EnvConfig._update('backupDir', val), combinedLogsOutputDir: (val: PathLike): void => EnvConfig._update('combinedLogsOutputDir', val), errorLogsOutputdir: (val: PathLike): void => EnvConfig._update('errorLogsOutputdir', val), debounceAmount: (val: number): void => EnvConfig._update('debounceAmount', val), rezAttempts: (val: number): void => EnvConfig._update('rezAttempts', val), rezCooldown: (val: number): void => EnvConfig._update('rezCooldown', val), } private static _update(key: keyof EnvConfigStruct, val: any) { EnvConfig._config = { ...EnvConfig._config, ...{ [key]: val, }, } } static update = EnvConfig._updateFuncs } export default EnvConfig
Java
UTF-8
283
2.53125
3
[]
no_license
package cognizant.date; import java.time.Clock;; public class ClockTime { public static void main(String[] args) { Clock time = Clock.systemUTC(); Clock def = Clock.systemDefaultZone(); System.out.println(time); System.out.println("Default : " + def); } }
Java
UTF-8
8,102
2.109375
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 GUI; import Controller.MateriaisController; import Utilitarios.Conexao; import Utilitarios.Corretores; import Utilitarios.LimiteDigitos; import java.io.InputStream; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.view.JasperViewer; public class GeraRelatorioMateriaisTela extends javax.swing.JInternalFrame { MateriaisController materialC; public GeraRelatorioMateriaisTela() { initComponents(); materialC = new MateriaisController(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); btnGeraRel = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); txtDataIni = new com.toedter.calendar.JDateChooser(); txtDataFim = new com.toedter.calendar.JDateChooser(); setClosable(true); setIconifiable(true); setTitle("Geração de Relatório"); jLabel1.setText("Data inicial:"); jLabel2.setText("Data final:"); btnGeraRel.setText("Gerar"); btnGeraRel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGeraRelActionPerformed(evt); } }); jLabel3.setForeground(new java.awt.Color(0, 0, 255)); jLabel3.setText("Usar como referência --> Início: 01 de cada mês"); jLabel4.setForeground(new java.awt.Color(0, 0, 255)); jLabel4.setText("Final: ultimo dia de cada mês"); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnGeraRel, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(21, 21, 21)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(26, 26, 26))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtDataIni, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE) .addComponent(txtDataFim, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(31, 31, 31) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(46, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4) .addGap(30, 30, 30)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(txtDataIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(txtDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(24, 24, 24) .addComponent(jLabel2)))) .addGap(18, 18, 18) .addComponent(btnGeraRel) .addContainerGap(40, Short.MAX_VALUE)) ); setBounds(500, 120, 316, 243); }// </editor-fold>//GEN-END:initComponents private void btnGeraRelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGeraRelActionPerformed if((txtDataIni.getDate() == null)||(txtDataFim.getDate() == null)){ JOptionPane.showMessageDialog(null, "Os campos data são obrigatórios, siga a recomendação acima.","Atenção",1); }else{ SimpleDateFormat dataFormato = new SimpleDateFormat("dd/MM/yyyy"); String dataIniFormatada = dataFormato.format(txtDataIni.getDate()); String dataFimFormatada = dataFormato.format(txtDataFim.getDate()); String dataIniSQL = Corretores.ConverterParaSQL(dataIniFormatada); String dataFimSQL = Corretores.ConverterParaSQL(dataFimFormatada); boolean confirma = materialC.verificaDataBuscaRelatorio(dataIniSQL, dataFimSQL); if(confirma == true){ dispose(); } } }//GEN-LAST:event_btnGeraRelActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnGeraRel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JSeparator jSeparator1; private com.toedter.calendar.JDateChooser txtDataFim; private com.toedter.calendar.JDateChooser txtDataIni; // End of variables declaration//GEN-END:variables }
C++
UTF-8
3,500
2.640625
3
[]
no_license
#include "AFMotor.h" #include "AFMotor.h" AF_DCMotor motor_FL(1); AF_DCMotor motor_FR(2); int Left_Follow = 0; int Right_Follow = 1; int Center_Follow = 2; int count=0; void setup() { Serial.begin(9600); motor_FL.run(RELEASE); motor_FL.setSpeed(0); motor_FR.run(RELEASE); motor_FR.setSpeed(0); int x; int y; int z; int s; } void AllForward(int x) { motor_FL.run(FORWARD); motor_FL.setSpeed(x); motor_FR.run(FORWARD); motor_FR.setSpeed(x); } void TurnRight(int y) { motor_FL.run(BACKWARD); motor_FL.setSpeed(y); motor_FR.run(FORWARD); motor_FR.setSpeed(y); } void TurnRRight(int s) { motor_FL.run(RELEASE); motor_FL.setSpeed(0); motor_FR.run(FORWARD); motor_FR.setSpeed(s); } void TurnLeft(int z) { motor_FL.run(FORWARD); motor_FL.setSpeed(z); motor_FR.run(BACKWARD); motor_FR.setSpeed(z); } void AllStop() { motor_FL.run(RELEASE); motor_FL.setSpeed(0); motor_FR.run(RELEASE); motor_FR.setSpeed(0); } void loop() { int LeftDFR = digitalRead(Left_Follow); int CenterDFR = digitalRead(Center_Follow); int RightDFR = digitalRead(Right_Follow); Serial.println(); Serial.println(); Serial.print(LeftDFR); Serial.print(CenterDFR); Serial.print(RightDFR); Serial.print(count); //For our sensor zero means it found the line!! switch (count) { case 0: { if(LeftDFR == 1 && CenterDFR == 0 && RightDFR == 1){ AllForward(175); } else if(LeftDFR == 1 && CenterDFR == 1 && RightDFR == 0){ TurnRight(125); } else if (LeftDFR == 1 && CenterDFR == 0 && RightDFR == 0){ TurnRight(125); } else if(LeftDFR == 0 && CenterDFR == 1 && RightDFR == 1){ TurnLeft(150); } else if(LeftDFR == 0 && CenterDFR == 0 && RightDFR == 1){ TurnLeft(125); } else if(LeftDFR == 0 && CenterDFR == 0 && RightDFR == 0){ AllStop(); delay(1000); TurnRRight(225); delay(800); AllForward(100); delay(150); count++; } } break; case 1: { if(LeftDFR == 1 && CenterDFR == 0 && RightDFR == 1){ AllForward(125); } if(LeftDFR == 1 && CenterDFR == 1 && RightDFR == 0){ TurnRight(125); } if(LeftDFR == 0 && CenterDFR == 1 && RightDFR == 1){ TurnLeft(125); } if(LeftDFR == 1 && CenterDFR == 0 && RightDFR == 0){ AllStop(); delay(1000); TurnRRight(220); delay(800); count++; } if(LeftDFR == 0 && CenterDFR == 0 && RightDFR == 0){ AllStop(); delay(1000); TurnRRight(220); delay(800); count++; } } break; case 2: { if(LeftDFR == 1 && CenterDFR == 0 && RightDFR == 1){ AllForward(200); } if(LeftDFR == 0 && CenterDFR == 1 && RightDFR == 1){ TurnLeft(150); } if(LeftDFR == 1 && CenterDFR == 0 && RightDFR == 0){ TurnRight(150); } if(LeftDFR == 1 && CenterDFR == 1 && RightDFR == 0){ TurnRight(150); } if(LeftDFR == 0 && CenterDFR == 0 && RightDFR == 0){ TurnLeft(225); delay(600); count++; } } break; case 3: { if(LeftDFR == 1 && CenterDFR == 0 &&RightDFR == 1){ AllForward(200); } if(LeftDFR == 1 && CenterDFR == 1 && RightDFR == 0){ TurnRight(150); } if(LeftDFR == 0 && CenterDFR == 1 && RightDFR == 1){ TurnLeft(150); } if(LeftDFR == 0 && CenterDFR == 0 && RightDFR == 0){ TurnRight(200); count=0; } } break; /*else{ motor_FL.run(RELEASE); motor_FL.setSpeed(0); motor_FR.run(RELEASE); motor_FR.setSpeed(0);*/ } }
TypeScript
UTF-8
559
2.515625
3
[]
no_license
export enum LoadingState { LOADED = 'LOADED', ERROR = 'ERROR', NEVER = 'NEVER', LOADING = 'LOADING' } export enum AddFormState { ERROR = 'ERROR', NEVER = 'NEVER', LOADING = 'LOADING' } export type TweetType = { _id:string text: string user: UserType createdAt: string, updatedAt: string } export type UserType = { fullname: string username: string avatarUrl: string } export type TweetsStateType = { items: Array<TweetType> loadingState: LoadingState, addFormState: AddFormState }
Python
UTF-8
3,022
3.015625
3
[]
no_license
import os import telebot import requests API_KEY = os.getenv('API_KEY') bot = telebot.TeleBot(API_KEY) PASSWORD = os.getenv('PASSWORD') base_url = "https://tele-bot-back-end.herokuapp.com/" @bot.message_handler(commands=['start']) def greet(message): bot.reply_to(message, '''Welcome to our bot!\nSome helpful commands:(YOU MUST TYPE THE PASSWORD AFTER EACH COMMAND) \n1)students list [To show all students names]\n2)search (student name or id) [To show a certain student detail\n3)create session (title) (YYYY-MM-DD) (HR:MIN:SEC)] ''') def get_students(message): req = message.text.split() if req[-1] != PASSWORD: return False else: if len(req) < 2 or req[0].lower() not in "students": return False else: return True @bot.message_handler(func=get_students) def reply_get_students(message): students = requests.get(f"{base_url}students/").json() msg = "" for student in students: msg += str(student['id']) + "]" + student['name'] + '\n' bot.reply_to(message, msg) def search_student(message): req = message.text.split() if req[-1] != PASSWORD: return False else: if len(req) < 2 or req[0].lower() not in "search": return False else: return True @bot.message_handler(func=search_student) def reply_search_student(message): name = "" counter = 0 msg_lst = list(message.text.split(" ")) for word in msg_lst: if counter > 0: name += word name += "%20" counter += 1 name_query = name[:-11] url = f"{base_url}students/{name_query}" student = requests.get(url).json() student_data = f"id:{student['id']}\nName: {student['name']}\nEmail: {student['email']}\nContact: {student['number']}\nTelegram id: {student['telegram_id']}" bot.reply_to(message, student_data) def create_session(message): req = message.text.split() if req[-1] != PASSWORD: return False else: if "session" not in req: bot.reply_to(message, 'Enter a valid format\nfor help type /start') return False elif len(req) < 5: bot.reply_to(message, 'Enter a valid format\nfor help type /start') return False else: return True @bot.message_handler(func=create_session) def create_new_session(message): form_data = [] counter = 0 msg_lst = list(message.text.split(" ")) for word in msg_lst: if counter > 1: form_data.append(word) counter += 1 url = f"{base_url}create/session/" data = { 'title': form_data[0], 'date': form_data[1], 'time': form_data[2] } requests.request("POST", url, data=data) bot.send_message(chat_id='-1001503615060', text=f"A new session has just created: \nTitle:{form_data[0]}\nDate:{form_data[1]}\nTime:{form_data[2]}") bot.reply_to(message, "Session scheduled successfully") bot.polling()
PHP
UTF-8
2,211
2.828125
3
[]
permissive
<?php declare(strict_types=1); namespace Laminas\Mvc\I18n; use Laminas\I18n\Translator\TranslatorInterface as I18nTranslatorInterface; use Laminas\Validator\Translator\TranslatorInterface as ValidatorTranslatorInterface; use function call_user_func_array; use function method_exists; use function sprintf; class Translator implements I18nTranslatorInterface, ValidatorTranslatorInterface { public function __construct(protected I18nTranslatorInterface $translator) { } /** * Proxy unknown method calls to underlying translator instance * * Note: this method is only implemented to keep backwards compatibility * with pre-2.3.0 code. * * @deprecated * * @param string $method * @param array $args * @return mixed */ public function __call($method, array $args) { if (! method_exists($this->translator, $method)) { throw new Exception\BadMethodCallException(sprintf( 'Unable to call method "%s"; does not exist in translator', $method )); } return call_user_func_array([$this->translator, $method], $args); } /** * @return I18nTranslatorInterface */ public function getTranslator() { return $this->translator; } /** * Translate a message using the given text domain and locale * * @param string $message * @param string $textDomain * @param string $locale * @return string */ public function translate($message, $textDomain = 'default', $locale = null) { return $this->translator->translate($message, $textDomain, $locale); } /** * Provide a pluralized translation of the given string using the given text domain and locale * * @param string $singular * @param string $plural * @param int $number * @param string $textDomain * @param string $locale * @return string */ public function translatePlural($singular, $plural, $number, $textDomain = 'default', $locale = null) { return $this->translator->translatePlural($singular, $plural, $number, $textDomain, $locale); } }
Go
UTF-8
1,477
3.171875
3
[]
no_license
package main import ( "crypto/rand" "fmt" "flag" "strings" ) var ( helpFlag = flag.Bool("h", false, "Show this help") knownPrefix = flag.String("p", "28:99:c7", "Specify the OUI (first six hex) separated by colon (:) or dash (-)") numFlag = flag.Int("n", 1, "Number of entries to generate (up to 1000)") ) const usage = "`macGenerator` [options]" func main() { flag.Parse() if *helpFlag { fmt.Println(usage) flag.PrintDefaults() return } var prefix []string if *knownPrefix != "" { prefix = strings.Split(*knownPrefix, ":") if len(prefix) < 3 { prefix = strings.Split(*knownPrefix, "-") if len(prefix) < 3 { fmt.Printf("Unknown OUI supplied: %s\n", *knownPrefix) return } } } else { prefix = []string{"", "", ""} } switch { case *numFlag < 1: return case *numFlag > 1000: return default: generateMac(prefix, *numFlag) } } // controls iterations and prints directly to stdout func generateMac(p []string, n int) { var buf []byte var hasPrefix bool if p[0] != "" { hasPrefix = true } for i := 0; i < n; i++ { buf = randomSix() if hasPrefix { fmt.Printf("%s:%s:%s:%02x:%02x:%02x\n", p[0], p[1], p[2], buf[3], buf[4], buf[5]) } else { fmt.Printf("%02x:%02x:%02x:%02x:%02x:%02x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]) } } } func randomSix() []byte { buf := make([]byte, 6) _, err := rand.Read(buf) if err != nil { fmt.Println(err) return nil } buf[0] |= 2 return buf }
C++
WINDOWS-1251
1,815
2.984375
3
[]
no_license
// 9.11.cpp: . // #include "stdafx.h" #include <string> struct List1Element { char str[100]; List1Element * next; }; List1Element * createList() { List1Element * tmp = new List1Element; tmp->str[0] = 0; tmp->next = NULL; return tmp; } void delList(List1Element *head) { List1Element *tmp = head; while (tmp) { List1Element *t = tmp->next; delete tmp; tmp = t; } } struct Hash { List1Element *h[255]; }; Hash *createHash() { Hash *tmp = new Hash; for (int i = 0; i < 255; i++) tmp->h[i] = NULL; return tmp; } void delHash(Hash *hash) { for (int i = 0; i < 255; i++) delList(hash->h[i]); delete hash; } int hFunc(char *s) { int tmp = 0; int i = 0; while (s[i++] && i < 5) tmp = (tmp + s[i]) % 255; return tmp; } void hashAdd(Hash *hash, char *s) { int index = hFunc(s); List1Element *tmp = hash->h[index]; while (tmp) { if (strcmp(s, tmp->str) == 0) return; tmp = tmp->next; } tmp = createList(); strcpy(tmp->str, s); tmp->next = hash->h[index]; hash->h[index] = tmp; } List1Element *hfind(Hash *hash, char *s) { int index = hFunc(s); List1Element *tmp = hash->h[index]; while (tmp) { if (strcmp(s, tmp->str) == 0) break; tmp = tmp->next; } return tmp; } int _tmain(int argc, _TCHAR* argv[]) { FILE * f1 = fopen("1.txt", "r"); FILE * f2 = fopen("2.txt", "r"); char line[100]; Hash *hash = createHash(); while (fgets(line, 100, f1)) hashAdd(hash, line); fclose(f1); FILE * fileOut = fopen("out.txt", "w"); printf("Add to out file:\n"); char line2[100]; while(fgets(line2, 100, f2)) if (hfind(hash, line2)) { fprintf(fileOut, "%s", line2); printf("%s", line2); } fclose(fileOut); fclose(f2); delHash(hash); return 0; }
C++
UTF-8
931
2.703125
3
[ "MIT" ]
permissive
// // BaseScrollHandle.h // ofxMUI_scrollbars // // Created by Roy Macdonald on 2/9/20. // #pragma once #include "ofEvents.h" namespace ofx { namespace MUI { template <typename DataType> class BaseScrollHandle{ public: virtual ~BaseScrollHandle(){} ofEvent<DataType> handleChangeEvent; ///\brief sets the handleValue to the passed argument. Will notify handleChangeEvent if passed value is different to handleValue ///returns true if value passed value was different, false otherwise /// possible implementation: /// if(handleValue != val){ /// handleValue = val; /// ofNotifyEvent(handleChangeEvent, handleValue, this); /// return true; /// } /// return false; virtual bool setValue(const DataType& val ) = 0; const DataType& getValue() const { return handleValue; } ///\brief will move the handle bool addToValue(float amt); protected: DataType handleValue; }; } } // ofx::MUI
Markdown
UTF-8
875
2.5625
3
[]
no_license
# CSE557_a4 https://mayhoo.github.io/CSE557_a4/a4.html ![](https://raw.githubusercontent.com/MayHoo/CSE557_a4/master/a4.PNG) √ 2 pts: When unzipped, project runs without errors or modifications on our part. √ 30 pts: Map displays data from file, states are accurately positioned. √ 10 pts: Hovering implemented and information is displayed accurately. √ 10 pts: Legend implemented and color mapping is appropriate. √ 20 pts: Timeline implemented and cartogram updates when user selects dates. √ 10 pts: States are colored by percentage win. √ 5 pts: Visualization posted online. --Extra Points: √ 10 pts: Image added for each president. √ 20 pts: Map implemented. 10 pts: Scaling Option A: User is able to scale cartogram by electoral votes. 15 pts: Scaling Option B: User is able to map by electoral votes.
C
UTF-8
2,669
3.390625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tlouekar <tlouekar@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/07 10:48:15 by tlouekar #+# #+# */ /* Updated: 2019/12/02 09:30:12 by tlouekar ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.c" #include "get_next_line.h" #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include "libft/includes/libft.h" int main(int argc, char **argv) { int fd; char *line; int linecount; int i; int countdown; char anykey[59] = "\033[1;32m-----------------------------\nPress enter.\n\n\033[0m"; i = 1; linecount = 0; countdown = 2; printf("\n\nPrinting up to %d lines from files, swapping fd in between. I hope you remembered to enter some as arguments..\n\n", countdown + 1); printf("%s", anykey); getchar(); while (i < argc) { fd = open(argv[i], O_RDONLY); i++; } while (countdown > 0) { fd++; if (fd > argc + 1) fd = 3; while (get_next_line(fd, &line) == 1) { linecount++; ft_putstr(line); ft_putchar('\n'); free(line); printf("%s", anykey); getchar(); if (fd < argc + 1) fd++; else fd = 3; } close(fd); countdown--; } line = NULL; printf("\n\nOn the next part you should only see -1. \n\n"); printf("%s", anykey); getchar(); ft_putnbr(get_next_line(1, NULL)); ft_putnbr(get_next_line(0, NULL)); ft_putnbr(get_next_line(1000, NULL)); ft_putnbr(get_next_line(-1, NULL)); ft_putnbr(get_next_line(1000, &line)); ft_putnbr(get_next_line(-1, &line)); ft_putnbr(get_next_line(-1000, &line)); ft_putnbr(get_next_line(42, &line)); ft_putchar('\n'); printf("\n\nOk, moving on to the input. CTRL-D to exit.\n\n"); while (get_next_line(0, &line) == 1) { ft_putstr(line); ft_putchar('\n'); free(line); } printf("%s", anykey); getchar(); printf("\n\nAnd last, the basic tests.\n\n"); printf("%s", anykey); getchar(); //printf("Return value: %d, File descriptor: %d, Argc count: %d, Lines read: %d\n", returnvalue, fd, argc - 1, linecount); return (0); }
JavaScript
UTF-8
1,609
2.5625
3
[]
no_license
var inquirer = require("inquirer"); var axios = require("axios"); var fs = require("fs"); const doc = require('./doc.js') inquirer .prompt([ { type: "input", message: "What's your Github username?", name: "username" }, { type: "list", message: "What color do you prefer?", choices: ["blue", "red", "yellow", "purple", "green"], name: "color" }, ]).then(function (response) { var queryName = response.username; var queryColor = response.color; console.log(queryColor); console.log(queryName); axios .get("https://api.github.com/users/" + queryName) .then(function (res) { var info = res.data; // var profile = (queryColor, info) => { // return `# <span style= ${queryColor}>${info.name}</span> // ${info.avatar_url} // Bio:${info.bio} // User Url: ${info.url} // Repos: ${info.url} // Followers: ${info.followers} // Following: ${info.following} // Location: ${info.location} `; // } const saved = doc(info, queryColor) console.log(info); fs.writeFile(response.username+".md", saved, function(err){ if (err) {console.log(err);} else {console.log("Commit logged!");} }); }) })
PHP
UTF-8
3,310
3.0625
3
[]
no_license
<?php namespace Snowy\Helpers; /** * Class Uri * @package Snowy\Helpers */ class Uri{ /** * Текущий адрес * @var null|array */ private static $currentUrl = null; /** * Возвращает текущий адрес * @param int $flag * @return string */ public static function getCurrent($flag = URI_RETURN_PATH){ if(is_null(self::$currentUrl)){ //Собираем адрес self::$currentUrl = [ "protocol" => "", "site" => "", "path" => "", "q" => [], "port" => 80 ]; $protocol = (!empty($_SERVER['HTTPS']))?"https":"http"; $default_port = ($protocol==="https")?443:80; $port = "";//($_SERVER['SERVER_PORT'] == $default_port)?"":":".$_SERVER['SERVER_PORT']; $site = $_SERVER['HTTP_HOST']; $path = self::preparePath($_SERVER['REQUEST_URI']); $q = $_GET; self::$currentUrl['protocol'] = $protocol; self::$currentUrl['site'] = $site . $port; self::$currentUrl['path'] = $path; self::$currentUrl['q'] = $q; self::$currentUrl['port'] = $_SERVER['SERVER_PORT']; } $url = ""; if($flag&URI_RETURN_SITE) $url .= self::$currentUrl['protocol'] . "://" . self::$currentUrl['site']; if($flag&URI_RETURN_PATH) $url .= self::$currentUrl['path']; if($flag&URI_RETURN_Q) { if(count(self::$currentUrl['q']) > 0) $url .= "?"; $_ = []; foreach(self::$currentUrl['q'] as $k=>$v){ $_[] = $k . "=" . $v; } $url .= implode("&", $_); } return $url; } /** * @param string $uri * @return string */ public static function preparePath($uri){ $uri = trim(urldecode($uri), "\t\n\r\0\x0B/"); if(($qPos = mb_strpos($uri, "?")) !== false) $uri = mb_substr($uri, 0, $qPos); if(mb_strpos($uri, "/") !== 0) $uri = "/" . $uri; if(mb_strrpos($uri, "/") !== mb_strlen($uri)-1) $uri .= "/"; return $uri; } /** * @param string $path1 * @param string $path2 * @return string */ public static function concatPaths($path1, $path2){ $path = ""; $path1 = Uri::preparePath($path1); $path2 = Uri::preparePath($path2); $path = mb_substr($path1, 0, mb_strlen($path1)-1); $path .= $path2; return $path; } /** * @param string $path * @return int */ public static function getLength($path){ $path = Uri::preparePath($path); return count(explode("/", $path)); } /** * @return string */ public static function assetsLink(){ $assets = config()->get("links.assets"); $linkType = "internal"; if(preg_match("/^https?:\/\//", $assets)) $linkType = "external"; if($linkType==="internal") $assets = ((mb_strpos($assets, "/")===0)?$assets:"/".$assets); return (($linkType==="external")?$assets:(self::getCurrent(URI_RETURN_SITE) . $assets)); } } ?>
PHP
UTF-8
145
3.078125
3
[]
no_license
<html> <head> <title> PHP: Strings </title> </head> <body> <?php $string = "Hello"; $string .= " World!"; echo $string ?> </body> </html>
PHP
UTF-8
400
2.59375
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: LINH * Date: 5/23/2019 * Time: 5:53 PM */ namespace App\BusinessService; use App\Business\GetChartBL; class GetChartBS { private $getChartBL; public function __construct(GetChartBL $getChartBL) { $this->getChartBL = $getChartBL; } public function getCharts() { return $this->getChartBL->getCharts(); } }
PHP
UTF-8
357
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; use \App\Instruksi; class InstruksiSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i=1;$i<=10;$i++) { Instruksi::create(['id_workshop'=>$i,'id_pemateri'=>$i,'judul'=>"Judul ".$i,'urutan'=>$i]); } } }
Python
UTF-8
750
3.828125
4
[]
no_license
# -*- coding: utf-8 -*- cars = 100 # numbers of cars space_in_a_car = 4 # 4.0 floating point | sits per car drivers = 30 # number of drivers passengers = 90 # number of passengers cars_not_driven = cars - drivers # one driver per car cars_driven = drivers # one driver per car i = 30 carpool_capacity = cars_driven * space_in_a_car # j = 30 * 4 average_passagers_per_car = passengers / cars_driven # x = 90 / 30 print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passagers_per_car, "in each car."
Python
UTF-8
672
3.171875
3
[]
no_license
#! /usr/bin/python import random import sys def getBin(numStr): xr = "" for i in numStr: if i == '0': xr += chr(0) else: xr += chr(1) return xr i = int(sys.argv[1]) f = open("numbers",'w') x = random.randint(pow(2,i-1),pow(2,i)-1) y = random.randint(pow(2,i-1),pow(2,i)-1) xb = "{0:b}".format(x) yb = "{0:b}".format(y) x = lambda x,y: (bin(int(x,2)+int(y,2))[2:]) #f.write(getBin(xb)) f.write(xb) f.write('\n') #f.write(getBin(yb)) f.write(yb) op = open("operands",'w') op.write(xb) op.write('\n') op.write(yb) op.close() s = x(xb,yb) if s > len(xb): print s[1:] print "overflow" else: print s f.close()
Python
UTF-8
361
2.859375
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/15 14:16 # @Author : glacier # @Site : # @File : make_readable.py # @Software: PyCharm Edu import time def make_readable(seconds): tt = time.localtime(seconds) str1 = time.strftime("%H:%M:%S",tt) print(str1) # Do something make_readable(86400)
C#
UTF-8
2,210
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using LMGEDIApp.Infrastructure.ApplicationServices.Contracts; namespace LMGEDIApp.Infrastructure.Services { public class ARCommonServices : IARCommonServices { public void CreateErrorLog(string errorMessage, string Stacktrace) { try { //create errorlog folder if not exist....hp DirectoryInfo dr = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/")); if (!dr.CreateSubdirectory("ErrorLog").Exists) dr.CreateSubdirectory("ErrorLog"); string path = "~/ErrorLog/" + DateTime.Today.ToString("MM-dd-yyyy") + ".txt"; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } //HttpContext.Current.Response.Write(System.Web.HttpContext.Current.Server.MapPath(path)); using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { w.WriteLine("\r\nLog Entry : "); w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)); string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() + Environment.NewLine; err += "Error Message:" + errorMessage + Environment.NewLine; err += "Error Stacktrace:" + Stacktrace + Environment.NewLine; err += "User IP:" + System.Web.HttpContext.Current.Request.UserHostAddress.ToString(); w.WriteLine(err); w.WriteLine("_________________________________________________________"); w.Flush(); w.Close(); } } catch (Exception ex) { System.Web.HttpContext.Current.Response.Write(ex.StackTrace); } } } }
Markdown
UTF-8
2,162
3.25
3
[]
no_license
--- layout: post title: Android中移除除了首页的历史Activity date: 2018-09-10 09:18:31 +0800 author: yitimo categories: android tags: ["android", "activity stack"] keywords: - android, - round corner, - activity stack, description: Android中如何在打开新页面时清空除了首页的历史纪录,即从新页面返回时为首页 --- 对于Android中Activity栈的操作提及比较多的是在``Intent``中使用这几个``Flag``: * Intent.FLAG_ACTIVITY_CLEAR_TASK * Intent.FLAG_ACTIVITY_CLEAR_TOP * Intent.FLAG_ACTIVITY_NEW_TASK 其中一个使用情景是,当用户的登录状态过期后,需要清除历史纪录直接重定向到登录页,也就是当前打开页面为``A -> B -> C``时,发现登录已过期需要跳转到``D``,就需要: ``` val intent = Intent(Context, D) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ``` 这样跳转到``D``后整个应用只会留下``D``页面。 但是靠这几个Flag做不到一件事,就是本文标题所描述的,**如何从``A -> B -> C``想要跳转到``D``时得到``A -> D``这样的页面栈**,即在跳转到新页面时移除除了首页外的其他页面,得到从新页面返回时直接是回到首页的效果。 此需求的使用场景之一就是在购物下单流程中,用户选择完商品并下单后,原先的商品或购物车页面已经不再需要,甚至如果不清除掉这些页面,当用户从订单页返回时又会回到下单前的状态,已经完成购买的商品,数量都还留在页面里。 最终对笔者起到帮助的只有[这个链接](https://stackoverflow.com/questions/38879150/clear-activity-stack-except-first-activity)。 上面的链接让笔者最终决定使用的做法是:当从``C``跳转到``D``时,添加参数``putExtra("clear_top", true)``,并在``D``的``onBackPressed()``中判断此参数,若为``true``则使用上文提及的方式清除所有页面并跳转到首页,否则正常执行返回流程。此方法没有使用上文提及的几个``Flag``,或者说笔者没发现这几个``Flag``有达到此效果的能力。
Python
UTF-8
531
2.9375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Apr 29 13:05:33 2019 @author: David """ import sys, os path_tools = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) sys.path.insert(1, path_tools) from tools import * def err_deg(a1,ref): ### Calculate the error ref-a1 in an efficient way in the circular space ### it uses complex numbers! ### Input in degrees (0-360) a1=np.radians(a1) ref=np.radians(ref) err = np.angle(np.exp(1j*ref)/np.exp(1j*(a1) ), deg=True) err=round(err, 2) return err
C
UTF-8
887
3.3125
3
[]
no_license
#include <string.h> void inputSideConvolution(int lenH, int *h, int lenX, int *x, int *y) { if (lenH > lenX) { inputSideConvolution(lenX, x, lenH, h, y); return; } // from here: lenH <= lenX int lenY = lenH + lenX - 1; memset(y, 0, lenY*sizeof(int)); // sets y[i]=0 for all i for(int i=0; i < lenX; i++) { for(int j=0; j < lenH; j++) { y[i+j] += x[i]*h[j]; } } } void outputSideConvolution(int lenH, int *h, int lenX, int *x, int *y) { // from here: lenH <= lenX int lwb, upb, lenY = lenH + lenX - 1; for(int i = 0; i < lenY; i++) { // lwb and upb are chosen such that: 0<=j && j<lenH && 0<=i-j && i-j<lenX // which is equivalent with: MAX(0,i+1-lenX) <= j < MIN(i+1,lenH) lwb = (i < lenX ? 0: i-lenX+1); upb = (i < lenH ? i+1 : lenH); y[i] = 0; for (int j = lwb; j < upb; j++) { y[i] += h[j]*x[i-j]; } } }
Java
UTF-8
1,247
2.078125
2
[]
no_license
package testNg_Example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class Wd_Test { WebDriver driver ; @BeforeClass public void startUp() { System.setProperty("webdriver.chrome.driver", "E:\\ASISH FOLDER\\Software Testing\\AUTOMATION TESTING\\DRIVER\\chromedriver.exe"); driver =new ChromeDriver(); } @AfterClass public void tearDown() { driver.close(); } @Test public void Tc002()throws Exception { driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php"); System.out.println(driver.getTitle()); Reporter.log(driver.getTitle()); driver.findElement(By.name("txtUserName")).sendKeys("admin"); driver.findElement(By.name("txtPassword")).sendKeys("admin"); driver.findElement(By.name("Submit")).click(); Thread.sleep(6000); System.out.println("Log in Compleated"); Reporter.log("Log in Compleated"); driver.findElement(By.linkText("Logout")).click(); System.out.println("Log Out Compleated"); Reporter.log("Log out Compleated"); } }
Rust
UTF-8
13,890
2.671875
3
[]
no_license
use std::cmp; use tcod::colors::*; use tcod::console::*; mod object; use object::*; mod mytcod; use mytcod::*; mod gamemap; use gamemap::*; use tcod::input::{self, Event, Key}; use tcod::map::Map as FovMap; use rand::Rng; const PLAYER: usize = 0; const HEAL_AMOUNT: i32 = 4; const LIGHTNING_DAMAGE: i32 = 40; const LIGHTNING_RANGE: i32 = 5; const CONFUSE_RANGE: i32 = 8; const CONFUSE_NUM_TURNS: i32 = 10; #[derive(Clone, Copy, Debug, PartialEq)] enum PlayerAction { TookTurn, DidntTakeTurn, Exit, } pub struct Game { pub map: Map, inventory: Vec<Object>, messages: Messages, } impl Game { fn render_all(&mut self, tcod: &mut Tcod, objects: &Vec<Object>, fov_recompute: bool) { if fov_recompute { tcod.compute_fov(objects[PLAYER].x, objects[PLAYER].y); } let mut to_draw: Vec<_> = objects .iter() .filter(|o| tcod.fov.is_in_fov(o.x, o.y)) .collect(); to_draw.sort_by(|o1, o2| o1.blocks.cmp(&o2.blocks)); for object in &to_draw { object.draw(&mut tcod.con); } objects[PLAYER].draw(&mut tcod.con); for y in 0..MAP_HEIGHT { for x in 0..MAP_WIDTH { let visible = tcod.fov.is_in_fov(x, y); let explored = &mut self.map[x as usize][y as usize].explored; if visible { *explored = true; } if *explored { let color = self.map[x as usize][y as usize].color(visible); tcod.con .set_char_background(x, y, color, BackgroundFlag::Set); } } } if let Some(fighter) = objects[PLAYER].fighter { tcod.root.print_ex( 1, SCREEN_HEIGHT - 2, BackgroundFlag::None, TextAlignment::Left, format!("HP: {}/{}", fighter.hp, fighter.max_hp), ) } } fn move_player_by(&mut self, objects: &mut Vec<Object>, x: i32, y: i32) { self.move_object_by(PLAYER, objects, x, y); } fn move_object_by(&mut self, id: usize, objects: &mut Vec<Object>, x: i32, y: i32) { let nx = objects[id].x + x; let ny = objects[id].y + y; if !self.is_tile_blocked(objects, nx, ny) { objects[id].move_by(x, y); } } fn player_move_or_attack(&mut self, objects: &mut Vec<Object>, x: i32, y: i32) -> PlayerAction { let nx = objects[PLAYER].x + x; let ny = objects[PLAYER].y + y; let target_id = objects .iter() .position(|object| object.fighter.is_some() && object.pos() == (nx, ny)); match target_id { Some(target_id) => { let (player, monster) = mut_two(PLAYER, target_id, objects); player.attack(monster, self); } None => { self.move_player_by(objects, x, y); } } PlayerAction::TookTurn } fn is_tile_blocked(&self, objects: &Vec<Object>, x: i32, y: i32) -> bool { is_blocked(x, y, &self.map, objects) } fn pick_item_up(&mut self, object_id: usize, objects: &mut Vec<Object>) { if self.inventory.len() >= 26 { self.messages.add( format!( "Your inventory is full, cannot pick up {}.", objects[object_id].name ), RED, ) } else { let item = objects.swap_remove(object_id); self.messages .add(format!("You picked up a {}!", item.name), GREEN); self.inventory.push(item); } } } fn main() { println!("Starting Crabline game 🦀"); tcod::system::set_fps(LIMIT_FPS); let mut player = Object::new(0, 0, '@', "player", WHITE, true); player.alive = true; player.fighter = Some(Fighter { max_hp: 30, hp: 30, defense: 2, power: 5, on_death: DeathCallback::Player, }); let mut objects = vec![player]; let mut game = Game { map: make_map(&mut objects), messages: Messages::new(), inventory: vec![], }; game.messages.add("Welcome, gl hf!", RED); let con = Offscreen::new(MAP_WIDTH, MAP_HEIGHT); let panel = Offscreen::new(SCREEN_WIDTH, PANEL_HEIGHT); let root = Root::initializer() .font("arial10x10.png", FontLayout::Tcod) .font_type(FontType::Greyscale) .size(SCREEN_WIDTH, SCREEN_HEIGHT) .title("Crablike") .init(); let mut tcod = Tcod { root: root, fov: FovMap::new(MAP_WIDTH, MAP_HEIGHT), con: con, panel: panel, key: Default::default(), }; tcod.populate_fov_map(MAP_WIDTH, MAP_HEIGHT, &mut game); let mut previous_player_position = (-1, -1); while !tcod.root.window_closed() { tcod.con.clear(); let fov_recompute = previous_player_position != (objects[PLAYER].x, objects[PLAYER].y); match input::check_for_event(input::KEY_PRESS) { Some((_, Event::Key(k))) => tcod.key = k, _ => tcod.key = Default::default(), } game.render_all(&mut tcod, &objects, fov_recompute); tcod.panel.set_default_background(BLACK); tcod.panel.clear(); let hp = objects[PLAYER].fighter.map_or(0, |f| f.hp); let max_hp = objects[PLAYER].fighter.map_or(0, |f| f.max_hp); tcod.render_bar(1, 1, BAR_WIDTH, "HP", hp, max_hp, LIGHT_RED, DARKER_RED); tcod.print_messages(&game.messages); tcod.blit_con(SCREEN_WIDTH, SCREEN_HEIGHT); tcod.blit_panel(SCREEN_WIDTH, SCREEN_HEIGHT, PANEL_Y); tcod.root.flush(); let action = handle_keys(&mut tcod, &mut objects, &mut game); match action { PlayerAction::Exit => break, PlayerAction::TookTurn if objects[PLAYER].alive => { for id in 0..objects.len() { if objects[id].ai.is_some() { ai_take_turn(id, &tcod, &mut objects, &mut game); } } } _ => {} } } } fn handle_keys(tcod: &mut Tcod, objects: &mut Vec<Object>, game: &mut Game) -> PlayerAction { use tcod::input::KeyCode::*; use PlayerAction::*; let player_alive = objects[PLAYER].alive; match (tcod.key, tcod.key.text(), player_alive) { (Key { code: Up, .. }, _, true) => game.player_move_or_attack(objects, 0, -1), (Key { code: Down, .. }, _, true) => game.player_move_or_attack(objects, 0, 1), (Key { code: Left, .. }, _, true) => game.player_move_or_attack(objects, -1, 0), (Key { code: Right, .. }, _, true) => game.player_move_or_attack(objects, 1, 0), (Key { code: Escape, .. }, _, _) => Exit, ( Key { code: Enter, alt: true, .. }, _, _, ) => { let fullscreen = tcod.root.is_fullscreen(); tcod.root.set_fullscreen(!fullscreen); DidntTakeTurn } (Key { code: Text, .. }, "g", true) => { let item_id = objects .iter() .position(|object| object.pos() == objects[PLAYER].pos() && object.item.is_some()); if let Some(item_id) = item_id { game.pick_item_up(item_id, objects); }; TookTurn } (Key { code: Text, .. }, "i", true) => { let inventory_index = inventory_menu( &game.inventory, "Press the key next an item to use it, or any other to cancel.\n", &mut tcod.root, ); if let Some(inventory_index) = inventory_index { use_item(inventory_index, tcod, game, objects); } TookTurn } _ => DidntTakeTurn, } } fn ai_take_turn(monster_id: usize, tcod: &Tcod, objects: &mut Vec<Object>, game: &mut Game) { use Ai::*; if let Some(ai) = objects[monster_id].ai.take() { let new_ai = match ai { Basic => ai_basic(monster_id, tcod, objects, game), Confused { previous_ai, num_turns, } => ai_confused(monster_id, tcod, objects, game, previous_ai, num_turns), }; objects[monster_id].ai = Some(new_ai); } } fn ai_basic(monster_id: usize, tcod: &Tcod, objects: &mut Vec<Object>, game: &mut Game) -> Ai { let (monster_x, monster_y) = objects[monster_id].pos(); if tcod.fov.is_in_fov(monster_x, monster_y) { if objects[monster_id].distance_to(&objects[PLAYER]) >= 2.0 { let (player_x, player_y) = objects[PLAYER].pos(); move_towards(monster_id, player_x, player_y, &game.map, objects); } else if objects[PLAYER].fighter.map_or(false, |f| f.hp > 0) { let (player, monster) = mut_two(PLAYER, monster_id, objects); monster.attack(player, game); } } Ai::Basic } fn ai_confused( monster_id: usize, _tcod: &Tcod, objects: &mut Vec<Object>, game: &mut Game, previous_ai: Box<Ai>, num_turns: i32, ) -> Ai { if num_turns >= 0 { game.move_object_by( monster_id, objects, rand::thread_rng().gen_range(-1, 2), rand::thread_rng().gen_range(-1, 2), ); Ai::Confused { previous_ai: previous_ai, num_turns: num_turns - 1, } } else { game.messages.add( format!("The {} is no longer confused!", objects[monster_id].name), RED, ); *previous_ai } } /// Mutably borrow two *separate* elements from the given slice. /// Panics when the indexes are equal or out of bounds. fn mut_two<T>(first_index: usize, second_index: usize, items: &mut [T]) -> (&mut T, &mut T) { assert!(first_index != second_index); let split_at_index = cmp::max(first_index, second_index); let (first_slice, second_slice) = items.split_at_mut(split_at_index); if first_index < second_index { (&mut first_slice[first_index], &mut second_slice[0]) } else { (&mut second_slice[0], &mut first_slice[second_index]) } } enum UseResult { UsedUp, Cancelled, } fn use_item(inventory_id: usize, tcod: &mut Tcod, game: &mut Game, objects: &mut [Object]) { use Item::*; if let Some(item) = game.inventory[inventory_id].item { let on_use = match item { Heal => cast_heal, Lightning => cast_lightning, Confuse => cast_confuse, }; match on_use(inventory_id, tcod, game, objects) { UseResult::UsedUp => { game.inventory.remove(inventory_id); } UseResult::Cancelled => { game.messages.add("Cancelled", WHITE); } } } else { game.messages.add( format!("The {} cannot be used.", game.inventory[inventory_id].name), WHITE, ) } } fn cast_heal( _inventory_id: usize, _tcod: &mut Tcod, game: &mut Game, objects: &mut [Object], ) -> UseResult { if let Some(fighter) = objects[PLAYER].fighter { if fighter.hp == fighter.max_hp { game.messages.add("You are alraedy at full health.", RED); return UseResult::Cancelled; } game.messages.add("Your wounds are closing!", LIGHT_VIOLET); objects[PLAYER].heal(HEAL_AMOUNT); return UseResult::UsedUp; } UseResult::Cancelled } fn cast_lightning( _inventory_id: usize, tcod: &mut Tcod, game: &mut Game, objects: &mut [Object], ) -> UseResult { let monster_id = closest_monster(tcod, objects, LIGHTNING_RANGE); if let Some(monster_id) = monster_id { game.messages.add( format!( "A lightting bolt strikes the {} with a loud thunder! for {} hit points.", objects[monster_id].name, LIGHTNING_DAMAGE, ), LIGHT_BLUE, ); objects[monster_id].take_damage(LIGHTNING_DAMAGE, game); UseResult::UsedUp } else { game.messages .add("No enemy is close enough to strike.", RED); UseResult::Cancelled } } fn closest_monster(tcod: &Tcod, objects: &[Object], max_range: i32) -> Option<usize> { let mut closest_enemy = None; let mut closest_dist = (max_range + 1) as f32; for (id, object) in objects.iter().enumerate() { if (id != PLAYER) && object.fighter.is_some() && object.ai.is_some() && tcod.fov.is_in_fov(object.x, object.y) { let dist = objects[PLAYER].distance_to(object); if dist < closest_dist { closest_enemy = Some(id); closest_dist = dist; } } } closest_enemy } fn cast_confuse( _inventory_id: usize, tcod: &mut Tcod, game: &mut Game, objects: &mut [Object], ) -> UseResult { let monster_id = closest_monster(tcod, objects, CONFUSE_RANGE); if let Some(monster_id) = monster_id { game.messages.add( format!("{} looks confused", objects[monster_id].name,), LIGHT_GREEN, ); let old_ai = objects[monster_id].ai.take().unwrap_or(Ai::Basic); objects[monster_id].ai = Some(Ai::Confused { previous_ai: Box::new(old_ai), num_turns: CONFUSE_NUM_TURNS, }); UseResult::UsedUp } else { game.messages .add("No enemy is close enough to strike.", RED); UseResult::Cancelled } }
Java
UTF-8
1,524
2.6875
3
[]
no_license
package io.github.cmansfield.card; import io.github.cmansfield.deck.constants.Format; import io.github.cmansfield.deck.constants.Legality; import io.github.cmansfield.io.CardReader; import org.testng.annotations.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import static org.testng.Assert.*; public class CardUtilsTest { @Test public void test_legalitiesBuilder() { List<String> legalitiesStr = new ArrayList<>(); legalitiesStr.add(Format.COMMANDER.toString()); legalitiesStr.add(Format.BATTLE_FOR_ZENDIKAR_BLOCK.toString()); legalitiesStr.add(Format.MODERN.toString()); legalitiesStr.add(Format.LEGACY.toString()); List<Map<String,String>> legalities = new CardUtils .LegalitiesBuilder() .format(Format.COMMANDER) .format(Format.BATTLE_FOR_ZENDIKAR_BLOCK) .format(Format.MODERN) .format(Format.LEGACY) .build(); assertNotNull(legalities); assertEquals(legalities.size(),4); legalities.forEach(legality -> { assertTrue(legalitiesStr.contains(legality.get(Legality.FORMAT.toString()))); }); } @Test(enabled = true) public void test_getListOfLegalities() throws IOException { List<Card> cards = CardReader.loadCards(); Set<String> legalities = CardUtils.getListOfLegalities(cards); for(Format format : Format.values()) { assertTrue(legalities.contains(format.toString())); } } }
Markdown
UTF-8
260
2.71875
3
[]
no_license
The least squares problem, also often known as linear regression allows one to fit a linear model to observed data. It can be solved using one of two methods: * Standard Equation * Gradient Descent In this implementation we'll focus on using gradient descent
C++
UTF-8
873
3.28125
3
[]
no_license
#include <bits/stdc++.h> #include <vector> #include <set> using namespace std; class Solution { public: struct Comp { bool operator()(int a, int b) { if (a % 2 == 0) { return true; } return false; } }; vector<int> sortArrayByParity(vector<int> &ar) { // sort(ar.begin(), ar.end(), comp); set<int, Comp> st; for (int val : ar) { st.insert(val); } vector<int> arr(ar.size()); int i = 0; for (int val : st) { arr[i++] = val; } return arr; } }; int main() { Solution sol; vector<int> arr = {2, 4, 3, 1, 7, 4}; vector<int> res = sol.sortArrayByParity(arr); for (int val : res) { cout << val << " "; } cout << "\n"; }
PHP
UTF-8
1,250
3
3
[ "MIT" ]
permissive
<?php namespace Crummy\Phlack\Common\Formatter; use Crummy\Phlack\WebHook\CommandInterface; class Sequencer implements FormatterInterface { const SEQUENCE = '<%s>'; /** * @param string $text The text to be sequenced * @param string $label An optional label * * @return string */ public function format($text, $label = null) { return $this->sequence($text, $label); } /** * @param string $text * @param null $label * * @return string */ public static function sequence($text, $label = null) { $text = $label ? $text.'|'.$label : $text; return sprintf(static::SEQUENCE, $text); } /** * @param CommandInterface $command * * @return array */ public static function command(CommandInterface $command) { return [ 'channel' => self::sequence('#'.$command['channel_id'], $command['channel_name']), 'user' => self::sequence('@'.$command['user_id'], $command['user_name']), ]; } /** * @param string $channel * * @return string */ public static function alert($channel) { return self::sequence('!'.$channel); } }
PHP
UTF-8
2,407
2.515625
3
[ "MIT" ]
permissive
<?php /** * Calendar item * Visualise image, date(s) and title. */ // Variables $thumb = has_post_thumbnail ()? wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large' ): [null]; if (!$thumb[0]){ if ( get_post_meta( $post->ID, '_scheduled_thumbnail_id' ) ){ $array = get_post_meta( $post->ID, '_scheduled_thumbnail_id' ); $thumb = wp_get_attachment_image_src( $array [0], 'large' ); } else if ( get_post_meta( $post->ID, '_scheduled_thumbnail_list') ){ $list = get_post_meta( $post->ID, '_scheduled_thumbnail_list'); $array =json_decode($list[0]); $thumb = wp_get_attachment_image_src( $array[0], 'large' ); } else { $thumb = [null]; } } $past = null; $start = get_field('start_date')? strtotime (get_field ('start_date')): null; if( $start && $start < time() ){ $start = null; } if( get_field('end_date') && strtotime (get_field ('end_date')) < time() ){ $past = true; } ?> <article class="item col-xs-6 col-sm-4 col-md-2"> <a href="<?=the_permalink()?>" rel="bookmark" title="<?=the_title_attribute()?>"> <div class="header-circle"<?=isset ($thumb['0'])? ' style="background-image:url(' . $thumb['0'] . ');"': null?>> <div> <?php if ($start) { ?> <span class="month"><?=date("M", $start);?></span> <span class="day"><?=date("j", $start);?></span> <?php } else if( $past ) { ?> <span class="running"><p class="ongoing-event">Past</p></span> <?php } else { ?> <span class="running"><p class="ongoing-event">Ongoing</p></span> <?php } ?> </div> </div> <h1 class="grey-font"><?=the_title()?></h1> <h3><?=get_field('sub-title')?: get_the_excerpt()?></h3> </a> <div class="agenda-share"> <a href="http://twitter.com/share?url=<?=the_permalink()?>" target="_blank"><i class='ion-social-twitter'></i></a> <a href="http://www.facebook.com/sharer.php?u=<?=the_permalink()?>" target="_blank"><i class='ion-social-facebook'></i></a> <a href="javascript:void((function()%7Bvar%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','//assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)%7D)());" target="_blank"><i class='ion-social-pinterest'></i></a> <a href="http://www.tumblr.com/share/link?<?=the_permalink()?>" target="_blank"><i class='ion-social-tumblr'></i></a> </div> </article>
C
UTF-8
987
2.71875
3
[]
no_license
#ifndef VECTOR_H #define VECTOR_H #include "Point.h" #define VECTOR_INIT_CAPACITY 4 #define VECTOR_INIT(vec) vector vec; vector_init(&vec) #define VECTOR_ADD(vec, item) vector_add(&vec, item) #define VECTOR_SET(vec, idx, item) vector_set(&vec, idx, item) #define VECTOR_INSERT(vec, idx, item) vector_insert(&vec, idx, item) #define VECTOR_GET(vec, type, idx) (type) vector_get(&vec, idxx) #define VECTOR_DELETE(vec, idx) vector_delete(&vec, idx) #define VECTOR_TOTAL(vec) vector_total(&vec) #define VECTOR_FREE(vec) vector_free(&vec) typedef struct vector { point *items; int cap; int size; } vector; void vector_init(vector *); int vector_total(vector *); static void vector_resize(vector *, int); void vector_add(vector *, point *); void vector_set(vector *, int, point *); void vector_insert(vector *, int, point *); point *vector_get(vector *, int); void vector_delete(vector *, int); void vector_free(vector *); void vector_copy(vector *, vector *); #endif
Markdown
UTF-8
3,531
2.75
3
[]
no_license
--- description: "Step-by-Step Guide to Prepare Homemade Jackfruit Laddu" title: "Step-by-Step Guide to Prepare Homemade Jackfruit Laddu" slug: 3176-step-by-step-guide-to-prepare-homemade-jackfruit-laddu date: 2021-12-24T15:48:56.122Z image: https://img-global.cpcdn.com/recipes/7204066d7a958733/680x482cq70/jackfruit-laddu-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/7204066d7a958733/680x482cq70/jackfruit-laddu-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/7204066d7a958733/680x482cq70/jackfruit-laddu-recipe-main-photo.jpg author: Ethel Campbell ratingvalue: 4.9 reviewcount: 24450 recipeingredient: - "1 cup jackfruit pulp" - "1 cup rava" - "2 tbsp cream" - "1/4 cup milk" - "3 tsp Sugaramount depends upon your taste and sweetness of jackfruit" - "1 tbsp ghee" - "2 tbsp milkpowder" - "1/4 teaspoon elaichi powder and" - "As required dryfruits for garnishing" recipeinstructions: - "At first make a paste of jackfruit pulp, milk, cream and sugar in a mixer." - "In a pan roast rava till golden colour." - "Now add jackfruit paste and cook till mixture becomes thick. Now add milk powder. Mix well." - "Turn off the flame.Let the mixture cool for a while." - "Now add elaichi powder and mix well." - "Make small laddus and garnish with dryfruits of your choice." categories: - Recipe tags: - jackfruit - laddu katakunci: jackfruit laddu nutrition: 240 calories recipecuisine: American preptime: "PT23M" cooktime: "PT36M" recipeyield: "4" recipecategory: Dinner --- ![Jackfruit Laddu](https://img-global.cpcdn.com/recipes/7204066d7a958733/680x482cq70/jackfruit-laddu-recipe-main-photo.jpg) Hello everybody, it's me, Dave, welcome to my recipe page. Today, we're going to make a special dish, jackfruit laddu. It is one of my favorites food recipes. For mine, I will make it a little bit unique. This is gonna smell and look delicious. Jackfruit Laddu is one of the most well liked of current trending meals in the world. It is enjoyed by millions daily. It's easy, it's fast, it tastes delicious. They are nice and they look wonderful. Jackfruit Laddu is something which I've loved my entire life. To get started with this particular recipe, we must first prepare a few ingredients. You can have jackfruit laddu using 9 ingredients and 6 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Jackfruit Laddu: 1. Take 1 cup jackfruit pulp 1. Make ready 1 cup rava 1. Get 2 tbsp cream 1. Prepare 1/4 cup milk 1. Take 3 tsp Sugar(amount depends upon your taste and sweetness of jackfruit) 1. Make ready 1 tbsp ghee 1. Take 2 tbsp milkpowder 1. Prepare 1/4 teaspoon elaichi powder and 1. Take As required dryfruits for garnishing <!--inarticleads2--> ##### Instructions to make Jackfruit Laddu: 1. At first make a paste of jackfruit pulp, milk, cream and sugar in a mixer. 1. In a pan roast rava till golden colour. 1. Now add jackfruit paste and cook till mixture becomes thick. Now add milk powder. Mix well. 1. Turn off the flame.Let the mixture cool for a while. 1. Now add elaichi powder and mix well. 1. Make small laddus and garnish with dryfruits of your choice. So that's going to wrap it up with this special food jackfruit laddu recipe. Thanks so much for your time. I'm confident that you will make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to save this page on your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
JavaScript
UTF-8
5,297
3
3
[]
no_license
function summitElements(total, num) { return total + num; } function findFishsOverVolumes() { let fish = fishFarm.filter((fishes) => fishes.stockVolumeInKg > 500); let fishNames = fish.map((pFish) => { console.log(pFish.fishType); }); return fishNames; } function filterFishForPrice() { let costsSpace = fishFarm.filter( (pPrice) => pPrice.price > 9 && pPrice.price < 12 ); let fishNames = costsSpace.map((pFish) => { console.log(pFish.fishType); }); return fishNames; } function findFishsFromBern() { let fishsOfBern = []; fishFarm.filter((fish) => { if (fish.season == "Winter") { fish.saleLocations.filter((place) => { if (place == "BE") { fishsOfBern.push(fish); } }); } }); return fishsOfBern; } function sortLastUseDate() { let newList = []; fishFarm.map((day) => { day.entryDate.setDate(day.entryDate.getDate() + day.durationInDays); let lastUseDate = new Date(day.entryDate); newList.push({ date: lastUseDate, name: day.fishType }); }); console.log(newList); return newList; } let newListToSort = sortLastUseDate().sort(function (a, b) { return a.date.getTime() - b.date.getTime(); }); function selectFishsFromEu() { let country = []; let fish = fishFarm.filter((fishes) => { if (fishes.price < 10) { if (fishes.originCountry != "Vietnam") { if (fishes.originCountry != "Egypt") { if (fishes.originCountry != "Japan") { country.push(fishes); } } } } }); console.log(country); } function sumFishStock() { let stock = []; let fishStock = fishFarm.map((stockAmount) => stock.push(stockAmount.stockVolumeInKg) ); let sum = stock.reduce(summitElements); return sum; } function findHeihestPrice() { let priceArray = []; let fishPrice = fishFarm.map((cost) => priceArray.push(cost.price)); let maxPrice = priceArray.reduce(function (a, b) { return Math.max(a, b); }); let expensiveFish = fishFarm.filter((fish) => { if (fish.price == maxPrice) { console.log( "teuerste Fisch ist: " + fish.fishType + " und Kostet : " + fish.price + "CHF" ); } }); return expensiveFish; } function selectFishsWithLongDuration() { let fishs = []; let fishDuration = fishFarm.map((duration) => fishs.push(duration.durationInDays) ); let maxDuration = fishs.reduce(function (a, b) { return Math.max(a, b); }); let longDuration = fishFarm.filter((fish) => { if (fish.durationInDays == maxDuration) { console.log( "En uzun dayanan balik: " + fish.fishType + " geldigi ülke : " + fish.originCountry ); } }); return longDuration; } function selectFishPriceFromSwissRomande() { let winterAutummFishs = []; fishFarm.filter((fish) => { if (fish.season == "Autumn" || fish.season == "Winter") { fish.saleLocations.filter((place) => { if ( place == "VD" || place == "BE" || place == "FR" || place == "NE" || place == "GE" ) { { if (winterAutummFishs.includes(fish.price) == false) { winterAutummFishs.push(fish.price); } } } }); } }); let sum = winterAutummFishs.reduce(summitElements); console.log( "Kis/Sonbahar sezonu swiss romande de satilan ortalama balik fiyati: " + Math.round((sum / winterAutummFishs.length) * 100) / 100 ); return sum; } function findFishstockFromTicino() { let fishTI = []; let ListOfTicino = fishFarm.filter((fish) => { let ticinosFish = fish.saleLocations.filter((place) => { if (place == "TI") { fishTI.push(fish.stockVolumeInKg); } }); }); let sum = fishTI.reduce(summitElements); console.log("Ticino icin balik stogu: " + sum); return sum; } function findNotEUFishs() { let fishsOfNonEU = []; let notEUFishs = fishFarm.filter((fish) => { if (fish.season == "Summer") { if ( fish.originCountry == "Vietnam" || fish.originCountry == "Egypt" || fish.originCountry == "Japan" ) { let placeZurich = fish.saleLocations.filter((place) => { if (place == "ZH") { fishsOfNonEU.push(fish.itemWeightInGrams); } }); } } }); let sum = fishsOfNonEU.reduce(summitElements); console.log( "Avrupa birligi disindan gelen ve zürichte yazin satilan baliklarin ortalama gramaji: " + sum / fishsOfNonEU.length ); return sum; } console.log("ödev 1: Stokta 500 kg üzerinde olan baliklar: "); findFishsOverVolumes(); console.log("ödev 2:9 Frank ile 12 Frank araliginda olan baliklar: "); filterFishForPrice(); console.log("ödev 3: Bernde ve kisin satilan baliklar: "); console.log(findFishsFromBern()); console.log("ödev 4: Son kullanma tarihine göre siralanmis balik listesi:"); sortLastUseDate(); console.log("ödev 5: EU da satilan 10 Frankin altindaki baliklar: "); selectFishsFromEu(); console.log("ödev 6: Toplam balik stogu: " + sumFishStock() + "kg"); findHeihestPrice(); selectFishsWithLongDuration(); selectFishPriceFromSwissRomande(); findFishstockFromTicino(); findNotEUFishs();
Java
UTF-8
1,742
2.328125
2
[]
no_license
package com.luan.java8defaultcrudapplication.service.dto; import java.io.Serializable; import java.time.LocalDate; public class AddressDTO implements Serializable{ private static final long serialVersionUID = 1L; private Long id; private String street; private String district; private Long number; private String city; private String state; private String country; private String cep; private Long idClient; private LocalDate alterationDate; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public String getDistrict() { return this.district; } public void setDistrict(String district) { this.district = district; } public Long getNumber() { return this.number; } public void setNumber(Long number) { this.number = number; } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public String getCountry() { return this.country; } public void setCountry(String country) { this.country = country; } public String getCep() { return this.cep; } public void setCep(String cep) { this.cep = cep; } public Long getIdClient() { return this.idClient; } public void setIdClient(Long idClient) { this.idClient = idClient; } public LocalDate getAlterationDate() { return this.alterationDate; } public void setAlterationDate(LocalDate alterationDate) { this.alterationDate = alterationDate; } }
Swift
UTF-8
1,487
3.046875
3
[]
no_license
// // Controller.swift // Tic Tac Toe // // Created by Tobin Bell on 7/7/16. // Copyright © 2016 Tobin Bell. All rights reserved. // import UIKit class TicTacToeController: UIViewController { @IBOutlet weak var boardView: UIView! @IBOutlet weak var statusLabel: UILabel! var game = TicTacToeModel() @IBAction func newGameButtonPressed(sender: UIButton) { game.reset() for case let button as UIButton in boardView.subviews { button.setTitle("", forState: []) button.userInteractionEnabled = true } statusLabel.text = "\(game.nextPlayer)'s Turn" boardView.userInteractionEnabled = true view.backgroundColor = UIColor.whiteColor() } @IBAction func boardButtonPressed(sender: UIButton) { game.play(at: sender.tag) sender.setTitle(game.previousPlayer, forState: []) sender.userInteractionEnabled = false if game.state == .Won { statusLabel.text = "\(game.previousPlayer) Wins!" boardView.userInteractionEnabled = false view.backgroundColor = UIColor.lightBlueColor() } else if game.state == .Tied { statusLabel.text = "It's a Tie!" boardView.userInteractionEnabled = false view.backgroundColor = UIColor.lightBlueColor() } else { statusLabel.text = "\(game.nextPlayer)'s Turn" } } }
Java
UTF-8
1,568
2.3125
2
[]
no_license
package com.aleksandra.go4mytrip; public class NoteModel { String IdNote; String NoteTitle; String TextNote; String DateTime; String NoteColor; String Link; String Image; public NoteModel() { } public NoteModel(String idNote, String noteTitle, String textNote, String dateTime, String noteColor, String link, String image) { IdNote = idNote; NoteTitle = noteTitle; TextNote = textNote; DateTime = dateTime; NoteColor = noteColor; Link = link; Image = image; } public String getImage() { return Image; } public void setImage(String image) { Image = image; } public String getLink() { return Link; } public void setLink(String link) { Link = link; } public String getNoteColor() { return NoteColor; } public void setNoteColor(String noteColor) { NoteColor = noteColor; } public String getIdNote() { return IdNote; } public void setIdNote(String idNote) { IdNote = idNote; } public String getNoteTitle() { return NoteTitle; } public void setNoteTitle(String noteTitle) { NoteTitle = noteTitle; } public String getTextNote() { return TextNote; } public void setTextNote(String textNote) { TextNote = textNote; } public String getDateTime() { return DateTime; } public void setDateTime(String dateTime) { DateTime = dateTime; } }
Markdown
UTF-8
237
2.953125
3
[ "MIT" ]
permissive
### 布局 `span`表示每列占多少比列,是平均 `gutter`表示每列之间的间隔,`gutter:20`表示空格是`2em` 目前只支持均匀分布,更多的功能,比如:混合分布/分栏偏移等,请使用`u-row/u-col`
Python
UTF-8
1,986
3.53125
4
[]
no_license
#!/usr/bin/env python3 import argparse import glob import os description = """"show the sets of 2 strings. string can input strings or glob or string file.""" parser = argparse.ArgumentParser(description=description) parser.add_argument('-1', '--strings_1', nargs='+', required=True) parser.add_argument('-2', '--strings_2', nargs='+', required=True) parser.add_argument('-ed', '--eliminate_directory', action='store_true', help="eliminate directory") parser.add_argument('-ee', '--eliminate_extension', action='store_true', help="eliminate extension") parser.add_argument('-o1', '--show_only_1', action='store_true', help="show names that only first have") parser.add_argument('-o2', '--show_only_2', action='store_true', help="show names that only second have") parser.add_argument('-b', '--show_both', action='store_true', help="show names that both have") args = parser.parse_args() def load_strings(strings): if len(strings) > 1: return strings path = strings[0] if os.path.exists(path): with open(path) as f: return f.read().split() else: return glob.glob(path) def get_names(strs, eliminate_directory, eliminate_extension): if eliminate_directory: strs = (os.path.basename(n) for n in strs) if eliminate_extension: strs = (os.path.splitext(n)[0] for n in strs) return set(strs) names1 = get_names(load_strings(args.strings_1), args.eliminate_directory, args.eliminate_extension) names2 = get_names(load_strings(args.strings_2), args.eliminate_directory, args.eliminate_extension) print('num of first:', len(names1)) print('num of second:', len(names2)) print('num of both contained:', len(names1 & names2)) if args.show_only_1: print('only first:') for n in (names1 - names2): print(n) if args.show_only_2: print('only second:') for n in (names2 - names1): print(n) if args.show_both: print('both:') for n in (names2 & names1): print(n)
C++
UTF-8
1,718
3
3
[]
no_license
// // Created by shaob on 2020/2/25. // #include <iostream> #include <cstdio> #include <algorithm> #include <utility> #include <vector> using namespace std; struct student { string name; char gender{}; string ID; int grade{}; student() = default; student(string _name, char _gender, string _ID, int grade) : name(std::move(_name)), gender(_gender), ID(std::move(_ID)), grade(grade) {} }; vector<student> StudentVector; int pat_solver() { int N; string a, c; char b; int d; int diff = -1, maleScore = 0xffff, femaleScore = -1, maleId = -1, femaleId = -1; scanf("%d", &N); for (int i = 0; i < N; ++i) { cin >> a >> b >> c >> d; student s(a, b, c, d); StudentVector.push_back(s); } for (int j = 0; j < N; ++j) { student s = StudentVector[j]; if (s.gender == 'F') { // female if (s.grade > femaleScore) { femaleId = j; femaleScore = s.grade; } } else { // male if (s.grade < maleScore) { maleId = j; maleScore = s.grade; } } } if (femaleId == -1) { printf("Absent\n"); } else { printf("%s %s\n", (StudentVector[femaleId].name).c_str(), (StudentVector[femaleId].ID).c_str()); } if (maleId == -1) { printf("Absent\n"); } else { printf("%s %s\n", (StudentVector[maleId].name).c_str(), (StudentVector[maleId].ID).c_str()); } if (maleScore == 0xffff or femaleScore == -1) { printf("NA"); } else { printf("%d", femaleScore - maleScore); } }
JavaScript
UTF-8
557
2.90625
3
[]
no_license
var btnGuardar = document.getElementById("btnguardar"); var inputTexto = document.getElementById("inputtexto"); var btnObtener = document.querySelector("#btnobtener"); var element = document.querySelector("#snacks") btnGuardar.addEventListener("click", function(){ var texto = inputTexto.value; localStorage.setItem("snack", texto); localStorage.setItem("Clave","º1278ett78"); }) btnObtener.addEventListener("click", function(){ var snack = localStorage.getItem("snack"); console.log("Snack encontrado",snack) element.innerHTML = snack; })
Java
UTF-8
1,626
2.5625
3
[ "MIT" ]
permissive
package com.mari05lim.covidinfo.model; import com.google.gson.annotations.SerializedName; public class WorldModel { @SerializedName("lastUpdate") private String lastUpdate; @SerializedName("confirmed") private Confirmed confirmed; @SerializedName("deaths") private Deaths deaths; @SerializedName("recovered") private Recovered recovered; public WorldModel(String lastUpdate, Confirmed confirmed, Deaths deaths, Recovered recovered) { this.lastUpdate = lastUpdate; this.confirmed = confirmed; this.deaths = deaths; this.recovered = recovered; } public String getLastUpdate() { return lastUpdate; } public Confirmed getConfirmed() { return confirmed; } public Deaths getDeaths() { return deaths; } public Recovered getRecovered() { return recovered; } public class Confirmed { @SerializedName("value") private int value; public Confirmed(int value) { this.value = value; } public int getValue() { return value; } } public class Deaths { @SerializedName("value") private int value; public Deaths(int value) { this.value = value; } public int getValue() { return value; } } public class Recovered { @SerializedName("value") private int value; public Recovered(int value) { this.value = value; } public int getValue() { return value; } } }
Java
UTF-8
1,875
2.109375
2
[ "Apache-2.0" ]
permissive
package org.elkan1788.extra.nuby.service; import org.elkan1788.extra.nuby.bean.Couponlog; import org.nutz.dao.Cnd; import org.nutz.dao.sql.Criteria; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.lang.Lang; import org.nutz.log.Log; import org.nutz.log.Logs; import java.util.Date; import java.util.List; import java.util.Map; /** * 游戏记录业务逻辑 * * @author 凡梦星尘(elkan1788@gmail.com) * @since 2015/4/24 * @version 1.0.0 */ @IocBean(fields = {"dao"}) public class CouponlogService extends BaseService<Couponlog> { private static final Log log = Logs.get(); public void add(Couponlog cl) { cl.setCreateTime(new Date()); try { cl = dao().insert(cl); if (Lang.isEmpty(cl.getConId())){ log.errorf("添加用户[%s-%s]优惠券发送记录失败!!!", cl.getOpenid(), cl.getType()); } } catch (Exception e) { throw Lang.wrapThrow(e, "添加用户优惠券发送记录出现异常!!!"); } } public boolean isSend(Integer couponId, String openId) { boolean flag = false; Criteria cri = Cnd.cri(); cri.where().and("conId", "=", couponId).and("openid", "=", openId); try { List<Couponlog> couponlogs = dao().query(Couponlog.class, cri); if (!Lang.isEmpty(couponlogs)) { flag = true; } } catch (Exception e) { throw Lang.wrapThrow(e, "查询用户[%s]优惠券发送记录异常!!!"); } return flag; } public Map<String, Object> list(int page, int rows, String nickName) { Criteria cri = Cnd.cri(); if (!Lang.isEmpty(nickName)){ } cri.getOrderBy().desc("createTime"); Map<String, Object> map = this.easyuiDGPager(page, rows, cri, true); return map; } }
Markdown
UTF-8
3,750
2.78125
3
[]
no_license
# Graph explorer ## Design goals A highly interactive dashboard to satisfy ad-hoc information needs across many similar metrics and graphs using mainly expressive queries as input. Plenty of dashboards provide statically configured pages for realtime and/or historic dashboards, others provide some dynamism but are often hard to navigate and too restrictive when trying to find and correllate time-series data. This tool aims to: * show you the information you're looking for as quickly as possible, and with minimal cruft * let you rearrange contents of graphs and more interactive features like realtime zooming, panning, legend reordering, etc * diverge from the graphite API as little as possible. (no custom DSL like with gdash) * use expressive queries to navigate and manipulate display of individual graphite targets as well as complete graphs generated from templates * use simple version-controllable and editable plaintext files, avoid databases * be simple as possible to get running from scratch. No *just use sinatra* `sudo gem install crap loadError && wget http://make-a-mess.sh | sudo bash -c ; passenger needs gcc to recompile nginx; **loadError**` ![Screenshot](https://raw.github.com/Dieterbe/graph-explorer/master/screenshot.png) # Interactive queries Given: * a list of all metrics available in your graphite system (you can just download this from graphite box) * a bunch of small template files which define which graphs can be generated based on the available metrics you have, as well as individual targets which may be interesting by themselves (and for each target one or more tags; which you can use to categorize by server, by service, etc) * an input query provided by the user Graph-explorer will filter out all graphs as well as individual targets that match the query. the targets are then grouped by a tag (given by user or from a default config) and yield one or more additional graphs. All graphs are given clear names that are suitable for easy filtering. Note: * patterns are regexes, but for convenience ' ' is interpreted as '.*' * `group by <tag>` to group targets by a certain tag. for example, the cpu template yields targets with tags type:cpu and server:<servername>. grouping by type yields a graph for each cpu metric type (sys, idle, iowait, etc) listing all servers. grouping by server shows a graph for each server listing all cpu metrics for that server. Examples: * `cpu`: all cpu graphs * `web cpu`: cpu graphs for all servers matching 'web'. (grouped by server by default) * `web cpu total.(system|idle|user|iowait)`: restrict to some common cpu metrics * `web cpu total.(system|idle|user|iowait) group by type`: same, but compare matching servers on a graph for each cpu metric * `web123`: all graphs of web123 * `server[1-5] (mem|cpu)`: memory and cpu graphs of servers 1 through 5 ## Dependencies * python2 ## Installation * git clone graph-explorer * git submodule init; git submodule update * cd graphitejs; git submodule init; git submodule update ## Configuration of graph-explorer * cd graph-explorer * make sure you have a list of your metrics in json format, you can easily get it like so: source config.py curl http://$graphite_url/metrics/index.json > metrics.json * $EDITOR config.py ## Configuration of graphite server you'll need a small tweak to allow this app to request data from graphite. (we could use jsonp, but see https://github.com/obfuscurity/tasseo/pull/27) For apache2 this works: Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET, OPTIONS" Header set Access-Control-Allow-Headers "origin, authorization, accept" ## Running `./app.py` and your page is available at `<ip>:8080`
Python
UTF-8
2,523
2.828125
3
[ "BSD-3-Clause" ]
permissive
""" Unit tests for QuTiP partial transpose functions. """ import numpy as np from qutip import Qobj, partial_transpose, tensor, rand_dm from qutip.partial_transpose import _partial_transpose_reference def test_partial_transpose_bipartite(): """partial transpose of bipartite systems""" rho = Qobj(np.arange(16).reshape(4, 4), dims=[[2, 2], [2, 2]]) # no transpose rho_pt = partial_transpose(rho, [0, 0]) assert (np.abs(np.max(rho_pt.full() - rho.full())) < 1e-12) # partial transpose subsystem 1 rho_pt = partial_transpose(rho, [1, 0]) rho_pt_expected = np.array([[0, 1, 8, 9], [4, 5, 12, 13], [2, 3, 10, 11], [6, 7, 14, 15]]) assert (np.abs(np.max(rho_pt.full() - rho_pt_expected)) < 1e-12) # partial transpose subsystem 2 rho_pt = partial_transpose(rho, [0, 1]) rho_pt_expected = np.array([[0, 4, 2, 6], [1, 5, 3, 7], [8, 12, 10, 14], [9, 13, 11, 15]]) assert (np.abs(np.max(rho_pt.full() - rho_pt_expected)) < 1e-12) # full transpose rho_pt = partial_transpose(rho, [1, 1]) assert (np.abs(np.max(rho_pt.full() - rho.trans().full())) < 1e-12) def test_partial_transpose_comparison(): """partial transpose: comparing sparse and dense implementations""" N = 10 rho = tensor(rand_dm(N, density=0.5), rand_dm(N, density=0.5)) # partial transpose of system 1 rho_pt1 = partial_transpose(rho, [1, 0], method="dense") rho_pt2 = partial_transpose(rho, [1, 0], method="sparse") np.abs(np.max(rho_pt1.full() - rho_pt1.full())) < 1e-12 # partial transpose of system 2 rho_pt1 = partial_transpose(rho, [0, 1], method="dense") rho_pt2 = partial_transpose(rho, [0, 1], method="sparse") np.abs(np.max(rho_pt1.full() - rho_pt2.full())) < 1e-12 def test_partial_transpose_randomized(): """partial transpose: randomized tests on tripartite system""" rho = tensor(rand_dm(2, density=1), rand_dm(2, density=1), rand_dm(2, density=1)) mask = np.random.randint(2, size=3) rho_pt_ref = _partial_transpose_reference(rho, mask) rho_pt1 = partial_transpose(rho, mask, method="dense") np.abs(np.max(rho_pt1.full() - rho_pt_ref.full())) < 1e-12 rho_pt2 = partial_transpose(rho, mask, method="sparse") np.abs(np.max(rho_pt2.full() - rho_pt_ref.full())) < 1e-12
Python
UTF-8
719
3.71875
4
[]
no_license
""" useful methods for the demos """ def title(fun): """ Add a title from the first line of the docstring to the console output if no docstring is given, then rakes the name of the method""" def wrapper(*args, **kwargs): if fun.__doc__: print('\n\t', fun.__doc__.split('\n')[0]) else: print('\n\t', fun.__qualname__.replace('_', ' ')) print() fun(*args, **kwargs) print() return wrapper if __name__ == '__main__': @title def f_1(): print('first function') f_1() @title def f_2(): """The title Not the title""" print('second function') f_2()
Python
UTF-8
6,729
3.15625
3
[]
no_license
from flask import Flask, render_template, request import requests, urllib, json, openpyxl, forecastio, datetime, math, decimal from sklearn import svm from datetime import timedelta ''' Exporting the data from our workbook ''' wb = openpyxl.load_workbook('finalML.xlsx') # open the workbook ws = wb.get_sheet_by_name("Sheet1") # ws is a sheet object, this sets the active sheet to sheet1, the only sheet biglist = [] # create a "master list" - this will be a list of lists ylist = [] # another list- this will be a list of yes/no for x in range(1, 1271): xlist = [] # list created for each row e = ws.cell(row=x, column=6).value # get the value of the 7th column for each row, which contains the yes/no values ylist.append(e) # append the yes/no value in ylist for y in range(1, 6): # for every row, iterate through the 5 columns d = ws.cell(row=x, column=y).value # get value at each column xlist.append(str(d)) # append the value to xlist biglist.append(xlist) # append xlist to biglist x = biglist y = ylist ''' Using sklearn to build classifier ''' clf = svm.SVC() clf.fit(biglist, ylist) ''' function to find the date of the next new moon ''' dec = decimal.Decimal def nextNewMoon(d): now = datetime.datetime.now() # current datetime object date = now + timedelta(days=d) # current + incremented day; starts out day = 2 d += 1 # increment diff = date - datetime.datetime(2001,1,1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) pos = lunations % dec(1) index = (pos * dec(8)) + dec("0.5") index = math.floor(index) # end result if int(index) & 7 == 0: # if index == 0, return the date of the new moon; else recurse with incremented "d" return date # datetime is 1 or 2 days behind astronomical new moon but this is consistent else: date = nextNewMoon(d) return date ''' function to fetch cc and vis data via apixu API call ''' def apixu (locale): r = requests.get('https://api.apixu.com/v1/forecast.json?key=insert key here='+str(locale)+'&days=10') jobj = r.json() lat = jobj['location']['lat'] # get latitude numbers longo = jobj['location']['lon'] # get longitude numbers dateobj = nextNewMoon(d=0) # fetch datetime obj for date of next appearance of new moon increDate = dateobj + timedelta(days=2) # increment fetched datetime by 2 days strDate = str(increDate) # cast inreDate as string date = strDate.split(" ") # "split" based on whitespace cc = 0.0 # our cloud cover vis = 0.0 # visbility forecast = jobj['forecast']['forecastday'] for i in forecast: # if the data is available in the JSON response from apixu API if i['date'] == date[0]: # Date of New Moon for a in i['hour']: # get our cloud cover and visibility data based on coordinates cloud = float(a['cloud']) cc += cloud # because apixu returns "cloud" 24 times for each hour, we'll add to cc after every loop, and then divide by 24 later visi = float(a['vis_miles']) vis += visi # same deal, add, then divide by 24 later cc = cc/24 # get average cloudcover because apixu returns cloudcover for each and all 24 hours of that day cc = (round(cc))/100 # divide cloudCover by 100 to get range from 1.00 to 0.00 per Dark Sky's specifications vis = vis/24 # get average visibility because same deal as apixu vis = round(vis) # visibility in miles return vis, cc, lat, longo ''' function to fetch cc and vis data via Dark Sky API call ''' def DarkSky (lat, longo, vis, cc, count): api_key = 'insert key here' date = nextNewMoon (d=0) d = date + timedelta(days=count) # needed for recursion, count forecast = forecastio.load_forecast(api_key, lat, longo, time=d) count += 1 # increment count, this will happen every recursion daily = forecast.daily() cc = 0.0 # cloud cover vis = 0.0 # visbility if daily.data: # if daily data exists, perform loop, else execute recursive function call for nearby coordinates on the next concurrent day until daily data is found for i in daily.data: # for each value in daily data try: # Try retrieving values, else if errors are found, perform exception handling vis = float (i.visibility) cc = float (i.cloudCover) return vis, cc except Exception: vis, cc = DarkSky (str (float (lat) - 1.00), str (float (longo) - 1.00), vis, cc, count) return vis, cc else: vis, cc = DarkSky (str (float (lat) - 1.00), str (float (longo) - 1.00), vis, cc, count) return vis, cc ''' function to fetch elevation data via Google Maps Elevation API call ''' def fetch_elevation (lat, long): google_elevationURL = "https://maps.googleapis.com/maps/api/elevation/json?locations=" + str(lat) + "," + str(long) + "&key=insert key here" # parsing through JSON response with urllib.request.urlopen(google_elevationURL) as f: response = json.loads(f.read().decode()) status = response["status"] result = response["results"][0] elevation = float (result["elevation"]) # cast elevation data as float return round(elevation, 2) # return elevation at two decimal places ''' Flask implementation ''' app = Flask(__name__) @app.route("/apixu", methods = ['POST']) def main(): # think of this like in c++ int main function locale = request.form["location"] # user input vis, cc, lat, longo = apixu (locale) # fetch visibility, cloudcover, latitude, and longitude via Apixu API call if vis == 0.0 and cc == 0.0: # if no visibility and cloudcover data fetched by apixu function call, execute Dark Sky call vis, cc = DarkSky (lat, longo, vis, cc, count = 2) # count = 2 for timedelta because new moon algorithm is behind 2 days elevation = fetch_elevation(lat, longo) # fetch elevation data prediction = str(clf.predict([[lat, longo, int(vis), cc, elevation]])) # our prediction prediction = prediction[2:-2] ''' get the date of the astronomical new moon and next following day ''' dateobj = nextNewMoon(d=0) # fetch date of next upcoming new moon; 2 days behind so we'll use timedelta to add "days" to the "date" ''' next following day ''' increDate = dateobj + timedelta(days=3) strDate = str(increDate) date = strDate.split(" ") # have to "split" because datetime obj contains hours and seconds which we dont want ''' astronomical new moon ''' increDate2 = dateobj + timedelta(days=2) strDate2 = str(increDate2) date2 = strDate2.split(" ") return render_template('apixu.html', predict = prediction, lat=lat, longo=longo, elevation=elevation, bruh=cc, vis=vis, date=date[0], astronomicalNewMoon=date2[0], location=locale) @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run()
Markdown
UTF-8
237
2.765625
3
[]
no_license
# Dice ## Description A randomised dice generator that picks numbers between 1-6. ## Instructions 1. Shake the micro:bit to start the randomised dice trow – the LEDs will display dice values from 6-1 and then the randomised result