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
885
2.84375
3
[]
no_license
# rpgMapSim The purpose of this program is to build an rpg map for use with games such as dungeons and dragons, or offsets of D&D. Current status: the current version of this application creates a user defined number of rooms, then generates a maze around the rooms. Once the maze is created, it opens a single door along the edge of each room. (randomly selected) The dead ends are then removed, to create a dungeon. Todo: - reduce corridors that are very snake-like - add another form that displays a fog of war version of the map - add functionality to other user controls on map creation form - save / open maps - make the map look better - add creature generation that will pull from a list of creatures dependant on the dungeon motif, and place them randomly in both corridors and rooms. Creature generation will be based on how long the DM wants the dungeon to last.
C++
UTF-8
1,296
2.75
3
[]
no_license
#include <iostream> #include <cstdio> #include <unordered_map> using namespace std; const int MAXN = 100005; int par[MAXN] , Rank[MAXN]; void init(){ for(int i = 1 ; i <= MAXN ; i++){ par[i] = i; Rank[i] = 1; } } int root(int i){ if(par[i] == i) return i; par[i] = root(par[i]); // path compression return par[i]; } int Union(int a,int b){ int p = root(a); int q = root(b); if(p != q){ if(Rank[p] < Rank[q]){ Rank[q] += Rank[p]; par[p] = q; return Rank[q]; } Rank[p] += Rank[q]; par[q] = p; return Rank[p]; } return Rank[p]; } int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int T; scanf("%d",&T); while(T--){ int n; scanf("%d",&n); init(); unordered_map < string , int > ump; string a,b; int k = 1; for(int i = 0 ; i < n ; i++){ cin >> a >> b; if(ump.find(a) == ump.end()) ump[a] = k++; if(ump.find(b) == ump.end()) ump[b] = k++; int x = ump[a]; int y = ump[b]; int pp = root(x); int qq = root(y); printf("%d\n",Union(x,y)); } } return 0; }
Java
UTF-8
4,420
1.765625
2
[]
no_license
package com.ht.extra.pojo.insurance; import java.math.BigDecimal; import java.util.Date; public class ScanPay { private BigDecimal id; private String ipAddr; private String userId; private String patientName; private String authCode; private String operaterId; private String patientId; private String clinicLabel; private Date visitDate; private String amPm; private String totalCosts; private String chargeType; private String payWay; private String hospitalMark; private String trandeNo; private String rcptNo; private String resultComment; private String origTradeNo; private Short visitId; private String operDate; public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } public String getIpAddr() { return ipAddr; } public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr == null ? null : ipAddr.trim(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getPatientName() { return patientName; } public void setPatientName(String patientName) { this.patientName = patientName == null ? null : patientName.trim(); } public String getAuthCode() { return authCode; } public void setAuthCode(String authCode) { this.authCode = authCode == null ? null : authCode.trim(); } public String getOperaterId() { return operaterId; } public void setOperaterId(String operaterId) { this.operaterId = operaterId == null ? null : operaterId.trim(); } public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId == null ? null : patientId.trim(); } public String getClinicLabel() { return clinicLabel; } public void setClinicLabel(String clinicLabel) { this.clinicLabel = clinicLabel == null ? null : clinicLabel.trim(); } public Date getVisitDate() { return visitDate; } public void setVisitDate(Date visitDate) { this.visitDate = visitDate; } public String getAmPm() { return amPm; } public void setAmPm(String amPm) { this.amPm = amPm == null ? null : amPm.trim(); } public String getTotalCosts() { return totalCosts; } public void setTotalCosts(String totalCosts) { this.totalCosts = totalCosts == null ? null : totalCosts.trim(); } public String getChargeType() { return chargeType; } public void setChargeType(String chargeType) { this.chargeType = chargeType == null ? null : chargeType.trim(); } public String getPayWay() { return payWay; } public void setPayWay(String payWay) { this.payWay = payWay == null ? null : payWay.trim(); } public String getHospitalMark() { return hospitalMark; } public void setHospitalMark(String hospitalMark) { this.hospitalMark = hospitalMark == null ? null : hospitalMark.trim(); } public String getTrandeNo() { return trandeNo; } public void setTrandeNo(String trandeNo) { this.trandeNo = trandeNo == null ? null : trandeNo.trim(); } public String getRcptNo() { return rcptNo; } public void setRcptNo(String rcptNo) { this.rcptNo = rcptNo == null ? null : rcptNo.trim(); } public String getResultComment() { return resultComment; } public void setResultComment(String resultComment) { this.resultComment = resultComment == null ? null : resultComment.trim(); } public String getOrigTradeNo() { return origTradeNo; } public void setOrigTradeNo(String origTradeNo) { this.origTradeNo = origTradeNo == null ? null : origTradeNo.trim(); } public Short getVisitId() { return visitId; } public void setVisitId(Short visitId) { this.visitId = visitId; } public String getOperDate() { return operDate; } public void setOperDate(String operDate) { this.operDate = operDate == null ? null : operDate.trim(); } }
Java
UTF-8
2,687
3.171875
3
[]
no_license
package model; public class Tort { private int szamlalo; private int nevezo; public Tort(int szamlalo, int nevezo) { this.szamlalo = szamlalo; if (nevezo != 0) { this.nevezo = nevezo; } else { this.nevezo = 1; System.err.println("Nevezőben 0 nem lehet"); } egyszerusit(); } public Tort(int szamlalo) { this.szamlalo = szamlalo; this.nevezo = 1; } public void egyszerusit() { if (szamlalo == nevezo) { szamlalo = nevezo = 1; } else { int i; int a = (szamlalo>=0) ? (szamlalo):(szamlalo*-1); int b = (nevezo>=0) ? (nevezo):(nevezo*-1); if (a < b) { i = a; a = b; b = i; } i = b; while (a % i != 0 || b % i != 0) { i = i - 1; } szamlalo/=i; nevezo/=i; } } public Tort osszead(Tort t) { Tort tmp = new Tort(1); if (this.nevezo==t.nevezo){ tmp.setNevezo(this.nevezo); tmp.setSzamlalo(this.szamlalo+t.szamlalo); } else { int i; int a = (szamlalo>=0) ? (szamlalo):(szamlalo*-1); int b = (nevezo>=0) ? (nevezo):(nevezo*-1); if (a < b) { i = a; a = b; b = i; } i = b; while (a % i != 0 || b % i != 0) { i = i - 1; } i=(this.nevezo*t.nevezo)/i; tmp.setNevezo(i); a = (i/this.nevezo)*this.szamlalo; b = (i/t.nevezo)*t.szamlalo; tmp.setSzamlalo(a+b); } tmp.egyszerusit(); return tmp; } public Tort kivon(Tort t){ return this.osszead(new Tort(-t.szamlalo, t.nevezo)); } public Tort szoroz(Tort t) { Tort tmp = new Tort(this.szamlalo * t.szamlalo, this.nevezo * t.nevezo); return tmp; } public Tort oszt(Tort t) { Tort tmp = new Tort(this.szamlalo * t.nevezo, this.nevezo * t.szamlalo); return tmp; } public Tort reciprok() { Tort tmp = new Tort(this.nevezo, this.szamlalo); return tmp; } public int getSzamlalo() { return szamlalo; } public void setSzamlalo(int szamlalo) { this.szamlalo = szamlalo; } public int getNevezo() { return nevezo; } public void setNevezo(int nevezo) { this.nevezo = nevezo; } public void println() { System.out.println(szamlalo + "/" + nevezo); } }
JavaScript
UTF-8
18,470
2.546875
3
[]
no_license
////бургер меню//////// var navburlink = document.querySelector('.nav__burger-button'); var navadapt = document.querySelector('.burgerclick'); navburlink.addEventListener('click', toggleClass); var navadaptlink = document.querySelectorAll ("a.burgerclick__link"); for (var link of navadaptlink){ link.addEventListener('click', toggleClass); } function toggleClass() { navburlink.classList.toggle("nav__burger-button__active"); navadapt.classList.toggle("burgerclick_active"); } /*const hamburger = document.querySelector(".nav__burger-button"); const fixedMenu = document.querySelector(".burgerclick"); hamburger.addEventListener('click', function () { fixedMenu.classList.toggle('burgerclick__open'); document.body.classList.toggle('scroll-block'); hamburger.classList.toggle("nav__burger-button__active"); });*/ ///////команда////// function accordeon(btn) { $(btn).on("click", function () { let thisBtn = this; $(btn).each(function (index, element) { let accordItem = $(this).parent(); if (thisBtn == element) { if (accordItem.hasClass("team__item--active")) { accordItem.removeClass("team__item--active"); } else { accordItem.addClass("team__item--active"); } } else { if (accordItem.hasClass("team__item--active")) { accordItem.removeClass("team__item--active"); } } }) }); } accordeon(".team__link"); ////////отзывы///////// function openReviews() { const openButton = document.querySelectorAll(".button--btn"); for (var button of openButton) { button.addEventListener('click', function(e) { let content = e.target.previousElementSibling.textContent; let title = e.target.previousElementSibling.previousElementSibling.textContent; if (e.target.classList.contains("button--desctop")) { document.body.appendChild(openOverlay(content, title)); } else { content = e.target.previousElementSibling.previousElementSibling.textContent; title = e.target.previousElementSibling.previousElementSibling.previousElementSibling.textContent; document.body.appendChild(openOverlay(content, title)); } }); } } openReviews() function openOverlay(content, title) { const overlayElement = document.createElement("div"); overlayElement.classList.add("overlay"); overlayElement.addEventListener("click", e => { if (e.target === overlayElement) { closeElement.click(); } }); const containerElement = document.createElement("div"); containerElement.classList.add("overlaycontainer"); const contentElement = document.createElement("div"); contentElement.classList.add("overlaycontent"); contentElement.innerHTML = content; const titleElement = document.createElement("h3"); titleElement.classList.add("overlaytitle"); titleElement.textContent = title; const closeElement = document.createElement("a"); closeElement.classList.add("close"); closeElement.textContent = "x"; closeElement.href = "#"; closeElement.addEventListener("click", function() { document.body.removeChild(overlayElement); }); closeElement.addEventListener('click', function(event) { event.preventDefault(); }); overlayElement.appendChild(containerElement); containerElement.appendChild(closeElement); containerElement.appendChild(titleElement); containerElement.appendChild(contentElement); return overlayElement; }; //меню// function accordionMenu() { const menuItem = document.querySelectorAll(".menu__item"); const menuAccord = document.querySelector(".menu__list"); menuAccord.addEventListener("click", event => { let target = event.target.parentNode; let item = target.parentNode; let content = target.nextElementSibling; console.log(event.target); const listWidth = target.clientWidth; const windowWidth = document.documentElement.clientWidth; const layoutContentWidth = 480; const breakpointPhone = 480; const closeMenuWidth = listWidth * menuItem.length; const openMenuWidth = closeMenuWidth + layoutContentWidth; if (event.target.classList.contains("menu__text")) { menus() } target = event.target; item = target.parentNode; content = target.nextElementSibling; if (target.classList.contains("menu__button")) { menus() } function menus() { for (const iterator of menuItem) { if (iterator !== item) { iterator.classList.remove("menu__item--active"); iterator.lastElementChild.style.width = 0; menuAccord.style.transform = 'translateX(0)'; } } if (item.classList.contains("menu__item--active")) { item.classList.remove("menu__item--active"); content.style.width = 0; } else { item.classList.add("menu__item--active"); if (windowWidth > breakpointPhone && windowWidth < openMenuWidth) { content.style.width = windowWidth - closeMenuWidth + 'px'; } else if (windowWidth <= breakpointPhone) { let num for (let i = 0; i < menuItem.length; i++) { if(menuItem[i] === item) { num = menuItem.length - (i + 1) } } menuAccord.style.transform = `translateX(${listWidth * num}px)`; content.style.width = windowWidth - listWidth + 'px'; } else { content.style.width = layoutContentWidth + 'px'; } } } }); } accordionMenu() ///////слайдер/////// const list = document.querySelector(".slider__list"); const widthContainer = document.querySelector('.slider__wrap').clientWidth; const controls = document.querySelector('.slider__arrows'); var pos = 0; function calcWidthList() { const itemCount = list.children.length; const widthList = itemCount * widthContainer; list.style.width = `${widthList}px`; } function handlerClick(event) { if (event.target.tagName === 'BUTTON') { slide(event.target); } } function slide(target) { const vector = target.dataset.vector; switch (vector) { case 'next': slideTo(vector); break; case 'prev': slideTo(vector); break; } } function slideTo(vector) { const active = document.querySelector('.active'); if (vector === 'next') { var nextElement = active.nextElementSibling; } else { var prevElement = active.previousElementSibling; } if (nextElement) { pos -= widthContainer; active.classList.remove('active'); nextElement.classList.add('active'); translate(pos); } else if (prevElement) { pos += widthContainer; active.classList.remove('active'); prevElement.classList.add('active'); translate(pos); } } function translate(pos) { list.style.transform = `translateX(${pos}px)`; } controls.addEventListener('click', handlerClick); window.addEventListener('load', calcWidthList); ////////форма//////// const myForm = document.querySelector ('.form'); const sendButton = document.querySelector('.payment__button'); sendButton.addEventListener('click', e => { e.preventDefault(); if (validateForm(myForm)) { console.log('right'); const data = { name: myForm.elements.name.value, phone: myForm.elements.phone.value, comment: myForm.elements.comment.value, to: "mail@mail.ru" }; const xhr = new XMLHttpRequest(); var openOverlayForm; xhr.responseType = "json"; xhr.open( 'POST', 'https://webdev-api.loftschool.com/sendmail'); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.send(JSON.stringify(data)); xhr.addEventListener('load', function() { if (xhr.status === 200) { document.body.appendChild(openOverlayForm(xhr.response.message)); } else { document.body.appendChild(openOverlayForm(xhr.response.message)); } }); } function openOverlayForm(content) { const overlayElement = document.createElement("div"); overlayElement.classList.add("over-lay"); overlayElement.addEventListener("click", e => { if (e.target === overlayElement) { closeElement.click(); } }); const containerElement = document.createElement("div"); containerElement.classList.add("overlay-container"); const contentElement = document.createElement("div"); contentElement.classList.add("overlay-content"); contentElement.innerHTML = content; const closeElement = document.createElement("button"); closeElement.classList.add("button_close"); closeElement.textContent = "закрыть"; closeElement.addEventListener("click", function() { document.body.removeChild(overlayElement); }); overlayElement.appendChild(containerElement); containerElement.appendChild(contentElement); containerElement.appendChild(closeElement); return overlayElement; } function validateForm(form){ let valid = true; if (!validateField(form.elements.name)) { valid = false; } if (!validateField(form.elements.phone)) { valid = false; } if (!validateField(form.elements.comment)) { valid = false; } return valid; } function validateField(formblock) { formblock.nextElementSibling.textContent = formblock.validationMessage; return formblock.checkValidity(); } }) //map// ymaps.ready(init); function init() { var map = new ymaps.Map('map',{ center: [59.92, 30.32], zoom:12, controls:['zoomControl'], behaviors: ['drag'] }); var placemark = new ymaps.Placemark([59.97, 30.31] , { hintContent: 'BurgerShop' } , { iconImageHref: 'png/mapmarker.png', iconImageSize: [46, 57], iconImageOffset: [-23, -57], iconLayout: 'default#image' }); var placemark2 = new ymaps.Placemark([59.94, 30.38] , { hintContent: 'BurgerShop' } , { iconLayout: 'default#image', iconImageHref: 'png/mapmarker.png', iconImageSize: [46, 57], iconImageOffset: [-23, -57] }); var placemark3 = new ymaps.Placemark([59.91, 30.49] , { hintContent: 'BurgerShop' } , { iconLayout: 'default#image', iconImageHref: 'png/mapmarker.png', iconImageSize: [46, 57], iconImageOffset: [-23, -57] }); map.geoObjects.add(placemark); map.geoObjects.add(placemark2); map.geoObjects.add(placemark3); } //api video player// let player; function onYouTubeIframeAPIReady() { player = new YT.Player("youtubeplayer", { width: "660", height: "405", videoId: "DY_RHowHIFs", playerVars: { controls: 0, showinfo: 0, autoplay: 0, modestbranding: 0, disablekb: 0, rel: 0 }, events: { onReady: onPlayerReady, } }); } function onPlayerReady() { const duration = player.getDuration(); let interval; clearInterval(interval); interval = setInterval(() => { const completed = player.getCurrentTime(); const percent = (completed / duration) * 100; changeButtonPosition(percent); }, 1000); } const playerStart = document.querySelector('.player__start'); $('.player__start').on("click", e => { e .preventDefault() const block = $(e.currentTarget); const playerStatus = player.getPlayerState(); if (playerStatus !== 1) { player.playVideo(); $('.player__arrow').addClass('none'); $('.player__start').addClass('paused'); } else { player.pauseVideo(); $('.player__arrow').removeClass('none'); $('.player__start').removeClass('paused'); } }); $('.player__arrow').on("click", e => { e .preventDefault() $('.player__arrow').addClass('none'); $('.player__start').addClass('paused'); player.playVideo(); }); $('.player__back').on('click', e => { e.preventDefault() const bar = $(e.currentTarget); const newButtonPosition = e.pageX - bar.offset().left; const clickedPercent = (newButtonPosition / bar.width()) * 100; const newPlayerTime = (player.getDuration() / 100) * clickedPercent; player.seekTo(newPlayerTime); changeButtonPosition(percent); }) $('.player__volume-line').on('click', e => { e.preventDefault() const volume = 100; const volumeLine = $(e.currentTarget); const newVolumePosition = e.pageX - volumeLine.offset().left; const clickedVolumePercent = (newVolumePosition / volumeLine.width()) * 100; const newVolume = (volume / 100) * clickedVolumePercent; player.setVolume(newVolume); changeVolumePosition(newVolume); }) function changeButtonPosition(percent) { $('.player__back-button').css({ left: `${percent}%` }); } function changeVolumePosition(newVolume) { $('.player__volume-button').css({ left: `${newVolume}%` }); } //onePage scroll// (function () { const container = document.querySelector('.wrapper'); const nav = document.querySelector('.switcher'); const menu = document.querySelector('.navigation__list'); const burgerClick = document.querySelector('.burgerclick__list'); const orderButton = document.querySelectorAll('.button--knock'); const mainDown = document.querySelector('.main__down-link'); const duration = 1500; let posY = 0; let isAmimate = false window.addEventListener('wheel', handlerWheel); nav.addEventListener('click', handlerClick); menu.addEventListener('click', menuHandlerClick); burgerClick.addEventListener('click', burgerClickHandlerClick); mainDown.addEventListener('click', downHandlerClick); function downHandlerClick(e) { e.preventDefault(); if (e.target.parentNode.tagName === "A") { const index = e.target.parentNode.getAttribute('href'); const [active, activenav] = getActives(); reActive(false, active, 'section', null, index); reActive(false, activenav, 'switcher__item', null, index); posY = index; translate(posY); } } function burgerClickHandlerClick(e) { e.preventDefault(); if (e.target.tagName === 'A') { const index = e.target.getAttribute('href'); const [active, activenav, activemenu, activetabletMenu] = getActives(); reActive(false, active, 'section', null, index); reActive(false, activenav, 'switcher__item', null, index); posY = index; translate(posY); } } function buttonHandlerClick(e) { e.preventDefault(); if (e.target.tagName === 'A') { const index = e.target.getAttribute('href'); const [active, activenav, activebutton] = getActives(); reActive(false, active, 'section', null, index); reActive(false, activenav, 'switcher__item', null, index); posY = index; translate(posY); } } for (btn of orderButton) { btn.addEventListener('click', buttonHandlerClick); } function menuHandlerClick(e) { e.preventDefault(); if (e.target.tagName === 'A') { const index = e.target.getAttribute('href'); const [active, activenav, activemenu] = getActives(); reActive(false, active, 'section', null, index); reActive(false, activenav, 'switcher__item', null, index); posY = index; translate(posY); } } function handlerClick(e) { e.preventDefault(); if (e.target.tagName === 'A') { const index = e.target.getAttribute('href'); const [active, activenav, activemenu] = getActives(); reActive(false, active, 'section', null, index); reActive(false, activenav, 'switcher__item', null, index); posY = index; translate(posY); } } function handlerWheel(e) { if (isAmimate) return; if (e.deltaY > 0) { const isNext = isSlide('next'); slideTo(isNext, 'next'); } else { const isPrev = isSlide('previous'); slideTo(isPrev, 'prev'); } } function slideTo(resolve, vector) { if (vector === 'next' && resolve) { posY++; translate(posY); } if (vector === 'prev' && resolve) { posY--; translate(posY); } } function translate(pos) { container.style.transform = `translate3d(0, ${-pos * 100}%,0)`; container.style.transition = `all ${duration}ms ease 0s`; isAmimate = true setTimeout(() => { isAmimate = false; }, duration) } function isSlide(vector) { const [active, activenav] = getActives() if (active[`${vector}ElementSibling`]) { reActive(true, active, 'section', vector); reActive(true, activenav, 'switcher__item', vector); return true } } function reActive(isSibling, elem, _class, vector, index) { if (isSibling) { elem.classList.remove(`${_class}_active`); elem[`${vector}ElementSibling`].classList.add(`${_class}_active`); } else { elem.classList.remove(`${_class}_active`); document.querySelectorAll(`.${_class}`)[index].classList.add(`${_class}_active`); } } function getActives() { const active = document.querySelector('.section_active'); const activenav = document.querySelector('.switcher__item_active'); return [active, activenav]; } })();
TypeScript
UTF-8
831
2.703125
3
[ "ISC" ]
permissive
export abstract class SnippetFactory { constructor(protected snippet: string) { } public createSnippetWithNoBlanksAround(): string { return this.snippet .replace(/%BLANK_BEFORE%\n/g, '') .replace(/%BLANK_AFTER%\n/g, ''); } public createSnippetWithBlanksAround(): string { return this.snippet .replace(/%BLANK_BEFORE%\n/g, '\n') .replace(/%BLANK_AFTER%\n/g, '\n'); } public createSnippetWithBlanksOnlyBefore(): string { return this.snippet .replace(/%BLANK_BEFORE%\n/g, '\n') .replace(/%BLANK_AFTER%\n/g, ''); } public createSnippetWithBlanksOnlyAfter(): string { return this.snippet .replace(/%BLANK_BEFORE%\n/g, '') .replace(/%BLANK_AFTER%\n/g, '\n'); } }
Python
UTF-8
3,591
2.859375
3
[]
no_license
# @Time : 2019-04-07 11:06:48 # @Author : lemon_xiuyu # @Email : 5942527@qq.com # @File : test_login.py import unittest from common.do_excel import DoExcel # 引入读写类 from common.request import Request # 引入请求类 from common import contants, logger # 引入常量 ,同时引入两个 # from ddt import ddt, data from libext.ddtnew import ddt, data # mango老师复制更改的ddt logger = logger.get_logger(logger_name='login') # 获取logger实例 # 一个接口一个类,一个类一个方法 #如此模块 ,100个接口100个py文件,有的接口要数据校验,有的不需要数据校验。 # 一个类,多个方法,多个接口 #如text_api.py # 一个类,一个方法,全部接口----老师不建议后面接口会复杂,但如果接口是非常简单的调用然后判断返回,这种方式是最省事的,自己实践 @ddt class LoginTest(unittest.TestCase): # 可类里,也可模块外 do_excel = DoExcel(contants.case_file) # 传入cases.xlsx cases = do_excel.read('login') request = Request() # 实例化一个对象 # 可类里,也可模块外 def setUp(self): pass @data(*cases) # 此处传入数据,so读数据就要从test_login()方法移到方法外面,for case in cases:也需删掉 def test_login(self, case): # 加case接收解包数据 logger.info("开始执行第{0}行用例".format(case.case_id)) # 使用分装好的request来完成请求 resp = self.request.request(case.method, case.url, case.data) # 实例对象已移到外面,这里要加self. # 将返回结果与期望结果对比 # 当用unittest时,比对用断言,不用if恒等==手动了 try: self.assertEqual(case.expected, resp.text, 'login error') # 一致就写入Excel的结果PASS self.do_excel.write_back(case.case_id + 1, resp.text, 'PASS') # 实例对象已放外面,类变量加self. logger.info("第{0}行用例执行结果:PASS".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id + 1, resp.text, 'FAIL') # 实例对象已放外面,类变量加self.调用 logger.error("断言出错了:{}".format(e)) logger.error("第{0}行用例执行结果:FAIL".format(case.case_id)) raise e def tearDown(self): pass """ 执行的时候一定要写main函数吗? (鼠标右键test_案例,与右键class类,运行不一样) 如何不写mai 又能去run? Pycharm右上角播放左侧按钮点击- Edit Configurations左上角+加号- Python tests- Unitteses- 会生成一个Unnamed- 右侧Unittests里Target:选Module name执行- 点右侧三个点- 进入搜索test_login选模块而不是方法- 点OK- 顶部Name改名字为Unittests- 点右下角Apply- 再点OK- 此时运行的时候不需要鼠标右键点运行- 而是Pycharm右上角的运行播放按钮。 但这样对Unittest来说只运行了一个用例---看左下角,但实际对test_login这个方法工作台运行了6个用例。 Project: 选根目录 Python interpreter:选根目录 这俩不一样会导致运行失败,通过右上角点Unittests和在函数外点鼠标右键运行很像 基于这种方法相相实现6个用例而不是1个用例怎么办?----用ddt,再运行之后就发现左下角变6个用例了 unittest没有这功能,但ddt可再unittest基础上实现此功能 未来多个接口(多个sheet表单)是用一个TestCase执行还是用多个TestCase来执行? """
Java
UTF-8
2,438
2.65625
3
[]
no_license
package com.ollijepp.poastr.shared.socialService; import java.util.ArrayList; import java.util.List; import com.google.inject.Inject; import com.google.inject.Singleton; import com.ollijepp.poastr.client.DataAdapter; import com.ollijepp.poastr.client.crypto.ClipperzCrypto; import com.ollijepp.poastr.shared.socialService.ServiceProvider.AuthMethod; /** * This factory makes available a list of service providers, which should * be displayed in some manner. It then builds SocialService objects (accounts) * using a copy of one of these providers, and the necessary user info. * * It also makes available methods to retrieve the clear text of the user- * names and passwords of the accounts. * * @author Oliver Uvman * */ @Singleton public class SocialServiceFactory { private final DataAdapter dataAdapter; //private final ArrayList<ServiceProvider> serviceProviders; @Inject public SocialServiceFactory(DataAdapter dataAdapter) { this.dataAdapter = dataAdapter; } public static List<ServiceProvider> getProviders() { ArrayList<ServiceProvider> serviceProviders = new ArrayList<ServiceProvider>(); serviceProviders.add(new FacebookProvider()); serviceProviders.add(new TwitterProvider()); return serviceProviders; } public SocialService buildSocialService(ServiceProvider serviceProvider, String accountOwner, String userName, String password){ SocialService prototype = serviceProvider.getPrototype(); prototype.setAccountOwnerHashed(hash(accountOwner)); prototype.setUserNameEncrypted(encrypt(userName)); if(serviceProvider.getAuthMethod() == AuthMethod.Password){ prototype.setPasswordEncrypted(encrypt(password)); } return prototype; } public static String getHash(String accountOwnerClearText){ return hash(accountOwnerClearText); } public String getClearTextName(SocialService account){ return decrypt(account.getUserNameEncrypted()); } public String getClearTextPassword(SocialService account){ return decrypt(account.getPasswordEncrypted()); } private static String hash(String clearText){ return ClipperzCrypto.hash(clearText); } private String encrypt(String clearText){ return ClipperzCrypto.encrypt(clearText, dataAdapter.getPassPhrase()); } private String decrypt(String cryptoText){ return ClipperzCrypto.decrypt(cryptoText, dataAdapter.getPassPhrase()); } }
Java
UTF-8
7,467
2.15625
2
[]
no_license
/* */ package net.risenphoenix.commons.localization; /* */ /* */ import java.io.File; /* */ import java.util.HashMap; /* */ import java.util.Map; /* */ import java.util.Map.Entry; /* */ import java.util.logging.Level; /* */ import net.risenphoenix.commons.Plugin; /* */ import net.risenphoenix.commons.stores.LocalizationStore; /* */ import org.bukkit.configuration.file.FileConfiguration; /* */ import org.bukkit.configuration.file.YamlConfiguration; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class LocalizationManager /* */ { /* */ private Map<String, String> translation; /* */ private Map<String, String> defaultTranslation; /* */ private String selectedLanguage; /* */ private FileConfiguration loadedLanguage; /* */ /* */ public LocalizationManager(Plugin plugin, String langID) /* */ { /* 51 */ File f = new File(plugin.getDataFolder() + File.separator + langID + ".yml"); /* */ /* */ /* 54 */ if (f.exists()) { /* 55 */ this.selectedLanguage = langID; /* */ } else { /* 57 */ this.selectedLanguage = "en"; /* 58 */ if (!langID.equalsIgnoreCase("en")) { plugin.sendConsoleMessage(Level.WARNING, "Translation Index " + langID + ".yml " + "could not be found. Falling back to Default Translation " + "(English)."); /* */ } /* */ } /* */ /* */ /* */ /* 64 */ loadTranslation(f); /* */ } /* */ /* */ private final void loadTranslation(File path) { /* 68 */ if ((!this.selectedLanguage.equals("en")) || (!this.selectedLanguage.isEmpty())) { /* 69 */ this.loadedLanguage = YamlConfiguration.loadConfiguration(path); /* 70 */ initializeTranslationIndex(); /* */ } /* */ /* */ /* 74 */ loadDefaultTranslation(); /* */ } /* */ /* */ private final void initializeTranslationIndex() { /* 78 */ this.translation = new HashMap(); /* */ /* 80 */ for (Map.Entry<String, Object> entry : this.loadedLanguage.getValues(true) /* 81 */ .entrySet()) { /* 82 */ this.translation.put(entry.getKey(), entry.getValue().toString()); /* */ } /* */ } /* */ /* */ private final void loadDefaultTranslation() { /* 87 */ this.defaultTranslation = new HashMap(); /* */ /* */ /* */ /* */ /* 92 */ this.defaultTranslation.put("NO_IMPLEMENT", "Base class does not implement."); /* */ /* 94 */ this.defaultTranslation.put("CMD_REG_ERR", "Failed to register command. Perhaps it is already registered? Command-ID: "); /* */ /* 96 */ this.defaultTranslation.put("NUM_ARGS_ERR", "An incorrect number of arguments was specified."); /* */ /* 98 */ this.defaultTranslation.put("ILL_ARGS_ERR", "An illegal argument was passed into the command."); /* */ /* 100 */ this.defaultTranslation.put("PERMS_ERR", "You do not have permission to execute this command."); /* */ /* 102 */ this.defaultTranslation.put("NO_CONSOLE", "This command cannot be executed from Console."); /* */ /* 104 */ this.defaultTranslation.put("NO_CMD", "An invalid command was specified."); /* */ /* 106 */ this.defaultTranslation.put("CMD_NULL_ERR", "An error occurred while generating a Command Instance. The command has been aborted."); /* */ /* 108 */ this.defaultTranslation.put("BAD_PARSE_SET", "The parse instructions for this Parser have not been determined. Please override method Parser.parseCommand() in your parsing class."); /* */ /* */ /* */ /* */ /* 113 */ this.defaultTranslation.put("BAD_CFG_SET", "Failed to register Configuration Option. Perhaps it is already specified? Cfg-ID: "); /* */ /* */ /* 116 */ this.defaultTranslation.put("CFG_INIT_ERR", "The Configuration could not be refreshed because it has not yet been initialized."); /* */ /* */ /* */ /* 120 */ this.defaultTranslation.put("DB_CNCT_ERR", "An error occurred while attempting to connect to the database."); /* */ /* 122 */ this.defaultTranslation.put("BAD_DB_DRVR", "The database driver requested could not be found. Requested driver: "); /* */ /* 124 */ this.defaultTranslation.put("DB_OPEN_SUC", "Established connection to database."); /* */ /* 126 */ this.defaultTranslation.put("DB_CLOSE_SUC", "The connection to the database was closed successfully."); /* */ /* 128 */ this.defaultTranslation.put("DB_CLOSE_ERR", "An error occurred while attempting to close the connection to the database. Error: "); /* */ /* 130 */ this.defaultTranslation.put("DB_QUERY_ERR", "An error occurred while attempting to query the database. Error: "); /* */ /* 132 */ this.defaultTranslation.put("DB_QUERY_RETRY", "Retrying Query..."); /* 133 */ this.defaultTranslation.put("DB_PREP_STMT_ERR", "An error occurred while attempting to generate a prepared statement for the database."); /* */ /* */ /* 136 */ this.defaultTranslation.put("DB_DEBUG_ACTIVE", "Database Debugging is active. All SQL queries will be logged as they are received."); /* */ /* */ /* 139 */ this.defaultTranslation.put("BAD_SQL_INPUT", "A parameter passed to the StatementObject is invalid! Valid parameters are those of type String and type Integer."); /* */ } /* */ /* */ /* */ public final String getLocalString(String key) /* */ { /* */ String value; /* */ /* 147 */ if (this.translation != null) { /* 148 */ String value = (String)this.translation.get(key); /* */ /* */ /* 151 */ if ((value == null) || (value.equals("null"))) { /* 152 */ value = (String)this.defaultTranslation.get(key); /* */ } /* */ } else { /* 155 */ value = (String)this.defaultTranslation.get(key); /* */ } /* */ /* 158 */ if ((value == null) || (value.equals("null")) || (value.isEmpty())) { /* 159 */ return "Invalid Translation-Key: " + key; /* */ } /* 161 */ return value; /* */ } /* */ /* */ public final void addDefaultValue(String key, String value) /* */ { /* 166 */ this.defaultTranslation.put(key, value); /* */ } /* */ /* */ public final void appendLocalizationStore(LocalizationStore values) { /* 170 */ Map<String, String> finalMap = new HashMap(); /* 171 */ finalMap.putAll(this.defaultTranslation); /* 172 */ finalMap.putAll(values.getValues()); /* */ /* 174 */ this.defaultTranslation = finalMap; /* */ } /* */ } /* Location: D:\[ Plugins ] Minecraft - Editar\IP-Check.jar!\net\risenphoenix\commons\localization\LocalizationManager.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
Python
UTF-8
3,057
3.265625
3
[]
no_license
# Importing necessary packages import tensorflow as tf import numpy as np from lr_utils import load_dataset import matplotlib.pyplot as plt %matplotlib inline # Loading the training data train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes = load_dataset() train_set_x_orig.shape train_set_y_orig.shape # Assigning number of training examples, number of features to corresponding variables m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] # Reshaping the training set to be able to fit the model train_x_flat = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T test_x_flat = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T train_x_flat.shape # Preprocessing the data train_x = train_x_flat/255. test_x = test_x_flat/255. # Declaring X, y placeholder variables so that they can be fit during running the session X = tf.placeholder(tf.float32, shape=[12288,None]) y = tf.placeholder(tf.float32, shape=[1,None]) # Setting seed so that everytime we run it generates same random numbers tf.set_random_seed(1) # Initializing weights and biases W = tf.Variable(tf.random_normal([1,12288],stddev=0.35)) b = 0 # Defining Activation function Z = tf.sigmoid(tf.add(tf.matmul(W,X),b)) # Defining Logistic Loss function loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Z, labels=y)) # Defining the gradient descent optimizer opt = tf.train.GradientDescentOptimizer(learning_rate=0.0001).minimize(loss) init = tf.global_variables_initializer() # Opening the session with tf.Session() as sess: sess.run(init) # Initializing writer to save the graph writer = tf.summary.FileWriter('./graphs/logistic_reg', sess.graph) # Training the model for 500 iterations for i in range(500): _,cost = sess.run([opt,loss], feed_dict={X:train_x,y:train_set_y_orig}) # Printing cost for every 10 epochs if i%100==0: print("Cost in Epoch-"+ str(i)+": "+str(cost)) # Closing writer writer.close() # Saving the trained parameters parameters = sess.run(W,b) # Printing accuracy y_pred = predict(train_x,parameters) print("train accuracy: {} %".format(100 - np.mean(np.abs(y_pred - train_set_y_orig)) * 100)) # Importing packages to get input image to be predicted and preprocess it to shape the algorithm expects import scipy from PIL import Image from scipy import ndimage # Input image to predict my_image = "dog.jpg" fname = my_image image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(64,64)).reshape((1, 64*64*3)).T my_image = my_image/255. parameters = tf.cast(parameters, tf.float64) # Calling predict function my_image_prediction = predict(my_image, parameters) plt.imshow(image) if np.squeeze(my_image_prediction) > 0.80: print("The algorithm predicts cat "+"with probability "+ str(np.squeeze(my_image_prediction))) else: print("The algorithm predicts not cat "+"with probability "+ str(np.squeeze(my_image_prediction)))
Markdown
UTF-8
172
2.515625
3
[]
no_license
# pangrams ruby pangrams challenge Simple challenge to create a function that takes a sentence and returns "pangrams" if sentence is a pangram or "not pangram" if not.
Python
UTF-8
473
3.953125
4
[]
no_license
""" Write a function that changes every letter to the next letter: * "a" becomes "b" * "b" becomes "c" * "d" becomes "e" * and so on ... ### Examples move("hello") ➞ "ifmmp" move("bye") ➞ "czf" move("welcome") ➞ "xfmdpnf" ### Notes There will be no z's in the tests. """ def move(word): final_string = '' word_2 = [ord(i)+1 for i in word] for i in word_2: final_string = final_string + chr(i) return final_string
TypeScript
UTF-8
1,938
2.734375
3
[ "MIT" ]
permissive
import "introcs"; import { SVG, Group, Color, Rectangle } from "introcs/graphics"; import { Emoji } from "./Emoji"; const searchBar: HTMLInputElement = document.getElementById("searchBar") as HTMLInputElement; function main(): void { toggle(); // calls the emoji toggle function // pageSwitch(); fakeSearch(); } // function pageSwitch(): void { // searchBar.onsubmit = function(event: KeyboardEvent): void { // alert("hey"); // }; // } function toggle(): void { let scene: Group = initScene(); let clicks: number = -1; let icon: Emoji = new Emoji(-1, new Color(0.884, 0.088, 0.088)); scene.add(icon.shapes()); document.onclick = function(event: MouseEvent): void { clicks++; if (clicks % 3 === 1) { // happy icon = new Emoji(0, new Color(0.957, 0.792, 0.098)); scene.add(icon.shapes()); } else if (clicks % 3 === 2) { // meh icon = new Emoji(-1, new Color(0.884, 0.088, 0.088)); scene.add(icon.shapes()); } else { // mad icon = new Emoji(1, new Color(0.676, 0.876, 0.249)); scene.add(icon.shapes()); } }; } function fakeSearch(): void { let name1: string = "Cynthia Dong"; let name2: string = "Samuel Zhang"; let name: string = ""; let count: number = 0; if (window.location.href === "http://localhost:3000/RateMyStudent/assets/html/page2.html") { name = name2; } else { name = name1; } if (count < name.length) { searchBar.onkeyup = function(event: KeyboardEvent): void { searchBar.value = name.slice(0, searchBar.value.length); count++; }; } else { searchBar.value = name; } } function initScene(): Group { let svgTag: SVG = new SVG("artboard"); svgTag.autoScale = true; let scene: Group = new Group(); svgTag.render(scene); return scene; } main();
JavaScript
UTF-8
4,508
2.640625
3
[]
no_license
// Runner prefab class Runner extends Phaser.Physics.Arcade.Sprite{ constructor(scene, x, y, texture, frame, pointValue, direction) { super(scene, x, y, texture, frame); this.direction = direction; // add object to the existing scene scene.add.existing(this); scene.physics.add.existing(this); this.ACCELERATION = 500; this.MAX_X_VEL = 300; // pixels/second this.MAX_Y_VEL = 1500; this.DRAG = 600; this.JUMP_VELOCITY = -650; this.finishedLevel = false; this.body.setMaxVelocity(this.MAX_X_VEL, this.MAX_Y_VEL); // this.setAccelerationX(this.scene.runnerAccelerationX); // allow player to jump through platforms this.body.checkCollision.up = false; // set the double jump state this.doubleJump = false; // playerOne animation config this.scene.anims.create({ key: 'playerWalkAni', frames: this.scene.anims.generateFrameNumbers('playerRun', {start: 0, end: 8, first: 0}), repeat: -1, frameRate: 15 }); this.scene.anims.create({ key: 'playerIdleAni', frames: this.scene.anims.generateFrameNumbers('playerIdle', {start: 0, end: 3, first: 0}), repeat: -1, frameRate: 1 }); this.scene.anims.create({ key: 'playerVictoryAni', frames: this.scene.anims.generateFrameNumbers('playerVictory', {start: 0, end: 16, first: 0}), repeat: 0, frameRate: 5 }); this.scene.anims.create({ key: 'playerJumpAni', frames: this.scene.anims.generateFrameNumbers('playerjump', {start: 0, end: 3, first: 0}), repeat: 0, frameRate: 15 }); } update() { this.running(); this.moveForward(); this.directionChange(); this.unTunnel(); if (Phaser.Input.Keyboard.JustDown(keyUP)) { this.jump(); } this.levelFinish(); } reset() { } moveForward() { // this allows the runner to not run into platforms during a jump if (this.body.velocity.y != 0) { this.body.checkCollision.right = false; } else { this.body.checkCollision.right = true; } } running(){ let keyDown = Phaser.Input.Keyboard.JustDown(keyRIGHT); // because justDown can only be called once per loop if (keyDown && this.body.onWall()) { console.log('miniJump ', this.body.velocity.y); this.setVelocityY(this.scene.miniJumpVelocity); } else if (keyDown){ this.setVelocityX(this.scene.runnerVelocityX); } if (Phaser.Input.Keyboard.JustDown(keyLEFT)) { this.setVelocityX(-this.scene.runnerVelocityX); } } // this.body.blocked().right jump() { // make runner go up if (this.body.velocity.y == 0) { // the main jump code console.log('jump one ', this.body.velocity.y) this.setVelocityY(this.scene.jumpVelocity); this.doubleJump = true; } else if (this.doubleJump) { // a second press gives a boost jump console.log('jump two ', this.body.velocity.y) this.setVelocityY(this.scene.doublejumpVelocity); this.doubleJump = false; } } directionChange(){ if (this.body.velocity.x >= 0){ this.flipX = false; } else if (this.body.velocity.x < 0){ this.flipX = true; } } unTunnel(){ if (this.y >= 821){ // if char falls through a tunnel re-spawn this.y = 256; this.x -= 64; this.body.velocity.x = -200; this.body.velocity.y-200; this.scene.sound.play('cameraSound'); } } levelFinish(){ if (this.x >= this.scene.pixelLength) { // stop the runner at level end this.setAccelerationX(0); this.setVelocityX(0); if (!this.finishedLevel) { this.finishedLevel = true; // set flag so these are only done once this.scene.sound.play('sagoi'); this.scene.dialogBox.visible = true; // show dialog at end of level if (this.y > 256){ // lower dialog box if not on platform this.scene.dialogBox.y = 480; } } } } }
C#
UTF-8
652
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Treton.Core.Resources { public interface IResourceLoaders { void Add(uint type, ILoader loader); void Remove(uint type); ILoader Get(uint type); } public class ResourceLoaders : IResourceLoaders { private readonly Dictionary<uint, ILoader> _loaders = new Dictionary<uint, ILoader>(); public void Add(uint type, ILoader loader) { _loaders.Add(type, loader); } public void Remove(uint type) { _loaders.Remove(type); } public ILoader Get(uint type) { return _loaders[type]; } } }
C#
UTF-8
817
2.71875
3
[]
no_license
using System; using System.Diagnostics; namespace JenkinsNotifier { public static class Utilities { public static string Base64Encode(this string plainText) { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } public static string Base64Decode(this string base64EncodedData) { var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } public static void OpenWithDefaultProgram(string path) { Process opener = new Process {StartInfo = {FileName = "explorer", Arguments = "\"" + path + "\""}}; opener.Start(); } } }
SQL
GB18030
7,368
3.28125
3
[]
no_license
--ZLHISִУ޸zlsol룬ipʵ[SERVICE_NAME] create database link ZLSOL_DBL connect to ZLSOL identified by ZLSOL_PASSWORD using '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.60)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = orcl12) ) )'; --Ժ(޸IJID7748) insert into Sol_Inf_Puerpera@ZLSOL_DBL( Pid, Tid, Name, Old, Bedno, Pno, Diagnosis, Status, Outtime) Select b.id, b.ҳid, a., a., a.ǰ, a.סԺ, c., 1 As Status, Null From Ϣ A, Ժ B, ϼ¼ C Where a.id = b.id And a.ҳid = b.ҳid And b.id = 7748 And b.id = c.id And b.ҳid = c.ҳid And c.¼Դ = 3 And c. = 2 And c.ϴ = 1 CREATE OR REPLACE Procedure Zl_Apex_״̬ͬ ( id_In ˱䶯¼.id%Type, ҳid_In ˱䶯¼.ҳid%Type, id_In ˱䶯¼.id%Type, _In Number, --1.ƣ2.ƣ3.Ժ,4-Ժ,5 6.,7.Ժϸ,8,ɾԺ _in ˱䶯¼.%Type, Ժʱ_In ˱䶯¼.ֹʱ%Type := Null ) As n_Count Number(5); n_Mid Number(18); v_bedno varchar(10); Begin Select Count(1) Into n_Count From ˵ Where id = id_In And = ''; If n_Count = 1 Then --1. If _In = 1 Then Select Count(1) Into n_Count From Sol_Inf_Puerpera@ZLSOL_DBL Where Pid = id_In And Tid = ҳid_In; If n_Count = 0 Then Insert Into Sol_Inf_Puerpera@ZLSOL_DBL (Pid, Tid, Name, Old, Bedno, Pno, Diagnosis,status) Select a.id, a.ҳid, a., a., a.ǰ, a.סԺ, c.,0 From Ϣ A, ϼ¼ C Where a.id = id_In And a.ҳid = ҳid_In And a.id = c.id(+) And a.ҳid = c.ҳid(+) And c.¼Դ(+) = 3 And c.(+) = 2 And c.ϴ(+) = 1; End If; Elsif _In = 2 Then Select Nvl(Max(Mid), 0) Into n_Mid From Sol_Inf_Puerpera@ZLSOL_DBL A Where a.Pid = id_In And a.Tid = ҳid_In And a.Status = 0; --δ뷿δд¼ٲ¼ɾ,¼Ѵڣɲд If n_Mid > 0 Then /*Select Count(1) Into n_Count From Sol_Rs_Expectant@ZLSOL_DBL Where Mid = n_Mid; If n_Count = 0 Then Select Count(1) Into n_Count From Sol_Rs_Birth@ZLSOL_DBL Where Mid = n_Mid; If n_Count = 0 Then*/ Delete Sol_Inf_Puerpera@ZLSOL_DBL Where Mid = n_Mid; /* End If; End If;*/ End If; Elsif _In = 3 Then --Ժ Update Sol_Inf_Puerpera@ZLSOL_DBL A Set Status = 3, Outtime = Ժʱ_In Where a.Pid = id_In And a.Tid = ҳid_In; Elsif _In = 4 Then --Ժ Update Sol_Inf_Puerpera@ZLSOL_DBL A Set Status = 2, Outtime = Null Where a.Pid = id_In And a.Tid = ҳid_In And a.Status = 3; Elsif _In = 5 Then -- Update Sol_Inf_Puerpera@ZLSOL_DBL A Set bedno=nvl(_in,'ͥ') Where a.Pid = id_In And a.Tid = ҳid_In; Elsif _In = 6 Then -- select ǰ into v_bedno from Ϣ where id = id_In And ҳid = ҳid_In; Update Sol_Inf_Puerpera@ZLSOL_DBL A Set bedno=v_bedno Where a.Pid = id_In And a.Tid = ҳid_In ; End If; End If; End Zl_Apex_״̬ͬ; / CREATE OR REPLACE Trigger t_Apex_״̬ͬ After Insert Or Delete Or Update On ˱䶯¼ For Each Row Declare v_Err_Msg Varchar2(255); Err_Item Exception; ----1. 2 3.Ժ 4.Ժ 5 6. Begin If Inserting Then -- If :New.ʼԭ In (2, 3) And :New.Ӵλ = 0 Then Zl_Apex_״̬ͬ(:New.id, :New.ҳid, :New.id, 1,:new.); End If; ----- If :New.ʼԭ =4 Then Zl_Apex_״̬ͬ(:New.id, :New.ҳid, :New.id, 5,:new.); End If; Elsif Deleting Then -- If :Old.ʼԭ In (2, 3) Then Zl_Apex_״̬ͬ(:Old.id, :Old.ҳid, :Old.id, 2,:new.); End If; -- If :Old.ʼԭ = 4 Then Zl_Apex_״̬ͬ(:Old.id, :Old.ҳid, :Old.id, 6,:new.); End If; --Ժ Elsif Updating Then If :New.ֹԭ = 1 And :Old.ֹʱ Is Null And :Old.Ӵλ = 0 Then Zl_Apex_״̬ͬ(:New.id, :New.ҳid, :New.id, 3,:new., :New.ֹʱ); End If; --Ժ If :Old.ֹԭ = 1 And :New.ֹʱ Is Null Then Zl_Apex_״̬ͬ(:New.id, :New.ҳid, :New.id, 4,:new.); End If; End If; Exception When Err_Item Then Raise_Application_Error(-20101, '[ZLSOFT]' || v_Err_Msg || '[ZLSOFT]'); When Others Then zl_ErrorCenter(SQLCode, SQLErrM); End t_Apex_״̬ͬ; / Create Or Replace Procedure Zl_Apex_״̬ͬ_ ( id_In ϼ¼.id%Type, ҳid_In ϼ¼.ҳid%Type, _In Number, --1.޸ϣ2.ɾ _In ϼ¼.%Type := Null ) As n_Count Number(5); n_Mid Number(18); Begin Select Count(1) Into n_Count From ϼ¼ a, Ժ b, ˵ c Where a.id = b.id And a.ҳid = b.ҳid And b.id = c.id And c. = '' And a.id = id_In And a.ҳid = ҳid_In; If n_Count = 1 Then If _In = 1 Then Update Sol_Inf_PuerperaZLSOL_DBL Set Diagnosis = _In Where Pid = id_In And Tid = ҳid_In; Elsif _In = 2 Then Update Sol_Inf_PuerperaZLSOL_DBL Set Diagnosis = Null Where Pid = id_In And Tid = ҳid_In; End If; End If; End Zl_Apex_״̬ͬ_; / Create Or Replace Trigger t_Apex_״̬ͬ_ After Insert Or Delete Or Update On ϼ¼ For Each Row Declare v_Err_Msg Varchar2(255); Err_Item Exception; Begin --޸ If Inserting Or Updating Then If :New.¼Դ In (2, 3) And :New. = 2 And :New.ϴ = 1 Then Zl_Apex_״̬ͬ_(:New.id, :New.ҳid, 1, :New.); End If; --ɾ Elsif Deleting Then If :Old.¼Դ In (2, 3) And :New. = 2 And :New.ϴ = 1 Then Zl_Apex_״̬ͬ_(:Old.id, :Old.ҳid, 2); End If; End If; Exception When Err_Item Then Raise_Application_Error(-20101, '[ZLSOFT]' || v_Err_Msg || '[ZLSOFT]'); When Others Then Zl_Errorcenter(Sqlcode, Sqlerrm); End t_Apex_״̬ͬ_;
C
UTF-8
544
2.875
3
[]
no_license
#include <stdlib.h> #include <signal.h> #include <stdio.h> #include <unistd.h> void sig_handler(int signo) { printf("received SIGUSR1\n"); } int main() { if(signal(SIGUSR1, sig_handler) == SIG_ERR){ printf("cannot catch SIGUSR1\n"); } pid_t pid; pid = fork(); if(pid==0){ while(1); } else { kill(pid, SIGUSR1); sleep(1); kill(pid, SIGUSR1); kill(pid, SIGUSR1); kill(pid, SIGUSR1); kill(pid, SIGUSR1); kill(pid, SIGUSR1); kill(pid, SIGUSR1); while (1); } return 0; } // nie sa kolejkowane
C++
UTF-8
1,645
3.203125
3
[]
no_license
#include "SudokuJudger.h" bool SudokuJudger::judgeColumn(int x, int y, int value, int sudoku[LENGTH][LENGTH]) { for (int i = 0; i < x; i++) { if (sudoku[i][y] == value) { return false; } } return true; } bool SudokuJudger::judgeSmallSudoku(int x, int y, int value, int sudoku[LENGTH][LENGTH]) { int startX = x / 3 * 3; int startY = y / 3 * 3; for (int i = startX; i < x; i++) { for (int j = startY; j < startY + 3; j++) { if (sudoku[i][j] == INITDATA) break; else if (sudoku[i][j] == value) { return false; } } } return true; } bool SudokuJudger::meetRequirement(int x, int y, int value, int sudoku[LENGTH][LENGTH]) { return judgeColumn(x, y, value, sudoku) && judgeSmallSudoku(x, y, value, sudoku); } int SudokuJudger::judgeTempRow(int row, int* tempArray, int sudoku[LENGTH][LENGTH]) { int result = this->judgeTempRow(row, 0, tempArray, sudoku); return result; } int SudokuJudger::judgeTempRow(int row, int column, int* tempArray, int sudoku[LENGTH][LENGTH]) { for (int j = column; j < LENGTH; j++) { if (!meetRequirement(row, j, tempArray[j], sudoku)) { return j; } } return -1; } bool SudokuJudger::checkRequirement(int x, int y, int value, int sudoku[LENGTH][LENGTH]) { for (int i = 0; i < LENGTH; i++) { if (sudoku[i][y] == value) { return false; } if (sudoku[x][i] == value) { return false; } } int startX = x / 3 * 3; int startY = y / 3 * 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (sudoku[startX + i][startY + j] == INITDATA) continue; else if (sudoku[startX + i][startY + j] == value) { return false; } } } return true; }
Python
UTF-8
756
2.53125
3
[]
no_license
#!/usr/bin/env python3 import os import argparse import boto3 from datasets import aws_utils def upload(bucket, files, force=False): s3 = boto3.client('s3') aws_utils.upload(s3, bucket, files, force=force) if __name__ == "__main__": # Arg parsing parser = argparse.ArgumentParser(description="Uploads file to public S3") parser.add_argument('cmd', choices=["upload"]) parser.add_argument('files', nargs='*') parser.add_argument('-b', '--bucket', default="public-data-d0nkrs") parser.add_argument('-f', '--force', action='store_true') args = parser.parse_args() if args.cmd == "upload": print(f"Uploading: {args.bucket} {args.files} {args.force}") upload(args.bucket, args.files, force=args.force)
Go
UTF-8
3,049
2.640625
3
[ "MIT" ]
permissive
package main import ( "bufio" "fmt" "go/build" "io" "os" "path" "path/filepath" "golang.org/x/tools/cover" ) func main() { if len(os.Args) != 3 { fmt.Fprintf(os.Stderr, "Usage: %s <profile> <file>\n", os.Args[0]) os.Exit(1) } profiles, err := cover.ParseProfiles(os.Args[1]) if err != nil { fmt.Fprintf(os.Stderr, "cannot parse cover profile %s: %s\n", os.Args[1], err.Error()) os.Exit(1) } f, err := os.Open(os.Args[2]) if err != nil { fmt.Fprintf(os.Stderr, "cannot open %s: %s\n", os.Args[2], err.Error()) os.Exit(1) } defer f.Close() filename, err := getPackagePath(os.Args[2]) if err != nil { fmt.Fprintf(os.Stderr, "cannot find package for %s: %s\n", os.Args[2], err.Error()) os.Exit(1) } var profile *cover.Profile for _, p := range profiles { if p.FileName == filename { profile = p break } } var blocks []cover.ProfileBlock if profile != nil { blocks = profile.Blocks } w := bufio.NewWriter(os.Stdout) if err := annotate(w, f, blocks); err != nil { fmt.Fprintf(os.Stderr, "cannot annotate %s: %s\n", os.Args[2], err.Error()) os.Exit(1) } w.Flush() } func getPackagePath(filename string) (string, error) { abs, err := filepath.Abs(filename) if err != nil { return "", err } p, n := filepath.Split(abs) pkg, err := build.Default.ImportDir(p, build.FindOnly) if err != nil { return "", err } return path.Join(pkg.ImportPath, n), nil } func annotate(w io.Writer, r io.Reader, blocks []cover.ProfileBlock) error { br := bufio.NewReader(r) var linenum int var block int var keep bool var line []byte for { if !keep { linenum++ var err error line, err = br.ReadSlice('\n') if err != nil { return nil } } keep = false if block >= len(blocks) { if err := annotateLine(w, ' ', line); err != nil { return err } continue } if linenum < blocks[block].StartLine { if err := annotateLine(w, ' ', line); err != nil { return err } continue } if linenum == blocks[block].StartLine { if isSpace(line[blocks[block].StartCol:]) { if err := annotateLine(w, ' ', line); err != nil { return err } } else { if err := annotateCodeLine(w, blocks[block].Count > 0, line); err != nil { return err } } continue } if linenum > blocks[block].EndLine || linenum == blocks[block].EndLine && isSpace(line[:blocks[block].EndCol-1]) { keep = true block++ continue } if err := annotateCodeLine(w, blocks[block].Count > 0, line); err != nil { return err } } } func annotateLine(w io.Writer, c byte, line []byte) error { _, err := w.Write([]byte{c}) if err != nil { return err } _, err = w.Write(line) if err != nil { return err } return nil } func annotateCodeLine(w io.Writer, tested bool, line []byte) error { if tested { return annotateLine(w, '+', line) } return annotateLine(w, '-', line) } func isSpace(b []byte) bool { for _, c := range b { switch c { case ' ', '\r', '\n', '\t': continue default: return false } } return true }
Java
UTF-8
3,353
1.648438
2
[ "Apache-2.0" ]
permissive
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.showcase.extension.autodiscover.client; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.showcase.extension.autodiscover.ReflectionHelper; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.container.LibraryContainer; import org.jboss.shrinkwrap.resolver.api.DependencyResolvers; import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver; import org.mockito.Mock; /** * DeclarativeArchiveProcessor * * @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a> * @version $Revision: $ */ public class ArchiveProcessor implements ApplicationArchiveProcessor { private static final String ANNOTATION_CLASS_NAME = "org.mockito.Mock"; private static final String MOCKITO_ARTIFACT = "org.mockito:mockito-all"; private static final String FEST_ASSERTIONS_CLASS_NAME = "org.fest.assertions.Assertions"; private static final String FEST_ARTIFACT = "org.easytesting:fest-assert"; @Override public void process(Archive<?> applicationArchive, TestClass testClass) { if(ReflectionHelper.isClassPresent(FEST_ASSERTIONS_CLASS_NAME)) { appendFestLibrary(applicationArchive); } if(ReflectionHelper.isClassPresent(ANNOTATION_CLASS_NAME)) { if(ReflectionHelper.getFieldsWithAnnotation(testClass.getJavaClass(), Mock.class).size() > 0) { appendMockitoLibrary(applicationArchive); } } } private void appendFestLibrary(Archive<?> applicationArchive) { if(applicationArchive instanceof LibraryContainer) { LibraryContainer<?> container = (LibraryContainer<?>) applicationArchive; container.addAsLibraries( DependencyResolvers.use(MavenDependencyResolver.class) .loadMetadataFromPom("pom.xml") .artifact(FEST_ARTIFACT) .resolveAsFiles()); } } private void appendMockitoLibrary(Archive<?> applicationArchive) { if(applicationArchive instanceof LibraryContainer) { LibraryContainer<?> container = (LibraryContainer<?>)applicationArchive; container.addAsLibraries( DependencyResolvers.use(MavenDependencyResolver.class) .loadMetadataFromPom("pom.xml") .artifact(MOCKITO_ARTIFACT) .resolveAsFiles()); } } }
Markdown
UTF-8
1,174
3.390625
3
[]
no_license
ERROR: type should be string, got "https://katriencolson.github.io/learning-front-end/.\n\nExercise\n\nWe are going to make a calculator! The basic setup you can find in this HTML file. This calculator needs to have some basic functionality like any other calculator:\n\n Enter a number by clicking buttons 0, 1, 2, 3, ....\n Choose a basic operation +, -, *, /, % (modulo).\n Display the result of the calculation =.\n Clear any entries C.\n\nAdditionally, the buttons need to have a hover effect! But because we are learning events and not CSS, we are not going to use button:hover. Instead, we are going to use the class .hovering. We are going to add this class to and remove it from the buttons through the use of events!\n\nLastly, you need to make the calculator accept keyboard input by means of key events!\n\nHint: eval() isn't always evil!\n\nGood luck!\nRestrictions\n\nYou are not allowed add/remove/change any CSS or HTML untill the calculator is completely functional.\nGoals\n\n Understand how to select HTML elements in the DOM.\n Understand how to modify HTML elements through the DOM.\n Understand how to write a basic JS function.\n Understand how to use event listeners and event handlers.\n"
C#
UTF-8
1,291
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using LouisvilleSuperSubaru.Data.Interfaces; using LouisvilleSuperSubaru.Models.Tables; namespace LouisvilleSuperSubaru.Data.ADO { public class VehicleTypeRepositoryADO : IVehicleTypeRepository { public List<VehicleType> GetAll() { List<VehicleType> vehicleTypes = new List<VehicleType>(); using (var cn = new SqlConnection(Settings.GetConnectionString())) { SqlCommand cmd = new SqlCommand("VehicleTypesSelectAll", cn); cmd.CommandType = CommandType.StoredProcedure; cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { VehicleType currentRow = new VehicleType(); currentRow.VehicleTypeID = (int)dr["VehicleTypeID"]; currentRow.VehicleTypeName = dr["VehicleTypeName"].ToString(); vehicleTypes.Add(currentRow); } } } return vehicleTypes; } } }
Markdown
UTF-8
2,749
2.515625
3
[]
no_license
01/28/19 ## Authors: Balk, Helge and Sovegjarto, Bendik S. and Tuser, Michal and Frouzova, Jaroslava and Muska, Milan and Drastík, Vladislav and Baran, Roman and Kubecka, Jan ## Title: Surface-induced errors in target strength and position estimates during horizontal acoustic surveys. ## Keywords: acoustics, beam, surface, reflection, target strength, horizontal ## Geographic Coverage Rimov Reservoir, Czech Republic ## Field Dates: N/A ## Significance: Simulations and field observations of TS and angle biases due to surface reflection in horizontal acoustics and target tracking. ## Notes: During horizontal surveys, transducers are typically mounted within 1 meter of the surface. The surface layer has issues, due to beam directed at the surface, strong temperature gradients, and multipath reflections. The effectiveness of these surveys rely on an assumption of weak side beams. Here, they investigate that assumption, and the impact of surface reflections on target strength and split-beam locations. A transducer and fixed-calibration targets were mounted in a reservoir, using an EK60 running a 120-10x4 transducer. A similar arrangement was modeled in 2D space to simulate the surface, including the beam pattern of the transducer. Simulated beam pattern closely matches that measured. Both simulations and observations show a range dependent impact of smooth sea surface on targets. A target, moving away from the transducer, passes through three zones: - Near-transducer: correct and non-oscillating TS and range/position. One might expect a strong direct reflection and very weak surface reflected return. - Oscillation zone: small, high-frequency oscillations, with amplitude increasing and frequency decreasing as a target moves away. This is dependent on the range of both the target and transducer away from the surface. - Relaxation zone: TS and angles are influenced by surface reflection but do not oscillate. TS decreases with range The position also oscillates with range, further driving inaccurate TS estimation due to incorrect beam compensation from oscilating split-beam position. A smooth surface can clearly introduce errors, and theoretically assumed "zones" were observed in in situ data, with significant (+/- 10db) errors in TS. In surface waters, temperature gradients can also lead to refraction, bending the beam down in the water column and shifting the range of the target. Mirror reflections can be more serious noise concerns than a lightly wavy/disrupted surface. The first zone can be maximized by using a shorter pulse length and deeper transducer mounting, though target depth will still be a noise concern. Guidelines established in various sea state conditions are necessary, based on further modeling and experimental observations.
Markdown
UTF-8
6,777
2.609375
3
[]
no_license
## C Bit Fields ```c type-specifier declarator(opt) : constant-expression ``` * The type-specifier for the `declarator` must be `unsigned int`, `signed int`, or `int`, and the `constant-expression` must be a nonnegative integer value. * If the value is zero, the declaration has no `declarator`. * Arrays of bit fields, pointers to bit fields, and functions returning bit fields are NOT allowed. * The optional `declarator` names the bit field. * Bit fields can only be declared as part of a structure * The address-of operator (&) cannot be applied to bit-field components. * Unnamed bit fields cannot be referenced, and their contents at run time are unpredictable. They can be used as "dummy" fields, for alignment purposes * An unnamed bit field whose width is specified as 0 guarantees that storage for the member following it in the struct-declaration-list begins on an int boundary. About memeory consumption: https://stackoverflow.com/questions/824295/what-does-c-struct-syntax-a-b-mean/49722670#49722670 ## Little-endian vs Big-endian Little-endian is when the least significant bytes are stored before the more significant bytes, and big-endian is when the most significant bytes are stored before the less significant bytes. ## IP header ``` 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` ### IP header detials Ref - https://www.guru99.com/ip-header.html ### Raw Socket * The IPv4 layer generates an IP header when sending a packet unless the `IP_HDRINCL` socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving, the IP header is always included in the packet. * A protocol of `IPPROTO_RAW` implies enabled `IP_HDRINCL` and is able to send any IP protocol that is specified in the passed header. * If `IP_HDRINCL` is specified and the IP header has a nonzero destination address, then the destination address of the socket is used to route the packet. ### IP-header checksum The checksum field is the 16-bit ones' complement of the ones' complement sum of all 16-bit words in the header. For purposes of computing the checksum, the value of the checksum field is zero. Ref - https://en.wikipedia.org/wiki/IPv4_header_checksum ## testing bind9 ``` nslookup <hostname> <optional:dns server> ``` ## check who are connected to my router ``` nmap -sP netwrokIp/maskLen ``` ## Kernel helps a lot!! ``` ┌───────────────────────────────────────────────────┐ │IP Header fields modified on sending by IP_HDRINCL │ ├──────────────────────┬────────────────────────────┤ │IP Checksum │ Always filled in │ ├──────────────────────┼────────────────────────────┤ │Source Address │ Filled in when zero │ ├──────────────────────┼────────────────────────────┤ │Packet ID │ Filled in when zero │ ├──────────────────────┼────────────────────────────┤ │Total Length │ Always filled in │ └──────────────────────┴────────────────────────────┘ ``` ## DNS Request Ref - https://www.binarytides.com/dns-query-code-in-c-with-winsock/ ``` (RFC1035) +---------------------+ | Header | +---------------------+ | Question | the question for the name server +---------------------+ | Answer | RRs answering the question +---------------------+ | Authority | RRs pointing toward an authority +---------------------+ | Additional | RRs holding additional information +---------------------+ ``` ### DNS Header ``` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ``` ### DNS Query ``` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | / QNAME / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QTYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QCLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ``` ### QNAME field ``` /* Example: +---+---+---+---+---+---+---+---+---+---+---+ | a | b | c | . | d | e | . | c | o | m | \0| +---+---+---+---+---+---+---+---+---+---+---+ becomes: +---+---+---+---+---+---+---+---+---+---+---+---+ | 3 | a | b | c | 2 | d | e | 3 | c | o | m | 0 | +---+---+---+---+---+---+---+---+---+---+---+---+ */ ```
C
ISO-8859-9
5,246
2.984375
3
[]
no_license
#include <stdio.h> #include <ctype.h> #include <stdlib.h> char *morsChars[36][2]={ {"A",".-"}, {"B","-..."}, {"C","-.-."}, {"D","-.."}, {"E","."}, {"F","..-."}, {"G","--."}, {"H","...."}, {"I",".."}, {"J",".---"}, {"K","-.-"}, {"L",".-.."}, {"M","--"}, {"N","-."}, {"O","---"}, {"P",".--."}, {"Q","--.-"}, {"R",".-."}, {"S","..."}, {"T","-"}, {"U","..-"}, {"V","...-"}, {"W",".--"}, {"X","-..-"}, {"Y","-.--"}, {"Z","--.."}, {"0","-----"}, {"1",".----"}, {"2","..---"}, {"3","...--"}, {"4","....-"}, {"5","....."}, {"6","-...."}, {"7","--..."}, {"8","---.."}, {"9","----."}, }; // Mors kelimelerini ve karlk gelen karakterleri tutan dizi tanmland. char gelenKarakter='\0', // Okunan her bir karakteri tutacak deiken tanmland. morsKarakter='\0'; // Mors kelimelerinin tutulduu diziden, ilgili kelimeye karlk gelen karakteri tutacak deiken tanmland. int j=0; // Dng deikeni tanmland. int main() { int i=0; // Dng deikeni tanmland. char *gelenVeri, // Kullancnn girdii karakterleri tutacak deiken tanmland. *islem; // Kullanc tarafndan girilecek ilem tipini tutacak deiken tanmland. gelenVeri=calloc(1000,sizeof(char)); // Kullancnn girdii deikenleri tutacak deikene daha sonra temizlemek amacyla 1000 karakterlik alan tahsis edildi. islem=calloc(1,sizeof(char)); // Kullanc tarafndan girilecek ilem tipini tutacak deikene sonradan silinmek zere 1 karakterlik alan tahsis edildi. //Kullancy ynlendirmek iin oluturulan ekran ktlar. printf("Dosya uzerinden okumak icin 1'e basin."); printf("\nKlavyeden girmek icin 2'ye basin."); printf("\n\nLutfen islem tipini seciniz: "); gets(islem); // Kullancdan yapmak istedii ileme ait veri alnyor. if(!strcmp(islem,"1")) // Alnan veri ile ilgili ilem karlatrlyor. { FILE * filePointer; // Alacak dosyaya ait ierii tutacak deiken tanmland. char dataToBeRead[2], // Dosya ieriini okuduka ilgili karakteri tutacak deiken tanmland. *dosyaYolu; // Kullanc tarafndan almak istenen dosyaya ait yolun tutulaca deiken tanmland. dosyaYolu=calloc(100,sizeof(char)); // Kullanc tarafndan girilecek dosya yoluna ait deikene sonradan silinmek zere 100 karakterlik alan tahsis edildi. printf("\nDosya yolunu giriniz: "); gets(dosyaYolu); // Kullancdan iinde latin harflerinin olduu txt dosyasnn yolu alnyor. printf("\n"); filePointer = fopen(dosyaYolu, "r"); // Kullancnn girdii yoldaki dosya alyor. free(dosyaYolu); // Dosya yolu iin tahsis edilen 100 karakterlik alan temizlendi. if(filePointer==NULL) // Eer ki kullanc hatal veya olmayan bir dosya amaya alrsa burada yakalanacak. printf("Dosya acilirken bir hata olustu."); while( fgets ( dataToBeRead, 2, filePointer ) != NULL ) // Dosya ald takdirde ierisindeki veriler bitene kadar okunacak. harfBas(*dataToBeRead); // Dosyadan okunan karakterler fonksiyona gnderiliyor. fclose(filePointer); // Okuma ilemi tamamlannca dosya kapatlyor. } else if(!strcmp(islem,"2")) // Alnan veri ile ilgili ilem karlatrlyor. { printf("\n\nLutfen cevrilecek kelimeyi giriniz:"); gets(gelenVeri); // Kullancdan veri alyor. printf("\n"); while(gelenVeri[i]!='\0') // Gelen dizinin iinden veri olan ksm okunuyor. { harfBas(gelenVeri[i]); // Kullancnn girdii her bir karakter srayla fonksiyona gnderiliyor. i++; // Sonraki mors kelimesini okumak iin dng 1 adm ilerliyor. } free(gelenVeri); // gelen veriyi tutmak iin tahsis edilen 1000 karakterlik alan temizlendi. } else // Alnan veri ilemlere uymazsa hatal giri iin uyar veriliyor. printf("Hatali islem numarasi girdiniz."); return 0; } harfBas(int gelen) // Tekrar edecek ayn ilemleri bir fonksiyon ierisine alarak koddan tasarruf saland. { gelenKarakter=toupper(gelen);//Klavyeden girilen karakter okunuyor. Eer kk harf ise byk harfe evriliyor. for(j=0;j<36;j++) // Balangta kaydettiimiz tm mors kelimeleri kadar dnecek. { morsKarakter= *morsChars[j][0]; //Mors kelimelerinin tutulduu diziden dng durumuna gre ilgili kelimeye karlk gelen karakter ekiliyor. if(gelenKarakter==morsKarakter)// Mors kelimelerinin tutulduu diziden ekilen karakter, kullancnn girdii karakter ile karlatrlyor. printf(morsChars[j][1]); // Eer ki veriler eleirse, mors kelimelerinin tutulduu diziden ilgili kelime ekrana baslyor. } printf(" "); // imdiki kelime ile sonrakini ayrmak iin arada bir boluk braklyor. }
C#
UTF-8
4,634
2.59375
3
[]
no_license
namespace BusinessManagement.Services { using System; using System.Net; using System.Threading.Tasks; using ApiClient; using HydraWebUi.Services.Model; using Interfaces; using Model; using Model.DTO; using Model.StatusCodes; using Newtonsoft.Json; public class BlogTagService: BaseApiClient, IBlogTagService { private readonly string _blogUrl; public BlogTagService(string baseUrl) : base(baseUrl) { _blogUrl = "odata/blogtag"; } public async Task<PageResult<BlogTagDto>> AllAsync(int skip, int take, string searchString = null) { string url = $"{_blogUrl}?$select=*&$Skip=" + skip + "&$Top=" + take; if (searchString != null) { url += $"&$filter=contains(Name, '{searchString}')"; } var response = await GetResponseAsync(url); var result = new PageResult<BlogTagDto> { StatusCode = (int)response.StatusCode }; if (!response.IsSuccessStatusCode) { result.IsFailed = true; switch (response.StatusCode) { case HttpStatusCode.Conflict: { result.Massage = "Вече съществува такъв пост"; break; } default: { result.Massage = "Възникна грешка моля опитайте отново"; break; } } return result; } var jsonResult = await response.Content.ReadAsStringAsync(); result.Result = JsonConvert.DeserializeObject<OData<BlogTagDto>>(jsonResult).Value; return result; } public async Task<NoDataResult> AddAsync(BlogTagDto tag) { var url = $"{_blogUrl}"; var response = await PostResponseAsync(url, JsonConvert.SerializeObject(tag)); var result = new NoDataResult { StatusCode = (int)response.StatusCode }; if (!response.IsSuccessStatusCode) { result.IsFailed = true; switch ((int)response.StatusCode) { case StatusCode.Status422UnprocessableEntity: { result.Massage = "Има некоректно попълнени данни! Моля попълнете всички полета коректно"; break; } default: { result.Massage = "Възникна грешка моля опитайте отново"; break; } } } else { result.Massage = "Тага беше добавен успешно"; } return result; } public async Task<NoDataResult> EditAsync(BlogTagDto blogTag, Guid id) { var url = $"{_blogUrl}({id})"; var response = await PutResponseAsync(url, JsonConvert.SerializeObject(blogTag)); var result = new NoDataResult { StatusCode = (int)response.StatusCode }; if (!response.IsSuccessStatusCode) { result.IsFailed = true; switch ((int)response.StatusCode) { case StatusCode.Status422UnprocessableEntity: { result.Massage = "Има некоректно попълнени данни! Моля попълнете всички полета коректно"; break; } default: { result.Massage = "Възникна грешка моля опитайте отново"; break; } } } else { result.Massage = "Тага беше редактиран успешно"; } return result; } public NoDataResult Delete(Guid id) { throw new NotImplementedException(); } } }
Java
UTF-8
663
2.390625
2
[ "Apache-2.0" ]
permissive
package com.intellij.gitlab.util.result; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.Nullable; public class EmptyResult implements Result { private String response; private EmptyResult(@Nullable String response) { this.response = response; } public static EmptyResult create(String response){ return new EmptyResult(response); } public static EmptyResult error(){ return new EmptyResult("null"); } @Override public boolean isValid() { return StringUtil.isEmpty(response); } @Override public Object get() { return null; } }
PHP
UTF-8
1,916
2.890625
3
[]
no_license
<?php include_once(dirname(__FILE__) .'/../db/db.php'); class EmploymentDetails { // Employee Details public $code; public $job_title; public $job_category; public $employment_status; public $operating_unit; public $business_unit; public $supervisor; } class EducationBackground { // Education Details public $code; public $background_level; public $school_name; public $degree; public $date_start; public $date_end; public $year_graduated; public $honors; } class WorkExperience { public $company; public $position; public $appointment_status; public $date_from; public $date_to; } class EmergencyContactPerson { public $code; public $contact_name; public $relationship; public $mobile; public $work_telephone; public $home_telephone; } class Employee { public $code; public $status; public $message; // Basic Information public $name; public $firstname; public $middlename; public $lastname; public $extension; public $gender; public $birthdate; public $marital_status; public $nationality; // Contact Details public $email; public $mobile_number; public $telephone_number; // Address Details public $street; public $city; public $state_province; public $country; public $zip; // Employment Details public $employment_details; // Education Background public $education_background; // Work Experience public $work_experience; // Emergency Contact Person public $emergency_person; // Methods public static function all() { return DB::getEmployees(); } public static function find($id) { return DB::getEmployeeDetails($id); } public static function test($id) { return DB::getEmergencyContactPerson($id); } }
Python
UTF-8
2,071
3.4375
3
[]
no_license
import multiprocessing import os import time # 跳舞任务 def dance(): # 获取当前进程的编号 print("sing:", os.getpid()) # 获取当前进程 print("sing:", multiprocessing.current_process()) # 获取父进程的编号 print(f"【{multiprocessing.current_process().name}】的父进程编号:", os.getppid()) for i in range(5): print("dance...doing...") time.sleep(0.1) # 唱歌任务 def sing(): # 获取当前进程的编号 print("sing:", os.getpid()) # 获取当前进程 print("sing:", multiprocessing.current_process()) # 获取父进程的编号 print(f"【{multiprocessing.current_process().name}】的父进程编号:", os.getppid()) for i in range(5): print(f"sing{i + 1}...doing...") time.sleep(0.1) def task(count): # 获取当前进程的编号 print("task:", os.getpid()) # 获取当前进程 print("task:", multiprocessing.current_process()) # 获取父进程的编号 name = multiprocessing.current_process().name print(f"【{name}】的父进程编号:", os.getppid()) for i in range(count): print(f"task{i + 1}...{name}.doing...") time.sleep(0.2) if __name__ == '__main__': # 创建跳舞的子进程 # group: 表示进程组,目前只能使用None; assert group is None, 'group argument must be None for now' # target: 表示执行的目标任务名(函数名、方法名) dance_process = multiprocessing.Process(target=dance, name="dance") # name: 进程名称, 默认是Process-1, ..... sing_process = multiprocessing.Process(target=sing) # args 表示以元组的方式给执行任务传参 task_process = multiprocessing.Process(target=task, args=(3,), name='task') # kwargs 表示以字典方式给执行任务传参 task2_process = multiprocessing.Process(target=task, kwargs={'count': 2}, name='task2') # 启动子进程执行对应的任务 dance_process.start() sing_process.start() task_process.start() task2_process.start()
Ruby
UTF-8
158
3.3125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby def greet(x) print "Hello #{x}" end if __FILE__ == $0 then s = STDIN.gets while !s.nil? greet(s) s = STDIN.gets end end
Java
UTF-8
647
2.9375
3
[]
no_license
package com.thoughtworks.tdd; import java.util.Comparator; public class SuperSmartParkingBoy extends Paker implements Parkable{ public SuperSmartParkingBoy(ParkingLot... parkingLot) { super(parkingLot); } @Override public ParkingTicket parkCar(Car car) { if (getParkingLots().stream().allMatch(parkingLot -> parkingLot.isFull())){ throw new NotEnoughPositionException(); } ParkingLot parkingLot = getParkingLots().stream().max(Comparator.comparingDouble(ParkingLot::getAvailableRate)).orElse(null); ParkingTicket ticket = parkingLot.park(car); return ticket; } }
C++
UTF-8
2,599
2.828125
3
[]
no_license
// // Created by Enjoeyland on 2018-05-03. // #include "Controller.h" char ControllerHandler::handleInputPin(int *pinData) { int pinUpData = pinData[0]; int pinDownData = pinData[1]; int pinLeftData = pinData[2]; int pinRightData = pinData[3]; if (pinUpData == 1){ if (pinLeftData == 0 && pinRightData == 0) { return 'F'; } else if (pinLeftData == 1&& pinRightData == 0) { return 'G'; } else if (pinLeftData == 0 && pinRightData == 1){ return 'I'; } } else{ if (pinDownData == 1){ if (pinLeftData == 0 && pinRightData == 0) { return 'B'; } else if (pinLeftData == 1&& pinRightData == 0) { return 'H'; } else if (pinLeftData == 0 && pinRightData == 1){ return 'J'; } } else { if (pinLeftData == 0 && pinRightData == 0) { return 'S'; } else if (pinLeftData == 1&& pinRightData == 0) { return 'L'; } else if (pinLeftData == 0 && pinRightData == 1){ return 'R'; } } }; } void ControllerHandler::handleInput(char data) { switch(data) { case 'F': carMovement->goForward(255, 0); break; case 'B': carMovement->goBackward(255, 0); break; case 'L': carMovement->spinLeft(255,0,0); break; case 'R': carMovement->spinRight(255,0,0); break; case 'G': carMovement->turnLeft(255,10,0); break; case 'I': carMovement->turnRight(255,10,0); break; case 'H': carMovement->turnLeft(-255,10,0); break; case 'J': carMovement->turnRight(-255,10,0); break; case 'S': carMovement->stop(); break; case 'U': // back Lights On break; case 'u': // back light off break; case 'V': // Horn on break; case 'v': // Horn off break; case 'X': // Extra On break; case 'x': // Extra On break; // case '0': // setSpeed(0); // break; // case '1': // setSpeed(10); // break; // case '2': // setSpeed(20); // break; // case '3': // setSpeed(30); // break; // case '4': // setSpeed(40); // break; // case '5': // setSpeed(50); // break; // case '6': // setSpeed(60); // break; // case '7': // setSpeed(70); // break; // case '8': // setSpeed(80); // break; // case '9': // setSpeed(90); // break; // case 'q': // setSpeed(100); // break; // // // case 'D': //// stop all // stop; // break; default:break; } } // defining PinInputHandler //PinInputHandler::PinInputHandler(const Counter &counter, int pin, SwitchInput::Type type) : // counter(counter), SwitchInput(pin, DEFAULT_DEBOUNCE, type) {} // //void PinInputHandler::on_close() //{ // counter.increase(); //}
Markdown
UTF-8
489
2.765625
3
[]
no_license
#### - ACID 事务的原则 事务型数据库的4个特点 - A (原子性)事务作为一个整体,要么一起死,要么一起生 - C (一致性)事务确保数据库的状态从一个一致状态转变为另一个状态 - I (隔离性)多个事务同时执行,但是我们互相执行,你走你的阳关道,我走我的独木桥 - D (持久性)已提交的事务对于数据库的修改是持久性的,不能只有3秒钟,是男人就坚持下来
Java
UTF-8
10,749
2.484375
2
[]
no_license
package com.yetistep.delivr.util; import org.apache.log4j.Logger; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.RasterFormatException; import java.io.*; import java.util.Iterator; import java.util.StringTokenizer; /** * Created with IntelliJ IDEA. * User: golcha * Date: 9/24/13 * Time: 10:25 AM * To change this template use File | Settings | File Templates. */ public class ImageConverter { public static final Logger log = Logger.getLogger(ImageConverter.class); //private static String root_path = "/Volumes/Golcha/deal/uploads"; public static String convertToWebp(File file) { String s = null; String output_file = null; try { StringTokenizer stringTokenizer = new StringTokenizer(file.getName(), "."); String name = stringTokenizer.nextToken(); output_file = file.getParentFile().getAbsolutePath() + "/" + name + ".webp"; //String command = "C:\\libwebp-0.3.1-windows-x86\\cwebp " + source_file + " -noalpha -o " + output_file; String command = "cwebp " + file.getPath() + " -noalpha -o " + output_file; log.info("command: " + command); // run the Unix "ps -ef" command // using the Runtime exec method: // Process p = Runtime.getRuntime().exec("cwebp /Users/golcha/Dropbox/yetistep/swipr/ads/uploaded_ads/14.png -noalpha -o /Users/golcha/Dropbox/yetistep/swipr/ads/uploaded_ads/14.webp"); Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command log.debug("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command log.debug("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { log.debug(s); } stdInput.close(); stdError.close(); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. throw new YSException("RS110", e); } return output_file; } public static String convertToJpg(File file) { String s = null; String output_file = null; try { StringTokenizer stringTokenizer = new StringTokenizer(file.getName(), "."); String name = stringTokenizer.nextToken(); output_file = file.getParentFile().getAbsolutePath() + "/" + name + "dq.jpg"; String command = "convert " + file.getPath() + " -quality 50% " + output_file; log.info("command: " + command); // run the Unix "ps -ef" command // using the Runtime exec method: // Process p = Runtime.getRuntime().exec("cwebp /Users/golcha/Dropbox/yetistep/swipr/ads/uploaded_ads/14.png -noalpha -o /Users/golcha/Dropbox/yetistep/swipr/ads/uploaded_ads/14.webp"); Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command log.debug("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command log.debug("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { log.debug(s); } stdInput.close(); stdError.close(); } catch (Exception e) { System.out.println("exception happened - here's what I know: "); e.printStackTrace(); throw new YSException("RS111", e); } return output_file; } //compress the provided image and save in the provided desctination public static String compressImageNSave(File imageFile) throws Exception { float quality = 0.5f; StringTokenizer stringTokenizer = new StringTokenizer(imageFile.getName(), "."); String name = stringTokenizer.nextToken(); String desc = imageFile.getParentFile().getAbsolutePath() + File.separator + name + "_" + DisplaySize.XHDPI + ".jpg"; BufferedImage originalImage = ImageIO.read(imageFile); Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(quality); File file = new File(desc); writer.setOutput(new FileImageOutputStream(file)); IIOImage image = new IIOImage(originalImage, null, null); writer.write(null, image, iwp); writer.dispose(); log.info("Successfully compressed and saved image to " + desc); return desc; } //resizes and saves the image in the provided destination public static File resizeImageNSave(File image, int width, int height, String desc) throws IOException { BufferedImage originalImage = ImageIO.read(image); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizedImage = new BufferedImage(width, height, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, width, height, null); g.dispose(); File newImage = new File(desc); ImageIO.write(resizedImage, "jpg", newImage); return newImage; } //compress the provided image and saves. //[compressor creates JPG images] public static BufferedImage compressImage(File imageFile, String imgType, String imageName, float quality) throws Exception { //float quality = 0.5f; BufferedImage originalImage = ImageIO.read(imageFile); //convert to jpg image if png if (imgType.equalsIgnoreCase("png")) { BufferedImage newBufferedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB); newBufferedImage.createGraphics().drawImage(originalImage, 0, 0, Color.WHITE, null); originalImage = newBufferedImage; } //for jpg image Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(quality); // imgType = imgType.equalsIgnoreCase("png")? "jpg": imgType; imgType = "jpg"; String filePath = imageFile.getParentFile().getAbsolutePath() + File.separator + imageName + "." + imgType; File file = new File(filePath); FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(file); writer.setOutput(fileImageOutputStream); IIOImage image = new IIOImage(originalImage, null, null); writer.write(null, image, iwp); fileImageOutputStream.close(); writer.dispose(); log.info("Successfully compressed and saved image to " + filePath); return originalImage; } //resizes and saves the image in the provided destination public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) throws IOException { // BufferedImage originalImage = ImageIO.read(image); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizedImage = new BufferedImage(width, height, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, width, height, null); g.dispose(); // File newImage = new File(desc); // ImageIO.write(resizedImage, "jpg", newImage); return resizedImage; } // crops image public static BufferedImage cropImage(BufferedImage img, int cropWidth, int cropHeight, int cropStartX, int cropStartY) throws Exception { BufferedImage clipped = null; Dimension size = new Dimension(cropWidth, cropHeight); checkClipArea(img, size, cropStartX, cropStartY); clipped = img.getSubimage(cropStartX, cropStartY, cropWidth, cropHeight); try { clipped = img.getSubimage(cropStartX, cropStartY, cropWidth, cropHeight); } catch (RasterFormatException rfe) { log.error("Error occurred while cropping an image", rfe); throw rfe; } return clipped; } public static void decodeToImage(String encodedString, File newImage) throws IOException { int start = encodedString.indexOf(","); encodedString = encodedString.substring(start + 1);//remove data:image/png;base64 byte[] btDataFile = new sun.misc.BASE64Decoder().decodeBuffer(encodedString); FileOutputStream osf = new FileOutputStream(newImage); osf.write(btDataFile); osf.flush(); osf.close(); } //checks if the given range to clip image lies within the image boundary. private static void checkClipArea(BufferedImage img, Dimension size, int clipX, int clipY) throws Exception { clipX = clipX < 0 ? 0 : clipX;//if negative, set it to zero clipY = clipY < 0 ? 0 : clipY;//if negative, set it to zero int clippableWidth = size.width + clipX; int clippableHeight = size.height + clipY; boolean isClipOutOfImg = clippableWidth > img.getWidth() || clippableHeight > img.getHeight(); if (isClipOutOfImg) throw new Exception("Trying to clip outside the image boundary.Error!!!"); } }
JavaScript
UTF-8
1,336
2.796875
3
[]
no_license
(function () { var euler = EulerFactory.getInstance(); euler.addFunction(function (...args) { // var _largeFibonacci = euler.constructor.utils.largeFibonacci; var i = 2; var length = 0; var j = 0; for (i; i<args[0]; i++) { var usedRemainders = []; var result = ''; var cur = 1; var w = 0; while(1 == 1) { var rest = cur % i; var resX = Math.floor(cur / i); var index = usedRemainders.indexOf(rest); if (w == 0) { result += '0.'; } else { result += resX; } if (index !== -1) { var u = usedRemainders.splice(index); if (u.length > length) { length = u.length; j = i; } break; } if (rest === 0) { break; } usedRemainders.push(rest); cur = rest * 10; w++; } } return j; }, 26, [1000]) //2783915460 }()); /* 1 / 3 1 |_3___ 10 | 0.3 1 */
Go
UTF-8
775
2.6875
3
[]
no_license
package decoders import ( "github.com/jcw/flow" ) func init() { flow.Registry["Node-outdoorClimate"] = func() flow.Circuitry { return &OutdoorClimate{} } } // Decoder for the "OutdoorClimate" sketch. Registers as "Node-outdoorClimate". type OutdoorClimate struct { flow.Gadget In flow.Input Out flow.Output } // Start decoding OutdoorClimate packets. //struct {byte light; int humidity; int temperature; byte vcc; } payload; func (w *OutdoorClimate) Run() { for m := range w.In { if v, ok := m.([]byte); ok && len(v) >= 6{ m = map[string]int{ "<reading>": 1, "light": int(v[1]), "humi": int(v[2])+ (256 * int(v[3])), "temp": int(v[4])+ (256 * int(v[5])), "battery": (int(v[6]) * 20) + 1000, } } w.Out.Send(m) } }
C#
UTF-8
4,597
2.890625
3
[]
no_license
using Patterns.ChainOfResponsibility; using Patterns.Decorator; using Patterns.Facade; using Patterns.FactoryPattern.VehicleFactory; using Patterns.FamilyTax; using Patterns.FamilyTax.Calculator; using Patterns.FamilyTax.Entity; using Patterns.FamilyTax.Hub; using Patterns.Proxy; using Patterns.Strategy; using System; using System.Collections; using System.Collections.Generic; using SortedList = Patterns.Strategy.SortedList; namespace Patterns { class Program { /// <summary> /// Patterns /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("----------------------Factory Pattern-----------------"); IVehicleFactory carfactory = new CarFactory(); var car = carfactory.CreateVehicle(); car.Drive(20); car.FuelConsumption(); IVehicleFactory bikefactory = new BikeFactory(); var bike = bikefactory.CreateVehicle(); bike.Drive(5); bike.FuelConsumption(); Console.WriteLine("----------------------Decorator Pattern-----------------"); Cake cc1 = new Cake(); Console.WriteLine(cc1.Bake() + " ," + cc1.GetPrice()); Type1 cd1 = new Type1(cc1); Console.WriteLine(cd1.Bake() + " ," + cd1.GetPrice()); Type2 cd2 = new Type2(cc1); Console.WriteLine(cd2.Bake() + " ," + cd2.GetPrice()); Console.WriteLine("----------------------Visitor Pattern-----------------"); IElementFamily darman = new Darman(); IElementFamily dandan = new Dandan(); IElementFamily para = new Para(); var hub = new Hub(); hub.Attach(darman); hub.Attach(dandan); hub.Attach(para); hub.Execute(new TaxCalculator()); hub.Execute(new InvoiceCalculator()); Console.WriteLine("----------------------Strategy Pattern-----------------"); SortedList studentRecords = new SortedList(); studentRecords.Add("Samual"); studentRecords.Add("Jimmy"); studentRecords.Add("Sandra"); studentRecords.Add("Vivek"); studentRecords.Add("Anna"); studentRecords.SetSortStrategy(new QuickSort()); studentRecords.Sort(); studentRecords.SetSortStrategy(new ShellSort()); studentRecords.Sort(); studentRecords.SetSortStrategy(new MergeSort()); studentRecords.Sort(); Console.WriteLine("----------------------Chain Of Responsibility Pattern-----------------"); var fromCustomer = new Customer() { AccountValue = 1000, IsActive = true, MaxDateValue = 100, Password = "1234", }; Customer toCustomer = new Customer() { AccountValue = 10000, IsActive = true, MaxDateValue = 2000, Password = "1234", }; var transfer = new CheckPassword(new CheckValue(new CheckActive(new FinalTransfer(null)))); var result = transfer.Execute(new RequestContext() { FromCustomer = fromCustomer, ToCustomer = toCustomer, Password = "1234", Value = 150, }); Console.WriteLine(result.Message); Console.WriteLine("----------------------Chain Of Responsibility Pattern-----------------"); Image image = new ProxyImage("CodeGate.jpg"); //image will be loaded from disk image.display(); Console.WriteLine(""); //image will not be loaded from disk image.display(); Console.WriteLine("----------------------Facade Pattern-----------------"); var restaurant = new OnlineRestaurant(); var shippingService = new ShippingService(); var facade = new FacadePattern(restaurant, shippingService); var chickenOrder = new Order() { DishName = "Chicken with rice", DishPrice = 20.0, User = "User1", ShippingAddress = "Random street 123" }; var sushiOrder = new Order() { DishName = "Sushi", DishPrice = 52.0, User = "User2", ShippingAddress = "More random street 321" }; facade.OrderFood(new List<Order>() { chickenOrder, sushiOrder }); Console.ReadKey(); } } }
Python
UTF-8
257
3.15625
3
[]
no_license
import re def openFile(name): a = [] b = [] file = open(name, 'r') strings = file.read() for string in strings.split('\n'): x, y = (re.split('\s+', string)) a.append(float(x)) b.append(float(y)) return a, b
C++
UTF-8
11,166
3.21875
3
[]
no_license
/* * Skeleton code for project 3 in EE205 2018 Fall KAIST * Created by Wan Ju Kang. */ #include "rb_tree.h" #include <iostream> #include <string> #include "linked_list.h" using namespace std; /******************************************************/ /******************** CLASS BASICS ********************/ /******************************************************/ // constructor template <class T> RBTree<T>::RBTree(){ // root property: root is black root = new RBNode<T>("", false, NULL); } // destructor template <class T> RBTree<T>::~RBTree(){ while(!is_external(root)){ remove(root->key); } delete root; } /******************************************************/ /********************** DISPLAY ***********************/ /******************************************************/ // display template <class T> void RBTree<T>::display(){ if(is_external(root)){ cout << "Tree is empty." << endl; return; } cout << "root: " << root->key << endl;; inorder_print(root); cout << endl; preorder_print(root); cout << endl; } template <class T> void RBTree<T>::displayRB(){ if(is_external(root)){ cout << "Tree is empty." << endl; return; } cout << "root: " << root->key << endl;; inorder_printRB(root); cout << endl; preorder_printRB(root); cout << endl; } // inorder print template <class T> void RBTree<T>::inorder_print(RBNode<T> *n){ if(!is_external(n->leftChild)) inorder_print(n->leftChild); cout << n->key << " "; if(!is_external(n->rightChild)) inorder_print(n->rightChild); } template <class T> void RBTree<T>::inorder_printRB(RBNode<T> *n){ if(!is_external(n->leftChild)) inorder_printRB(n->leftChild); cout << n->key << "(" << (n->isRed ? "R" : "B") <<") "; if(!is_external(n->rightChild)) inorder_printRB(n->rightChild); } // preorder print template <class T> void RBTree<T>::preorder_print(RBNode<T> *n) { cout << n->key << " "; if(!is_external(n->leftChild)) preorder_print(n->leftChild); if(!is_external(n->rightChild)) preorder_print(n->rightChild); } template <class T> void RBTree<T>::preorder_printRB(RBNode<T> *n) { cout << n->key << "(" << (n->isRed ? "R" : "B") <<") "; if(!is_external(n->leftChild)) preorder_printRB(n->leftChild); if(!is_external(n->rightChild)) preorder_printRB(n->rightChild); } /******************************************************/ /****************** NODE INFORMATION ******************/ /******************************************************/ // is external template <class T> bool RBTree<T>::is_external(RBNode<T> *n) { return (n->leftChild == NULL && n->rightChild == NULL); } // is root template <class T> bool RBTree<T>::is_root(RBNode<T> *n) { return n->parent == NULL; } // get height template <class T> int RBTree<T>::height(RBNode<T> *n){ return n->height; } // update height template <class T> void RBTree<T>::update_height(RBNode<T> *n){ if(is_external(n)) { n->height = 0; } else { int lh = height(n->leftChild); int rh = height(n->rightChild); n->height = (lh >= rh ? lh : rh) + 1; } } /******************************************************/ /****************** TREE STRUCTURES *******************/ /******************************************************/ // restruct tree // given parent of double red template <class T> void RBTree<T>::restruct(RBNode<T> *v){ if(v->parent->leftChild == v){ if(v->leftChild->isRed){ RBNode<T> *parent = v->parent; // make v as root of subtree if(is_root(parent)) root = v; else{ if(parent->parent->leftChild == parent) parent->parent->leftChild = v; else parent->parent->rightChild = v; } v->parent = parent->parent; // connect v's right child as parent's left child parent->leftChild = v->rightChild; v->rightChild->parent = parent; // connect parent as v's right child v->rightChild = parent; parent->parent = v; // recolor v->isRed = false; parent->isRed = true; } else{ RBNode<T> *parent = v->parent; RBNode<T> *child = v->rightChild; // make child as root of subtree if(is_root(parent)) root = child; else{ if(parent->parent->leftChild == parent) parent->parent->leftChild = child; else parent->parent->rightChild = child; } child->parent = parent->parent; // connect child's left child as v's right child v->rightChild = child->leftChild; child->leftChild->parent = v; // connect child's right child as parent's left child parent->leftChild = child->rightChild; child->rightChild->parent = parent; // connect v as left child of child child->leftChild = v; v->parent = child; // connect parent as right child of child child->rightChild = parent; parent->parent = child; // recolor child->isRed = false; parent->isRed = true; } } else{ if(v->leftChild->isRed){ RBNode<T> *parent = v->parent; RBNode<T> *child = v->leftChild; // connect child as root of subtree if(is_root(parent)) root = child; else{ if(parent->parent->leftChild == parent) parent->parent->leftChild = child; else parent->parent->rightChild = child; } child->parent = parent->parent; // connect child's left child as parent's right child parent->rightChild = child->leftChild; child->leftChild->parent = parent; // connect child's right child as v's left child v->leftChild = child->rightChild; child->rightChild->parent = v; // connect parent as child's left child child->leftChild = parent; parent->parent = child; // connect v as child's right child child->rightChild = v; v->parent = child; // recolor child->isRed = false; parent->isRed = true; } else{ RBNode<T> *parent = v->parent; // connect v as root of subtree if(is_root(parent)) root = v; else{ if(parent->parent->leftChild == parent) parent->parent->leftChild = v; else parent->parent->rightChild = v; } v->parent = parent->parent; // connect v's left child as parent's right child parent->rightChild = v->leftChild; v->leftChild->parent = parent; // connect parent as v's left child v->leftChild = parent; parent->parent = v; // recolor v->isRed = false; parent->isRed = true; } } } // recolor tree // should be recursive template <class T> void RBTree<T>::recolor(RBNode<T> *v){ RBNode<T> *sibling; if(v->parent->leftChild == v) sibling = v->parent->rightChild; else sibling = v->parent->leftChild; sibling->isRed = false; v->isRed = false; if(!is_root(v->parent)){ v->parent->isRed = true; if(v->parent->parent->isRed) solve_double_red(v->parent); } } template <class T> void RBTree<T>::solve_double_red(RBNode<T> *n){ if(!is_root(n) && n->parent->isRed){\ RBNode<T> *s; if(n->parent->parent->leftChild == n->parent) s = n->parent->parent->rightChild; else s = n->parent->parent->leftChild; if(s->isRed) recolor(n->parent); else restruct(n->parent); } } /******************************************************/ /********************* OPERATIONS *********************/ /******************************************************/ // search template <class T> RBNode<T>* RBTree<T>::search(string key){ RBNode<T> *node = this->root; while(!is_external(node)){ if(node->key.compare(key) == 0) break; else if(node->key.compare(key) < 0) node = node->rightChild; else node = node->leftChild; } return node; } // insert template <class T> bool RBTree<T>::insert(string key){ RBNode<T> *n = search(key); if(is_external(n)){ n->key = key; n->isRed = true; // insert red if(is_root(n)) n->isRed = false; n->leftChild = new RBNode<T>("", false, n); n->rightChild = new RBNode<T>("", false, n); solve_double_red(n); return true; } return false; } template <class T> void cleanUpNode(RBNode<T>* node){ if(node == NULL) return; if(node->leftChild != NULL) delete node->leftChild; if(node->rightChild != NULL) delete node->rightChild; delete node; } template<class T> RBNode<T>* RBTree<T>::remove_from_binary_tree(string key){ RBNode<T> *n = search(key); if(is_external(n)) return NULL; if(!is_external(n->leftChild) && !is_external(n->rightChild)){ RBNode<T> *v = n->rightChild; while(!is_external(v->leftChild)) v = v->leftChild; // connect v's right child to parent RBNode<T> *s; // sibling of v v->rightChild->parent = v->parent; if(v->parent->leftChild == v){ v->parent->leftChild = v->rightChild; s = v->parent->rightChild; } else{ v->parent->rightChild = v->rightChild; s = v->parent->leftChild; } if(v->isRed || v->rightChild->isRed){ v->rightChild->isRed = false; s = NULL; // do not need to solve double black } n->key = v->key; delete n->value; n->value = v->value; v->value = NULL; v->rightChild = NULL; cleanUpNode(v); return s; } else if(!is_external(n->leftChild) && is_external(n->rightChild)){ n->key = n->leftChild->key; delete n->value; n->value = n->leftChild->value; n->leftChild->value = NULL; RBNode<T>* r = n->leftChild; n->leftChild = new RBNode<T>("", false, n); cleanUpNode(r); return NULL; // solved } else if(is_external(n->leftChild) && !is_external(n->rightChild)){ n->key = n->rightChild->key; delete n->value; n->value = n->rightChild->value; n->rightChild->value = NULL; RBNode<T>* r = n->rightChild; n->rightChild = new RBNode<T>("", false, n); cleanUpNode(r); return NULL; // solved } else{ if(is_root(n)){ root = new RBNode<T>("", false, NULL); cleanUpNode(n); return NULL; } RBNode<T> *s; if(n->parent->leftChild == n){ n->parent->leftChild = new RBNode<T>("", false, n->parent); s = n->parent->rightChild; } else{ n->parent->rightChild = new RBNode<T>("", false, n->parent); s = n->parent->leftChild; } if(n->isRed) s = NULL; // no need to solve cleanUpNode(n); return s; // solved } } template <class T> void RBTree<T>::solve_double_black(RBNode<T>* s){ if(is_external(s)) return; if(!s->isRed){ if(s->leftChild->isRed || s->rightChild->isRed){ // case 1: restruct s->isRed = true; restruct(s); } else{ // case 2: recolor if(s->parent->isRed){ // case 2-1 s->parent->isRed = false; s->isRed = true; } else{ s->isRed = true; s->parent->isRed = false; if(!is_root(s->parent)) solve_double_black(s->parent); } } } else{ // case 3 RBNode<T> *z, *r; if(s->parent->leftChild == s){ z = s->leftChild; // case 3-1 r = s->parent->rightChild; } else{ z = s->rightChild; // case 3-2 r = s->parent->leftChild; } z->isRed = true; restruct(s); z->isRed = false; s->isRed = false; r->parent->isRed = true; if(r->parent->leftChild == r) solve_double_black(r->parent->rightChild); else solve_double_black(r->parent->leftChild); } } // remove template <class T> bool RBTree<T>::remove(string key){ RBNode<T> *n = search(key); if(is_external(n)) return false; RBNode<T> *s = remove_from_binary_tree(key); if(s == NULL) return true; // finishe solve_double_black(s); return true; } template class RBTree<LinkedList>;
Shell
UTF-8
3,723
4.03125
4
[]
no_license
#!/bin/bash ########### # Uploads a single app in the 'products' folder to TestFairy. ########### # default values for optional parameters TESTER_GROUPS="" AUTO_UPDATE="on" MAX_DURATION="10m" VIDEO="off" COMMENT="" VAMS="off" NOTIFY="off" OPTIONS="" usage() { echo "Usage: upload-to-testfairy.sh -a <App Name> [ -t <Tester Groups> ] [ -u <Auto Update> ] [ -d <Duration> ] [ -r <Video> ] [ -c <Comment> ] [ -o <Options> ] [ -vn ] " echo echo -e " <App Name>\tThe name of the .ipa in the products folder of the app to upload." echo -e " <Groups>\tComma-separated list (no spaces) of tester groups from TestFairy account to whom this build will be shared." echo -e " -n\t\tNotify invited testers via e-mail." echo -e " -v\t\tSend the download URL to VAMS." echo -e " -u\t\t\"on\" or \"off\": whether this app should auto-update on testers' devices" echo -e " -d\t\tMaximum recording duration for a test session" echo -e " -r\t\t\"on\", \"off\", or \"wifi\": whether video recording is enabled for this build" echo -e " -c\t\tComment text to be included in the email sent to testers" echo } while getopts :a:t:u:d:r:c:o:vn opt; do case $opt in a ) APPNAME=`basename "$OPTARG"` ;; t ) TESTER_GROUPS="$OPTARG" ;; u ) AUTO_UPDATE="$OPTARG" ;; d ) MAX_DURATION="$OPTARG" ;; r ) VIDEO="$OPTARG" ;; c ) COMMENT="$OPTARG" ;; o ) OPTIONS="$OPTARG" ;; v ) VAMS="on" ;; n ) NOTIFY="on" ;; \? ) usage; exit 1 ;; esac done if [[ "$APPNAME" == "" ]]; then usage exit 1 fi IPA_FILENAME="products/$APPNAME.ipa" if [ ! -f "${IPA_FILENAME}" ]; then echo "Invalid input: Can't find an .ipa file in 'products' folder for app named '${APPNAME}'." usage exit 2 fi UPLOADER_VERSION=1.09 # TestFairy API_KEY here for build.server@getvictorious.com TESTFAIRY_API_KEY="61e501eea8b80b5596c7e17c9fea4739ec6e8a86" # locations of various tools CURL=curl SERVER_ENDPOINT=http://app.testfairy.com verify_tools() { # Check 'curl' tool ${CURL} --help >/dev/null if [ $? -ne 0 ]; then echo "Could not run curl tool, please check settings" exit 1 fi } verify_settings() { if [ -z "${TESTFAIRY_API_KEY}" ]; then usage echo "Please update API_KEY with your private API key, as noted in the Settings page" exit 1 fi } # before even going on, make sure all tools work verify_tools verify_settings /bin/echo "Uploading ${IPA_FILENAME} to TestFairy..." JSON=$( ${CURL} -s ${SERVER_ENDPOINT}/api/upload -F api_key=${TESTFAIRY_API_KEY} -F file="@${IPA_FILENAME}" -F video="${VIDEO}" -F options="${OPTIONS}" -F max-duration="${MAX_DURATION}" -F comment="${COMMENT}" -F testers-groups="${TESTER_GROUPS}" -F auto-update="${AUTO_UPDATE}" -F notify="${NOTIFY}" -A "TestFairy iOS Command Line Uploader ${UPLOADER_VERSION}" ) URL=$( echo ${JSON} | sed 's/\\\//\//g' | sed -n 's/.*"instrumented_url"\s*:\s*"\([^"]*\)".*/\1/p' ) if [ -z "$URL" ]; then echo "ERROR: Build uploaded, but no reply from server. Please contact support@testfairy.com: $JSON" exit 1 fi echo "SUCCESS: Build was successfully uploaded to TestFairy and is available at: ${URL}" # Post Test Fairy url to VAMS if requested if [ "$VAMS" == "on" ]; then echo echo "Posting Test Fairy url for ${APPNAME} to Victorious backend" RESPONSE=$(python "build-scripts/VAMS/vams_postbuild.py" ${APPNAME} ios ${URL} 2>&1) RESPONSE_CODE=$(echo "$RESPONSE" | cut -f1 -d '|') RESPONSE_MESSAGE=$(echo "$RESPONSE" | cut -f2 -d '|') if [ $RESPONSE_CODE -ne 0 ]; then echo $RESPONSE_MESSAGE exit 1 else echo "Test Fairy URL for ${APPNAME} was posted back to VAMS successfully" fi fi exit 0
Markdown
UTF-8
629
2.515625
3
[]
no_license
Assignment 2: Augmented Reality Movie Player See results/movie_t1 for final results. The movie is overlayed onto a book, and stays on top of the book even as the camera moves around and the book changes orientation. This is done using the BRIEF feature detector to get point pairs and find the position of the book. Every frame, a homography matrix is computed to find the orientation of the book, so that the video can be warped to that orientation and mapped onto the book cover. The RANSAC algorithm is used to detect outliers in the feature descripter, and compute the homography matrix faster using fewer data points.
C++
UTF-8
6,956
2.9375
3
[]
no_license
//----------------------------------------------------------------------- // Pthreads matrix multiply // This creates a stupid amount of threads to inefficiently // perform matrix multiplication. The point of this is to // create a workload with a large number of threads competing over // a shared resource //----------------------------------------------------------------------- // Original code by: Gita Alaghband, Lan Vu // Modified by Trevor Simonton, Anthony Pfaff, Cory Linfield, Alex Klein //----------------------------------------------------------------------- #include <iostream> #include <iomanip> #include <cmath> #include <time.h> #include <cstdlib> #include <stdio.h> #include <pthread.h> #define handle_error_en(en, msg) \ if(en != 0) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) int LOCK = 0; int UNLOCK = 1; using namespace std; // globals for p threads struct helper { pthread_t t; int idx; }; int n = 0; float **a,**b,**c; int** cmutexes; helper **threads; int locked = 0; int priority = 0; sched_param pri; pthread_attr_t attr; static inline void spinlock(int * a); static inline void spinunlock(int * b); //----------------------------------------------------------------------- // Get user input for matrix dimension or printing option //----------------------------------------------------------------------- bool GetUserInput(int argc, char *argv[],int& isPrint) { bool isOK = true; if(argc < 2) { cout << "Arguments:<X> [<Y>]" << endl; cout << "X : Matrix size [X x X]" << endl; cout << "Y = 1: Use mutex lock" << endl; cout << "Y <> 1 or missing: does not use mutex lock" << endl; cout << "Z : integer priority between 1 and 99, default if not specified" << endl; isOK = false; } else { //get matrix size n = atoi(argv[1]); if (n <=0) { cout << "Matrix size must be larger than 0" <<endl; isOK = false; } locked = 0; if (argc >=3) locked = (atoi(argv[2])==1 && n <=9)?1:0; else locked = 0; if(argc >= 4) { priority = atoi(argv[3]); if(priority < 1 || priority > 99) { cout << "Priority must be between 1 and 99, inclusive" << endl; isOK = false; } else { const struct sched_param const_pri = {priority}; handle_error_en(pthread_attr_init(&attr),"pthread_attr_init"); handle_error_en(pthread_attr_setschedpolicy(&attr,SCHED_RR), "pthread_attr_setschedpolicy"); handle_error_en(pthread_attr_setschedparam(&attr,&const_pri), "pthread_attr_setschedparam"); handle_error_en(pthread_setschedparam(pthread_self(),SCHED_RR , &const_pri), "pthread_setschedparam"); } } } return isOK; } //----------------------------------------------------------------------- //Initialize the value of matrix x[n x n] //----------------------------------------------------------------------- void InitializeMatrix(float** &x,float value) { x = new float*[n]; x[0] = new float[n*n]; for (int i = 1; i < n; i++) x[i] = x[i-1] + n; for (int i = 0 ; i < n ; i++) { for (int j = 0 ; j < n ; j++) { x[i][j] = value; } } cmutexes = new int*[n]; cmutexes[0] = new int[n*n]; for (int i = 1; i < n; i++) cmutexes[i] = cmutexes[i-1] + n; // init locks for (int i = 0 ; i < n; ++i) { for (int j = 0 ; j < n; ++j) { cmutexes[i][j] = &UNLOCK; } } // create helpers for threads threads = new helper*[n*n*n]; for (int i = 0 ; i < n*n*n; ++i) { threads[i] = new helper(); threads[i]->idx = i; } } //------------------------------------------------------------------ //Delete matrix x[n x n] //------------------------------------------------------------------ void DeleteMatrix(float **x) { delete[] x[0]; delete[] x; } //------------------------------------------------------------------ //Print matrix //------------------------------------------------------------------ void PrintMatrix(float **x) { for (int i = 0 ; i < n ; i++) { cout<< "Row " << (i+1) << ":\t" ; for (int j = 0 ; j < n ; j++) { printf("%.2f\t", x[i][j]); } cout<<endl ; } } //------------------------------------------------------------------ //Do Matrix Multiplication //------------------------------------------------------------------ // individual result matrix cell thread callback void* row_col_sum(void* idp) { int id = *(int*)idp; int k = id % n; id = id/n; int j = id % n; id = id/n; int i = id % n; if (locked == 1) { spinlock (&(cmutexes[i][j])); c[i][j] += a[i][k]*b[k][j]; spinunlock (&(cmutexes[i][j])); } else { c[i][j] += a[i][k]*b[k][j]; } pthread_exit(NULL); } void printPriInfo() { int pol; cout << "sched: " << pthread_getschedparam(pthread_self(), &pol, &pri) << endl; cout << "Attr pri: " << pri.sched_priority << endl; cout << "Attr pol: " << pol << ((pol==SCHED_RR)?"SCHED_RR":"") << endl; switch(pol) { case SCHED_RR: cout << "RR" << endl; break; case SCHED_OTHER: cout << "OTHER" << endl; break; case SCHED_FIFO: cout << "FIFO" << endl; break; case SCHED_IDLE: cout << "IDLE" << endl; break; case SCHED_BATCH: cout << "BATCH" << endl; break; } } static inline void spinlock(int * lock) { __asm__ __volatile__( "1: \n\t" "PUSH {r0-r2}\n\t" "LDR r0, %[lock]\n\t" "LDR r2, =0x12345678\n\t" "SWP r1, r2, [r0]\n\t" "CMP r1,r2\n\t" "BEQ 1b\n\t" "POP {r0-r2}\n\t" //"BX lr\n\t" //"ENDP\n\t" : : [lock] "m" (lock) : ); } static inline void spinunlock(int * lock) { __asm__ __volatile__( "PUSH {r0-r1}\n\t" "LDR r1, =0x87654321\n\t" "LDR r0, %[lock]\n\t" "STR r1, [r0]\n\t" "POP {r0-r1}\n\t" //"BX lr\n\t" //"ENDP\n\t" : : [lock] "m" (lock) : ); } void MultiplyMatrix() { for (int i = 0 ; i < n * n * n; i++) { if(priority != 0 ) { handle_error_en(pthread_create(&(threads[i]->t), &attr, row_col_sum, (void *) &(threads[i]->idx)),"pthread_create1"); } else { handle_error_en(pthread_create(&(threads[i]->t), NULL, row_col_sum, (void *) &(threads[i]->idx)),"pthread_create2"); } } } //------------------------------------------------------------------ // Main Program //------------------------------------------------------------------ int main(int argc, char *argv[]) { int isPrint; float runtime; if (GetUserInput(argc,argv,isPrint)==false) return 1; //Initialize the value of matrix a, b, c InitializeMatrix(a,9.0); InitializeMatrix(b,9.0); InitializeMatrix(c,0.0); runtime = clock()/(float)CLOCKS_PER_SEC; MultiplyMatrix(); void *status; for(int t=0; t<n*n*n; t++) { if(priority == 1) printPriInfo(); handle_error_en(pthread_join(threads[t]->t, &status), "pthread_join"); } runtime = clock()/(float)CLOCKS_PER_SEC - runtime; // check for errors in result bool ok = true; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (c[i][j] != c[0][0]) ok = false; } } if (ok) cout << "ok\t"; else cout << "wrong\t"; DeleteMatrix(a); DeleteMatrix(b); DeleteMatrix(c); pthread_exit(NULL); return 0; }
JavaScript
UTF-8
831
2.65625
3
[]
no_license
const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; var wall1,wall2,wall3,ground,paper; function preload() { } function setup() { createCanvas(800, 740); engine = Engine.create(); world = engine.world; //Create the Bodies Here. wall1 = new wall(750,700,20,80); wall2 = new wall(600,700,20,80); wall3 = new wall(670,730,150,20); paper = new Paper(200,100,20); ground = new Ground(600,height,1200,20); Engine.run(engine); } function draw() { rectMode(CENTER); background("black"); wall1.display(); wall2.display(); wall3.display(); paper.display(); ground.display(); drawSprites(); } function keyPressed() { if (keyCode === DOWN_ARROW) { Body.applyForce(paper.body,paper.body.position,{x:85,y:-85}) } }
Java
UTF-8
592
1.890625
2
[]
no_license
package com.example.hotelin_android.modul.preview_booking; import com.example.hotelin_android.base.BaseFragmentHolderActivity; public class PreviewBookingActivity extends BaseFragmentHolderActivity { @Override protected void initializeFragment() { initializeView(); String check_in = getIntent().getStringExtra("check_in"); String check_out = getIntent().getStringExtra("check_out"); PreviewBookingFragment previewBookingFragment = new PreviewBookingFragment(check_in, check_out); setCurrentFragment(previewBookingFragment, false); } }
Markdown
UTF-8
1,362
3
3
[]
no_license
# hello-dropwizard Thanks for giving the opportunity to perform this exercise. # Introduction Considering this as a dev environment, I have made the setup automated and deployment the API in local totally stress free. I have used the docker-compose to collaborate the Container for the API app and Nginx for handling the load balancing and http flow. Kind Note:- I have done this exercise on a Macbook and didn't require the vagrant to use. I have consider the docker engine running in my system. # How to deploy ? It is very simple execute below command in here. `docker-compose up` That's it !!! # What's happening behind the scene ? The docker compose contains 2 part :- <b> APP </b> - Dockerfile present in here. That will compile and package it up the code and run the java against that jar file and expose that to port 8080. <b> NGINX </b> - Nginx gets the required configurations present from nginx/conf.d/nginx.conf and place it to the container. This map the port 8080(Exposed by the app) with 80(http) and handles the redirect required as per the business requirement. # How to use ? Just execute below on browser http://localhost/hello-world As per the requirement /hello should redirect to hello-dropwizard/hello-world, This is been convered by the nginx. http://localhost/hello redirects to http://localhost/hello-dropwizard/hello-world
C++
UTF-8
554
2.703125
3
[ "MIT" ]
permissive
#include <cpplib/stdinc.hpp> bool check(int a, int b, int c){ return a+b>c and a+c>b and b+c>a; } int32_t main(){ desync(); int t; cin >> t; while(t--){ int n; cin >> n; vii arr(n); for(int i=0; i<n; ++i){ cin >> arr[i].ff; arr[i].ss = i+1; } sort(all(arr)); if(check(arr[0].ff, arr[1].ff, arr[n-1].ff)) cout << -1 << endl; else cout << arr[0].ss << ' ' << arr[1].ss << ' ' << arr[n-1].ss << endl; } return 0; }
Python
UTF-8
481
2.765625
3
[]
no_license
import os for name in ['training', 'testing']: with open('mnist_dataset_{}.csv'.format(name), 'w') as output_file: print('=== creating {} dataset ==='.format(name)) output_file.write('image_path,label\n') for i in range(10): path = 'mnist_png/{}/{}'.format(name, i) for file in os.listdir(path): if file.endswith(".png"): output_file.write('{},{}\n'.format(os.path.join(path, file), str(i)))
Java
UTF-8
1,004
2.109375
2
[]
no_license
package com.ajs.speech.Activities; public class meechInit { private String mUid; private String title; private String content; private String uniqId; public meechInit() { } // ^ Firebase needs meechInit() here ^ public meechInit(String mUid, String title, String content, String uniqId) { this.mUid = mUid; this.title = title; this.content = content; this.uniqId = uniqId; } public String getMUid() { return mUid; } public void setMUid(String mUid) { this.mUid = mUid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUniqId() { return uniqId; } public void setUniqId(String uniqId) { this.uniqId = uniqId; } }
Markdown
UTF-8
9,586
2.875
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 第五章 乐莫乐兮心相知 --- 琴言衣带微招,就宛如一片紫云落了下来,片尘不起。 她向吴越王盈盈一礼,道:“王爷取笑了,琴言哪里有这么大的胆子。不过琴言猜王爷也没有这么大的胆子……” 她抬头一笑,看了吴越王一眼,道:“若是琴言这样的怀心肠做了皇帝的嫔妃啊,就怕第一天就忍不住撺掇着皇帝杀了王爷,第二天就让你的老皇帝死在我的手上哩,那多不好呢?我这个人就喜欢看着大家都欢欢喜喜的,才不想谁不开心呢。”她言语之中略带了点吴侬之音,姣姣软软,说不出的妩媚好听。 吴越王淡淡笑道:“只要琴言姑娘答应了,我保证这些事情一概不会发生!” 琴言道:“噢,那琴言就更是不敢去了。嫁了老皇帝不弄死他我不开心,弄死他了你们又不开心。反正总会有不开心的,那多不好啊。” 吴越王淡淡道:“既然姑娘没有这个念头,那就请让开了,不要误了我们恭迎贵妃。” 琴言轻抬双眸看他一眼,脸上依旧一副动人的媚笑,道:“贵妃?却不知是皇宫的贵妃呢,还是华音阁的圣妃?” 吴越王脸色一变,道:“难道这件事华音阁也想插一脚?” 琴言抬袖掩口笑道:“哪里是华音阁想插王爷一脚哩,而是看王爷肯不肯赏脸让我将阁主要的人带回去了。” 吴越王看了吉娜一眼,道:“你们阁主想要这个小丫头?” 琴言一福礼道:“琴言就知道王爷神机妙算,自然不用我来啰唆啦。” 吴越王冷哼一声道:“那你是不用想了。” 琴言轻轻抱琴,一手抬袖,俏指掩面,脸上显出无限委屈:“那王爷是想要琴言完不成任务,去受阁主的责罚吗?难道王爷忍心?”此人当真如胭脂捏就的一般,妩媚已入骨中,一行一动之间,尽是怡人荡意的万种风情,却偏生做得自然而然至极,浑然没有斧凿的刻意之感。 吴越王淡淡道:“素闻华音阁主卓王孙什么都是天下第一,江湖上更是推举为神一般的人物,本王早想拜识芝颜,可是仙山路遥,却从来没有这等机会。今日相遇,就来领教一下琴言姑娘的武功,看看强将之下,是否真的就无弱兵。” 琴言轻轻一笑,道:“言重了呢……莫非王爷觉得自己不够资格做我们阁主的敌人吗?” 吴越王双拳一聚,一道凌厉的杀气飙出,厉声道:“你说什么?” 琴言猛觉一阵寒意沛然而来,脸上的媚笑再也挂不住,神色一惊,不由自主退了一步。 吴越王一怒之下,也觉自己失态,当下袍袖一拂,满室骤然生暖。 琴言啧了一声道:“王爷好功夫,但可惜气量稍嫌窄了些。”笑容甜蜜,仿佛情人之间的细语,却是让人怎么都无法生气。吴越王倒也不好发作,招手道:“欧天健,你来会会这位姑娘。若是败了,也就不要回来见本王了。” 欧天健方才被吉娜一掌击伤,正是一口怨气没处发作,见琴言言笑温婉,抱琴而立,一派妩媚入骨的样子,顿时起了轻敌之心。虽然琴言的名字欧天健也曾听过,但一见之下,不由心想这种柔弱的女子,不过侥幸成名,论实际武功还能高到哪里去?于是上前两步,背负着双手,冷冷看着琴言,似乎还不屑于先动手。 琴言半点也不瞧他,慢拨着弦音震出,她的声音也如这琴音袅袅,充溢了整个茶寮:“若是琴言侥幸赢了这位欧大哥,那又怎样呢?”语音软侬,似乎并不是在战场争杀之际,倒像是跟情郎软语相商。 吴越王傲然道:“你若是能胜得了一招半式,难道本王还有脸皮再作纠缠不行?若是你输了,吉娜姑娘却要交我们带走。” 琴言妩媚一笑道:“若我输了,王爷想要怎样就怎样。” 吴越王也不去看她,只对欧天健道:“琴言姑娘司职华音阁新月妃,手中古琴天风环佩,自唐代传世七百年来,名动天下,你要留心了。” 欧天健向琴言怀中一瞥,冷笑道:“天下名宝,都应该珍藏在王爷的万宝楼中,琴言姑娘可肯割爱?” 琴言微微一笑,既不怒也不答话。 吴越王道:“天风环佩琴乃天下名器,琴曲共分为七叠,修习到极高处,可引来鸾凤合鸣,威力亦是强绝天下。琴言姑娘领华音阁新月妃之职,幼得嫡传,本王尚且不敢小视,何况你?” 欧天健看了看琴言,冷笑道:“华音阁的武功自然是高明的,却不知道琴姑娘花信之年,又能学到几分?” 琴言依旧笑道:“既然欧护法这样讲,琴言若不奉陪,怕是折不起华音阁的面子,失礼了。” 语未完,纤指倏然在琴弦上一划,欧天健猛觉数道凌厉的劲风袭至。有了吉娜前车之鉴,他倒也不敢大意,当下玄功暗运,呼地一掌,当胸向琴言击去。 欧天健的武功纯走阴柔一路,这一掌击出,满室寒气陡升,吉娜忍不住打了个冷战。却见琴言衣袂飘飘,随着欧天健的掌风催送,起在空中,浑然不似血肉之躯。两只纤手按住琴弦,一阵叮叮咚咚的柔音响起,就仿佛春花乍开,雏鸟共鸣,野芳新发,弱柳含苔,使人不禁有出游之兴。 吉娜舒了口气,就听吴越王曼声吟道:“春分惊蜇絮满天,云开日暖响丝弦。这一曲《春晓吟》,可称绝妙。” 琴言向他回眸一笑,琴音忽转清疏宽放,伶俐奔畅,峨峨忽有高山之意,汤汤而又做流水之磬。吴越王笑道:“好,你将我当成了樵夫了。” 琴言雪腮之上梨涡浅绽,意似酬答。欧天健只觉袭来的暗劲更加无声无息,忽强忽弱,缠绵柔软,一如琴言脸上的微笑,不得不将轻敌之心收起,当下拳势一展,三拳叠出,分袭琴言左右中路。 只听琴音忽然加大,莽然有千里平阔,浩渺森然之象。欧天健便觉拳劲如石沉大海,暗呼不妙,还未来得及变招,一道大到不可思议的劲力凌空压下。危急之刻不及细想,聚起全身劲力,要硬接这一来去无踪的招数。那劲力突然消失得无影无踪,欧天健正收势不及,又一股悄无声息的力道自身后涌出,他此时哪里还有变通的余地?一口鲜血标出,向前直跌出去。 琴言轻轻一笑,曲子又变得轻松柔和,宛如一个无忧无虑的少女,正在花园嬉戏。 就听吴越王叹道:“姑娘武功变化多端,这琴艺也妙到不可思议。由渔樵问答而到沧海龙吟,阳关三叠追杀欧天健,却由宫调变为商调,一阕寄生草就将他打得口吐鲜血,实在不由人不叹服。” 琴言正打得欧天健毫无还手之力,闻言微微一笑,道:“你主子只顾卖弄自己的才华,都不管你的死活了,我也就懒得理你,罢手吧!” 欧天健知道不妙,顾不得再招架,脚一点地,全速向上跃起。就听万千琴声归为一音,清越如笛,嘹响振耳,倏忽而来,就如一只无形的利箭一般,要将欧天健钉在空中! 欧天健只觉避无可避,恐惧之下,一声惊呼还未发出,眼前人影闪动,一只手凌空将这道箭劲夹住,却正是吴越王。 就见他袍袖展动,将欧天健的身形带住,目中神光暴出:“姑娘好功夫,本王来领教一招!”微一侧身,一记劈空掌隔了两丈余远劈至! 琴言就觉一道炽热的劲力从琴上升起,全身如受电击,知道不能抵挡,危急之中,将那柄天风环佩脱手飞起,飘然向后而退。 吴越王并不追赶,手一招,天风环佩凌空向他飞至,被他真气激得清响不绝,赞叹道:“果然是好琴。” 琴言飘飘从空中跃下,笑道:“王爷的功夫,就是不显,琴言也知道绝不是对手。可是这一仗,是谁赢了呢?” 吴越王淡淡道:“自然是你赢了。你觉得本王的武功跟你们阁主比较起来,谁更胜一筹?” 琴言微微一笑道:“嗯,王爷问这个,我可就不知道了。这几年来,我们阁主可从来没出过手,不像王爷这样好动。” 吴越王叹道:“世俗之事众多,这也是身不由己。琴还你,吉娜你也可以带走。草莽之地,龙蛇混杂,你不如到本王府中,想要什么样的前程,本王必不二言。” 琴言接过瑶琴,摇了摇头,道:“王爷的话我自然很相信,但我一个女子,要前程做什么?我还是老老实实地听阁主的话,将吉娜带回去就可以了。” 吴越王叹道:“本王知道姑娘这样的人,也不是一朝一夕可以求得的。卓王孙好福气,有你这样的帮手。这一点本王是甘拜下风了。” 琴言笑了一下,并不作答。 吴越王昂天一笑,道:“我们既然输了,就输得光明磊落一点。欧天健,你输在琴言姑娘手中,不算你的罪过。去收拾一下,我们赶紧走了,免得叫别人说本王食言而肥,不是英雄的手段。” 欧天健答应一声,吴越王飘然而出,长吟之声不绝,已经渐渐去得远了。 琴言看着他的背影,轻轻道:“你让我到你的府上,给我个满意的前程,你可知我所要的并不是什么劳什子前程呢。”言语之中,神色颇为复杂。
Java
UTF-8
385
1.96875
2
[]
no_license
package com.example.demo.repository; import com.example.demo.entity.Coin; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CoinRepository extends JpaRepository<Coin, Long> { List<Coin> findAllByMarketIdEquals(long id); List<Coin> findAllByNameEquals(String name); Coin save(Coin coin); List<Coin> findAll(); }
Python
UTF-8
1,233
3.5
4
[]
no_license
def print_first_line(textfile: str): my_file = open(textfile, mode='r') print(my_file.readline()) my_file.close() def print_fifs_line(textfile: str): my_file = open(textfile, mode='r') for _ in range(4): my_file.readline() print(my_file.readline()) my_file.close() def print_five_lines(textfile: str): my_file = open(textfile, mode='r') for _ in range(5): print(my_file.readline()) my_file.close() def print_from_to_lines(textfile: str, from_line, to_line): my_file = open(textfile, mode='r') for _ in range(from_line - 1): my_file.readline() for _ in range(to_line): print(my_file.readline()) my_file.close() def print_all_lines(textfile: str): my_file = open(textfile, mode='r') if not my_file.readline(): print(my_file.readline()) print_all_lines('text_file.txt') def write_lines_from_keyboard(): with open("text_file.txt", mode='r') as text_file: with open('text_file2.txt', 'w') as new_text_file: while True: readline if not: break converter_str. new_text_file.write(converter_str) write_lines_from_keyboard()
JavaScript
UTF-8
1,687
3.4375
3
[]
no_license
let movieList = []; let movieInput = document.querySelector('input[type="text"]'); let ul = document.querySelector("ul"); function createElement(tag, props = {}, [...children]) { let elm = document.createElement(tag); console.log(Array.isArray(children)); children.forEach((c) => { if (typeof c === "string") { let childElement = document.createTextNode(c); elm.append(childElement); } else if (typeof c === "object") { elm.append(c); } }); return elm; } function createUI(data = movieList, root = ul) { root.innerHTML = ""; data.forEach((movie, index) => { let checked = movie.isWatched ? "Watched" : "To Watch"; let p = createElement("p", null, movie.name); let button = createElement("button", { "data-id": index }, checked); let del = createElement("span", { "data-id": index }, "x"); let li = createElement("li", null, [p, button, del]); ul.append(li); }); } function toggleWatch(event) { if (event.target.nodeName === "BUTTON") { let id = event.target.dataset.id; movieList = movieList.map((movie, index) => { if (index == id) { return { ...movie, isWatched: !movie.isWatched, }; } return movie; }); createUI(); } } function handleInput(event) { if (event.keyCode === 13) { movieList = movieList.concat({ name: event.target.value, isWatched: false, }); event.target.value = ""; createUI(); } } function deleteMovie(event) { if (event.target.nodeName === "SPAN") { let id = event.target.dataset.id; movieList.splice(id, 1); createUI(); } } ul.addEventListener("click", toggleWatch); ul.addEventListener("click", deleteMovie); movieInput.addEventListener("keyup", handleInput);
Java
UTF-8
463
2.171875
2
[]
no_license
package com.xhs.mlecg; public class GlobalConfig { private static GlobalConfig instance = null; private String url = ""; private GlobalConfig() { } public static GlobalConfig getInstance() { if (instance == null) { instance = new GlobalConfig(); } return instance; } public String getUrl() { return this.url; } public void setUrl(String url2) { this.url = url2; } }
Java
UTF-8
3,762
2.234375
2
[]
no_license
package pageObjects; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * The page object for the Accordian Widget page Implemented locating through xpath * only when no other means applied. * * @author jPayne */ public class Accordion extends BasePage { /** * The main accordion menu in center of page (3 tabs) */ @FindBy(id = "ui-id-1") protected static WebElement defaultFunctionalityTab;// tab1 @FindBy(id = "ui-id-2") protected static WebElement customizeIconsTab;// tab2 @FindBy(id = "ui-id-3") protected static WebElement fillSpaceTab;// tab3 /** * Default Functionality tab's elements */ @FindBy(id = "ui-accordion-accordion-header-0") protected static WebElement section1headerTab1; @FindBy(id = "ui-accordion-accordion-panel-0") protected static WebElement section1panelTab1; @FindBy(id = "ui-accordion-accordion-header-1") protected static WebElement section2headerTab1; @FindBy(id = "ui-accordion-accordion-panel-1") protected static WebElement section2panelTab1; @FindBy(id = "ui-accordion-accordion-header-2") protected static WebElement section3headerTab1; @FindBy(id = "ui-accordion-accordion-panel-2") protected static WebElement section3panelTab1; @FindBy(id = "ui-accordion-accordion-header-3") protected static WebElement section4headerTab1; @FindBy(id = "ui-accordion-accordion-panel-3") protected static WebElement section4panelTab1; /** * Custom Icons tab's elements */ @FindBy(id = "ui-accordion-accordion_icons-header-0") protected static WebElement section1headerTab2; @FindBy(xpath=".//*[@id='ui-accordion-accordion_icons-header-0']/span") protected static WebElement section1Arrow; @FindBy(id = "ui-accordion-accordion_icons-panel-0") protected static WebElement section1panelTab2; @FindBy(id = "ui-accordion-accordion_icons-header-1") protected static WebElement section2headerTab2; @FindBy(xpath=".//*[@id='ui-accordion-accordion_icons-header-1']/span") protected static WebElement section2Arrow; @FindBy(id = "ui-accordion-accordion_icons-panel-1") protected static WebElement section2panelTab2; @FindBy(id = "ui-accordion-accordion_icons-header-2") protected static WebElement section3headerTab2; @FindBy(xpath=".//*[@id='ui-accordion-accordion_icons-header-2']/span") protected static WebElement section3Arrow; @FindBy(id = "ui-accordion-accordion_icons-panel-2") protected static WebElement section3panelTab2; @FindBy(id = "ui-accordion-accordion_icons-header-3") protected static WebElement section4headerTab2; @FindBy(xpath=".//*[@id='ui-accordion-accordion_icons-header-3']/span") protected static WebElement section4Arrow; @FindBy(id = "ui-accordion-accordion_icons-panel-3") protected static WebElement section4panelTab2; @FindBy(id = "toggle") protected static WebElement toggleButton; /** * Fill Space tab's elements */ @FindBy(id = "ui-accordion-accordion_fill-header-0") protected static WebElement section1headerTab3; @FindBy(id = "ui-accordion-accordion_fill-panel-0") protected static WebElement section1panelTab3; @FindBy(id = "ui-accordion-accordion_fill-header-1") protected static WebElement section2headerTab3; @FindBy(id = "ui-accordion-accordion_fill-panel-1") protected static WebElement section2panelTab3; @FindBy(id = "ui-accordion-accordion_fill-header-2") protected static WebElement section3headerTab3; @FindBy(id = "ui-accordion-accordion_fill-panel-2") protected static WebElement section3panelTab3; @FindBy(id = "ui-accordion-accordion_fill-header-3") protected static WebElement section4headerTab3; @FindBy(id = "ui-accordion-accordion_fill-panel-3") protected static WebElement section4panelTab3; }
Java
UTF-8
308
1.8125
2
[]
no_license
package org.gradle.test.performancenull_468; import static org.junit.Assert.*; public class Testnull_46713 { private final Productionnull_46713 production = new Productionnull_46713("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
PHP
UTF-8
1,987
2.78125
3
[ "MIT" ]
permissive
<?php /** * Slack API - api method implementation. * * @author Hiroki Yagyu. * @link https://github.com/HirokiYagyu/Slack * @package Slack.Controller.Component * @since SlackPlugin v1.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ App::uses('BaseComponent', 'Slack.Controller/Component'); /** * Slack API Api コンポーネント. * * Checks API calling code. * * @package Slack.Controller.Component */ class ApiComponent extends BaseComponent { /** * Slack API method name. * @var string * @see https://api.slack.com/methods */ protected static $_method = 'api'; /** * Error response to return. * @var string */ const OPTION_ERROR = 'error'; /** * API をテストする. * * This method helps you test your calling code. * * ### Eg. * ``` {.prettyprint .lang-php} * $Api->test([ * ApiComponent::OPTION_ERROR => 'my_error', * 'foo' => 'bar', * ]); * ``` * * ### Response. * ``` {.prettyprint .lang-js} * { * "ok": false, * "error": "my_error", * "args": { * "error": "my_error", * "foo": "bar" * } * } * ``` * * ### Use Option. * ApiComponent::OPTION_ERROR * : Error response to return. * * @param array $option オプション. * @return mixed レスポンスデータ. * * @see https://api.slack.com/methods/api.test */ public function test( array $option=[] ) { $requestData = [ self::OPTION_ERROR => null, // sample. 'bar' => null, // sample. ]; $requestData = array_merge( $requestData, $option ); $response = self::getRequest( 'test', self::_nullFilter($requestData) ); return $response; } }
PHP
UTF-8
360
2.578125
3
[]
no_license
<?php $filename = 'admin/playlist'; $playlist = array(); if (file_exists($filename)) { $file = fopen($filename, "r"); while (!feof($file)) { $line = trim(fgets($file)); if (empty($line)) continue; $playlist[] = explode('===',$line); }; fclose($file); }; echo json_encode($playlist);
Markdown
UTF-8
1,388
2.875
3
[ "MIT" ]
permissive
--- tags: programming layout: post title: "Give scripting languages their due" --- <a href="http://www.infoworld.com/article/03/02/06/06stratdev_1.html?s=tc">Shipping the Prototype</a> - Udell with another great column on why glue -- and more importantly, agile glue -- is so important when everything is moving lickety-split: <blockquote>In a world of distributed services in constant flux, when does exploration stop? Why would you ever want to switch from a codebase that is concise, malleable, and easily maintainable to one that isn't?</blockquote> <p>And this:</p> <blockquote>My point is that languages like Python, but also Perl, Ruby, and JavaScript/JScript/ActionScript/EcmaScript, are strategic in ways that we don't yet fully acknowledge. As I mentioned last time, the classic phased life cycle of software development -- design/develop/test/deploy -- is dissolving into a continuous process. Change is the only constant; the services we create and use are always exploratory. Languages that express programmers' intentions in fewer lines of code are a huge productivity win. The deliverable code is easier to understand and maintain -- and so, crucially, is the test infrastructure that supports it.</blockquote> <p>Maintainability - malleability - testability. Not quite " Libert&#233; - &#233;galit&#233; - fraternit&#233;," but it'll do.</p>
Java
UTF-8
35,915
1.804688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.querydsl.codegen; import static com.mysema.codegen.Symbols.*; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.*; import javax.annotation.Generated; import javax.inject.Inject; import javax.inject.Named; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.mysema.codegen.CodeWriter; import com.mysema.codegen.model.*; import com.querydsl.core.types.*; import com.querydsl.core.types.dsl.*; /** * {@code EntitySerializer} is a {@link Serializer} implementation for entity types * * @author tiwe * */ public class EntitySerializer implements Serializer { private static final Joiner JOINER = Joiner.on("\", \""); private static final Parameter PATH_METADATA = new Parameter("metadata", new ClassType(PathMetadata.class)); private static final Parameter PATH_INITS = new Parameter("inits", new ClassType(PathInits.class)); private static final ClassType PATH_INITS_TYPE = new ClassType(PathInits.class); protected final TypeMappings typeMappings; protected final Collection<String> keywords; /** * Create a new {@code EntitySerializer} instance * * @param mappings type mappings to be used * @param keywords keywords to be used */ @Inject public EntitySerializer(TypeMappings mappings, @Named("keywords") Collection<String> keywords) { this.typeMappings = mappings; this.keywords = keywords; } private boolean superTypeHasEntityFields(EntityType model) { Supertype superType = model.getSuperType(); return null != superType && null != superType.getEntityType() && superType.getEntityType().hasEntityFields(); } protected void constructors(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { String localName = writer.getRawName(model); String genericName = writer.getGenericName(true, model); boolean hasEntityFields = model.hasEntityFields() || superTypeHasEntityFields(model); boolean stringOrBoolean = model.getOriginalCategory() == TypeCategory.STRING || model.getOriginalCategory() == TypeCategory.BOOLEAN; String thisOrSuper = hasEntityFields ? THIS : SUPER; String additionalParams = getAdditionalConstructorParameter(model); String classCast = localName.equals(genericName) ? EMPTY : "(Class) "; // String constructorsForVariables(writer, model); // Path if (!localName.equals(genericName)) { suppressAllWarnings(writer); } Type simpleModel = new SimpleType(model); if (model.isFinal()) { Type type = new ClassType(Path.class, simpleModel); writer.beginConstructor(new Parameter("path", type)); } else { Type type = new ClassType(Path.class, new TypeExtends(simpleModel)); writer.beginConstructor(new Parameter("path", type)); } if (!hasEntityFields) { if (stringOrBoolean) { writer.line("super(path.getMetadata());"); } else { writer.line("super(", classCast, "path.getType(), path.getMetadata()" + additionalParams + ");"); } constructorContent(writer, model); } else { writer.line("this(", classCast, "path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));"); } writer.end(); // PathMetadata if (hasEntityFields) { writer.beginConstructor(PATH_METADATA); writer.line("this(metadata, PathInits.getFor(metadata, INITS));"); writer.end(); } else { if (!localName.equals(genericName)) { suppressAllWarnings(writer); } writer.beginConstructor(PATH_METADATA); if (stringOrBoolean) { writer.line("super(metadata);"); } else { writer.line("super(", classCast, writer.getClassConstant(localName) + COMMA + "metadata" + additionalParams + ");"); } constructorContent(writer, model); writer.end(); } // PathMetadata, PathInits if (hasEntityFields) { if (!localName.equals(genericName)) { suppressAllWarnings(writer); } writer.beginConstructor(PATH_METADATA, PATH_INITS); writer.line(thisOrSuper, "(", classCast, writer.getClassConstant(localName) + COMMA + "metadata, inits" + additionalParams + ");"); if (!hasEntityFields) { constructorContent(writer, model); } writer.end(); } // Class, PathMetadata, PathInits if (hasEntityFields) { Type type = new ClassType(Class.class, new TypeExtends(model)); writer.beginConstructor(new Parameter("type", type), PATH_METADATA, PATH_INITS); writer.line("super(type, metadata, inits" + additionalParams + ");"); initEntityFields(writer, config, model); constructorContent(writer, model); writer.end(); } } protected void constructorContent(CodeWriter writer, EntityType model) throws IOException { // override in subclasses } protected String getAdditionalConstructorParameter(EntityType model) { return ""; } protected void constructorsForVariables(CodeWriter writer, EntityType model) throws IOException { String localName = writer.getRawName(model); String genericName = writer.getGenericName(true, model); boolean stringOrBoolean = model.getOriginalCategory() == TypeCategory.STRING || model.getOriginalCategory() == TypeCategory.BOOLEAN; boolean hasEntityFields = model.hasEntityFields() || superTypeHasEntityFields(model); String thisOrSuper = hasEntityFields ? THIS : SUPER; String additionalParams = hasEntityFields ? "" : getAdditionalConstructorParameter(model); if (!localName.equals(genericName)) { suppressAllWarnings(writer); } writer.beginConstructor(new Parameter("variable", Types.STRING)); if (stringOrBoolean) { writer.line(thisOrSuper,"(forVariable(variable)",additionalParams,");"); } else { writer.line(thisOrSuper,"(", localName.equals(genericName) ? EMPTY : "(Class) ", writer.getClassConstant(localName) + COMMA + "forVariable(variable)", hasEntityFields ? ", INITS" : EMPTY, additionalParams,");"); } if (!hasEntityFields) { constructorContent(writer, model); } writer.end(); } protected void entityAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); writer.beginPublicMethod(queryType, field.getEscapedName()); writer.line("if (", field.getEscapedName(), " == null) {"); writer.line(" ", field.getEscapedName(), " = new ", writer.getRawName(queryType), "(forProperty(\"", field.getName(), "\"));"); writer.line("}"); writer.line(RETURN, field.getEscapedName(), SEMICOLON); writer.end(); } protected void entityField(EntityType model, Property field, SerializerConfig config, CodeWriter writer) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); if (field.isInherited()) { writer.line("// inherited"); } if (config.useEntityAccessors()) { writer.protectedField(queryType, field.getEscapedName()); } else { writer.publicFinal(queryType, field.getEscapedName()); } } protected boolean hasOwnEntityProperties(EntityType model) { if (model.hasEntityFields()) { for (Property property : model.getProperties()) { if (!property.isInherited() && property.getType().getCategory() == TypeCategory.ENTITY) { return true; } } } return false; } protected void initEntityFields(CodeWriter writer, SerializerConfig config, EntityType model) throws IOException { Supertype superType = model.getSuperType(); if (superType != null) { EntityType entityType = superType.getEntityType(); if (entityType != null && entityType.hasEntityFields()) { Type superQueryType = typeMappings.getPathType(entityType, model, false); writer.line("this._super = new " + writer.getRawName(superQueryType) + "(type, metadata, inits);"); } } for (Property field : model.getProperties()) { if (field.getType().getCategory() == TypeCategory.ENTITY) { initEntityField(writer, config, model, field); } else if (field.isInherited() && superType != null && superType.getEntityType().hasEntityFields()) { writer.line("this.", field.getEscapedName(), " = _super.", field.getEscapedName(), SEMICOLON); } } } protected void initEntityField(CodeWriter writer, SerializerConfig config, EntityType model, Property field) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); if (!field.isInherited()) { boolean hasEntityFields = field.getType() instanceof EntityType && ((EntityType) field.getType()).hasEntityFields(); writer.line("this." + field.getEscapedName() + ASSIGN, "inits.isInitialized(\"" + field.getName() + "\") ? ", NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\")", hasEntityFields ? (", inits.get(\"" + field.getName() + "\")") : EMPTY, ") : null;"); } else if (!config.useEntityAccessors()) { writer.line("this.", field.getEscapedName(), ASSIGN, "_super.", field.getEscapedName(), SEMICOLON); } } protected void intro(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { introPackage(writer, model); introImports(writer, config, model); writer.nl(); introJavadoc(writer, model); introClassHeader(writer, model); introFactoryMethods(writer, model); introInits(writer, model); if (config.createDefaultVariable()) { introDefaultInstance(writer, model, config.defaultVariableName()); } if (model.getSuperType() != null && model.getSuperType().getEntityType() != null) { introSuper(writer, model); } } @SuppressWarnings(UNCHECKED) protected void introClassHeader(CodeWriter writer, EntityType model) throws IOException { Type queryType = typeMappings.getPathType(model, model, true); TypeCategory category = model.getOriginalCategory(); Class<? extends Path> pathType; if (model.getProperties().isEmpty()) { switch (category) { case COMPARABLE : pathType = ComparablePath.class; break; case ENUM: pathType = EnumPath.class; break; case DATE: pathType = DatePath.class; break; case DATETIME: pathType = DateTimePath.class; break; case TIME: pathType = TimePath.class; break; case NUMERIC: pathType = NumberPath.class; break; case STRING: pathType = StringPath.class; break; case BOOLEAN: pathType = BooleanPath.class; break; default : pathType = EntityPathBase.class; } } else { pathType = EntityPathBase.class; } for (Annotation annotation : model.getAnnotations()) { writer.annotation(annotation); } writer.line("@Generated(\"", getClass().getName(), "\")"); if (category == TypeCategory.BOOLEAN || category == TypeCategory.STRING) { writer.beginClass(queryType, new ClassType(pathType)); } else { writer.beginClass(queryType, new ClassType(category, pathType, model)); } // TODO : generate proper serialVersionUID here long serialVersionUID = model.getFullName().hashCode(); writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", serialVersionUID + "L"); } protected void introDefaultInstance(CodeWriter writer, EntityType model, String defaultName) throws IOException { String simpleName = !defaultName.isEmpty() ? defaultName : model.getModifiedSimpleName(); Type queryType = typeMappings.getPathType(model, model, true); String alias = simpleName; if (keywords.contains(simpleName.toUpperCase())) { alias += "1"; } writer.publicStaticFinal(queryType, simpleName, NEW + queryType.getSimpleName() + "(\"" + alias + "\")"); } protected void introFactoryMethods(CodeWriter writer, final EntityType model) throws IOException { String localName = writer.getRawName(model); String genericName = writer.getGenericName(true, model); Set<Integer> sizes = Sets.newHashSet(); for (Constructor c : model.getConstructors()) { // begin if (!localName.equals(genericName)) { writer.suppressWarnings(UNCHECKED); } Type returnType = new ClassType(ConstructorExpression.class, model); final boolean asExpr = sizes.add(c.getParameters().size()); writer.beginStaticMethod(returnType, "create", c.getParameters(), new Function<Parameter, Parameter>() { @Override public Parameter apply(Parameter p) { Type type; if (!asExpr) { type = typeMappings.getExprType( p.getType(), model, false, false, true); } else if (p.getType().isFinal()) { type = new ClassType(Expression.class, p.getType()); } else { type = new ClassType(Expression.class, new TypeExtends(p.getType())); } return new Parameter(p.getName(), type); } }); // body // TODO : replace with class reference writer.beginLine("return Projections.constructor("); // if (!localName.equals(genericName)) { // writer.append("(Class)"); // } writer.append(writer.getClassConstant(localName)); writer.append(", new Class<?>[]{"); boolean first = true; for (Parameter p : c.getParameters()) { if (!first) { writer.append(COMMA); } if (Types.PRIMITIVES.containsKey(p.getType())) { Type primitive = Types.PRIMITIVES.get(p.getType()); writer.append(writer.getClassConstant(primitive.getFullName())); } else { writer.append(writer.getClassConstant(writer.getRawName(p.getType()))); } first = false; } writer.append("}"); for (Parameter p : c.getParameters()) { writer.append(COMMA + p.getName()); } // end writer.append(");\n"); writer.end(); } } protected void introImports(CodeWriter writer, SerializerConfig config, EntityType model) throws IOException { writer.staticimports(PathMetadataFactory.class); // import package of query type Type queryType = typeMappings.getPathType(model, model, true); if (!model.getPackageName().isEmpty() && !queryType.getPackageName().equals(model.getPackageName()) && !queryType.getSimpleName().equals(model.getSimpleName())) { String fullName = model.getFullName(); String packageName = model.getPackageName(); if (fullName.substring(packageName.length() + 1).contains(".")) { fullName = fullName.substring(0, fullName.lastIndexOf('.')); } writer.importClasses(fullName); } // delegate packages introDelegatePackages(writer, model); // other packages writer.imports(SimpleExpression.class.getPackage()); // other classes List<Class<?>> classes = Lists.<Class<?>>newArrayList(PathMetadata.class, Generated.class); if (!getUsedClassNames(model).contains("Path")) { classes.add(Path.class); } if (!model.getConstructors().isEmpty()) { classes.add(ConstructorExpression.class); classes.add(Projections.class); classes.add(Expression.class); } boolean inits = false; if (model.hasEntityFields() || model.hasInits()) { inits = true; } else { Set<TypeCategory> collections = Sets.newHashSet(TypeCategory.COLLECTION, TypeCategory.LIST, TypeCategory.SET); for (Property property : model.getProperties()) { if (!property.isInherited() && collections.contains(property.getType().getCategory())) { inits = true; break; } } } if (inits) { classes.add(PathInits.class); } writer.imports(classes.toArray(new Class<?>[classes.size()])); } private Set<String> getUsedClassNames(EntityType model) { Set<String> result = Sets.newHashSet(); result.add(model.getSimpleName()); for (Property property : model.getProperties()) { result.add(property.getType().getSimpleName()); for (Type type : property.getType().getParameters()) { if (type != null) { result.add(type.getSimpleName()); } } } return result; } protected boolean isImportExprPackage(EntityType model) { if (!model.getConstructors().isEmpty() || !model.getDelegates().isEmpty()) { boolean importExprPackage = false; for (Constructor c : model.getConstructors()) { for (Parameter cp : c.getParameters()) { importExprPackage |= cp.getType().getPackageName() .equals(ComparableExpression.class.getPackage().getName()); } } for (Delegate d : model.getDelegates()) { for (Parameter dp : d.getParameters()) { importExprPackage |= dp.getType().getPackageName() .equals(ComparableExpression.class.getPackage().getName()); } } return importExprPackage; } else { return false; } } protected void introDelegatePackages(CodeWriter writer, EntityType model) throws IOException { Set<String> packages = new HashSet<String>(); for (Delegate delegate : model.getDelegates()) { if (!delegate.getDelegateType().getPackageName().equals(model.getPackageName())) { packages.add(delegate.getDelegateType().getPackageName()); } } writer.importPackages(packages.toArray(new String[packages.size()])); } protected void introInits(CodeWriter writer, EntityType model) throws IOException { List<String> inits = new ArrayList<String>(); for (Property property : model.getProperties()) { for (String init : property.getInits()) { inits.add(property.getEscapedName() + DOT + init); } } if (!inits.isEmpty()) { inits.add(0, STAR); String initsAsString = QUOTE + JOINER.join(inits) + QUOTE; writer.privateStaticFinal(PATH_INITS_TYPE, "INITS", "new PathInits(" + initsAsString + ")"); } else if (model.hasEntityFields() || superTypeHasEntityFields(model)) { writer.privateStaticFinal(PATH_INITS_TYPE, "INITS", "PathInits.DIRECT2"); } } protected void introJavadoc(CodeWriter writer, EntityType model) throws IOException { Type queryType = typeMappings.getPathType(model, model, true); writer.javadoc(queryType.getSimpleName() + " is a Querydsl query type for " + model.getSimpleName()); } protected void introPackage(CodeWriter writer, EntityType model) throws IOException { Type queryType = typeMappings.getPathType(model, model, false); if (!queryType.getPackageName().isEmpty()) { writer.packageDecl(queryType.getPackageName()); } } protected void introSuper(CodeWriter writer, EntityType model) throws IOException { EntityType superType = model.getSuperType().getEntityType(); Type superQueryType = typeMappings.getPathType(superType, model, false); if (!superType.hasEntityFields()) { writer.publicFinal(superQueryType, "_super", NEW + writer.getRawName(superQueryType) + "(this)"); } else { writer.publicFinal(superQueryType, "_super"); } } protected void listAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { String escapedName = field.getEscapedName(); Type queryType = typeMappings.getPathType(field.getParameter(0), model, false); writer.beginPublicMethod(queryType, escapedName, new Parameter("index", Types.INT)); writer.line(RETURN + escapedName + ".get(index);").end(); writer.beginPublicMethod(queryType, escapedName, new Parameter("index", new ClassType(Expression.class, Types.INTEGER))); writer.line(RETURN + escapedName + ".get(index);").end(); } protected void mapAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { String escapedName = field.getEscapedName(); Type queryType = typeMappings.getPathType(field.getParameter(1), model, false); writer.beginPublicMethod(queryType, escapedName, new Parameter("key", field.getParameter(0))); writer.line(RETURN + escapedName + ".get(key);").end(); writer.beginPublicMethod(queryType, escapedName, new Parameter("key", new ClassType(Expression.class, field.getParameter(0)))); writer.line(RETURN + escapedName + ".get(key);").end(); } private void delegate(final EntityType model, Delegate delegate, SerializerConfig config, CodeWriter writer) throws IOException { Parameter[] params = delegate.getParameters().toArray(new Parameter[delegate.getParameters().size()]); writer.beginPublicMethod(delegate.getReturnType(), delegate.getName(), params); // body start writer.beginLine(RETURN + writer.getRawName(delegate.getDelegateType()) + "." + delegate.getName() + "("); writer.append("this"); if (!model.equals(delegate.getDeclaringType())) { int counter = 0; EntityType type = model; while (type != null && !type.equals(delegate.getDeclaringType())) { type = type.getSuperType() != null ? type.getSuperType().getEntityType() : null; counter++; } for (int i = 0; i < counter; i++) { writer.append("._super"); } } for (Parameter parameter : delegate.getParameters()) { writer.append(COMMA + parameter.getName()); } writer.append(");\n"); // body end writer.end(); } protected void outro(EntityType model, CodeWriter writer) throws IOException { writer.end(); } @Override public void serialize(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { intro(model, config, writer); // properties serializeProperties(model, config, writer); // constructors constructors(model, config, writer); // delegates for (Delegate delegate : model.getDelegates()) { delegate(model, delegate, config, writer); } // property accessors for (Property property : model.getProperties()) { TypeCategory category = property.getType().getCategory(); if (category == TypeCategory.MAP && config.useMapAccessors()) { mapAccessor(model, property, writer); } else if (category == TypeCategory.LIST && config.useListAccessors()) { listAccessor(model, property, writer); } else if (category == TypeCategory.ENTITY && config.useEntityAccessors()) { entityAccessor(model, property, writer); } } outro(model, writer); } protected void serialize(EntityType model, Property field, Type type, CodeWriter writer, String factoryMethod, String... args) throws IOException { Supertype superType = model.getSuperType(); // construct value StringBuilder value = new StringBuilder(); if (field.isInherited() && superType != null) { if (!superType.getEntityType().hasEntityFields()) { value.append("_super." + field.getEscapedName()); } } else { value.append(factoryMethod + "(\"" + field.getName() + QUOTE); for (String arg : args) { value.append(COMMA + arg); } value.append(")"); } // serialize it if (field.isInherited()) { writer.line("//inherited"); } if (value.length() > 0) { writer.publicFinal(type, field.getEscapedName(), value.toString()); } else { writer.publicFinal(type, field.getEscapedName()); } } protected void customField(EntityType model, Property field, SerializerConfig config, CodeWriter writer) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); writer.line("// custom"); if (field.isInherited()) { writer.line("// inherited"); Supertype superType = model.getSuperType(); if (!superType.getEntityType().hasEntityFields()) { String value = NEW + writer.getRawName(queryType) + "(_super." + field.getEscapedName() + ")"; writer.publicFinal(queryType, field.getEscapedName(), value); } else { writer.publicFinal(queryType, field.getEscapedName()); } } else { String value = NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\"))"; writer.publicFinal(queryType, field.getEscapedName(), value); } } // TODO move this to codegen private Type wrap(Type type) { if (type.equals(Types.BOOLEAN_P)) { return Types.BOOLEAN; } else if (type.equals(Types.BYTE_P)) { return Types.BYTE; } else if (type.equals(Types.CHAR)) { return Types.CHARACTER; } else if (type.equals(Types.DOUBLE_P)) { return Types.DOUBLE; } else if (type.equals(Types.FLOAT_P)) { return Types.FLOAT; } else if (type.equals(Types.INT)) { return Types.INTEGER; } else if (type.equals(Types.LONG_P)) { return Types.LONG; } else if (type.equals(Types.SHORT_P)) { return Types.SHORT; } else { return type; } } protected void serializeProperties(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { for (Property property : model.getProperties()) { // FIXME : the custom types should have the custom type category if (typeMappings.isRegistered(property.getType()) && property.getType().getCategory() != TypeCategory.CUSTOM && property.getType().getCategory() != TypeCategory.ENTITY) { customField(model, property, config, writer); continue; } // strips of "? extends " etc Type propertyType = new SimpleType(property.getType(), property.getType().getParameters()); Type queryType = typeMappings.getPathType(propertyType, model, false); Type genericQueryType = null; String localRawName = writer.getRawName(property.getType()); String inits = getInits(property); switch (property.getType().getCategory()) { case STRING: serialize(model, property, queryType, writer, "createString"); break; case BOOLEAN: serialize(model, property, queryType, writer, "createBoolean"); break; case SIMPLE: serialize(model, property, queryType, writer, "createSimple", writer.getClassConstant(localRawName)); break; case COMPARABLE: serialize(model, property, queryType, writer, "createComparable", writer.getClassConstant(localRawName)); break; case ENUM: serialize(model, property, queryType, writer, "createEnum", writer.getClassConstant(localRawName)); break; case DATE: serialize(model, property, queryType, writer, "createDate", writer.getClassConstant(localRawName)); break; case DATETIME: serialize(model, property, queryType, writer, "createDateTime", writer.getClassConstant(localRawName)); break; case TIME: serialize(model, property, queryType, writer, "createTime", writer.getClassConstant(localRawName)); break; case NUMERIC: serialize(model, property, queryType, writer, "createNumber", writer.getClassConstant(localRawName)); break; case CUSTOM: customField(model, property, config, writer); break; case ARRAY: serialize(model, property, new ClassType(ArrayPath.class, property.getType(), wrap(property.getType().getComponentType())), writer, "createArray", writer.getClassConstant(localRawName)); break; case COLLECTION: genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); String genericKey = writer.getGenericName(true, property.getParameter(0)); localRawName = writer.getRawName(property.getParameter(0)); queryType = typeMappings.getPathType(property.getParameter(0), model, true); serialize(model, property, new ClassType(CollectionPath.class, getRaw(property.getParameter(0)), genericQueryType), writer, "this.<" + genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createCollection", writer.getClassConstant(localRawName), writer.getClassConstant(writer.getRawName(queryType)), inits); break; case SET: genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); genericKey = writer.getGenericName(true, property.getParameter(0)); localRawName = writer.getRawName(property.getParameter(0)); queryType = typeMappings.getPathType(property.getParameter(0), model, true); serialize(model, property, new ClassType(SetPath.class, getRaw(property.getParameter(0)), genericQueryType), writer, "this.<" + genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createSet", writer.getClassConstant(localRawName), writer.getClassConstant(writer.getRawName(queryType)), inits); break; case LIST: genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); genericKey = writer.getGenericName(true, property.getParameter(0)); localRawName = writer.getRawName(property.getParameter(0)); queryType = typeMappings.getPathType(property.getParameter(0), model, true); serialize(model, property, new ClassType(ListPath.class, getRaw(property.getParameter(0)), genericQueryType), writer, "this.<" + genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createList", writer.getClassConstant(localRawName), writer.getClassConstant(writer.getRawName(queryType)), inits); break; case MAP: genericKey = writer.getGenericName(true, property.getParameter(0)); String genericValue = writer.getGenericName(true, property.getParameter(1)); genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(1)), model, false); String keyType = writer.getRawName(property.getParameter(0)); String valueType = writer.getRawName(property.getParameter(1)); queryType = typeMappings.getPathType(property.getParameter(1), model, true); serialize(model, property, new ClassType(MapPath.class, getRaw(property.getParameter(0)), getRaw(property.getParameter(1)), genericQueryType), writer, "this.<" + genericKey + COMMA + genericValue + COMMA + writer.getGenericName(true, genericQueryType) + ">createMap", writer.getClassConstant(keyType), writer.getClassConstant(valueType), writer.getClassConstant(writer.getRawName(queryType))); break; case ENTITY: entityField(model, property, config, writer); break; } } } private String getInits(Property property) { if (!property.getInits().isEmpty()) { return "INITS.get(\"" + property.getName() + "\")"; } else { return "PathInits.DIRECT2"; } } private Type getRaw(Type type) { if (type instanceof EntityType && type.getPackageName().startsWith("ext.java")) { return type; } else { return new SimpleType(type, type.getParameters()); } } private static CodeWriter suppressAllWarnings(CodeWriter writer) throws IOException { return writer.suppressWarnings("all", "rawtypes", "unchecked"); } }
C
UTF-8
538
3.046875
3
[]
no_license
#include <omp.h> #include <stdio.h> void main(int argc, char *argv[]) { int plus, minus; int a = 2; int b = 4; #pragma omp parallel num_threads(3) { #pragma omp sections { #pragma omp section { plus = a + b; printf("a + b = %d \n", plus); } #pragma omp section { minus = b - a; printf("b - a = %d \n", minus); } } } }
JavaScript
UTF-8
160
2.9375
3
[]
no_license
let _ = require('lodash'); // array element length let a = [1, '2', 3, '4']; let sum = _(a).map((el)=>{return parseFloat(el)}).sum(a); console.log(sum); // 10
Markdown
UTF-8
3,009
3.484375
3
[ "MIT" ]
permissive
参考 - Algorithms [Robert Sedgewick Kevin Wayne] 2-1-2 - https://algs4.cs.princeton.edu/21elementary/Selection.java.html - [912. 排序数组](https://leetcode-cn.com/problems/sort-an-array/) # SelectionSort ## 算法描述 - 首先,找到数组中最小的那个元素, - 其次,将它和数组的第一个元素交换位置(如果第一个元素就是最小元素那么它就和自己交换) 。 - 再次,在剩下的元素中找到最小的元素 ,将它与数组的第二个元素交换位置 。 - 如此往复,直到将整个数组排序 。 选择排序的内循环只是在比较当前元素与目前已知的最小元素(以及将当前索引加 1 和检查是否代码越界),这已经简单到了极点 。 交换元素的代码写在内循环之外,每次交换都能排定一个元素,因此交换的总次数是 `N`。 所以算法的时间效率取决于比较的次数 特点 - 运行时间和输入无关 。 为了找出最小的元素而扫描一遍数组并不能为下一遍扫描提供什么信息 。这种性质在某些情况下是缺点,因为使用选择排序的人可能会惊讶地发现, 一个已经有序的数组或是主键全部相等的数组和一个元素随机排列的数组所用的排序时间竟然一样长 ! - 数据移动是最少的 。 每次交换都会改变两个数组元素的值,因此选择排序用了 N 次交换—一交换次数和数组的大小是线性关系 。 我们将研究的其他任何算法都不具备这个特征(大部分的增长数量级都是线性对数或是平方级别) 。 ## 实现 ```C++ // Selection Sort // Increasing Order // 选最小位置 class Solution1 { public: vector<int> sortArray(vector<int>& nums) { for (auto i = 0; i != nums.size(); i++) { // 选出位置i int min = i; for (auto j = i + 1; j != nums.size(); j++) { // 选出i之后的最小的元素min if (nums[j] < nums[min]) min = j; } swap(nums[i], nums[min]); // 交换位置,交换后nums[i]就是第i小的元素 } return nums; } }; // 选最大位置 class Solution2 { public: vector<int> sortArray(vector<int>& nums) { for (auto end = nums.size() - 1; end != 0; end--) { int max = end; for (auto begin = 0; begin < end; begin++) // > Descending Order if (nums[begin] > nums[max]) max = begin; swap(nums[end], nums[max]); } return nums; } }; ``` ```C++ // 关键部分 for (auto i = 0; i != nums.size(); i++) { // 选出位置i int min = i; for (auto j = i + 1; j != nums.size(); j++) { // 选出i之后的最小的元素min if (nums[j] < nums[min]) min = j; } swap(nums[i], nums[min]); // 交换位置,交换后nums[i]就是第i小的元素 } ``` ## 算法分析 - $\sum_{i=0}^n\sum_{j=i+1}^n\cdot 1 = \sum_{i=0}^n(n-(i+1))$ - 粗略分析:二重循环$O(n^2)$
TypeScript
UTF-8
2,704
2.671875
3
[]
no_license
import THREE = require('three') import * as Model from './model' import * as Light from './light' import * as Interact from './interact' import * as R from 'ramda' const modelCount = 500 const lightCount = 10 export interface IThreeObjects { readonly scene : THREE.Scene readonly camera : THREE.Camera readonly renderer : THREE.Renderer } export interface IState { interactions: Interact.IInteractions | undefined models : Model.IModel[] lights : Light.ILight[] start : number | undefined before : number | undefined total : number | undefined progress: number | undefined } export const initRender = (width: number, height: number) => { const state = { interactions: <Interact.IInteractions | undefined>undefined, models : <Model.IModel[]>[], lights : <Light.ILight[]>[], start : <number | undefined>undefined, before : <number | undefined>undefined, total : <number | undefined>undefined, progress: <number | undefined>undefined } const scene = new THREE.Scene() Model.createModels(modelCount, state) scene.add(...R.map(x => x.src, state.models)) Light.createLights(lightCount, state) scene.add(...R.map(x => x.src, state.lights)) const camera = new THREE.PerspectiveCamera(60.0, width / height) camera.position.set(0.0, 0.0, 3.0) camera.lookAt(0.0, 0.0, 0.0) const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }) renderer.setClearColor(new THREE.Color(0.0, 0.0, 0.0), 1.0) renderer.setSize(width, height) const threeObjects = { scene, camera, renderer } const intr = Interact.initInteract(threeObjects, width, height) intr.subscribe(i => state.interactions = i) window.requestAnimationFrame(animate(threeObjects, state)) } const animate = (threeObjects: IThreeObjects, state: IState) => (timestamp: number) => { if (!state.start) { state.start = timestamp } if (!state.before) { state.before = timestamp } state.total = timestamp - state.start state.progress = timestamp - state.before state.before = timestamp render(threeObjects, state) window.requestAnimationFrame(animate(threeObjects, state)) } const render = (threeObjects: IThreeObjects, state: IState) => { R.forEach(Model.updateModel(state), state.models) R.forEach(Light.updateLight(state), state.lights) R.forEach(Model.transformModel(state), state.models) R.forEach(Light.transformLight(state), state.lights) threeObjects.renderer.render(threeObjects.scene, threeObjects.camera) }
PHP
UTF-8
851
2.5625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTeklifsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('teklifs', function (Blueprint $table) { $table->increments('id'); $table->integer('userId'); $table->integer('musteriId'); $table->double('fiyat'); $table->text('aciklama')->nullable(); $table->integer('status'); // 0 ise açık teklif , 1 ise onaylanmış teklif. $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('teklifs'); } }
Markdown
UTF-8
3,280
2.71875
3
[ "MIT" ]
permissive
# TreeD [![TreeD on PyPI](https://img.shields.io/pypi/v/treed.svg)](https://pypi.python.org/pypi/treed) ### Visual representation of the branch-and-cut tree of SCIP using spatial dissimilarities of LP solutions -- [Interactive Example](http://www.zib.de/miltenberger/treed-showcase.html) --- ![Example](res/treed-example.png) --- ![Example2D](res/tree2d-example.png) --- TreeD uses SCIP via [PySCIPOpt](https://github.com/scipopt/PySCIPOpt) to visualize the Branch-and-Cut tree traversed during the solution of a mixed-integer linear program (MIP or MILP). The LP solutions at each node are projected into a 2-dimensional space using a range of different transformation algorithms. Per default, multi-dimensional scaling (mds) is used. Other methods and further options can be displayed by running `python -m treed --help`. The 2-dimensional data points are visualized in a 3D space with regards to their respective LP solution value. Nodes higher up represent LP solutions with a higher value. These nodes are usually found later in the search and show the progress in increasing the lower or dual bound to close the MIP gap. The color of the individual nodes is used to show different values like node age, LP iteration count, or LP condition number. The shape of the nodes depict whether this LP solution was created through branching (🔵) or through LP resolves (🔷) at the ssame node, e.g. including cutting planes or added conflicts. There is also a more traditional mode that ignores the spatial dimension and draws an abstract tree. This is activated via the method `draw2d()` or the command line flag `--classic`. ## Installation ``` python -m pip install treed ``` ## Usage - run `python -m treed --help` to get usage information or use this code snippet in a Jupyter notebook: ``` from treed import TreeD treed = TreeD( probpath="model.mps", nodelimit=2000, showcuts=True ) treed.solve() fig = treed.draw() fig.show(renderer='notebook') ``` There is also a (faster) 2D mode that skips the projection of LP solutions and generates a more traditional tree instead: ``` ... fig = treed.draw2d() fig.show(renderer='notebook') ``` ## Dependencies - [PySCIPOpt](https://github.com/scipopt/PySCIPOpt) to solve the instance and generate the necessary tree data - [Plotly](https://plot.ly/) to draw the 3D visualization - [pandas](https://pandas.pydata.org/) to organize the collected data - [sklearn](http://scikit-learn.org/stable/) for multi-dimensional scaling - [pysal](https://github.com/pysal) to compute statistics based on spatial (dis)similarity; this is optional ## Export to [Amira](https://amira.zib.de/) - run `AmiraTreeD.py` to get usage information. `AmiraTreeD.py` generates the '.am' data files to be loaded by Amira software to draw the tree using LineRaycast. ### Settings ![Project View](res/ProjectView.png) - `DataTree.am`: SpatialGraph data file with tree nodes and edges. - `LineRaycast`: Module to display the SpatialGraph. Note that is needed to set the colormap according to py code output (For instance 'Color map from 1 to 70' in this picture). - `DataOpt.am`: SpatialGraph data file with optimun value. - `Opt Plane`: Display the optimal value as a plane. ### Preview ![Amira preview](res/AmiraTree.gif)
Markdown
UTF-8
2,468
2.703125
3
[]
no_license
--- layout: post title: "Baby Songs" tagline: songs to jam to while pregnant category: tags: - style: | body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } --- Paula and I are expecting a baby girl to arrive sometime this month! Here's a list of jams we've had fun rocking out to throughout the pregnancy. What are some of your favorites? Hope you enjoy! [I Got the Feelin’, James Brown](https://genius.com/James-brown-i-got-the-feelin-lyrics) >Baby, baby, baby >Baby, baby, baby >Baby, baby, baby >Baby, baby <img src="https://t2.genius.com/unsafe/440x440/https%3A%2F%2Fimages.genius.com%2Fd6425b6d329083faab85353b598a04bd.500x500x1.jpg" width="300px"> [Baby, I Love Your Way, Peter Frampton](https://genius.com/Peter-frampton-baby-i-love-your-way-lyrics) >Ooh, baby, I love your way >Wanna tell you I love your way >Wanna be with you night and day <img src="https://t2.genius.com/unsafe/440x442/https%3A%2F%2Fimages.genius.com%2F200870b0c3126676968f50fbe0dc70fb.315x316x1.jpg" width="300px"> [Push It, Salt-N-Pepa](https://genius.com/Salt-n-pepa-push-it-lyrics) >Oooh, baby, baby >Baby, baby <img src="https://t2.genius.com/unsafe/440x440/https%3A%2F%2Fimages.genius.com%2F4ef12d48c4a618a18e5f8467023ff9ec.600x600x1.jpg" width="300px"> [Baby Baby, Amy Grant](https://genius.com/Amy-grant-baby-baby-lyrics) >Baby, baby >I'm taken with the notion >To love you with the sweetest of devotion <img src="https://t2.genius.com/unsafe/440x440/https%3A%2F%2Fimages.genius.com%2Faea23e6897a2918ff959148ba173aa6f.1000x1000x1.jpg" width="300px"> [Where Did Our Love Go, The Supremes](https://genius.com/The-supremes-where-did-our-love-go-lyrics) >Baby, baby >Baby don't leave me >Ooh, please don't leave me >All by myself <img src="https://images.genius.com/a546b24484b7d104f3b4de521ea63b2f.180x182x1.png" width="300px"> [Ooh Baby Baby, Smokey Robinson](https://genius.com/Smokey-robinson-ooh-baby-baby-lyrics) >Ooh oo-ooh baby baby >Ooh oo-ooh baby baby <img src="https://t2.genius.com/unsafe/440x0/https%3A%2F%2Fimages.genius.com%2F7f4ec5f42aa3aa6cf222d0505089432c.348x348x1.jpg" width="300px"> [Baby, I Love You, Ramones](https://genius.com/Ramones-baby-i-love-you-lyrics) >Baby, I love you >Come on baby >Baby, I love you >Baby I love, I love only you <img src="https://t2.genius.com/unsafe/440x0/https%3A%2F%2Fimages.genius.com%2F5eb657106da20e9575ef253aaf41bb67.600x608x1.jpg" width="300px">
PHP
UTF-8
4,194
2.640625
3
[]
no_license
<?php require_once 'Includes/connection.php'; include 'header.php'; if (!isset($_SESSION['username']) || empty($_SESSION['username'])) { header("location: login.php"); exit; } $msg=""; if (!empty($_GET['msg'])) { $msg = $_GET['msg']; } if ($_SERVER['REQUEST_METHOD'] =='POST') { if (isset($_POST['add'])) { $stmt = $conn->prepare("SELECT Quantity FROM Carts WHERE product_id = ? AND member_id = ?"); $stmt->bind_param("ii", $_POST['add'], $_SESSION['memberID']); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $quantity = $row['Quantity']+1; $stmt = $conn->prepare("UPDATE Carts SET Quantity = ? WHERE product_id = ? AND member_id = ?"); $stmt->bind_param("iii", $quantity, $_POST['add'], $_SESSION['memberID']); if ($stmt->execute()) { $msg.= "Inserted sucessfully!"; } else { $msg.= "Failed!!"; } } else { $stmt = $conn->prepare("INSERT INTO Carts(member_id,product_id,Quantity) VALUES(?,?,1)"); $stmt->bind_param("ii", $_SESSION['memberID'], $_POST['add']); if ($stmt->execute()) { $msg.= "Inserted sucessfully!"; } else { $msg.= "Failed!!"; } } } if (isset($_POST['remove'])) { $stmt = $conn->prepare("DELETE FROM Carts WHERE product_id = ? AND member_id = ?"); $stmt->bind_param("ii", $_POST['remove'], $_SESSION['memberID']); if ($stmt->execute()) { $msg.= "Removed sucessfully!"; } else { $msg.= "Failed!!"; } } } $stmt = $conn->prepare("SELECT * FROM Addresses WHERE customer_id = ?"); $stmt->bind_param("i", $_SESSION['memberID']); $stmt->execute(); $result = $stmt->get_result(); $addresses = []; while ($row = $result->fetch_assoc()) { $addresses[$row['AddressID']] = $row['Address']; } $stmt = $conn->prepare("SELECT p.ProductID,p.ProductName,p.Price,c.Quantity,(p.Price * c.Quantity) AS total_price,(SELECT SUM(pp.Price * cc.Quantity) FROM Carts AS cc LEFT JOIN Products AS pp on cc.product_id=pp.ProductID WHERE cc.member_id=? GROUP BY member_id) as total FROM Carts AS c LEFT JOIN Products AS p on c.product_id=p.ProductID WHERE c.member_id=?"); $stmt->bind_param("ii", $_SESSION['memberID'], $_SESSION['memberID']); $stmt->execute(); $result = $stmt->get_result(); $cartView= "<table><tr> <th>ProductName</th> <th>Quantity</th> <th>Unit Price</th> <th>Total Price</th> </tr>"; $cartView .= "<form action='$site_root/cart.php' method='post'>"; $total =0; while ($row = $result->fetch_assoc()) { $cartView .= "<tr><td>".$row['ProductName']."</td> "; $cartView .= "<td>".$row['Quantity']."</td> "; $cartView .= "<td>".$row['Price']."</td> "; $cartView .= "<td>".$row['total_price']."</td> "; $total =$row['total']; $cartView .= "<td><button type='submit' name='remove' value=".$row['ProductID'].">Remove</button></td></tr> "; } $cartView.="</form>"; $cartView.="</table>"; $cartView.="Total cart value is Rs." .$total; $cartView.= "<form action='$site_root/transaction.php' method='post'><input name='total' type='hidden' value='". $total . "' disabled/>"; if (count($addresses) == 0) { $cartView .= "Please add an address before placing order"; $cartView.=" <a href='$site_root/add_address.php'>Add a new address</a>"; $cartView .="<button type='submit' name ='checkout' value='checkout' disabled> Checkout </button>"; } else { $cartView .=" Select Address :<select name='address'>"; $first = true; foreach ($addresses as $aID => $address_val) { $cartView .= "<option value=$aID ($first ? 'selected' : ' ') > $address_val </option>"; $first = false; } $cartView .= "</select>"; $cartView .="<button type='submit' name ='checkout' value='checkout' > Checkout </button>"; } ?> <?php if (strlen($msg)>0) { echo $msg; }?> <?php echo $cartView; ?> </body> </html>
C#
UTF-8
1,329
2.96875
3
[]
no_license
public class Room { public bool IsAvailable {get; set;} public RoomType RoomType {get; set;} public int RoomNo {get; set;} public int Floor {get; set;} public string RoomName {get; set;} } public enum RoomType { Single, Double, Twin, King, HoneymoonSuite } public class RoomManager { public RoomManager() { List<Room> AllRooms = new List<Room>(); AllRooms.Add(new Room(){ RoomType=RoomType.Single, RoomNo=1, Floor=1, RoomName="A101", IsAvailable=true}); AllRooms.Add(new Room(){ RoomType=RoomType.Double, RoomNo=2, Floor=1, RoomName="A102", IsAvailable=false}); AllRooms.Add(new Room(){ RoomType=RoomType.HoneyMoonSuite, RoomNo=1, Floor=2, RoomName="A201", IsAvailable=true}); } }
Markdown
UTF-8
1,096
2.703125
3
[ "BSD-3-Clause" ]
permissive
# Simple Memory Cards Trainer written in Elm Goal of the project is to provide a simple cards trainer with several question types like multiple choice, free choice, memory like combination or free text. - Practice the elm programming language: user interactivity, animations, server communication, JavaScript interop - ultimately provide a free tool for students, pupils and learners who are not satisfied with existing card trainers and learning experience. ## Install To mock the server part of the application, install the npm mock server _npm install -g json-server_ for more information see https://github.com/typicode/json-server ##Run the Sample Application The sample application is a chinese vocabulary trainer (as Chinese seems to be the most complicated language to train vocabulary for) Start the project with _elm reactor_ Start mockserver in the project folder with with _json-server .tests/db.json_ ### State of the project The project is in early development phase and not yet ready to use. However, feel free to contribute. Licence: any BSD license of your choice.
Markdown
UTF-8
5,043
3.15625
3
[]
no_license
--- title: "Puppet with a Agent-Master architecture" date: 2022-07-13T11:21:15+01:00 draft: false categories: ["Infrastructure"] tags: ["Puppet", "Configuration management"] --- There are many resources out there which—rightly—focus on teaching Puppet using simple architectures, e.g. a single node, masterless setup. However, I found less info on how to set up Puppet with an Agent-Master architecture. This short article gives a very high-level overview of the main steps. It is not a self-sufficient tutorial by any means—but I am hoping it will still be useful for those trying to understand the big picture. Briefly, we need multiple VMs. One VM will act as the master VM and will hold the Puppet manifests. Other VMs will be nodes—they will be running the Puppet Agent periodically to get the desired configuration from the master and execute the required tasks to make the node's state aligned with what is defined in the Puppet manifests. ## Puppet master We first need to create a virtual machine to act as our puppet master. Here we're using a VM running CentOS 7. Let's assume its FQDN is `puppet.myproject.example.com`. ```sh sudo su - rpm -Uvh https://yum.puppet.com/puppet6/puppet6-release-el-7.noarch.rpm yum install puppetserver systemctl enable --now puppetserver ``` The `puppetserver` service should now be running on your puppet master VM. To verify that the `puppetserver` CLI has been installed correctly, run ```sh puppetserver -v ``` on a new shell. If this does not work, it is probably because `puppetserver` has not been added to your `PATH`, so you'll need to investigate why that was the case. You should also test that the puppet agent can run on the master: ```sh sudo su - puppet agent --test --server {FQDN} ``` If the above agent run completed successfully, we are pretty much done with the initial master configuration. ## Puppet agent on a node VM Now we need to create at least one node VM to test if things really are working. Let's assume the VM is running CentOS 7 and that the FQDN is `node01.myproject.example.com`. Let's start by installing the agent and enabling it as a service ```sh sudo yum install puppet-agent sudo /opt/puppetlabs/bin/puppet resource service puppet ensure=running enable=true ``` Now we need to add `puppet` to our PATH and configure the server ```sh source /etc/profile.d/puppet-agent.sh puppet config set server puppet.myproject.example.com --section main ``` No we need to get the node talking to the master. To do that, we first run ```sh puppet ssl bootstrap ``` on the node VM. This should have requested a certificate signature to the master VM, which we now need to sign. SSH into the master VM, change to root and run ```sh puppetserver ca sign --certname node01.myproject.example.com ``` This should have successfully signed the certificate for the node VM, which means that the puppet master and the node VM should now be able to work together. We need to repeat this section for every node you want to manage with puppet, e.g. `node02.myproject.puppet.com`, `node03.myproject.puppet.com` and so on. At a high-level, this is pretty much it. The next step is to actually start writing some puppet manifests. ## Writing Puppet manifests Puppet's installation process should have created a set of files and folders on the master VM. They are located under `/etc/puppetlabs/code/`. This is where Puppet expects to find manifests. A standard production environment is created by default, with a standard structure for organising Puppet manifests. These can be found under `/etc/puppetlabs/code/environments/production`. It is a good idea to track changes in these files using a version control tool like `git`, and pull those changes onto the master VM once you are ready to test or apply them. I am going to start by creating a simple file resource just for testing purposes and I will apply it to all nodes. I create a `manifests/site.pp` file with the following contents ``` node default { file {'/tmp/test.txt': content => 'test file content', } } ``` This asks Puppet to create a file `/tmp/test.txt` with the content `test file content` for all nodes. To test that this is working, ssh into the node VM and run: ```bash puppet agent --test ``` The agent will then retrieve the desired system state from the master, and execute the corresponding tasks to achieve such state. If all worked well, the file `/tmp/test.txt` should now exist on the node VM. This is an embarrassingly simple example of what we can do with Puppet—for a proper treatment of Puppet's features, take a look at Puppet's documentation. ## Conclusion The aim of this short article was to provide a very high-level overview of how the basic steps that are required to set up Puppet with an Agent-Master architecture. I have skipped over lots of details (e.g. networking), but the goal here is to focus on the "big picture" rather than setup details, which will differ significantly depending on the OS platform or cloud provider of choice.
Python
UTF-8
966
2.765625
3
[]
no_license
from abc import ABC, abstractmethod import z3 class Sort(ABC): @abstractmethod def to_z3(self) -> z3.SortRef: pass @abstractmethod def to_c(self) -> str: pass class _TypeEq: def __eq__(self, other): return type(self) == type(other) def __repr__(self) -> str: return type(self).__name__ + '()' class SortInt(Sort, _TypeEq): def to_z3(self) -> z3.SortRef: return z3.BitVecSort(32) def to_c(self) -> str: return 'int' class SortBool(Sort, _TypeEq): def to_z3(self) -> z3.SortRef: return z3.BoolSort() def to_c(self) -> str: return 'bool' class SortString(Sort, _TypeEq): def to_z3(self) -> z3.SortRef: return z3.StringSort() def to_c(self) -> str: return 'string' class SortUnknown(Sort, _TypeEq): def to_z3(self) -> z3.SortRef: return z3.DeclareSort('unknown') def to_c(self) -> str: return 'any'
Java
UTF-8
3,510
2.59375
3
[]
no_license
package com.tufypace.yaedabot.utils; import android.content.Context; import android.content.SharedPreferences; public class SharedPreferencesDefaultProvider implements SharedPreferencesProvider { public final String PREFS = "yandex_prefs"; public final int PREFS_MODE = 0; public Context mContext; public SharedPreferencesDefaultProvider(Context context) { this.mContext = context; } @Override public Boolean getBoolean(String str) { boolean z; Boolean bool = (Boolean) getValue(str, Boolean.class); if (bool == null) { z = false; } else { z = bool; } return z; } @Override public Float getFloat(String str) { float f; Float f2 = (Float) getValue(str, Float.class); if (f2 == null) { f = 0.0f; } else { f = f2; } return f; } @Override public Integer getInteger(String str) { int i; Integer num = (Integer) getValue(str, Integer.class); if (num == null) { i = 0; } else { i = num; } return i; } @Override public Integer getInteger(String str, int i) { Integer num = (Integer) getValue(str, Integer.class); if (num != null) { i = num; } return i; } @Override public Long getLong(String str) { long j; Long l = (Long) getValue(str, Long.class); if (l == null) { j = 0; } else { j = l; } return j; } @Override public String getString(String str) { String str2 = (String) getValue(str, String.class); return str2 == null ? "" : str2; } @Override public void save(String str, Object obj) { SharedPreferences.Editor edit = this.mContext.getSharedPreferences(PREFS, 0).edit(); if (obj instanceof String) { edit.putString(str, (String) obj); } else if (obj instanceof Integer) { edit.putInt(str, (Integer) obj); } else if (obj instanceof Long) { edit.putLong(str, (Long) obj); } else if (obj instanceof Float) { edit.putFloat(str, (Float) obj); } else if (obj instanceof Boolean) { edit.putBoolean(str, (Boolean) obj); } else if (obj == null) { edit.remove(str); } edit.apply(); } private Object getValue(String str, Class cls) { try { SharedPreferences sharedPreferences = this.mContext.getSharedPreferences(PREFS, 0); if (!sharedPreferences.contains(str)) { return null; } String simpleName = cls.getSimpleName(); switch (simpleName) { case "String": return sharedPreferences.getString(str, ""); case "Integer": return sharedPreferences.getInt(str, 0); case "Long": return sharedPreferences.getLong(str, 0); case "Float": return sharedPreferences.getFloat(str, 0.0f); case "Boolean": return sharedPreferences.getBoolean(str, false); default: return null; } } catch (Exception e) { // Logs.d(e.getMessage()); return null; } } }
Python
UTF-8
3,134
3.140625
3
[]
no_license
#!/usr/bin/env python3 import pandas as pd from sklearn import datasets from sklearn.preprocessing import scale import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import numpy as np from sklearn.neighbors import KNeighborsClassifier iris = datasets.load_iris() species = [iris.target_names[x] for x in iris.target] iris = pd.DataFrame(iris['data'], columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width']) print(iris.describe().round(3)) iris['Species'] = species print(iris) def plot_iris(iris, col1, col2): sns.lmplot(x = col1, y = col2, data = iris, hue = "Species", fit_reg = False) plt.xlabel(col1) plt.ylabel(col2) plt.title('Iris species shown by color') plt.show() iris['count'] = 1 print(iris[['Species', 'count']].groupby('Species').count()) num_cols = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'] iris_scaled = scale(iris[num_cols]) iris_scaled = pd.DataFrame(iris_scaled, columns = num_cols) print(iris_scaled.describe().round(3)) # 字符串转换成数字 levels = {'setosa':0, 'versicolor':1, 'virginica':2} iris_scaled['Species'] = [levels[x] for x in iris['Species']] print(iris_scaled.head()) # 分割成样本训练集和评估数据集 np.random.seed(3456) iris_split = train_test_split(np.asmatrix(iris_scaled), test_size = 75) iris_train_features = iris_split[0][:, :4] iris_train_labels = np.ravel(iris_split[0][:, 4]) iris_test_features = iris_split[1][:, :4] iris_test_labels = np.ravel(iris_split[1][:, 4]) print(iris_train_features.shape) print(iris_train_labels.shape) print(iris_test_features.shape) print(iris_test_labels.shape) # plot_iris(iris, 'Petal_Width', 'Sepal_Length') # plot_iris(iris, 'Sepal_Width', 'Sepal_Length') KNN_mod = KNeighborsClassifier(n_neighbors = 3) KNN_mod.fit(np.asarray(iris_train_features), np.asarray(iris_train_labels)) iris_test = pd.DataFrame(iris_test_features, columns = num_cols) iris_test['predicted'] = KNN_mod.predict(np.asarray(iris_test_features)) iris_test['correct'] = [1 if x == z else 0 for x, z in zip(iris_test['predicted'], iris_test_labels)] accuracy = 100.0 * float(sum(iris_test['correct'])) / float(iris_test.shape[0]) print(accuracy) levels = {0:'setosa', 1:'versicolor', 2:'virginica'} iris_test['Species'] = [levels[x] for x in iris_test['predicted']] markers = {1:'^', 0:'o'} colors = {'setosa':'blue', 'versicolor':'green',} def plot_shapes(df, col1,col2, markers, colors): ax = plt.figure(figsize=(6, 6)).gca() # define plot axis for m in markers: # iterate over marker dictioary keys for c in colors: # iterate over color dictionary keys df_temp = df[(df['correct'] == m) & (df['Species'] == c)] sns.regplot(x = col1, y = col2, data = df_temp, fit_reg = False, scatter_kws={'color': colors[c]}, marker = markers[m], ax = ax) plt.xlabel(col1) plt.ylabel(col2) plt.title('Iris species by color') plt.show() plot_shapes(iris_test, 'Petal_Width', 'Sepal_Length', markers, colors) plot_shapes(iris_test, 'Sepal_Width', 'Sepal_Length', markers, colors)
Java
UTF-8
877
2.28125
2
[]
no_license
package com.lzl.netty.chapter10fileserver.httpxml.codec; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpResponse; import java.util.List; /** * @author lizanle * @Date 2019/2/27 14:30 */ public class HttpXmlResponseDecoder extends AbstractHttpXmlDecoder<DefaultFullHttpResponse> { public HttpXmlResponseDecoder(Class<?> clazz) { super(clazz); } public HttpXmlResponseDecoder(Class<?> clazz, boolean isPrint) { super(clazz, isPrint); } @Override protected void decode(ChannelHandlerContext ctx, DefaultFullHttpResponse response, List<Object> out) throws Exception { HttpXmlResponse httpXmlResponse = new HttpXmlResponse( response, decode0(ctx, response.content())); out.add(httpXmlResponse); } }
Python
UTF-8
558
3.203125
3
[]
no_license
from Domain.getter import getApart def delAllSpendings(apartNumber, spendingsList): ''' This function deletes all the spendings for a given apartment :param apartNumber: - int - the apartment number of the wanted spending :param spendingsList: - list - the spendings list :return: - ''' index = 0 while index < len(spendingsList): ok = 0 if getApart(spendingsList[index]) == apartNumber: spendingsList.pop(index) ok = 1 if not ok: index += 1
Java
UTF-8
911
3.46875
3
[]
no_license
import java.util.HashSet; import java.util.Set; public class SherlockAndValidString { public static void main(String[] args) { System.out.println(isValid("aabbccddeefghi")); } static String isValid(String s) { s = s.toLowerCase(); int[] count = new int[26]; for (int i = 0; i < s.length(); i++) { count[s.charAt(i) - 97]++; } Set<Integer> set = new HashSet<>(); for (int i = 0; i < 26; i++) if (count[i] > 0) set.add(count[i]); if (set.size() == 1) { return "YES"; } for (int i = 0; i < 26; i++) { set.clear(); for (int j = 0; j < 26; j++) if (count[j] > 0 && j != i) set.add(count[j]); if (set.size() == 1) { return "YES"; } } return "NO"; } }
Java
UTF-8
2,142
2.53125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import MODEL.Departamento; import MODEL.PublicacaoArea; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; /** * * @author crist */ public class PublicacaoAreaDao { public ArrayList<PublicacaoArea> listarPublicacaoArea() { try { ArrayList<PublicacaoArea> dados = new ArrayList(); PreparedStatement stmt = Conexao.abrir().prepareStatement("select publicacao.codigo_publicacao as 'Código', publicacao.titulo as 'Titulo da Publicação', area_topico.titulo as 'Área da pesquisa', publicacao_area_topico.data as 'Data'\n" + "from publicacao\n" + "inner join publicacao_area_topico\n" + "on publicacao.codigo_publicacao = publicacao_area_topico.codigo_publicacao\n" + "inner join area_topico\n" + "on publicacao_area_topico.codigo_topico = area_topico.codigo_topico"); ResultSet res = stmt.executeQuery(); while (res.next()) { System.out.println(res.getString("Código")); System.out.println(res.getString("Titulo da Publicação")); System.out.println(res.getString("Área da pesquisa")); System.out.println(res.getString("Data")); dados.add( new PublicacaoArea( Integer.parseInt(res.getString("Código")), res.getString("Titulo da Publicação"), res.getString("Área da pesquisa"), res.getString("Data") ) ); } res.close(); stmt.close(); Conexao.abrir().close(); return dados; } catch (Exception e) { System.out.println(e.getMessage()); return null; } } }
Java
UTF-8
451
2.390625
2
[]
no_license
package com.akivaliaho; import com.akivaliaho.config.annotations.Interest; import org.springframework.stereotype.Component; /** * Created by akivv on 1.5.2017. */ @Component public class SuperCalculator { @Interest(receives = CalculateSuperHardSumEvent.class) public CalculateSuperHardSumResultEvent calculateSuperHard(Integer one, Integer two) { int i = one + two; return new CalculateSuperHardSumResultEvent(i); } }
Java
UTF-8
367
2.234375
2
[]
no_license
package ejercicio5; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class App { private Frame ventana; App() { ventana = new Frame(); ventana.setLocationRelativeTo(null); ventana.setVisible(true); } public static void main(String[] args) { new App(); } }
JavaScript
UTF-8
5,157
3.59375
4
[]
no_license
const fs = require('fs'); let userlist = []; const user = function(name, age, eyeColor, friends = [], index = 0) { return { index: index, age: age, eyeColor: eyeColor, name: name, friends: friends } } // Load json file const loadUsers = function() { fs.readFile("./users.json", function(error, data) { if(error) { throw error; } userlist = JSON.parse(data); let method = process.argv[2]; let command = process.argv[3]; let args = process.argv.slice(4); switch(method.toLowerCase()) { case "get": getCommands(command, args); break; case "post": postCommands(command, args); break; case "put": putCommands(command, args); break; case "delete": deleteCommands(command, args); break; default: console.log("Invalid method: " + method); } }); } // Write json file const saveUsers = function() { data = JSON.stringify(userlist); fs.writeFile("./users.json", data, "utf8", function(error) { if(error) { throw error; } }); } // Process GETs const getCommands = function(command, args) { if(!command) { console.log("Missing command."); return; } switch(command.toLowerCase()) { case "users": console.log("Users: "); for(const cuser of userlist) { printUser(cuser); } break; case "user": if(userlist[args[0]]) { printUser(userlist[args[0]]); } else { console.log("User " + args[0] + " doesn't exist."); } break; case "friends": let cuser = userlist[args[0]]; if(userlist[args[0]]) { if(cuser.friends.length) { friends = []; for(friend of cuser.friends) { friends.push(friend.name); } console.log(cuser.name + "'s friends: " + friends.join(", ")); } else { console.log(cuser.name + " has no friends. Muahahahaha"); } } else { console.log("User " + args[0] + " doesn't exist."); } break; default: console.log("Invalid command: " + command); } } const printUser = function(cuser) { //console.log("User " + cuser.index + ':'); console.log(cuser.index + ": " + cuser.name + ", age " + cuser.age + ", eye color: " + cuser.eyeColor); if(cuser.friends.length) { friends = []; for(friend of cuser.friends) { friends.push(friend.name); } console.log("Friends: " + friends.join(", ")); } console.log(); } // Process POSTs const postCommands = function(command, args) { if(!command) { console.log("Missing command."); return; } switch(command.toLowerCase()) { case "user": let name = args[0]; let age = args[1]; let eyes = args[2]; // name, age, eyeColor, friends = [], index = 0 userlist.push(user(name, age, eyes, [], userlist.length)); console.log("User added:"); printUser(userlist[userlist.length - 1]); break; case "friends": let index = args[0]; let friendName = args[1]; if(!userlist[index]) { console.log("User index " + index + " doesn't exist."); } console.log("Current friends list: " + userlist[index].friends); let id = makeFriendId(userlist[index].friends); userlist[index].friends.push({id: id, name: friendName}); friends = []; for(friend of userlist[index].friends) { friends.push(friend.name); } console.log("Friend " + friendName + " has been added to " + userlist[index].name + "'s friend list. Their current friends list is now: " + friends.join(", ")); break; default: console.log("Invalid command: " + command); } saveUsers(); } const makeFriendId = function(friends) { let id = 0; for(friend of friends) { if(id == friend.id) { id++; } } return id; } // Process PUTs const putCommands = function(command, args) { if(!command) { console.log("Missing command."); return; } switch(command.toLowerCase()) { case "user": let index = args[0]; let propertyName = args[1]; let value = args[2]; if(typeof(value) == "undefined") { console.log("Syntax: PUT user <index> <property name> <new value>"); break; } if(typeof(userlist[index]) == "undefined") { console.log("User with index " + index + " does not exist."); break } console.log("User " + userlist[index].name + "'s " + propertyName + " property changed from " + userlist[index][propertyName] + " to " + value); userlist[index][propertyName] = value; break; default: console.log("Invalid command: " + command); } saveUsers(); } // Process DELETEs const deleteCommands = function(command, args) { if(!command) { console.log("Missing command."); return; } switch(command.toLowerCase()) { case "user": let index = args[0]; if(typeof(userlist[index]) == "undefined") { console.log("User with index " + index + " does not exist."); break } console.log("Deleting " + userlist[index].name); delete userlist[index]; let users = []; for(let user of userlist) { if(user != undefined) { users.push(user); } } // Reindex list userlist = []; let i = 0; for(let user of users) { user.index = i++; userlist.push(user); } break; default: console.log("Invalid command: " + command); } saveUsers(); } loadUsers();
Python
UTF-8
498
3.578125
4
[]
no_license
def minimumBribes(q): res = 0 while True: for i, (x, y) in enumerate(zip(q, q[1:]), 1): if (x - y) > 2: return "Too chaotic" if x > y: res += 1 q[i], q[i-1] = q[i-1], q[i] break else: return res return res #print(minimumBribes([2, 1, 5, 3, 4])) #3 print(minimumBribes([1, 2, 5, 3, 7, 8, 6, 4])) 7 #print(minimumBribes([2, 5, 1, 3, 4])) #"Too chaotic"
Java
UTF-8
1,391
2.53125
3
[]
no_license
package pl.limitless.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import pl.limitless.model.Client; import pl.limitless.service.IClientService; /** * Created by Kuba on 10.06.2017. */ @Component public class ClientValidator implements Validator { @Autowired private IClientService clientService; @Override public boolean supports(Class<?> aClass) { return Client.class.equals(aClass); } @Override public void validate(Object o, Errors errors) { Client client = (Client) o; ValidationUtils.rejectIfEmptyOrWhitespace(errors,"email","NotEmpty"); if (client.getEmail().length() < 6 || client.getEmail().length() > 40) { errors.rejectValue("email", "Size.userForm.username"); } if (clientService.findClientByEmail(client.getEmail()) != null) { errors.rejectValue("email", "Duplicate.userForm.username"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty"); if (client.getPassword().length() < 8 || client.getPassword().length() > 32) { errors.rejectValue("password", "Size.userForm.password"); } } }
C++
UTF-8
970
2.609375
3
[]
no_license
#ifndef UCT_h #define UCT_h #include <utility> #include <ctime> #include <memory> #include "Config.hpp" #include "Point.h" class Board; class TreeNode; class UCT { public: static double defaultPolicy(TreeNode *nowNode); static TreeNode *treePolicy(TreeNode *nowNode); static Point* UCTSearch(const int* boardStart, const int* topStart, int _M, int _N, int _noX, int _noY); ~UCT(); static Board board; static int top_cur[MAX_N]; static int M, N, noX, noY; enum class MoveType { AVERAGE, FORCING, LOSING }; private: UCT() {} using MoveResult = std::pair<MoveType, Point>; static TreeNode *root; static clock_t time0; static const int dirx[7], diry[7]; static const Point NO_MOVE; static const MoveResult LOSING; static const MoveResult AVERAGE; static const MoveResult getOptimalMove(Board &board_cur, int last_player, Point last_move); static int getGain(Board& board_cur, int remaining_moves, int player); }; #endif /* UCT_h */
Python
UTF-8
5,357
2.515625
3
[]
no_license
#!/usr/bin/env python3 # Copyright (c) 2019, Cameron Hochberg # All rights reserved. # # Author: Cameron Hochberg # Date: 07/2019 # Homepage: https://github.com/Susanou # Email: cam.hochberg@gmail.com # import sys, os import matplotlib.pyplot as plt import numpy as np import joblib from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import SGDClassifier from sklearn.naive_bayes import MultinomialNB as naive from sklearn.svm import SVC as svc from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.datasets import load_files from sklearn.model_selection import train_test_split from sklearn import metrics dataset = load_files('../dataFitting') def fitting1(): docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.99, random_state=42, shuffle=True) if not os.path.isfile("sgd_model.pkl"): vectorizer = TfidfVectorizer(ngram_range=(1,1), analyzer='word', use_idf=True) clf = Pipeline([ ('vect', vectorizer), ('clf', SGDClassifier(loss='log', penalty='l2', alpha=1e-3, random_state=42, max_iter=5, tol=None)) ]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2), (1,3), (1,4), (1,5)], 'clf__alpha': (1e-2, 1e-3, 5e-3, 7e-3, 4e-3, 3e-3, 2e-3, 8e-3, 9e-3), } gs_clf = GridSearchCV(clf, parameters, cv=5, iid=False, n_jobs=-1) gs_clf.fit(docs_train, y_train) return gs_clf, dataset.target_names else: return joblib.load("sgd_model.pkl"), dataset.target_names def fitting2(): if not os.path.isfile("naive_model.pkl"): docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.99, random_state=42, shuffle=True) vectorizer = TfidfVectorizer(ngram_range=(1,1), analyzer='word', use_idf=True) #MultinomialNB Pipeline clf = Pipeline([ ('vect', vectorizer), ('clf', naive(alpha=1.0, fit_prior=True)) ]) parameters={ 'vect__ngram_range': [(1, 1), (1, 2), (1,3), (1,4), (1,5)], 'clf__fit_prior': (True, False), 'clf__alpha': (1.0, 0.1, 0.5, 2.0, .25, 0.75, 0.002), } gs_clf = GridSearchCV(clf, parameters, cv=5, iid=False, n_jobs=-1) gs_clf.fit(docs_train, y_train) return gs_clf else: return joblib.load("naive_model.pkl") def fitting3(): if not os.path.isfile("svc_model.pkl"): docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.99, random_state=42, shuffle=True) vectorizer = TfidfVectorizer(ngram_range=(1,1), analyzer='word', use_idf=True) clf = Pipeline([ ('vect', vectorizer), ('clf', svc(tol=1e-3, random_state=42, C=1.0, max_iter=-1, gamma='scale', probability=True)) ]) parameters={ 'vect__ngram_range': [(1, 1), (1, 2), (1,3), (1,4), (1,5)], 'clf__tol':(1e-3, 1e-2, 5e-3, 2e-3, 3e-3,4e-3), 'clf__gamma':('auto', 'scale'), 'clf__C':(1.0,.1,.2,.3,.4, 0.5, 0.6, 0.7, 0.8, 0.9) } gs_clf = GridSearchCV(clf, parameters, cv=5, iid=False, n_jobs=-1) gs_clf.fit(docs_train, y_train) return gs_clf else: return joblib.load("svc_model.pkl") def vote(prob1, prob2, prob3): """Fonction nous permettant de voter sur le resulat en cas d'absence de choix Parameters ---------- prob1 : array-like liste de probabilite pour chaque classe selon le premier algorithme prob2 : array-like liste de probabilite pour chaque classe selon le deuxieme algorithme prob3 : array-like liste de probabilite pour chaque classe selon le troisieme algorithme Returns ------- int Renvoi soit l'indexe du resultat du resultat le plus probable float La probabilite associee au resultat """ top1 = np.argsort(prob1, axis=1)[:,-3:] top2 = np.argsort(prob2, axis=1)[:,-3:] top3 = np.argsort(prob3, axis=1)[:,-3:] top1 = top1[0] top2 = top2[0] top3 = top3[0] #top3 = [0, 0, 0] sums = dict() if top1[2] == top2[2] and top1[2] == top3[2]: return top1[2], prob1[0][top1[2]]+prob2[0][top1[2]]+prob3[0][top1[2]] elif top1[2] == top2[2]: return top1[2], prob1[0][top1[2]]+prob2[0][top1[2]]+.2 elif top1[2] == top3[2]: return top1[2], prob1[0][top1[2]]+prob3[0][top1[2]]+.2 elif top2[2] == top3[2]: return top2[2], prob2[0][top1[2]]+prob3[0][top1[2]]+.2 else: for i in top1: if i in sums: sums[i] += prob1[0][i] else: sums[i] = prob1[0][i] for j in top2: if j in sums: sums[j] += prob2[0][j] else: sums[j] = prob2[0][j] for k in top3: if k in sums: sums[k] += prob3[0][k] else: sums[k] = prob3[0][k] maxV = max(sums.values()) maxK = [k for k, v in sums.items() if v == maxV] return (maxK[0], maxV)
Python
UTF-8
1,756
2.515625
3
[ "Apache-2.0" ]
permissive
import os import pytest from itertools import chain from src.Graph import Graph from src.CFGrammar import CFGrammar from src.RFA import RFA from src.Utils import read_graph, parse_pairs import src.cfpq as cfpq DATA_PATH = os.path.join(os.getcwd(), 'tests/data/cfpq') grammars_name = ["grammar_1_parentheses.txt", "grammar_2_palindrome.txt", "grammar_3.txt"] graphs_name = ["graph_empty.txt", "graph_1.txt", "graph_2.txt", "graph_3.txt"] res_name = ["res_1.txt", "res_2.txt", "res_3.txt"] @pytest.fixture(scope='function', params=list(chain(*[ [ (grammars_name[0], graphs_name[0], algo_name, []), (grammars_name[1], graphs_name[2], algo_name, res_name[1]), (grammars_name[2], graphs_name[3], algo_name, res_name[2]) ] for algo_name in [f'cfpq_{name}' for name in ['hellings', 'matrices', 'tensor', 'tensor_wcnf', 'tensor_with_rfa']] ]))) def init(request): grammar_name, graph_name, algo_name, res_name = request.param grammar = CFGrammar(os.path.join(DATA_PATH, grammar_name)) rfa = RFA.create_from_cfg_regex(os.path.join(DATA_PATH, grammar_name)) graph = Graph(read_graph(os.path.join(DATA_PATH, graph_name))) expected = set(parse_pairs(os.path.join(DATA_PATH, res_name))) if res_name != [] else set([]) return { 'grammar': grammar, 'rfa': rfa, 'graph': graph, 'algo': algo_name, 'expected': expected } def test_cfpq(init): grammar, rfa, graph, algo_name, expected = init['grammar'], init['rfa'], init['graph'], init['algo'], init['expected'] algo = getattr(cfpq, algo_name) if algo_name == 'cfpq_tensor_with_rfa': assert set(algo(graph, rfa)) == expected else: assert set(algo(graph, grammar)) == expected
Markdown
UTF-8
3,984
2.578125
3
[ "MIT" ]
permissive
## Github-action 깃헙액션을 사용한 경험에 대해 작성해보고자 한다. 일단 `aws amplify` 로 기존에 프론트를 배포하고있었다. amplify CLI를 통해서 수동배포를 하고있었는데 이 부분을 깃헙액션을 통해 CI/CD 를 구축해보고자 한다. [amplify-cli-action](https://github.com/marketplace/actions/amplify-cli-action) 이라는 깃헙 액션 워크플로우 템플릿을 base로 yml을 작성했다. 깃헙액션 탭에 들어가면 기본적으로 많이쓰이는 템플릿을 제공하는데 그외에도 [github-action marketplace](https://github.com/marketplace/actions/) 에 가면 유저들이 만들어 놓은 많은 템플릿도 제공하고있다. 이중 자신이 필요한 CI/CD 베이스를 가져와 사용할 수 있다. ## what to do 깃헙액션을 사용한 경험에 대해 작성해보고자 한다. 일단 `aws amplify` 로 기존에 프론트를 배포하고있었다. amplify CLI를 통해서 수동배포를 하고있었는데 이 부분을 깃헙액션을 통해 CI/CD 를 구축해보고자 한다. [amplify-cli-action](https://github.com/marketplace/actions/amplify-cli-action) 이라는 깃헙 액션 워크플로우 템플릿을 base로 yml을 작성했다. 깃헙액션 탭에 들어가면 기본적으로 많이쓰이는 템플릿을 제공하는데 그외에도 [github-action marketplace](https://github.com/marketplace/actions/) 에 가면 유저들이 만들어 놓은 많은 템플릿도 제공하고있다. 이중 자신이 필요한 CI/CD 베이스를 가져와 사용할 수 있다. ## workflow 아래와 같이 workflow 파일을 생성할 수 있다. 파일위치는 `.github > workflows` 에 파일명 `aws.yml` 으로 위치해있다. 여러가지 다중 워크플로우를 설정해놓을 수도 있다. 보안이 필요한 키들은 깃헙 레포지터리 `setting > secrets`에 변수 설정해 놓고 가져올 수 있다. `e.g. ${{ secrets.AWS_ACCESS_KEY_ID }}` 아래 workflow는 `aws amplify`를 활용한 배포방식을 사용하고있는데, `rnd` 라는 env 환경으로 체크아웃후 빌드 및 배포하고 있다. 체크아웃후 `npm install` 로 필요한 노드모듈들을 설치후 `amplify build_command` 로 빌드 커맨드를 실행시켜준다. ```yaml name: 'Amplify Deploy' on: push: branches: - github-action-deploy jobs: test: name: test amplify-cli-action runs-on: ubuntu-latest strategy: matrix: node-version: [12.x] steps: - uses: actions/checkout@v1 - name: use node.js ${{ matrix.node-version }} uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - name: configure amplify uses: ambientlight/amplify-cli-action@0.2.0 with: amplify_command: configure amplify_env: rnd env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_REGION: ap-northeast-2 - name: install, build and test run: | npm install npm rebuild node-sass # build and test # npm run build # npm run test - name: deploy uses: ambientlight/amplify-cli-action@0.2.0 with: build_command: 'npm run build' amplify_command: publish amplify_env: rnd env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_REGION: ap-northeast-2 ``` ## 참조 - [github-action docs](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions) - [github-action market](https://github.com/marketplace?type=actions) - [blog.aliencube.org](https://blog.aliencube.org/ko/2019/12/13/publishing-static-website-to-azure-blob-storage-via-github-actions/?fbclid=IwAR3WYkF5_oSs0tYoMRiVIbTmk9bNl4wu-a3Cn8sfPtP6l-IYIPvYEzHj5-Y)
Java
UTF-8
2,968
2.5625
3
[]
no_license
package com.example.homework3cats; import androidx.room.Entity; import androidx.room.Ignore; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.ArrayList; //model for cats @Entity public class Cat implements Serializable { //array public ArrayList<Cat> cats; //based upon assignment criteria and Json Model //only dog friend is an integer private String id; private String name; private String description; private String weight_imperial; private String temperament; private String origin; private String life_span; private String wikipedia_url; int dog_friendly; @Ignore @SerializedName("weight") private Weight weight; private String url; //no images here // private ArrayList<Cat> cats; public Cat() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getWeight_imperial() { return weight_imperial; } public void setWeight_imperial(String weight_imperial) { this.weight_imperial = weight_imperial; } public String getTemperament() { return temperament; } public void setTemperament(String temperament) { this.temperament = temperament; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getLife_span() { return life_span; } public void setLife_span(String life_span) { this.life_span = life_span; } public String getWikipedia_url() { return wikipedia_url; } public void setWikipedia_url(String wikipedia_url) { this.wikipedia_url = wikipedia_url; } public int getDog_friendly() { return dog_friendly; } public void setDog_friendly(int dog_friendly) { this.dog_friendly = dog_friendly; } public ArrayList<Cat> getCats() { return cats; } public void setCats(ArrayList<Cat> cats) { this.cats = cats; } public Weight getWeight() { return weight; } public class Weight implements Serializable { private String imperial; private String metric; public String getImperial() { return imperial; } public void setImperial(String imperial) { this.imperial = imperial; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } } }
C++
UTF-8
1,166
2.65625
3
[ "MIT" ]
permissive
class Solution { public: int minJumps(vector<int>& arr) { const int N = arr.size(); const int INF = 1e9; unordered_map<int, vector<int>> posOf; for(int i = 0; i < N; ++i){ posOf[arr[i]].push_back(i); } vector<int> dist(N, INF); queue<int> q; q.push(0); dist[0] = 0; while(!q.empty() && dist[N - 1] == INF){ int i = q.front(); q.pop(); if(i - 1 >= 0 && dist[i - 1] == INF){ q.push(i - 1); dist[i - 1] = dist[i] + 1; } if(i + 1 < N && dist[i + 1] == INF){ q.push(i + 1); dist[i + 1] = dist[i] + 1; } while(!posOf[arr[i]].empty()){ int j = posOf[arr[i]].back(); if(dist[j] == INF){ q.push(j); dist[j] = dist[i] + 1; } posOf[arr[i]].pop_back(); } } return dist[N - 1]; } };
Python
UTF-8
945
2.984375
3
[]
no_license
import numpy as np import sys def counting_sheep(N): init_set = set() desti_set = set(['0','1','2','3','4','5','6','7','8','9' ]) #print desti_set #desti_set.remove('1') #print desti_set if N == 0 : return 'INSOMNIA' i = 0; while len(desti_set) != 0 : i=i+1 numbstr = str(i*N) #print numbstr for char in numbstr: if char in desti_set: #print char desti_set.remove(char) #print desti_set return str(i*N) if __name__ == "__main__": file_name = sys.argv[1] print file_name A_input = np.genfromtxt(file_name,dtype='i4') #print A_input case_num = A_input[0] for idx in range(1,case_num+1): ans = "Case #"+str(idx) + ": " + counting_sheep(A_input[idx]) print ans with open('output','a') as outputFile: outputFile.write(ans + '\n')
Python
UTF-8
365
3.421875
3
[]
no_license
# Loads a CSV file into a list def load_csv(filename): dataset = [] # Values in a data point are separated by a delimiter (comma, space, tab, etc.) delimiter = ',' file = open(filename, 'r') for line in file: if not line: continue line = line.split(delimiter) dataset.append(line) return dataset
Java
UTF-8
769
2.203125
2
[]
no_license
package com.bosch.wrd.export.pdf; import java.io.IOException; import java.io.InputStream; import com.bosch.wrd.dto.ProjectReviewDto; import com.bosch.wrd.dto.StearingCommiteeDto; import com.itextpdf.text.DocumentException; public class ExportPdfImpl implements ExportPdf { @Override public InputStream exportProjectTemplate(ProjectReviewDto dto) throws IOException, DocumentException { ProjectReviewHandlingPDF projectReview = new ProjectReviewHandlingPDF(dto); return projectReview.createPdf(); } @Override public InputStream exportStearingCommiteeTemplate(StearingCommiteeDto dto) throws IOException, DocumentException { StearingCommiteeHandlingPDF stearingCommitee = new StearingCommiteeHandlingPDF(dto); return stearingCommitee.createPdf(); } }
C#
UTF-8
2,433
2.53125
3
[ "CC-BY-4.0", "GPL-2.0-only", "MIT" ]
permissive
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2022 Dominik Reichl <dominik.reichl@t-online.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using KeePassLib.Utility; namespace KeePassLib.Serialization { public sealed class IocPropertyInfo { private readonly string m_strName; public string Name { get { return m_strName; } } private readonly Type m_t; public Type Type { get { return m_t; } } private string m_strDisplayName; public string DisplayName { get { return m_strDisplayName; } set { if(value == null) throw new ArgumentNullException("value"); m_strDisplayName = value; } } private List<string> m_lProtocols = new List<string>(); public IEnumerable<string> Protocols { get { return m_lProtocols; } } public IocPropertyInfo(string strName, Type t, string strDisplayName, string[] vProtocols) { if(strName == null) throw new ArgumentNullException("strName"); if(t == null) throw new ArgumentNullException("t"); if(strDisplayName == null) throw new ArgumentNullException("strDisplayName"); m_strName = strName; m_t = t; m_strDisplayName = strDisplayName; AddProtocols(vProtocols); } public void AddProtocols(string[] v) { if(v == null) { Debug.Assert(false); return; } foreach(string strProtocol in v) { if(strProtocol == null) continue; string str = strProtocol.Trim(); if(str.Length == 0) continue; bool bFound = false; foreach(string strEx in m_lProtocols) { if(strEx.Equals(str, StrUtil.CaseIgnoreCmp)) { bFound = true; break; } } if(!bFound) m_lProtocols.Add(str); } } } }
Java
GB18030
2,579
2.421875
2
[]
no_license
package org.lance.demo; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import org.lance.adapters.ChatAdapter; import org.lance.entity.ChatEntity; import org.lance.main.R; public class WeixinChatDemo extends BaseActivity { private Button sendButton = null; private EditText contentEditText = null; private ListView chatListView = null; private List<ChatEntity> chatList = null; private ChatAdapter chatAdapter = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.weixin_main); init(); } private void init() { contentEditText = (EditText) this.findViewById(R.id.et_content); sendButton = (Button) this.findViewById(R.id.btn_send); chatListView = (ListView) this.findViewById(R.id.listview); chatList = new ArrayList<ChatEntity>(); ChatEntity chatEntity = null; // ʼ for (int i = 0; i < 2; i++) { chatEntity = new ChatEntity(); if (i % 2 == 0) { chatEntity.setComeMsg(false); chatEntity.setContent("Hello"); chatEntity.setChatTime("2012-10-06 14:12:32"); } else { chatEntity.setComeMsg(true); chatEntity.setContent("Hello,nice to meet you!"); chatEntity.setChatTime("2012-10-02 15:13:32"); } chatList.add(chatEntity); } chatAdapter = new ChatAdapter(this, chatList); chatListView.setAdapter(chatAdapter); sendButton.setOnClickListener(new onClickListenerImpl()); } /** * Ϣ¼ * * @author JERRY * */ private class onClickListenerImpl implements OnClickListener { @Override public void onClick(View v) { if (!contentEditText.getText().toString().equals("")) { // Ϣ send(); } else { Toast.makeText(WeixinChatDemo.this, "ݲΪ", Toast.LENGTH_SHORT).show(); } } } /** * Ϣ */ private void send() { ChatEntity chatEntity = new ChatEntity(); Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); chatEntity.setChatTime(sdf.format(now)); chatEntity.setContent(contentEditText.getText().toString()); chatEntity.setComeMsg(false); chatList.add(chatEntity); chatAdapter.notifyDataSetChanged(); chatListView.setSelection(chatList.size() - 1); contentEditText.setText(""); } }
Java
UTF-8
1,468
2
2
[]
no_license
package com.icloud.model.signup; import java.util.Date; /** * 报名记录 * @author leiyi * */ public class SignUpRecord { private String id; private String nick; private String headerImg; private String phone; private String email; private String name; private String signUpConfigId; private Date createTime; private String signUpUserId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getHeaderImg() { return headerImg; } public void setHeaderImg(String headerImg) { this.headerImg = headerImg; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSignUpConfigId() { return signUpConfigId; } public void setSignUpConfigId(String signUpConfigId) { this.signUpConfigId = signUpConfigId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getSignUpUserId() { return signUpUserId; } public void setSignUpUserId(String signUpUserId) { this.signUpUserId = signUpUserId; } }
Shell
UTF-8
177
2.734375
3
[]
no_license
#!/bin/bash DOCKERFILE="Dockerfile" if [[ "$(uname -m)" == "arm"* ]]; then DOCKERFILE="Dockerfile.arm" fi docker build \ -t object-detection-server \ -f ../$DOCKERFILE ..
Java
UTF-8
901
3.125
3
[]
no_license
/** * Created by Murat on 20.12.2016. */ public class Tupel { private int houseNo; private String part; private String componentName; public Tupel(String componentName, int houseNo, String part) { this.componentName = componentName; this.houseNo = houseNo; this.part = part; } public int getHouseNo() { return houseNo; } public String getPart() { return part; } public boolean equals(int no, String p) { if(houseNo != no) return false; if(!part.equals(p)) return false; return true; } public void showTupel() { System.out.println("(" + houseNo + "," + part + ")"); } public boolean contains(String p) { if(part.equals(p)) return true; return false; } public String getComponentName() { return componentName; } }
TypeScript
UTF-8
5,012
2.515625
3
[]
no_license
/// <reference path="../.d.ts" /> import * as applicationSettingsModule from "application-settings"; import {Constants} from "../constants"; import {Notifications} from "../utilities/notifications"; import {StatusCodes} from "../utilities/statusCodes"; import * as http from "http"; class Authentication { private _token: string = null; private _username: string = null; public get isAuthenticated(): boolean { return applicationSettingsModule.hasKey(Constants.AuthenticationTokenKey); } public get token(): string { if (!this._token) { this._token = applicationSettingsModule.getString(Constants.AuthenticationTokenKey, null); } return this._token; } public get username(): string { if (!this._username) { this._username = applicationSettingsModule.getString(Constants.UsernameKey, null); } return this._username; } public get authorizationHeader(): string { return `Bearer ${this.token}`; } public login(username: string, password: string): Promise<any> { return new Promise<any>((resolve, reject) => { http.request({ url: Constants.Server.LoginEndpoint, method: "POST", headers: { "Content-Type": "application/json" }, content: JSON.stringify({ username: username, password: password }), timeout: 2000 /* miliseconds */ }) .then((response: http.HttpResponse) => { if (StatusCodes.isOK(response.statusCode)) { let token = response.content.toJSON().token; this.setupLocalSettings(token, username); resolve(response.content); } else { Authentication.showErrorAndReject(response.content.toString(), reject); } }, (error: any) => { Authentication.showErrorAndReject(error.message, reject); }) }); } public loginWithFb(fbApiToken: string): Promise<any> { return new Promise<any>((resolve, reject) => { http.request({ url: Constants.Server.FbLoginEndpoint, method: "POST", headers: { "Content-Type": "application/json" }, content: JSON.stringify({ token: fbApiToken, }), timeout: 2000 /* miliseconds */ }) .then((response: http.HttpResponse) => { if (StatusCodes.isOK(response.statusCode)) { let responseJson = response.content.toJSON(); this.setupLocalSettings(responseJson.token, responseJson.username); resolve(response.content); } else { Authentication.showErrorAndReject(response.content.toString(), reject); } }, (error: any) => { Authentication.showErrorAndReject(error.message, reject); }) }); } public logout(): void { this.clearLocalSettings(); } public signUp(username: string, password: string, confirmPassword: string): Promise<any> { return new Promise<any>((resolve, reject) => { http.request({ url: Constants.Server.RegisterEndpoint, method: "POST", headers: { "Content-Type": "application/json" }, content: JSON.stringify({ username: username, password: password, confirmPassword: confirmPassword }), timeout: 2000 /* miliseconds */ }) .then((response: http.HttpResponse) => { if (StatusCodes.isOK(response.statusCode)) { resolve(response.content.toJSON()); } else { Authentication.showErrorAndReject(response.content.toJSON().message, reject); } }, (error: any) => { Authentication.showErrorAndReject(error.message, reject); }) }); } private static showErrorAndReject(errorMessage: string, reject: (e: any) => void) { Notifications.showError(errorMessage); reject(errorMessage); } private setupLocalSettings(authenticationTokenKey: string, username: string): void { this._username = username; applicationSettingsModule.setString(Constants.AuthenticationTokenKey, authenticationTokenKey); applicationSettingsModule.setString(Constants.UsernameKey, username); } private clearLocalSettings(): void { this._username = null; applicationSettingsModule.remove(Constants.AuthenticationTokenKey); applicationSettingsModule.remove(Constants.UsernameKey); } } export let authentication = new Authentication();
Java
UTF-8
766
2.71875
3
[]
no_license
package com.mikeivan.apps.scatternotes; /** * Created by Mivan on 9/19/2016. * * This class is to be used with an adapter class for viewing movies * in a scrollview */ public class MovieEntry { // Only a subset of the movie row is used for display/data for intents // _id of movie // title of movie // date of table row creation private int mId; private String mMovie; private String mDate; // Constructor public MovieEntry(int id, String movie, String date) { mId = id; mMovie = movie; mDate = date; } // Getter functions used by adapter public int getId() { return mId; } public String getMovie() { return mMovie; } public String getDate() { return mDate; } }