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
JavaScript
UTF-8
2,170
2.609375
3
[]
no_license
export const addTic = (tic) => { return{ type: 'ADD_REQ', value: tic } } export const fetchReqs = () => { return dispatch => { fetch('/api/home') .then(res => res.json()) .then(response => { const action = { type: "FETCH_REQS", value: response } dispatch(action); console.log("fetch reqs response", dispatch) }) .catch(error => console.log(error)) } } export const removeTic = (req) => { return dispatch => { fetch(`/api/home/${req.id}`, { method:"delete", }) .then(res => res.json()) .then(response => { const action = { type: "REMOVE_TIC", value: req.id } dispatch(action); console.log("fetch reqs response", dispatch) }) .catch(error => console.log(error)) } } export const isLike = (req, isLiked1, isLiked2, isLiked3) => { return dispatch => { fetch(`/api/home/${req.id}`, { method:"put", body: JSON.stringify( { isLiked1: true, isLiked2: false, isLiked: false}) }) .then(res => res.json()) .then(response => { const action = { type: "IS_LIKE", value: true } dispatch(action); console.log("fetch reqs response", dispatch) }) .catch(error => console.log(error)) } } export const fetchReqs1 = () => { return dispatch => { fetch('/api/home') .then(res => res.json()) .then(response => { const action = { type: "FETCH_REQS1", value: response } dispatch(action); console.log("fetch reqs1 response", dispatch) }) .catch(error => console.log(error)) } } export const addTic1 = (tic1) => { return{ type: 'ADD_REQ1', value: tic1 } } export const removeTic1 = (index) => { return { type: 'REMOVE_TIC1', value: index } } export const login = () => { return { type: 'LOG_IN', value: true } } export const logout = () => { return { type: 'LOG_OUT', value: false } }
Java
UTF-8
644
1.578125
2
[]
no_license
package app.zenly.locator.chat; import java.util.List; import p389io.reactivex.C12279e; import p389io.reactivex.functions.Function; import p389io.reactivex.functions.Predicate; /* renamed from: app.zenly.locator.chat.p2 */ /* compiled from: lambda */ public final /* synthetic */ class C2194p2 implements Function { /* renamed from: e */ public static final /* synthetic */ C2194p2 f6735e = new C2194p2(); private /* synthetic */ C2194p2() { } public final Object apply(Object obj) { return C12279e.m32623b((Iterable<? extends T>) (List) obj).mo36459b((Predicate<? super T>) C2032k4.f6450e).mo36511n(); } }
C#
UTF-8
2,135
3.140625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace OOPClass { public partial class OCP : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { AppEvent myAppEvent = new AppEvent("Log"); //想產生不同Logger傳入指定字串即可 myAppEvent.GenerateEvent("Test"); // ConsoleLogger: Test } #region OCP開放封閉原則 // 採用分離與相依的技巧 public interface ILogger { void Log(string message); } public class ConsoleLogger : ILogger { public void Log(string message) { HttpContext.Current.Response.Write(string.Format("ConsoleLogger: {0}<br/>", message)); } } public class FileLogger : ILogger { public void Log(string message) { HttpContext.Current.Response.Write(string.Format("FileLogger: {0}<br/>", message)); } } public class AppEvent { // readonly通常會用在class流程設計,在建構子指派值之後,就不能更改 private readonly ILogger _Logger; public AppEvent(string loggerType) { this._Logger = LoggerFactory.CreateLogger(loggerType); } public void GenerateEvent(string message) { _Logger.Log(message); } } // 工廠模式,傳入一個名稱給他,會想辦法回傳一個物件給你 public class LoggerFactory { public static ILogger CreateLogger(string loggerType) { if(loggerType == "Log") return new ConsoleLogger(); else if(loggerType == "File") return new FileLogger(); else throw new NotFiniteNumberException(); } } #endregion } }
Markdown
UTF-8
1,786
2.71875
3
[]
no_license
Angularjs with amCharts === 用途為開發較為複雜的HTML5+Angularjs網站使用. 包含的套件如下: 環境套件 * nodejs * bower * gulp 函式庫 * Angularjs * Angular ui-router * Bootstrap4 * font-awesome * lodash * moment * numeral * toastr * ui-bootstrap * ui-router * amstock3 ## 範本示範內容 1. 專案架構 2. 使用ui-router的view規劃SPA 3. 透過promise取得遠端資料 4. 使用amChart畫chart及stockChart --- # 安裝及載入 ### 安裝amStock及angular-amchart 1. amStock包含了amChart及amStock ``` bower install amstock3 --save-dev ``` 2. amCharts-Angular ``` bower install amcharts-angular --save ``` 但因為這個directive只有做amChart, 我自己將它拿來改, 所以之後要使用自己改的函式庫。 ### 引入amStock ``` <link rel="stylesheet" href="/bower_components/amstock3/amcharts/style.css" type="text/css"> <script src="./bower_components/amstock3/amcharts/amcharts.js"></script> <script src="./bower_components/amstock3/amcharts/serial.js"></script> <script src="./bower_components/amstock3/amcharts/amstock.js"></script> ``` --- # 畫出第一個價量圖 參考[DEMO-Multiple Data Sets](http://www.amcharts.com/demos/multiple-data-sets/)用amStock畫出第一個圖. ### 重點 1. 如果要畫出以小時為單位的圖, categoryAxesSettings的minPeriod一定要設定。 `hh`表示最小單位為1小時. (Specifies the shortest period of your data. fff - millisecond, ss - second, mm - minute, hh - hour, DD - day, MM - month, YYYY - year.) , 也可以用`2hh`代表2小時為最小單位. ``` categoryAxesSettings: { minPeriod: 'hh' } ``` 2. 若要全部顯示不壓縮所有資料(預設為150, 只要資料超過150點就會壓縮圖) ``` categoryAxesSettings: { maxSeries: 0 } ``` ### 相關資源
Python
UTF-8
4,277
3.75
4
[]
no_license
# -*- conding:utf-8 -*- # 编写“计算机类”,属性包括CPU型号,内存大小,硬盘大小。 # 行为包括介绍CPU型号,展示内存大小,展示硬盘大小,综合介绍。 class Computer: def __init__(self,CPU,internal_storage,hard_disk): self.CPU=CPU self.internal_storage=internal_storage self.hard_disk=hard_disk def infor_CPU(self): return self.CPU def infor_storage(self): return self.internal_storage def infor_disk(self): return self.hard_disk def infor_all(self): return f'CPU 的规格{self.CPU},内存条大小{self.internal_storage},硬盘的规格{self.hard_disk}' c=Computer('i7','3G','6G') print(c.infor_CPU()) print(c.infor_storage()) print(c.infor_disk()) print(c.infor_all()) # 编写一个银行卡类,具有账号,人名与余额属性。编写提款机类,接收一张银行卡,并且具有存款,提款,查询余额,转账功能。 class BankCard: def __init__(self,id,name,money): self.id=id self.name=name self.money=money class ATM: def __init__(self,name): self.name=name def in_money(self,bankCard,number): bankCard.money +=number def out_money(self,bankCard,number): bankCard.money -=number def search_infor(self,bankCard): print(bankCard.money) def trans_money(self,bankCard,card2,number): self.out_money(bankCard,number) self.in_money(bankCard2,number) bankCard=BankCard('001','lz',9999) bankCard2=BankCard('002','lzz',100) atm=ATM('工行') atm.trans_money(bankCard,bankCard2,100) atm.search_infor(bankCard) atm.search_infor(bankCard2) # 编写一个计数器,能够记录一个类创建了多少个对象。 class Counter: num=0 def __init__(self): pass @classmethod def count(cls): cls.num += 1 @classmethod def totall(cls): print(cls.num) class TestC: def __init__(self,counter): self.counter=counter counter.count() counter=Counter() for i in range(5): TestC(counter) counter.totall() # 将第一题中的计算机对象放入列表中输出,会出现什么现象? li=[Computer('i3',3,4),Computer('i5',6,7),Computer('i7',8,8)] print(li) # 编写程序,设计单张扑克牌类Card,具有花色,牌面与具体值。 # 同时设计整副扑克牌类Cards,具有52张牌。Cards类能够具有发牌,对任意三张牌断定牌的类型。 import random class Card: colors=['红砖','黑桃','梅花','红桃'] faces=['A','2','3','4','5','6','7','8','9','10','J','Q','K'] values=[1,2,3,4,5,6,7,8,9,10,11,12,13] def __init__(self,color,face,value): self.color=color self.face=face self.value=value def infor(self): print(f'花色:{self.color},牌面:{self.face},数值:{self.value}') class Cards: cards=[] def __init__(self): pass def del_cards(self): li=[] for i in range(3): index=random.randint(0,51) li.append(self.__class__.cards[index]) return li def judge(self,li): worth=[li[0].value,li[1].value,li[2].value] big=max(worth) small=min(worth) if li[0].value==li[1].value==li[2].value: return '豹子!' if li[0].value==li[1].value or li[0].value==li[2].value or li[2].value==li[1].value: return '对子!' if li[0].color==li[1].color==li[2].color: if big- small==2: return '同花顺' return '同花' if big-small==2: return '顺子!' else: return '散牌!' def new_cards(self,Card): for c in Card.colors: for f,v in enumerate(Card.faces,1): self.__class__.cards.append(Card(c,v,f)) cards=Cards() cards.new_cards(Card) li=cards.del_cards() print(cards.judge(li)) for i in li: i.infor()
JavaScript
UTF-8
18,811
2.53125
3
[]
no_license
require(['jquery', 'step-bar', 'layer', 'uploadify'], function ($, stepBar) { //格式化时间 function formatTime(obj) { if (obj) { var year = obj.getFullYear(), month = parseInt(obj.getMonth()) + 1 > 9 ? parseInt(obj.getMonth()) + 1 : '0' + (parseInt(obj.getMonth()) + 1), day = obj.getDate() > 9 ? obj.getDate() : '0' + obj.getDate(), hour = obj.getHours() > 9 ? obj.getHours() : '0' + obj.getHours(), min = obj.getMinutes() > 9 ? obj.getMinutes() : '0' + obj.getMinutes(), sec = obj.getSeconds() > 9 ? obj.getSeconds() : '0' + obj.getSeconds(); return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec; } else { return obj; } } //倒计时 参数是秒 console.log(djs(194375)); //2天5小时59分35秒 function djs(second) { var day, hour, min, sec; day = parseInt(second / 86400); hour = parseInt((second - day * 86400) / 3600); hour > 9 ? hour = hour : hour = '0' + hour; min = parseInt((second - day * 86400 - hour * 3600) / 60); min > 9 ? min = min : min = '0' + min; sec = second - day * 86400 - hour * 3600 - min * 60; sec > 9 ? sec = sec : sec = '0' + sec; return day + '天' + hour + '小时' + min + '分' + sec + '秒'; } //处理剩余时间 function getLessTime(obj, sno, type) { var str = obj.html(); $.ajax({ url: '/buyer/order/refoundTime', type: 'post', data: { sale_order_number: sno, orderid: afterSale.orderid, type: type }, success: function (data) { var timer = null; if (data.errorCode === 0) { clearInterval(timer); obj.html(str + '0天00小时00分00秒'); } if (data.errorCode === 1) { if (data.datastr.meta.code === 200) { timer = setInterval(function () { if (data.datastr.body <= 0) { clearInterval(timer); obj.html(str + '0天00小时00分00秒'); } else { obj.html(str + djs(data.datastr.body)); data.datastr.body--; } }, 1000); } else { clearInterval(timer); obj.html(str + '0天00小时00分00秒'); } } if (data.errorCode === 2) { location.href = '/buyer/login'; } } }); } //获取退款原因 function refoundReason(type) { $.ajax({ url: '/buyer/order/getReasonList', type: 'post', data: { type: type }, success: function (data) { var str = '<option value="0">-请选择退款原因-</option>'; if (data.errorCode === 0) { layer.msg('服务器异常,请稍后再试'); } if (data.errorCode === 1) { if (data.datastr.meta.code === 200) { for (var i in data.datastr.body) { str += '<option value="' + data.datastr.body[i].reason_id + '" data-reasontype="' + data.datastr.body[i].reason_type + '">' + data.datastr.body[i].type_val + '</option>'; } $('#refoundReason').html(str); } else { layer.msg(data.datastr.meta.msg); } } if (data.errorCode === 2) { location.href = '/buyer/login'; } } }); } //提交售后申请或修改售后申请 function submitModifyAfterSale(sno, type, img) { $.ajax({ url: '/buyer/order/applyAfterSale', type: 'post', data: { sorder_no: sno, applyType: type, //1-未发货发起的仅退款;2-已发货发起的仅退款;3-已发货发起的退货退款 orderid: afterSale.orderid, storeid: afterSale.storeid, ogid: afterSale.ogid, reason_id: $('#refoundReason').val(), apply_amountStr: $('#money').html().split(' ')[0], description: $('#explain').val(), imgs: img }, success: function (data) { if (data.errorCode === 0) { layer.msg('服务器异常,请稍后再试'); } if (data.errorCode === 1) { if (data.datastr.meta.code === 200) { layer.msg('已提交售后申请,请耐心等待卖家处理'); location.reload(); } else { layer.msg(data.datastr.meta.msg); } } if (data.errorCode === 2) { location.href = '/buyer/login'; } } }); } if (afterSale.osid === 3) { if (afterSale.serviceStatus === 0) { stepBar.init('.step-bar', { stepCount: 3, currentStep: 1, stepContent: ['买家申请退款', '商家处理退款申请', '退款完成'] }); //获取退款原因 refoundReason(1); } if (afterSale.serviceStatus === 1) { //退款中 stepBar.init('.step-bar', { stepCount: 3, currentStep: 2, stepContent: ['买家申请退款', '商家处理退款申请', '退款完成'] }); //商家处理退款申请剩余时间 getLessTime($('#remain'), $('#gname').attr('data-sno'), 1) } if (afterSale.serviceStatus === 2) { //退款成功 stepBar.init('.step-bar', { stepCount: 3, currentStep: 3, stepContent: ['买家申请退款', '商家处理退款申请', '退款完成'] }); //商家处理退款申请剩余时间 getLessTime($('#remain'), $('#gname').attr('data-sno'), 1) } if (afterSale.serviceStatus === 3) { //卖家已拒绝退款申请 stepBar.init('.step-bar', { stepCount: 3, currentStep: 3, stepContent: ['买家申请退款', '商家处理退款申请', '已拒绝退款申请'] }); } if (afterSale.serviceStatus === 4) { stepBar.init('.step-bar', { stepCount: 2, currentStep: 2, stepContent: ['买家申请退款', '售后已撤销'] }); } } if (afterSale.osid === 7) { if (afterSale.serviceStatus === 2) { //退款成功 stepBar.init('.step-bar', { stepCount: 3, currentStep: 3, stepContent: ['买家申请退款', '商家处理退款申请', '退款完成'] }); } } /* 获取原因列表类型。 1-申请仅退款原因; 2-申请退货退款原因; 3-拒绝申请仅退款; 4-拒绝申请退款退货原因。 传入其他值返回code=405 */ //上传图片 function initUploadify(obj, fn) { var url = afterSale.domain; obj.uploadify({ 'fileTypeDesc': 'Image Files', //类型描述 'removeCompleted': true, //是否自动消失 'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp', //允许类型 'queueSizeLimit': 5, //可上传的文件个数 'fileSizeLimit': '2MB', //允许上传最大值 'swf': '/plugIn/uploadify/uploadify.swf', //上传处理swf程序 'uploader': "/api/uploadImage", //上传处理程序路径 'buttonText': '上传图片', //按钮的文字 'buttonClass': 'buttonClass', 'onUploadSuccess': function (file, filename, response) { //成功上传返回 fn(file, filename, response, url); } }); } //上传凭据 initUploadify($('#uploadImg'), uploadEvidenceSuc); initUploadify($('#uploadImg2'), uploadEvidenceSuc2); //上传凭据后回调 function uploadEvidenceSuc(file, filename, response, url) { $('#allImg').show(); if ($('#imgList').find('img').length >= 5) { //最多上传张数 layer.msg('最多上传5张图片'); return false; } $('#imgList').append('<img src="' + url + filename + '" width="100" height="100">'); } function uploadEvidenceSuc2(file, filename, response, url) { $('#imgArea').show(); if ($('#imgArea').find('img').length >= 5) { //最多上传张数 layer.msg('最多上传5张图片'); return false; } $('#imgArea').append('<img src="' + url + filename + '" width="100" height="100">'); } //删除凭据图片 $('#imgList').on({ click: function () { var self = $(this); layer.open({ btn: ['确定', '取消'], title: false, area: ['395px', 'auto'], content: '<p class="del-confirm">确认删除这张图片?</p>', yes: function (index) { self.remove(); if ($('#imgList').find('img').length === 0) { $('#allImg').hide(); } layer.close(index); } }); }, mouseenter: function () { var self = this; layer.tips('点击图片可删除', self, { tips: 1, time: 1000 }); } }, 'img'); //删除留言图片 $('#imgArea').on({ click: function () { var self = $(this); layer.open({ btn: ['确定', '取消'], title: false, area: ['395px', 'auto'], content: '<p class="del-confirm">确认删除这张图片?</p>', yes: function (index) { self.remove(); if ($('#imgArea').find('img').length === 0) { $('#imgArea').hide(); } layer.close(index); } }); }, mouseenter: function () { var self = this; layer.tips('点击图片可删除', self, { tips: 1, time: 1000 }); } }, 'img'); //提交申请售后或修改售后申请 $('#applyRefound').on('click', function () { var arr = [], img = '', reg = new RegExp(afterSale.domain), type = parseInt($(this).attr('data-type')); if (!parseInt($('#refoundReason').val())) { layer.msg('请选择退款原因'); return false; } //图片拼接 if ($('#imgList img').length) { $('#imgList img').each(function (i, d) { arr.push(d.src.replace(reg, '')); }); img = arr.join('|-|'); } if (type == 0) { //提交申请 submitModifyAfterSale('', 1, img); //提交售后申请 } else { //修改申请 submitModifyAfterSale($('#gname').attr('data-sno'), 1, img); } }); //修改退款申请跳转 $('#modAfterSale').on('click', function () { $(this).closest('.right-lose').hide(); $('#modifyApply').show(); //获取退款原因 refoundReason(1); }); //获取留言 if (afterSale.serviceStatus) { getLeaveWords(); } //获取留言 function getLeaveWords() { $.ajax({ url: '/buyer/order/getApplyRecordList', type: 'post', data: { sale_order_number: $('#gname').attr('data-sno') }, success: function (data) { console.log(data); var str = '', img = '', arr = [], photo = '', url = afterSale.domain, //reg = new RegExp(url); reg = /http/; if (data.errorCode === 0) { layer.msg('服务器异常,请稍后再试'); } if (data.errorCode === 1) { if (data.datastr.meta.code === 200) { for (var i = 0; i < data.datastr.body.length; i++) { img = ''; arr = data.datastr.body[i].imgs.split("|-|"); if (data.datastr.body[i].imgs) { for (var j = 0; j < arr.length; j++) { img += '<img src="' + url + arr[j] + '" width="120">'; } } else { img = ''; } if (reg.test(data.datastr.body[i].roleImg)) { photo = data.datastr.body[i].roleImg; } else { photo = url + data.datastr.body[i].roleImg; } str += '<div class="message"><img src="' + photo + '" width="55" height="55" class="user-photo"><div class="msg-txt"><p class="p1">' + data.datastr.body[i].roleName + '-' + data.datastr.body[i].roleType + '</p><p class="p2">' + data.datastr.body[i].content + '</p><div class="msg-img">' + img + '</div></div><span>' + formatTime(new Date(data.datastr.body[i].logTime * 1000)) + '</span></div>'; } $('#detail').html(str); } else { layer.msg(data.datastr.meta.msg); } } if (data.errorCode === 2) { location.href = '/buyer/login'; } } }); } //发表留言 $('#sendMsg').on('click', function () { $('#msgText,#upload').toggle(); }); //发表留言 $('#sendMsgBtn').on('click', function () { //获取已上传图片的路径 var img = $('#imgArea').find('img'), arr = [], url = afterSale.domain, reg = new RegExp(url); if (!$.trim($('#msgContent').val())) { layer.msg('留言内容不能为空'); return false; } img.each(function (i, d) { arr.push(d.src.replace(reg, '')); }); if (afterSale.serviceStatus) { applyAfterSaleMsg($('#gname').attr('data-sno'), arr, $('#msgContent'), $('#imgArea')); } else { applyAfterSaleMsg('', arr, $('#msgContent'), $('#imgArea')); } }); //发表留言(申请或修改) function applyAfterSaleMsg(sNo, imgArr, obj1, obj2) { $.ajax({ url: '/buyer/order/leaveWords', type: 'post', data: { sorder_no: sNo, //修改时,些参数必填 imgs: imgArr.join('|-|'), content: obj1.val() }, success: function (data) { if (data.errorCode === 0) { layer.msg('服务器异常,请稍后再试'); } if (data.errorCode === 1) { if (data.datastr.meta.code === 200) { obj1.val(''); obj2.html('').hide(); $('#sendMsg').click(); layer.msg('发表留言成功') getLeaveWords(); } else { layer.msg(data.datastr.meta.msg); } } if (data.errorCode === 2) { location.href = '/buyer/login'; } } }); } //取消退款申请 $('#cancelRefound,#revoke').on('click', function () { layer.open({ title: false, area: ['350px', '200px'], btn: ['确定', '取消'], content: '<p style="text-align: center;margin-top: 50px">确定要取消申请吗? </p>', yes: function () { $.ajax({ url: '/buyer/order/cancelApply', type: 'post', data: { sorder_no: $('#gname').attr('data-sno'), }, success: function (data) { if (data.errorCode === 0) { layer.msg('服务器异常,请稍后再试'); } if (data.errorCode === 1) { if (data.datastr.meta.code === 200) { layer.msg('已取消申请'); location.reload(); } else { layer.msg(data.datastr.meta.msg); } } if (data.errorCode === 2) { location.href = '/buyer/login'; } } }); } }); }); $('#modifyAfterSaleApply').on('click', function () { $('#refuse').hide(); $('#modify').show(); refoundReason(1); }); $('#submitApplyRefound').on('click', function () { var arr = [], img = '', reg = new RegExp(afterSale.domain); if (!parseInt($('#refoundReason').val())) { layer.msg('请选择退款原因'); return false; } //图片拼接 if ($('#imgList img').length) { $('#imgList img').each(function (i, d) { arr.push(d.src.replace(reg, '')); }); img = arr.join('|-|'); } submitModifyAfterSale($('#gname').attr('data-sno'), 1, img); }); })
Java
UTF-8
4,348
2.46875
2
[]
no_license
package com.igo.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import com.igo.dao.DogDAO; import com.igo.entity.Dogs; import com.igo.entity.Types; public class DogDAOImpl implements DogDAO { SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public List getAllTypes() { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Query query = session.createQuery("from Types"); return query.list(); } @Override public List getAllDog(int page) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Criteria c = null; List dogList = null; try { c = session.createCriteria(Dogs.class); c.setFirstResult(8 * (page - 1)); c.setMaxResults(8); dogList = c.list(); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return dogList; } @Override public Integer getCountOfAllDog() { // TODO Auto-generated method stub Integer count = null; try { Session session = sessionFactory.openSession(); Criteria c = session.createCriteria(Dogs.class); count = c.list().size(); } catch (Exception e) { e.printStackTrace(); } return count; } @Override public List getDogByCondition(Dogs condtion, int page) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Criteria c = session.createCriteria(Dogs.class); if (condtion != null) { if ((condtion.getName() != null) && (!condtion.getName().equals(""))) { c.add(Restrictions.like("name", condtion.getName(), MatchMode.ANYWHERE)); } if ((condtion.getTypes() != null) && (!condtion.getTypes().equals(""))) { c.add(Restrictions.like("types.tid", condtion.getTypes() .getTid())); } } c.setFirstResult(6 * (page - 1)); c.setMaxResults(6); return c.list(); } @Override public Integer getCountOfDog(Dogs condtion) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Criteria c = session.createCriteria(Dogs.class); if (condtion != null) { if ((condtion.getName() != null) && (!condtion.getName().equals(""))) { c.add(Restrictions.like("name", condtion.getName(), MatchMode.ANYWHERE)); } if ((condtion.getTypes() != null) && (!condtion.getTypes().equals(""))) { c.add(Restrictions.like("types.tid", condtion.getTypes() .getTid())); } } return c.list().size(); } @Override public void addDog(Dogs dog) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.save(dog); } @Override public void addTypes(Types types) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.save(types); } @Override public Types searchTypes(Types types) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); Criteria c = session.createCriteria(Types.class); Example example = Example.create(types); c.add(example); if (c.list().size() > 0) return (Types) c.list().get(0); else return null; } @Override public List searchDogsByUid(String name) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); String hql = "from Dogs d where d.owner = '" + name + "'"; Query query = session.createQuery(hql); return query.list(); } @Override public List searchAdoptByUid(int uid) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); String hql = "from Adopt a where a.users.uid = " + uid; Query query = session.createQuery(hql); return query.list(); } @Override public Dogs getDogs(int did) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); return (Dogs) session.get(Dogs.class, did); } @Override public void modify(Dogs dogs) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.update(dogs); } }
C++
UTF-8
324
2.890625
3
[]
no_license
#include <iostream> using namespace std; struct gagat { double x; double y; }; int main() { gagat A, B, C, D, O; cin >> A.x >> A.y; cin >> B.x >> B.y; cin >> C.x >> C.y; O.x = (A.x + C.x)/2; O.y = (A.y + C.y)/2; D.x = 2 * O.x - B.x; D.y = 2 * O.y - B.y; cout << D.x; cout << endl << D.y; system("Pause"); }
C#
UTF-8
621
3.09375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Thanos.Common { public static class Extensions { public static List<T> ReduceByHalf<T>(this List<T> input) { var output = new List<T>(input); int halfOfCount = output.Count() / 2; var random = new Random(); var shuffledList = output.OrderBy(i => random.Next()).ToList(); shuffledList.RemoveRange(0, halfOfCount); output = output.Where(x => shuffledList.Contains(x)).ToList(); return output; } } }
Python
UTF-8
5,666
2.671875
3
[]
no_license
from scrapy.spider import Spider from Bookies.items import EventItem2 from Bookies.loaders import EventLoader from scrapy.contrib.loader.processor import TakeFirst from scrapy import log from scrapy.http import Request import json take_first = TakeFirst() # # The data seems to come with the initial GET request, # but it is stored in the `lb_fb_cpn_init(...)` function # , which presumably creates some HTML from it. Thus we seem # to have two choices: 1) rip the JSON like data from between # the <script> tags of the initial GET, then parse them with some # python, or 2) use Selenium webdriver to get the js version of the # response (slow) # class PaddypowerSpider(Spider): name = "Paddypower" allowed_domains = ["paddypower.com"] start_urls = ['http://www.paddypower.com/football/football-matches'] # First get the league links def parse(self, response): # Get leagues from script (this saves all junk from quicknav) all_scripts = response.xpath('//script') wanted_script = take_first([script for script in all_scripts if 'fb_hp_other_nav_ls_init' in script.extract()]) jsonLeaguesData = json.loads(wanted_script.extract().splitlines()[6][:-1]) headers = {'Host': 'www.paddypower.com', 'Referer': 'http://www.paddypower.com/football/football-matches', } for league in jsonLeaguesData: if 'coupon_url' in league.keys(): # not an solely outright competition link = league['coupon_url'] yield Request(url=link, headers=headers, callback=self.pre_parseData) def pre_parseData(self, response): all_scripts = response.xpath('//script') wanted_script = take_first([script for script in all_scripts if 'lb_fb_cpn_init' in script.extract()]) jsonEventsData = json.loads(wanted_script.extract().splitlines()[14][:-1]) headers = {'Host': 'www.paddypower.com', 'Referer': response.url, } for event in jsonEventsData: moreLink = event['url'] yield Request(url=moreLink, headers=headers, callback=self.parseData) def parseData(self, response): log.msg('Going to parse data for URL: %s' % response.url, level=log.INFO) l = EventLoader(item=EventItem2(), response=response) l.add_value('sport', u'Football') l.add_value('bookie', self.name) dateTime = take_first(response.xpath('//div[@class="time"]/text()').extract()) l.add_value('dateTime', dateTime) eventName = take_first(response.xpath('//div[starts-with(@class, "super-nav-left")]/' 'ul/li[1]/a/span[1]/text()').extract()) if eventName: teams = eventName.lower().split(' v ') l.add_value('teams', teams) # Markets # Markets are duplicated allMktDicts = [] already_seen = set() # First get id and name then later get prices for this marketId mkts = response.xpath('//div[starts-with(@id, "contents_mkt_id")]') for mkt in mkts: marketId = take_first(mkt.xpath('@data-ev-mkt-id').extract()) if not marketId: continue if marketId in already_seen: continue else: already_seen.add(marketId) marketName = take_first(mkt.xpath('h3/a/span[@class="sub_market_name"]/text()').extract()) mDict = {'marketName': marketName, 'runners': []} # Now using marketId get prices (note sometimes the market is listed # several times (e.g. in top markets and win markets say) so we just # take the first in list. mktData = take_first(response.xpath('//div[starts-with(@class, "fb-market-content")]/' 'div[@class="fb-sub-content" and @data-ev-mkt-id="%s"]' % marketId)) runners = mktData.xpath('div[@class="fb-odds-group item"]/span[@class="odd"]/a') for runner in runners: runnerName = take_first(runner.xpath('span[@class="odds-label"]/text()').extract()) price = take_first(runner.xpath('span[@class="odds-value"]/text()').extract()) mDict['runners'].append({'runnerName': runnerName, 'price': price, }) allMktDicts.append(mDict) # Do some PP specific post processing and formating for mkt in allMktDicts: if 'Win-Draw-Win' in mkt['marketName'].strip(): mkt['marketName'] = 'Match Odds' for runner in mkt['runners']: if teams[0] in runner['runnerName'].lower(): runner['runnerName'] = 'HOME' elif teams[1] in runner['runnerName'].lower(): runner['runnerName'] = 'AWAY' elif 'Draw' in runner['runnerName']: runner['runnerName'] = 'DRAW' elif 'Correct Score' == mkt['marketName'].strip(): mkt['marketName'] = 'Correct Score' for runner in mkt['runners']: if teams[1] in runner['runnerName'].lower(): runner['reverse_tag'] = True else: runner['reverse_tag'] = False # Add markets l.add_value('markets', allMktDicts) # Load item return l.load_item()
Java
UTF-8
891
2.125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package es.cemi.appfinal.action; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import es.cemi.appfinal.util.Constants; /** * @author cyague */ public class Logout extends ActionSupport { public Logout() { } @Override public String execute() { removeUserData(); return SUCCESS; } /** * Elimina de sesión los datos del usuario logado. * */ private void removeUserData() { HttpSession session = ServletActionContext.getRequest().getSession(); Object userDataObj = session.getAttribute(Constants.USER_SESSION_PARAM); if (userDataObj != null) { session.removeAttribute(Constants.USER_SESSION_PARAM); } } /** * getter & setters<br> * ================ */ }
Java
UTF-8
3,895
2.078125
2
[ "MIT" ]
permissive
/** * The MIT License (MIT) * * Copyright (c) 2016 Caratacus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.baomidou.hibernateplus.entity; import java.util.Iterator; import java.util.Set; import org.hibernate.SessionFactory; import com.baomidou.hibernateplus.utils.CollectionUtils; import com.baomidou.hibernateplus.utils.StringUtils; /** * <p> * 简单的反射信息 * </p> * * @author Caratacus * @Date 2016-11-23 */ public class EntityInfo { /** * 表名称 */ private String tableName; /** * 表主键ID 属性名 */ private String keyProperty; /** * 表主键ID 字段名 */ private String keyColumn; /** * 实体字段 */ private Set<EntityFieldInfo> fieldInfos; /** * select */ private String select; /** * Master SessionFactory */ private SessionFactory master; public String getTableName() { return tableName; } /** * Slave SessionFactory */ private Set<SessionFactory> slaves; public void setTableName(String tableName) { this.tableName = tableName; } public String getKeyProperty() { return keyProperty; } public void setKeyProperty(String keyProperty) { this.keyProperty = keyProperty; } public String getKeyColumn() { return keyColumn; } public void setKeyColumn(String keyColumn) { this.keyColumn = keyColumn; } public Set<EntityFieldInfo> getFieldInfos() { return fieldInfos; } public void setFieldInfos(Set<EntityFieldInfo> fieldInfos) { this.fieldInfos = fieldInfos; } public String getSelect() { if (StringUtils.isBlank(select)) { StringBuilder selectBuild = new StringBuilder(); selectBuild.append(getKeyColumn()); selectBuild.append(" AS "); selectBuild.append(getKeyProperty()); selectBuild.append(","); Set<EntityFieldInfo> fieldInfos = getFieldInfos(); if (CollectionUtils.isNotEmpty(fieldInfos)) { Iterator<EntityFieldInfo> iterator = fieldInfos.iterator(); int _size = fieldInfos.size(); int i = 1; while (iterator.hasNext()) { EntityFieldInfo fieldInfo = iterator.next(); String column = fieldInfo.getColumn(); String property = fieldInfo.getProperty(); if (i == _size) { selectBuild.append(column); selectBuild.append(" AS "); selectBuild.append(property); } else { selectBuild.append(column); selectBuild.append(" AS "); selectBuild.append(property); selectBuild.append(","); } i++; } } setSelect(selectBuild.toString()); } return select; } public void setSelect(String select) { this.select = select; } public SessionFactory getMaster() { return master; } public void setMaster(SessionFactory master) { this.master = master; } public Set<SessionFactory> getSlaves() { return slaves; } public void setSlaves(Set<SessionFactory> slaves) { this.slaves = slaves; } }
C#
UTF-8
2,073
2.90625
3
[ "Apache-2.0" ]
permissive
using Knowledge.Prospector.Data.Entities; using Knowledge.Prospector.Data.Relationships; namespace Knowledge.Prospector.Data.Collections { /// <summary> /// Rules used by Entity Graph Builder. /// </summary> public static class EntityGraphBuilderRules { /// <summary> /// Add to IEntityGraph all instances of ITrueEntity from IEntityList. /// </summary> /// <param name="builder">IEntityGraph to with add entities.</param> /// <returns>New IEntityGraph.</returns> public static void UseEntitiesRule(IEntityGraphBuilder builder) { for (int i = 0; i < builder.Source.Count; i++) { if (builder.Source[i] is ITrueEntity) builder.Add(builder.Source[i] as ITrueEntity); } } /// <summary> /// Convert all IRelationshipEntity to corresponding IRelationship. /// </summary> /// <param name="builder"></param> /// <returns></returns> public static void UseConvertRelationshipEntityToRelationshipRule(IEntityGraphBuilder builder) { foreach (IEntityList<IEntity> sentence in builder.Source.Split(new IEntity[] { SeparatorEntity.Dot, SeparatorEntity.Comma })) { IEntity[] relationshipEntities = sentence.FindAllByType(typeof(RelationshipEntity)); if (relationshipEntities != null && relationshipEntities.Length == 1) { IEntity[] leftClassEntities = sentence.GetLeftPartFrom(relationshipEntities[0]).FindAllByType(typeof(IClassEntity)); IEntity[] rightClassEntities = sentence.GetRightPartFrom(relationshipEntities[0]).FindAllByType(typeof(IClassEntity)); if (leftClassEntities != null && leftClassEntities.Length == 1 && rightClassEntities != null && rightClassEntities.Length == 1) { //Add Relationship IRelationship relation = RelationshipAdapter.CreateRelationship(relationshipEntities[0] as RelationshipEntity); relation.Entities.Add(TrueEntity.ToTrueEntity(leftClassEntities[0])); relation.Entities.Add(TrueEntity.ToTrueEntity(rightClassEntities[0])); builder.Add(relation); } } } } } }
Go
UTF-8
2,155
2.71875
3
[]
no_license
package main import ( "fmt" "net/http" "github.com/gorilla/handlers" "log" "github.com/garyburd/redigo/redis" "os" "time" "os/signal" "syscall" "strings" ) var ( Pool *redis.Pool appSettings AppSettings ) func init() { // TODO: proper config file appSettings = AppSettings{ RedisHost: "[ec2-52-200-201-70.compute-1.amazonaws.com]:6379", RedisPassword: "a71f97758647d4aa5b093943db3b16c8656dfdb7ef1289fc5b7b37c1e2895e63", Env: "local", } redisHost := appSettings.RedisHost password := appSettings.RedisPassword Pool = newPool(redisHost, password) cleanupHook() fmt.Println("Connected to Redis") fmt.Println("Initialization Complete") } func main() { fmt.Println("Server Starting") r := MakeHttpHandler(Pool) // Cors Options headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Access-Control-Allow-Origin: *"}) originsOk := handlers.AllowedOrigins([]string{"*"}) methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"}) // Start HTTPS if strings.ToLower(appSettings.Env) == "prod"{ go func() { err_https := http.ListenAndServeTLS(":443", "fullchain.pem", "privkey.pem", handlers.CORS(originsOk, headersOk, methodsOk)(r)) if err_https != nil { log.Fatal("Web server (HTTPS): ", err_https) } }() } // Start HTTP err_http := http.ListenAndServe(":80", handlers.CORS(originsOk, headersOk, methodsOk)(r)) if err_http != nil { log.Fatal("Web server (HTTP): ", err_http) } } /** * Initialize a new Redis pool */ func newPool(server string, password string) *redis.Pool { return &redis.Pool{ MaxIdle: 3, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", server) if err != nil { return nil, err } _, err = c.Do("AUTH", password) if err != nil { return nil, err } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, } } func cleanupHook() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) signal.Notify(c, syscall.SIGTERM) signal.Notify(c, syscall.SIGKILL) go func() { <-c Pool.Close() os.Exit(0) }() }
PHP
UTF-8
2,185
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('form_validation'); $this->load->model('UtilityMethods'); $this->load->model('loginmodel'); } // Show login page public function index() { if(isset($this->session->userdata['logged_in']['user_id'])){ redirect(base_url('home')); } $this->load->view('login'); } // Check for user login process public function login_process() { $login_error_data = ''; if(isset($this->session->userdata['logged_in']['user_id'])){ redirect(base_url('home')); } else { $data = array( 'username' => $this->input->post('username'), 'password' => $this->input->post('password') ); $result = $this->loginmodel->userAuthentication($data); if ($result == TRUE) { $username = $this->input->post('username'); $password = $this->input->post('password'); $pswd = md5($password); $result = $this->loginmodel->read_user_information($username); $user_pswd = $this->UtilityMethods->getRealPassword($result[0]->user_password); if ($user_pswd == $pswd) { $session_data = array( 'user_id' => $result[0]->user_id, 'username' => $result[0]->user_username, 'caption_name' => $result[0]->user_name, ); // Add user data in session $this->session->set_userdata('logged_in', $session_data); $this->session->set_flashdata('login_success', 'Logged in Successfully..'); redirect(base_url('home')); }else{ $this->session->set_flashdata('login_error', 'Invalid Password...!'); redirect(base_url()); } } else { $this->session->set_flashdata('login_error', 'Invalid Username...!'); redirect(base_url()); } } } // Logout from admin page public function logout() { $sess_array = array( 'username' => '','caption_name' => '','user_id' => '' ); $this->session->sess_destroy(); $this->session->set_flashdata('login_error', 'Successfully Logged out..'); redirect(base_url()); } }
Python
UTF-8
613
4.15625
4
[]
no_license
# Author: Andrey Maiboroda # brealxbrealx@gmail.com # Homework15 # task2 #Write a decorator that takes a list of stop words and\ # replaces them with * inside the decorated function def stop_words(words: list): def check_func(func): def replace(name): x = func(name) for word in words: x = x.replace(word, '*') return x return replace return check_func @stop_words(['pepsi', 'BMW']) def create_slogan(name: str) -> str: return f"{name} drinks pepsi in his brand new BMW!" assert create_slogan("Steve") == "Steve drinks * in his brand new *!"
Java
UTF-8
1,478
2.125
2
[]
no_license
package org.hds.mapper; import org.apache.ibatis.jdbc.SQL; import org.hds.model.statistic; public class statisticSqlProvider { public String insertSelective(statistic record) { SQL sql = new SQL(); sql.INSERT_INTO("t_statistics"); if (record.getRecordingtime() != null) { sql.VALUES("RecordingTime", "#{recordingtime,jdbcType=VARCHAR}"); } if (record.getTotal() != null) { sql.VALUES("Total", "#{total,jdbcType=INTEGER}"); } if (record.getDtu() != null) { sql.VALUES("DTU", "#{dtu,jdbcType=INTEGER}"); } if (record.getLed() != null) { sql.VALUES("LED", "#{led,jdbcType=INTEGER}"); } if (record.getUpdated() != null) { sql.VALUES("Updated", "#{updated,jdbcType=INTEGER}"); } if (record.getWaiting() != null) { sql.VALUES("Waiting", "#{waiting,jdbcType=INTEGER}"); } if (record.getRenewable() != null) { sql.VALUES("Renewable", "#{renewable,jdbcType=INTEGER}"); } if (record.getProjectid() != null) { sql.VALUES("projectid", "#{projectid,jdbcType=VARCHAR}"); } if (record.getUpdateRate() != null) { sql.VALUES("UpdateRate", "#{UpdateRate,jdbcType=VARCHAR}"); } return sql.toString(); } }
Java
UTF-8
945
3.21875
3
[]
no_license
/** * https://leetcode.com/problems/super-ugly-number/description/ */ public class SuperUglyNumber { public int nthSuperUglyNumber(int n, int[] primes) { if (n < 1 || primes == null || primes.length == 0) { return -1; } int[] cursor = new int[primes.length]; int[] uglyNum = new int[n]; int uglyCnt = 0; uglyNum[uglyCnt++] = 1; while(uglyCnt < n) { int nextUrlyNum = -1; int indexOfPrimeToMove = -1; for (int i = 0; i < primes.length; i++) { if (nextUrlyNum > 0 && primes[i] >= nextUrlyNum) { break; } int tmp = primes[i] * uglyNum[cursor[i]]; if (nextUrlyNum < 0 || nextUrlyNum > tmp) { nextUrlyNum = tmp; indexOfPrimeToMove = i; } } if (nextUrlyNum > uglyNum[uglyCnt - 1]) { uglyNum[uglyCnt++] = nextUrlyNum; } cursor[indexOfPrimeToMove]++; } return uglyNum[n - 1]; } }
Python
UTF-8
3,469
2.984375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import asyncio from lighthouse import LighthouseV1, LighthouseV2 from bleak import discover, BleakClient from output import output class LighthouseLocator(): """Discover lighthouses in the local environment via Bluetooth. """ async def discover(self): """Discover all potential lighthouses in the local environment and check that we can control them. Returns: list: A collection of valid lighthouses. """ devices = await discover() potential_lighthouses = filter(None, map(self._create_lighthouse_from_device, devices)) lighthouses = [] for lighthouse in potential_lighthouses: if await self._is_device_lighthouse(lighthouse): lighthouses.append(lighthouse) return lighthouses def _create_lighthouse_from_device(self, device): """Create the appropriate Lighthouse object for a given BLEDevice Args: device (BLEDevice): A BLEDevice that may or may not be a lighthouse Returns: Union(LighthouseV1, LighthouseV2, None) """ if device.name.startswith(LighthouseV1.name_prefix): output.debug(device.address + ": potential 1.0 lighthouse '" + device.name +"'") output.debug(device.address + ": signal strength is " + str(device.rssi)) return LighthouseV1(device.address, device.name) elif device.name.startswith(LighthouseV2.name_prefix): output.debug(device.address + ": potential 2.0 lighthouse '" + device.name +"'") output.debug(device.address + ": signal strength is " + str(device.rssi)) return LighthouseV2(device.address, device.name) else: return None async def _is_device_lighthouse(self, lighthouse): """Determine if a device is a lighthouse we can communicate with. Args: lighthouse (Union[LighthouseV1, LighthouseV2]): An instance of LighthouseV1 or LighthouseV2 Returns: bool """ async with BleakClient(lighthouse.address) as client: try: services = await client.get_services() except Exception as e: output.exception(str(e)) return False for service in services: if self._service_has_lighthouse_characteristics(service, lighthouse): return True return False def _service_has_lighthouse_characteristics(self, service, lighthouse): """Determine if the passed service has the correct characteristics for power management. Args: service (BleakGATTServiceCollection): The GATT service collection from a potential lighthouse lighthouse (Union[LighthouseV1, LighthouseV2]): An instance of LighthouseV1 or LighthouseV2 Returns: bool """ if (service.uuid != lighthouse.service): return False output.debug(lighthouse.address + ": found service '" + service.uuid + "'") for characteristic in service.characteristics: if characteristic.uuid == lighthouse.characteristic: output.debug(lighthouse.address + ": found characteristic '" + characteristic.uuid + "'") output.debug(lighthouse.address + ": is a valid " + str(lighthouse.version) + ".0 lighthouse") return True return False
C++
WINDOWS-1252
844
2.8125
3
[]
no_license
#include<stdio.h> #include<string.h> int main(void) { //printf("how many times do ypu want to try") int n; int i=0; scanf("%d",&n); char str[100]="scu"; char str1[100]; scanf("%s",str1); int len; len = strlen(str1); if (n<10&&len<=100) { printf("YES"); while(i<n) { len = strlen(str1); if (len<=100) { if (len==3) { if (strcmp(str1,str)==0) { printf("YES"); } else { printf("NO"); } } if (len!=3) { int j,k; int a=0; for (a=0;a<len;a++) if (str1[a]=='S'&&str1[a+1]=='C'&&str1[a+2]=='U') break; for(j=a;str1[j-1]=='A';j--); for(k=a+3;str1[k]=='A';k++); {if(j==0&&k==i) printf("yes!\n"); else printf("no!\n");} } } i++;} }//if n<10 else { printf("NO"); } }
Java
UTF-8
996
2.453125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Modelo; /** * * @author Kami */ public class Parentesco_Patologia { private int id_parentesco_pat; private String descrip_parentesco; public Parentesco_Patologia() { } public Parentesco_Patologia(int id_parentesco_pat, String descrip_parentesco) { setId_parentesco_pat(id_parentesco_pat); setDescrip_parentesco(descrip_parentesco); } public int getId_parentesco_pat() { return id_parentesco_pat; } public void setId_parentesco_pat(int id_parentesco_pat) { this.id_parentesco_pat = id_parentesco_pat; } public String getDescrip_parentesco() { return descrip_parentesco; } public void setDescrip_parentesco(String descrip_parentesco) { this.descrip_parentesco = descrip_parentesco; } }
Markdown
UTF-8
1,214
2.6875
3
[ "MIT" ]
permissive
# texture.pixelHeight > --------------------- ------------------------------------------------------------------------------------------ > __Type__ [Number][api.type.Number] > __Object__ [TextureResourceCanvas][api.type.TextureResourceCanvas] > __Library__ [graphics.*][api.library.graphics] > __Revision__ [REVISION_LABEL](REVISION_URL) > __See also__ [TextureResource][api.type.TextureResource] > [TextureResourceCanvas][api.type.TextureResourceCanvas] > [texture.pixelWidth][api.type.TextureResourceCanvas.pixelWidth] > [texture.height][api.type.TextureResourceCanvas.height] > [display.setDefault()][api.library.display.setDefault] > --------------------- ------------------------------------------------------------------------------------------ ## Overview This read-only property indicates the vertical pixel dimensions of the texture that the canvas resource is rendered to. Creating textures with low `pixelWidth` and `pixelHeight` like `32` or `64` can create nice pixelated effects. To make pixel edges sharp, use <nobr>`display.setDefault( "magTextureFilter", "nearest" )`</nobr> before creating the texture.
C++
UTF-8
9,048
2.953125
3
[]
no_license
#define OLC_PGE_APPLICATION #include "olcPixelGameEngine.h" #include "olcPGEX_AdditionalColors.h" #include <iostream> #include <random> #include <string> #include <vector> class Gear { private: // Location of the gear int x; int y; bool bGrabbed; /* * Classification of the gear * * 1 - Wood Gear * 2 - Iron Gear * 3 - Diamond Gear */ int classification; public: Gear() { x = 1; y = 1; classification = 0; bGrabbed = false; } void setX(int newX) { x = newX; } void setY(int newY) { y = newY; } int getX() const { return x; } int getY() { return y; } void setClassification(int newClass) { classification = newClass; } int getClassification() { return classification; } void grab() { bGrabbed = true; } void drop() { bGrabbed = false; } bool IsGrabbed() { return bGrabbed; } }; class GameDemo : public olc::PixelGameEngine { public: GameDemo() { // Name your application sAppName = "Sort the Gears"; spawnTimer = 0; moveTimer = 1; score = 0; lives = 3; bGrabbed = false; } private: std::vector<Gear> gears; bool bGrabbed; int score; int lives; int spawnTimer; int moveTimer; olc::vi2d vGearSize = {16 , 16}; std::unique_ptr<olc::Sprite> sprTile; static int getGearSpawnPointX() { static std::random_device rd; static std::mt19937 eng(rd()); std::uniform_int_distribution<int> distr(1, 14); return distr(eng); } static int getGearClassification() { static std::random_device rd; static std::mt19937 eng(rd()); std::uniform_int_distribution<int> distr(1, 3); return distr(eng); } public: bool OnUserCreate() override { // Called once at the start, so create things here sprTile = std::make_unique<olc::Sprite>("gfx/Gears-x16.png"); gears = {}; return true; } bool OnUserUpdate(float fElapsedTime) override { // Game Over condition if(lives == 0) { std::ofstream scoreFile; scoreFile.open("highscore.txt"); scoreFile << std::to_string(score) + "\n"; scoreFile.close(); exit(score); } // Checks to make sure a gear is still being grabbed if(bGrabbed) { bool stillGrabbing = false; for (Gear& g : gears) { if(g.IsGrabbed()) { stillGrabbing = true; break; } } if(!stillGrabbing) { bGrabbed = false; } } // Gear moving logic spawnTimer++; moveTimer++; if(GetMouse(0).bHeld && !bGrabbed) { int x = GetMouseX() - 10; int y = GetMouseY() - 10; int converted_X = x / 16; int converted_Y = y / 16; for(Gear& g : gears) { if(converted_X == g.getX() && converted_Y == g.getY()) { bGrabbed = true; g.grab(); break; } } } if(GetMouse(0).bHeld && bGrabbed) { int x = GetMouseX() - 10; int converted_X = x / 16; for(Gear& g : gears) { if(g.IsGrabbed() && converted_X > 0 && converted_X < 15) { g.setX(converted_X); break; } } } if(GetMouse(0).bReleased && bGrabbed) { for(Gear& g : gears ) { if(g.IsGrabbed()) { g.drop(); bGrabbed = false; break; } } } // Spawning timer + mechanism if(spawnTimer == 1) { Gear newGear; newGear.setX(getGearSpawnPointX()); newGear.setClassification(getGearClassification()); gears.push_back(newGear); }else if(spawnTimer == (300 - score^3) + 5) { spawnTimer = 0; } //Movement timer if(moveTimer == 1) { for(int i = 0; i < gears.size(); i++) { Gear& g = gears[i]; int newY; switch(g.getClassification()) { case 1: newY = g.getY() + 1; break; case 2: newY = g.getY() + 2; break; case 3: newY = g.getY() + 3; break; } if (newY > 13) { int gX = g.getX(); // Wood Gear 1 - 5 if (gX == 1 || gX == 2 || gX == 3 || gX == 4 || gX == 5) { if (g.getClassification() == 1) { score++; }else{ lives--; } } // Iron Gear 6 - 10 if (gX == 6 || gX == 7 || gX == 8 || gX == 9 || gX == 10) { if (g.getClassification() == 2) { score += 2; }else{ lives--; } } // Diamond Gear 11 - 14 if (gX == 11 || gX == 12 || gX == 13 || gX == 14) { if (g.getClassification() == 3) { score += 3; }else{ lives--; } } gears.erase(gears.begin() + i); }else{ g.setY(newY); } } }else if(moveTimer == 100) { moveTimer = 0; } // Erase previous frame Clear(olc::DARK_BLUE); // Draw Boundary DrawLine(ScreenWidth() - 10, 10, ScreenWidth() - 10, ScreenHeight() - 10, olc::YELLOW); // Left DrawLine(10, 10, 10, ScreenHeight() - 10, olc::YELLOW); // Right DrawLine(10, ScreenHeight() - 10, ScreenWidth() - 10, ScreenHeight() - 10, olc::YELLOW); // Bottom DrawLine(10, 10, ScreenWidth() - 10, 10, olc::YELLOW); // Top // Draw score and lives remaining DrawString(1, 1, "Lives: " + std::to_string(lives)); std::string scoreString = std::to_string(score); int scoreLength = scoreString.length(); DrawString(ScreenWidth() - (scoreLength * 8) - 1, 1, scoreString); // Draw Gears SetPixelMode(olc::Pixel::MASK); // Don't draw pixels which have transparency for(Gear& g : gears) { switch(g.getClassification()) { case 1: DrawPartialSprite(olc::vi2d(g.getX(), g.getY()) * vGearSize, sprTile.get(), olc::vi2d(0, 0) * vGearSize, vGearSize); break; case 2: DrawPartialSprite(olc::vi2d(g.getX(), g.getY()) * vGearSize, sprTile.get(), olc::vi2d(1, 0) * vGearSize, vGearSize); break; case 3: DrawPartialSprite(olc::vi2d(g.getX(), g.getY()) * vGearSize, sprTile.get(), olc::vi2d(2, 0) * vGearSize, vGearSize); break; default: break; } } SetPixelMode(olc::Pixel::NORMAL); // Draw all pixels // Draw Gear Containers DrawRect(11, ScreenHeight() - 61, ((ScreenWidth() - 11) / 3) - 3, 50, olc::Colors::VERY_DARK_BROWN); FillRect(11, ScreenHeight() - 61, ((ScreenWidth() - 11) / 3) - 3, 50, olc::Colors::VERY_DARK_BROWN); DrawRect(((ScreenWidth() - 11) / 3) + 9, ScreenHeight() - 61, ((ScreenWidth() - 11) / 3) - 3, 50, olc::WHITE); FillRect(((ScreenWidth() - 11) / 3) + 9, ScreenHeight() - 61, ((ScreenWidth() - 11) / 3) - 3, 50, olc::WHITE); DrawRect((2 * ((ScreenWidth() - 11) / 3)) + 7, ScreenHeight() - 61, ((ScreenWidth() - 11) / 3) - 5, 50, olc::DARK_CYAN); FillRect((2 * ((ScreenWidth() - 11) / 3)) + 7, ScreenHeight() - 61, ((ScreenWidth() - 11) / 3) - 5, 50, olc::DARK_CYAN); return true; } }; int main() { GameDemo demo; if(demo.Construct(256, 240, 4, 4, false, true)) demo.Start(); return 0; }
Java
UTF-8
772
2.21875
2
[]
no_license
package com.rpckid.common; /**************************************************** * * @Description: 服务器-输出 * * @Author: DONGWENQI * @Date: Created in 9:03 AM 2018/11/22 * @Modified By: ****************************************************/ public class MessageOutput { //输出类型 private String type; //消息id private String id; //消息的json序列化字符串内容 private String payLoad; public MessageOutput(String type, String id, String payLoad) { this.type = type; this.id = id; this.payLoad = payLoad; } public String getType() { return type; } public String getId() { return id; } public String getPayLoad() { return payLoad; } }
Python
UTF-8
2,158
4.25
4
[]
no_license
# Design a function that returns # of elements in an array. this array is sorted # so high level algorithmic description # we will use the binary search to find the 1st index # use another binary search to find the 2nd index # if the first index <= 2nd index: this means that its valid # - case: first index = 2nd index: -> 1 element # - case first index < 2nd index: -> more than 1 element # will the data have any corrupted input i.e. None in between the array # … 90% of the time => NO (we addressed this part) ############################################################ # test cases # Empty: # [], _ -> 0 # out of bounds -> # left-hand-side [1,2,3,4,5], -1 -> 0 # right-hand-side [1,2,3,4,5], 1000 -> 0 # no elements existing -> # [1,2,3,4,6], 5 -> 0 # elements existing -> # single element: [1,2,3,4,5], 1 -> 1 # [1,2,3,4,5], 5 -> 1 # somewhere in between [1,2,3,4,5], 3 -> 1 # k elements-existing # [1,2,3,5,6,7,8], 4 -> 6 # implementation # for now lets assume that we have a binary search that exists # now lets implement binary search def lower_bound(array, lo, hi, target): while lo <= hi: mid = (lo + hi) // 2 if array[mid] >= target: hi = mid - 1 else: lo = mid + 1 return lo def num_elements(array, target): if not array: return 0 lo = lower_bound(array, 0, len(array) - 1, target) hi = lower_bound(array, lo, len(array) - 1, target + 1) - 1 return (hi - lo + 1) if lo <= hi else 0 # Empty Case: # f([], 8) -> 0 # f([], 0) -> 0 # Nothing found: # f([1,1,1,2,2,2,5], 8) -> 0 # Found: # f([1,1,1,1,1], 1) -> 5 # Out of bound: # f([1,2,3,4,5], 1000) -> 0 # f([1,2,3,4,5], -1) -> 0 # One element: # f([1], 1) -> 1 # f([1], 0) -> 0 def lower_bound(low, hi, prop): while low <= hi: mid = (low+hi)//2 if prop(mid): hi = mid-1 else: low = mid+1 return low def NumElement(arr, target): if not arr: return 0 lower = lower_bound(0, len(arr)-1, lambda x: arr[x] >= target) upper = lower_bound(0, len(arr)-1, lambda x: arr[x] > target)-1 if lower >= len(arr) or upper < 0: return 0 return upper-lower+1
Java
UTF-8
875
3.375
3
[]
no_license
package trees; public class PathSum3 { public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(-3); root.left.left = new TreeNode(3); root.left.right = new TreeNode(2); root.left.left = new TreeNode(3); root.left.right = new TreeNode(2); root.left.right.right = new TreeNode(1); root.right.right = new TreeNode(11); PathSum3 p = new PathSum3(); System.out.println(p.pathSum(root, 8)); } int count = 0; public int pathSum(TreeNode root, int sum) { if(root == null || sum == 0){ return 0; } if(sum > root.val ){ pathSum(root.left, sum-root.val); pathSum(root.right, sum-root.val); } else if(sum == root.val){ System.out.println("Root: "+root.val); count++; } else{ pathSum(root.left, sum); pathSum(root.right, sum); } return count; } }
TypeScript
UTF-8
125
2.921875
3
[]
no_license
/** * Interface representing heat map data point. */ export interface Point { x: number; y: number; value: number; }
C#
UTF-8
2,715
2.9375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Healthee.EFModels; using Healthee.DataModels; using Healthee.Logging; using System.Diagnostics; namespace Healthee.DataAbstraction { public class AppointmentDAL : AbstractDAL { /// <summary> /// Adds new appointment /// </summary> /// <returns></returns> public static int InsertAppointment(int doctorid, int patientid, int statusid, string date, string time, string notes) { try { HealtheeEntities db = new HealtheeEntities(); if (DEBUG) db.Database.Log = Console.WriteLine; Appointment a = new Appointment { DoctorID = doctorid, PatientID = patientid, StatusID = statusid, AppointmentDate = date, AppointmentTime= time, Notes = notes }; db.Appointments.Add(a); db.SaveChanges(); return a.AppointmentID; } catch (Exception e) { return 0; } } /// <summary> /// returns appointments for a doctor /// </summary> /// <param name="doctorid"></param> /// <returns></returns> public static List<Appointment> GetDoctorAppointments(int doctorid) { try { HealtheeEntities db = new HealtheeEntities(); //db.Database.Log = msg => Trace.WriteLine(msg); var query = from a in db.Appointments where a.DoctorID == doctorid select a; return query.ToList<Appointment>(); } catch (Exception e) { return null; } } /// <summary> /// returns appointments for patients /// </summary> /// <param name="patientid"></param> /// <returns></returns> public static List<Appointment> GetPatientAppointments(int patientid) { try { HealtheeEntities db = new HealtheeEntities(); if (DEBUG) db.Database.Log = Console.WriteLine; var query = from a in db.Appointments where a.PatientID == patientid select a; return query.ToList<Appointment>(); } catch (Exception e) { return null; } } } }
Java
UTF-8
602
2.515625
3
[]
no_license
package Managers; import Models.User; import ObjectFactory.UserFactory; import java.util.ArrayList; import java.util.List; public class UserManager extends Manager<User>{ protected UserFactory factory; protected List<User> collection; public UserManager(){ super(new ArrayList<User>(){ { add(new User("user 1", "")); add(new User("user 2", "")); add(new User("user 3", "")); add(new User("user 4", "")); add(new User("user 5", "")); } }, new UserFactory()); } }
Java
UTF-8
1,183
3.109375
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 hw11_recursivatorrejuego; /** * * @author FAMILIA TONATO */ public class HW11_RecursivaTorrejuego { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here HW11_RecursivaTorrejuego objHanoi = new HW11_RecursivaTorrejuego(); objHanoi.torresHanoi(4,1,2,3); System.out.println("Juego Completado"); } //Para soluccionar los tores de un juego // link de juego: http://www.uterra.com/juegos/torre_hanoi.php public void torresHanoi(int disco,int torre1,int torre2,int torre3){ // Caso Base if(disco == 1){ System.out.println("Mover Disco de Torre" + torre1 + " a Torre" + torre3); }else{ // Dominio torresHanoi(disco-1,torre1,torre3,torre2); System.out.println("Mover Disco de Torre" + torre1 + " a Torre" + torre3); torresHanoi(disco-1,torre2,torre1,torre3); } } }
Java
UTF-8
5,599
2.96875
3
[]
no_license
import java.util.*; import java.io.*; public class reduce { //static int total; static Pair[] x; static Pair[] y; static boolean[] chosen; static int ans = Integer.MAX_VALUE; static multiset<Integer> xvals = new multiset<>(); static multiset<Integer> yvals = new multiset<>(); public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new FileReader("reduce.in")); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("reduce.out"))); int n = Integer.parseInt(st.nextToken()); x = new Pair[n]; y = new Pair[n]; chosen = new boolean[12]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int x1 = Integer.parseInt(st.nextToken()); int y1 = Integer.parseInt(st.nextToken()); x[i] = new Pair(x1, y1); y[i] = new Pair(y1, x1); } Arrays.sort(x); Arrays.sort(y); for (Pair p : y) { int temp = p.b; p.b = p.a; p.a = temp; xvals.add(p.a); yvals.add(p.b); } //total = (y[n - 1].a - y[0].a) * (x[n - 1].a - x[0].a); ArrayList<Pair> vals = new ArrayList<>(); for (int i = 0; i < 3; i++) { vals.add(x[i]); vals.add(y[i]); vals.add(x[n - 1 - i]); vals.add(y[n - 1 - i]); } //search(new ArrayList<Pair>(), vals, 0); ArrayList<Pair> permutation = new ArrayList<Pair>(); for (int i = 0; i < 10; i++) { permutation.add(vals.get(i)); for (int j = i + 1; j < 11; j++) { permutation.add(vals.get(j)); for (int k = j + 1; k < 12; k++) { permutation.add(vals.get(k)); multiset<Integer> xvalstemp = (multiset<Integer>) xvals.clone(); multiset<Integer> yvalstemp = (multiset<Integer>) yvals.clone(); for (Pair p : permutation) { if (xvalstemp.containsKey(p.a)) xvalstemp.remove1(p.a); if (yvalstemp.containsKey(p.b)) yvalstemp.remove1(p.b); } ans = Math.min(ans, (xvalstemp.lastKey() - xvalstemp.firstKey()) * (yvalstemp.lastKey() - yvalstemp.firstKey())); permutation.remove(permutation.size() - 1); } permutation.remove(permutation.size() - 1); } permutation.remove(permutation.size() - 1); } //multiset<Integer> yval = new multiset<>(); // Current y values for range x // multiset<Integer> xval = new multiset<>(); // Current x values for range y //int start = 0; //int end = n - 4; /*do { // Find minimum for both x and y ans = Math.min(ans, (x[end].a - x[start].a) * (yval.lastKey() - yval.firstKey())); ans = Math.min(ans, (y[end].a - y[start].a) * (xval.lastKey() - xval.firstKey())); // Remove previous elements from multisets yval.remove1(x[start].b); xval.remove1(y[start].b); // Increment pointers start++; end++; // Add new element if (end < n) { yval.add(x[end].b); xval.add(y[end].b); } } while (end < n);*/ out.print(ans); out.close(); br.close(); } /*static void search(ArrayList<Pair> permutation, ArrayList<Pair> vals, int start) { if (permutation.size() == 3) { //int minx = Integer.MAX_VALUE; //int maxx = 0; //int miny = Integer.MAX_VALUE; //int maxy = 0; multiset<Integer> xvalstemp = xvals; multiset<Integer> yvalstemp = yvals; for (Pair p : permutation) { if (xvalstemp.containsKey(p.a)) xvalstemp.remove1(p.a); if (yvalstemp.containsKey(p.b)) yvalstemp.remove1(p.b); } ans = Math.min(ans, (xvalstemp.lastKey() - xvalstemp.firstKey()) * (yvalstemp.lastKey() - yvalstemp.firstKey())); //for (Pair p : permutation) { // xvals.add(p.a); // yvals.add(p.b); //} } else { for (int i = start; i < 12; i++) { permutation.add(vals.get(i)); search(permutation, vals, i); permutation.remove(permutation.size() - 1); } } }*/ static class Pair implements Comparable<Pair> { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } } public static class multiset<K> extends TreeMap<K,Integer>{ public void add(K x) { if (this.containsKey(x)) { this.put(x,this.get(x)+1); } else { this.put(x,1); } } public void remove1 (K x) { if (!this.containsKey(x)) return; this.put(x,this.get(x)-1); if (this.get(x) == 0) { this.remove(x); } } } }
Markdown
UTF-8
1,441
3.421875
3
[]
no_license
## Problem statement All of us receive a ton of messages and emails on a daily basis. Collectively, that is a lot of data which can provide useful insights about the messages that each of us gets. What if you could know whether a certain message has brought you good news or bad news before opening the actual message. In this challenge, we will use Machine Learning to achieve this. Given are 53 distinguishing factors that can help in understanding the polarity(Good or Bad) of a message, your objective as a data scientist is to build a Machine Learning model that can predict whether a text message has brought you good news or bad news. You are provided with the normalized frequencies of 50 words/emojis (Freq_Of_Word_1 to Freq_Of_Word_50) along with 3 engineered features listed below: TotalEmojiCharacters: Total number of individual emoji characters normalized. (eg. 🙂 ) LengthOFFirstParagraph: The total length of the first paragraph in words normalized StylizedLetters: Total number of letters or characters with a styling element normalized Target Variable: IsGoodNews ## Data Description The unzipped folder will have the following files. Train.csv – 947 observations. Test.csv – 527 observations. Sample Submission – Sample format for the submission. ## LeaderBoard: ### Public LB: 25 rank ### Private LB: 63 rank [https://www.machinehack.com/course/message-polarity-prediction-weekend-hackathon-3/leaderboard]
Java
UTF-8
1,106
3.359375
3
[]
no_license
package com.itheima.demo03.LambdaTest; import java.util.ArrayList; import java.util.Collections; /** * @author shkstart * @create 2019-11-07 14:59 */ public class Demo03ComparatorTest { public static void main(String[] args) { ArrayList<Person> list = new ArrayList<>(); list.add(new Person("a", 30)); list.add(new Person("b", 20)); // Collections.sort(list, new Comparator<Person>() { // @Override // public int compare(Person o1, Person o2) { // //return o1.getName().compareTo(o2.getName()); // return o1.getAge()-o2.getAge(); // } // }); // // System.out.println(list); // lambda方式: // Collections.sort(list, (Person o1, Person o2) -> { // return o1.getName().compareTo(o2.getName()); // //return o1.getAge()-o2.getAge(); // }); // // System.out.println(list); // lambda---简化方式: Collections.sort(list, (Person o1, Person o2) -> o1.getAge()-o2.getAge()); System.out.println(list); } }
Java
UTF-8
2,365
2.046875
2
[]
no_license
package com.atguigu.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.atguigu.dao.impl.dao; import com.atguigu.pojo.Province; import com.atguigu.service.UserService; import com.atguigu.service.impl.UserServiceImpl; import com.atguigu.util.Utils; import com.google.gson.Gson; public class UserServlet { private static final long serialVersionUID = 1L; private void world_dt(HttpServletRequest request, HttpServletResponse response)throws SQLException, ServletException, IOException { List<Province> list = dao.getWorldData_(); Gson gson = new Gson(); String json = gson.toJson(list); response.getWriter().write(json); } /** * @param request * @param response */ private void history(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException { List<Province> list = dao.getWorldData_H(); Gson gson = new Gson(); String json = gson.toJson(list); response.getWriter().write(json); } /** * @param request * @param response */ private void total(HttpServletRequest request, HttpServletResponse response)throws SQLException, ServletException, IOException { List<Province> list = dao.getWorldData_(); List<Province> list_1 = dao.getWorldData_1(); List<Province> list_2 = dao.getWorldData_2(); int allTotal = 0; int allDead = 0; int allHeal = 0; for (Province total : list) { allTotal += Integer.parseInt(total.getConfirm()); allDead += Integer.parseInt(total.getDead()); allHeal += Integer.parseInt(total.getHeal()); } request.setAttribute("list", list); request.setAttribute("list_1", list_1); request.setAttribute("list_2", list_2); request.setAttribute("allTotal", allTotal); request.setAttribute("allDead", allDead); request.setAttribute("allHeal", allHeal); request.getRequestDispatcher("worldyq.jsp").forward(request, response); } }
Python
UTF-8
160
3.25
3
[]
no_license
N = int(input()) d = [int(input()) for _ in range(N)] d.sort() print(sum(d)) if 1 < N and sum(d[:-1]) > d[-1]: print(0) else: print(d[-1] - sum(d[:-1]))
Python
UTF-8
840
2.9375
3
[]
no_license
from score_libraries import * def get_book_order(library_order, book_scores): book_order = {} scanned_books = set() for library in library_order: all_books = set(library.books) duplicated_books = all_books.intersection(scanned_books) books_to_scan = list(all_books.difference(duplicated_books)) sorted_book_order = sorted( books_to_scan, key=lambda book_id: book_scores[book_id], reverse=True) sorted_book_order.extend(list(duplicated_books)) scanned_books = scanned_books.union(set(sorted_book_order)) book_order[library.lib_id] = sorted_book_order return book_order if __name__ == "__main__": library_order, book_scores = get_library_order(sys.argv[1]) print(get_book_order(library_order, book_scores))
C#
UTF-8
3,003
2.828125
3
[]
no_license
using System; //TODO make antitheft work with my server //NOTE: App will check server to see if it should delete itself port 8555 //Server delete response: jazyisawesome //Server ok response: applepie //Make the jazy.ia record last successful time of change namespace Quick_Join_KCISCisco { public class KCISCiscoScript { public static void Main(string[] args) { KCISCiscoScript script = new KCISCiscoScript(); script.AntiTheft(); } public KCISCiscoScript() { /// Do some house work System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); string sciprtName = "Quick_Join_KCISCisco.Resources.hi.bat"; string scriptPath = @"C:\Windows\Temp\hi.bat"; /// Copy the script to its intended location using (System.IO.Stream scriptResource = assembly.GetManifestResourceStream(sciprtName)) using (System.IO.Stream outputDest = System.IO.File.Create(scriptPath)) { //Using ensures that the objects are disposed (As opposed to making a long try{}catch{}finally{} statement) byte[] buffer = new byte[2048]; int bytesread = 0; while ((bytesread = scriptResource.Read(buffer, 0, buffer.Length)) > 0) { //Write the script to its destination outputDest.Write(buffer, 0, bytesread); } } /// Run the script try { System.Diagnostics.Process.Start(scriptPath); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); } } public void AntiTheft() { ///Anti theft mechanism if (!System.IO.File.Exists("jazy.ia")) { //Uh oh Gotta delete this bad boy string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location; try { System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd", "/c \"timeout 1 & del /F /Q \"" + appPath + "\"\""); psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process.Start(psi); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); } } else { //Make sure it's hidden ;) try { System.IO.File.SetAttributes("jazy.ia", System.IO.FileAttributes.Hidden); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); } } } } }
Java
UTF-8
2,741
2.765625
3
[]
no_license
package fr.quintipio.gestionChargeMon.ihm.recettes; import java.awt.Color; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.EmptyBorder; import fr.quintipio.gestionChargeMon.entite.Recette; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; /** * Fenetre permettant d'afficher la description de la recette * * */ public class DescriptionRecetteFrame extends JFrame { private static final long serialVersionUID = -4850884407301395791L; private JPanel contentPane; private JLabel lblDescription; private JScrollPane scrollDescription; private JButton btnFermer; /** * Constructeur * @param frameParent : l'objet Component demandant d'afficher cette fenetre * @param selectedRecette : la recette selectionné é affiché */ public DescriptionRecetteFrame(JFrame frameParent,Recette selectedRecette) { //configuration de la fenetre setTitle("Description de "+selectedRecette.getNom()); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setResizable(false); setBounds(100, 100, 450, 300); setLocationRelativeTo(frameParent); setIconImage(Toolkit.getDefaultToolkit().getImage("ressources/logo.gif")); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setBackground(new Color(204,181,132)); setContentPane(contentPane); contentPane.setLayout(null); String description; if(selectedRecette.getDescription() == null) {description = "Aucune description";} else { description = "<html>"; description += selectedRecette.getDescription(); description += "</html>"; } description = description.replaceAll("(\r\n|\n)","<br/>"); lblDescription = new JLabel(description); lblDescription.setBackground(new Color(204,181,132)); lblDescription.setFont(new Font("Tahoma", Font.PLAIN, 11)); lblDescription.setVerticalAlignment(SwingConstants.TOP); scrollDescription = new JScrollPane(lblDescription); scrollDescription.setBackground(new Color(204,181,132)); scrollDescription.setBounds(10, 11, 424, 213); contentPane.add(scrollDescription); btnFermer = new JButton("Fermer"); btnFermer.setBounds(10, 237, 424, 23); btnFermer.addActionListener(new EvenementBouton()); contentPane.add(btnFermer); setVisible(true); } /** * Classe interne pour l'événement du bouton fermer * * */ class EvenementBouton implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == btnFermer) { dispose(); } } } }
C++
UTF-8
1,053
2.53125
3
[ "MIT" ]
permissive
#include "PCH.h" #include "ResourceDimension.h" using namespace std; using namespace SlimShader; string SlimShader::ToString(ResourceDimension value) { switch (value) { case ResourceDimension::Buffer : return "buffer"; case ResourceDimension::Texture1D : return "texture1d"; case ResourceDimension::Texture2D : return "texture2d"; case ResourceDimension::Texture2DMultiSampled : return "texture2dms"; case ResourceDimension::Texture3D : return "texture3d"; case ResourceDimension::TextureCube : return "texturecube"; case ResourceDimension::Texture1DArray : return "texture1darray"; case ResourceDimension::Texture2DArray : return "texture2darray"; case ResourceDimension::Texture2DMultiSampledArray : return "texture2dmsarray"; case ResourceDimension::TextureCubeArray : return "texturecubearray"; case ResourceDimension::RawBuffer : return "raw_buffer"; case ResourceDimension::StructuredBuffer : return "structured_buffer"; default : throw runtime_error("Unsupported value: " + to_string((int) value)); } }
Rust
UTF-8
630
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
//! Common Interrupt interface defintions shared between peipherals. /// A common interrupt number interface, which returns the associated interrupt /// of the peripheral. /// /// Used to unmask / enable the interrupt with [`cortex_m::peripheral::NVIC::unmask()`]. /// This is useful for all `cortex_m::peripheral::INTERRUPT` functions. pub trait InterruptNumber { /// The type used to represent the Interrupt Number. /// /// This type of interrupt should be compatible with [`cortex_m::peripheral::NVIC`]. type Interrupt; /// The assocaited constant of the interrupt const INTERRUPT: Self::Interrupt; }
TypeScript
UTF-8
590
2.578125
3
[]
no_license
import { IEntry } from "models/entry"; import { NavigateFn } from "@reach/router"; import { genUrl } from "./genUrl"; export const navigateToEntry = (navigate: NavigateFn, entry: IEntry) => { navigateToConceptAndLanguage(navigate, entry.concept, entry.language || ""); }; export const navigateToConceptAndLanguage = ( navigate: NavigateFn, concept: string, language: string ) => { navigate(genUrl(`entries/${concept}/${language || ""}`)); window.scrollTo(0, 0); }; export const navigateToRoot = (navigate: NavigateFn) => { navigate(genUrl("")); window.scrollTo(0, 0); };
Markdown
UTF-8
4,933
2.859375
3
[]
no_license
--- title: "PA1_template.Rmd" output: html_document: keep_md: true --- ## Reproducible Research Peer-graded Assignment Course Project 1 ## Project Introduction This assignment makes use of data from a personal activity monitoring device. This device collect data at 5 minute intervals throughout the day. The data consists of two months of data from an anonymous individual collected during the months of October and November, 2012 and include the number of steps taken in 5 minute intervals each day. ### Data The data for this assignment can be downloaded from the course website. Dataset: Activity monitoring data The variables included in this dataset are: step:Number of steps taking in a 5-minute interval date:The date on which the measurement was taken in YYYY-MM-DD format interval: Identifier for the 5-minute interval in which measurement was taken The dataset is stored in a comma-separated-value(CSV)file and there are a total of 17,568 observations in this dataset. ### 1.Read and Processing the data ```r activity<- read.csv("/Users/Nickychu/desktop/activity.csv", header=TRUE, sep=",") activity$date<-as.Date(activity$date, format="%Y-%m-%d") ``` ### 2.Plot the histogram of the total number of steps taken each day during the two months ```r library(dplyr) ``` ``` ## ## Attaching package: 'dplyr' ``` ``` ## The following objects are masked from 'package:stats': ## ## filter, lag ``` ``` ## The following objects are masked from 'package:base': ## ## intersect, setdiff, setequal, union ``` ```r steps_day<- tapply(activity$steps, activity$date, sum, na.rm=TRUE) steps_day<- data.frame(steps_day) hist(steps_day$steps_day, col = "lightblue", border = "pink", xlab="Sum of Steps per Day", main="Histogram of Steps per Day") ``` ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-2-1.png) ### 3.Mean and Median number of steps taken each day ```r library(dplyr) steps_day_mean<-mean(steps_day$steps_day) steps_day_median<-median(steps_day$steps_day) ``` The mean steps taken each day is 9354.2295082 ; The median steps taken each day is 10395. ### 4. Time series plot of the average number of steps taken ```r library(dplyr) steps_ave_by5min<-tapply(activity$steps, activity$interval, mean, na.rm=TRUE) plot(steps_ave_by5min ~ unique(activity$interval), type="l", col="blue", xlab="5-minute Interval", ylab="Average steps", main="Time Series Plot of Average Steps of 5-minute Interval") ``` ![plot of chunk unnamed-chunk-4](figure/unnamed-chunk-4-1.png) ### 5. The 5-minute Interval that, on average, contains teh maximum number of steps ```r steps_max<- round(steps_ave_by5min[which.max(steps_ave_by5min)]) print(steps_max) ``` ``` ## 835 ## 206 ``` ### 6. Code to describe and show a strategy for imputing missing data ```r table(is.na(activity$steps)==TRUE) ``` ``` ## ## FALSE TRUE ## 15264 2304 ``` ```r data_missing<-mean(is.na(activity$steps)) total_missing<-sum(is.na(activity$steps)) ``` The total numbers of missing data in this dataset is 2304, and the proportion of missing data is 0.1311475. ### Filling in the missing data with the mean of the steps of 5-minute intervals ```r activity1<- activity for(i in 1:nrow(activity)){ if(is.na(activity$steps[i])){ activity1$steps[i]<-steps_ave_by5min[[as.character(activity[i,"interval"])]] } } ``` ### 7.Histogram of the total number of steps taken each day after missing values are imputed ```r steps_td<-tapply(activity1$steps, activity1$date, sum) hist(steps_td, col="blue", xlab="Steps by day", main="Histogram of Steps by Day with Missing Data Being Filled") ``` ![plot of chunk unnamed-chunk-8](figure/unnamed-chunk-8-1.png) ### 8. Panel plot comparing the average number of steps per 5-minute interval across weekdays and weekends ```r activity1<-activity activity1$weekday<-weekdays(activity$date) activity1[which(activity1$weekday %in% c("Saturday","Sunday")),]$weekday<-"weekend" activity1[which(activity1$weekday %in% c("Monday","Tuesday","Wednesday","Thursday","Friday")),]$weekday<-"weekday" activity_weekend<- subset(activity1, activity1$weekday=="weekend") activity_weekday<- subset(activity1, activity1$weekday=="weekday") steps_5mins_weekend<- tapply(activity_weekend$steps, activity_weekend$interval, mean,na.rm=TRUE) steps_5mins_weekday<- tapply(activity_weekday$steps, activity_weekday$interval, mean,na.rm=TRUE) par(mfrow=c(2,1),mar=c(4,4,2,1)) plot(steps_5mins_weekday ~ unique(activity_weekday$interval), type="l", col="blue", xlab="5-minute Interval", ylab="Steps during Weekday", main="Time Series Plot of Average Steps of 5-minute Interval during Weekday") plot(steps_5mins_weekend ~ unique(activity_weekend$interval), type="l", col="green", xlab="5-minute Interval", ylab="Steps during Weekend", main="Time Series Plot of Average Steps of 5-minute Interval during Weekend") ``` ![plot of chunk unnamed-chunk-9](figure/unnamed-chunk-9-1.png)
C
UTF-8
1,567
3.0625
3
[]
no_license
// This file specifies the interface between the inter-processor communication // code (written by Kiran) and the control code (written by Kier). #ifndef __COMMS_INTERFACE_H #define __COMMS_INTERFACE_H // A structure to hold the setpoints (positions of the levers) sent from the // RC transmitter via the RC receiver and communications processor. // Definition of axes in the body coordinate system: // x axis: points directly between rotors A and B ("forwards") // y axis: points in the direction of thrust ("upwards") // z axis: points directly between rotors B and C ("to the right") typedef struct { // Velocity along the world frame Z axis. Positive indicates upwards (away // from the ground). Units are metres/second. float z_vel; // Roll angle (rotation about the body frame X axis). Positive indicates // rolling to the right (the right-hand side of the vehicle is lower than the // left-hand side). Units are radians. float roll; // Pitch angle (rotation about the body frame Y axis). Positive indicates // pitching downwards (the front of the vehicle is lower than the rear). Units // are radians. float pitch; // Yaw velocity (angular velocity about the body frame Z axis). Positive // indicates counterclockwise rotation when the vehicle is viewed from above. // Units are radians/second. float yaw_vel; } desired_state_t; // Communicate with the communications processor, filling the 'desired_state' // structure with the received setpoint information. void communicate(desired_state_t *desired_state); #endif
Java
UTF-8
283
2.6875
3
[ "Apache-2.0" ]
permissive
package com.syberos.learnjava.abstract_factory_pattern; /** * Created by toby on 18-3-20. */ // 具体产品类 B2 public class ConcreteProductB2 extends AbstractProductB { @Override public void method() { System.out.println("具体产品 B2 的方法"); } }
Python
UTF-8
2,932
3.171875
3
[]
no_license
import numpy import matplotlib.pyplot as plt import pandas as pd import math from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from sklearn.metrics import mean_squared_error # convert an array of values into a dataset matrix def create_data(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset)-look_back): a = dataset[i:(i+look_back), 0] dataX.append(a) dataY.append(dataset[i + look_back, 0]) return numpy.array(dataX), numpy.array(dataY) # fix random seed for reproducibility numpy.random.seed(7) # load the dataset dataframe = pd.read_excel('us_gdp.xlsx', index_col=0) plt.figure() plt.plot(dataframe) dataset = dataframe.values look_back = 5 X, Y = create_data(dataset, look_back) lasta = dataset[len(dataset)-look_back:len(dataset), 0] X = numpy.vstack([X, numpy.reshape(lasta, (1, lasta.shape[0]))]) # split into train and test sets train_size = int(len(Y) * 0.67) test_size = len(Y) - train_size trainX, testX, testX1 = X[:train_size, :], X[train_size:len(Y), :], X[train_size:(len(Y)+1), :] trainY, testY = Y[:train_size], Y[train_size:len(Y)] # create and fit the LSTM network model = Sequential() #model.add(Dense(2, input_dim=look_back)) trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1])) testX1 = numpy.reshape(testX1, (testX1.shape[0], 1, testX1.shape[1])) model.add(LSTM(2, input_dim=look_back)) model.add(Dense(1)) model.compile(loss='mse', optimizer='adam') print(model.summary()) res = model.fit(trainX, trainY, nb_epoch=100, batch_size=10) plt.figure() plt.plot(res.epoch, res.history['loss']) plt.show() # make predictions trainPredict = model.predict(trainX) testPredict = model.predict(testX) testPredict1 = model.predict(testX1) # calculate root mean squared error trainScore = math.sqrt(mean_squared_error(trainY, trainPredict[:, 0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY, testPredict[:, 0])) print('Test Score: %.2f RMSE' % (testScore)) # shift train predictions for plotting trainPredictPlot = numpy.empty_like(dataset) trainPredictPlot[:, :] = numpy.nan trainPredictPlot[(look_back-1):len(trainPredict)+(look_back-1), :] = trainPredict # shift test predictions for plotting testPredictPlot = numpy.empty_like(dataset) testPredictPlot[:, :] = numpy.nan testPredictPlot[(len(trainPredict)+(look_back-1)):, :] = testPredict1 # plot baseline and predictions dataframe['train'] = pd.DataFrame(trainPredictPlot, index=dataframe.index)[0] dataframe['test'] = pd.DataFrame(testPredictPlot, index=dataframe.index)[0] dataframe.plot() plt.show() plt.figure() plt.plot(dataframe['train'] - dataframe['US GDP YoY']) plt.plot(dataframe['test'] - dataframe['US GDP YoY'])
C++
UTF-8
524
2.703125
3
[]
no_license
class Solution { public: vector<int> singleNumber(vector<int>& nums) { int x=0,a=0; vector<int> res; for(auto i:nums) x^=i; int bitmask=0x00000001; for(int i=0;i<31;++i) { if((x&bitmask)>>i) break; else bitmask=bitmask<<1; } for(auto i:nums) if((i&bitmask)==bitmask) a^=i; res.push_back(a^x); res.push_back(a); return res; } };
Java
UTF-8
1,180
2.3125
2
[]
no_license
package com.jjc.ssoClient.common.bean; /* * $Id: Page.java,v 1.1 2012/05/04 00:22:32 hugq Exp $ * Copyright(c) 2000-2007 HC360.COM, All Rights Reserved. */ import java.util.List; /** * 分页查询结果Bean * @author hugq * */ public class Page { /** 查询结果 */ private List<?> lstResult; /** 分页信息Bean */ private PageBean pageBean; /** * (空) */ public Page() {} /** * 根据查询结果、分页信息构造 * @param lstResult 查询结果 * @param pageBean 分页信息Bean */ public Page(List<?> lstResult, PageBean pageBean) { this.lstResult = lstResult; this.pageBean = pageBean; } /** * 取得查询结果 * @return 查询结果 */ public List<?> getLstResult() { return lstResult; } /** * 设置查询结果 * @param lstResult 查询结果 */ public void setLstResult(List<?> lstResult) { this.lstResult = lstResult; } /** * 取得分页信息Bean * @return 分页信息Bean */ public PageBean getPageBean() { return pageBean; } /** * 设置分页信息Bean * @param pageBean 分页信息Bean */ public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } }
Java
UTF-8
2,495
4
4
[]
no_license
package main.java.ladders.BinaryTree; /** * 453. Flatten Binary Tree to Linked List Flatten a binary tree to a fake "linked list" in pre-order traversal. Here we use the right pointer in TreeNode as the next pointer in ListNode. Notice Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded. Have you met this question in a real interview? Example 1 \ 1 2 / \ \ 2 5 => 3 / \ \ \ 3 4 6 4 \ 5 \ 6 Challenge Do it in-place without any extra memory. Tags Binary Tree Depth First Search Related Problems Medium Flatten 2D Vector 45 % Medium Flatten Nested List Iterator 28 % Easy Convert Binary Tree to Linked Lists by Depth 40 % Medium Convert Binary Search Tree to Doubly Linked List 30 % Medium Convert Sorted List to Balanced BST 30 % * */ /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class FlasttenBinaryTreeToLinkedList { /** * @param root: a TreeNode, the root of the binary tree * @return: nothing */ // public TreeNode parentNode = null; //Total Runtime: 3441 ms public void flatten(TreeNode root) { dfs(root); /*if(root == null){ return; } if(parentNode != null){ parentNode.left = null; parentNode.right = root; } parentNode = root; TreeNode right = root.right; flatten(root.left); flatten(right);*/ } private TreeNode dfs(TreeNode root) { //Total Runtime: 2776 ms if(root==null){ return null; } if(root.left==null&&root.right==null){ return root; } if(root.left ==null){ return dfs( root.right); } if(root.right ==null){ root.right=root.left; root.left=null; return dfs( root.right); } TreeNode l = dfs( root.left); TreeNode r = dfs( root.right); l.right=root.right; root.right=root.left; root.left=null; return r; } }
C#
UTF-8
1,336
2.953125
3
[]
no_license
using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using System.Linq; using System.IO; using System; public class OfflineCityBikeDataFetcher : ICityBikeDataFetcher { int bikesAvailable; bool knownName; string[] stationList1; public async Task<int> GetBikeCountInStation(string stationName) { if (stationName.Any(char.IsDigit)) { throw new System.ArgumentException(); } //BikeRentalStationList stationList; //string url = "http://api.digitransit.fi/routing/v1/routers/hsl/bike_rental"; //HttpClient Client = new HttpClient(); //stationList = JsonConvert.DeserializeObject<BikeRentalStationList>(await Client.GetStringAsync(url)); knownName = false; string[] stationList = File.ReadAllLines(@"bikedata.txt"); for(int i = 0; i < stationList.Length; i++) { stationList1 = stationList[i].Split(":"); if(stationList1[0].Trim() == stationName) { bikesAvailable = Int32.Parse(stationList1[1].Trim()); knownName = true; } } if(!knownName) { throw new NotFoundException(); } return bikesAvailable; } }
C++
UTF-8
3,142
2.859375
3
[ "Unlicense" ]
permissive
#ifndef KEYBOARDCONTROLSYSTEM_H #define KEYBOARDCONTROLSYSTEM_H #include "../ECS/ECS.h" #include "../EventBus/EventBus.h" #include "../Events/KeyPressedEvent.h" #include "../Events/KeyReleasedEvent.h" #include "../Components/KeyboardControlledComponent.h" #include "../Components/RigidBodyComponent.h" #include "../Components/SpriteComponent.h" class KeyboardControlSystem: public System { public: KeyboardControlSystem() { RequireComponent<KeyboardControlledComponent>(); RequireComponent<SpriteComponent>(); RequireComponent<RigidBodyComponent>(); } void SubscribeToEvents(std::unique_ptr<EventBus>& eventBus) { eventBus->ListenToEvent<KeyPressedEvent>(this, &KeyboardControlSystem::OnKeyPressed); eventBus->ListenToEvent<KeyReleasedEvent>(this, &KeyboardControlSystem::OnKeyReleased); } void OnKeyPressed(KeyPressedEvent& event) { for (auto entity: GetSystemEntities()) { const KeyboardControlledComponent keyboardcontrol = entity.GetComponent<KeyboardControlledComponent>(); SpriteComponent& sprite = entity.GetComponent<SpriteComponent>(); RigidBodyComponent& rigidbody = entity.GetComponent<RigidBodyComponent>(); switch (event.symbol) { case SDLK_UP: rigidbody.velocity = keyboardcontrol.upVelocity; sprite.srcRect.y = sprite.height * 0; break; case SDLK_RIGHT: rigidbody.velocity = keyboardcontrol.rightVelocity; sprite.srcRect.y = sprite.height * 1; break; case SDLK_DOWN: rigidbody.velocity = keyboardcontrol.downVelocity; sprite.srcRect.y = sprite.height * 2; break; case SDLK_LEFT: rigidbody.velocity = keyboardcontrol.leftVelocity; sprite.srcRect.y = sprite.height * 3; break; } } } void OnKeyReleased(KeyReleasedEvent& event) { // for (auto entity: GetSystemEntities()) { // RigidBodyComponent& rigidbody = entity.GetComponent<RigidBodyComponent>(); // switch (event.symbol) { // case SDLK_UP: // rigidbody.velocity = glm::vec2(0, 0); // break; // case SDLK_RIGHT: // rigidbody.velocity = glm::vec2(0, 0); // break; // case SDLK_DOWN: // rigidbody.velocity = glm::vec2(0, 0); // break; // case SDLK_LEFT: // rigidbody.velocity = glm::vec2(0, 0); // break; // } // } } void Update(std::unique_ptr<Registry>& registry) { } }; #endif
C++
UHC
978
3.359375
3
[]
no_license
#include <stdlib.h> #include <iostream> #include "mystack.h" using namespace std; #define MAXSIZE 10 template<class T> stack<T>::stack() { size = MAXSIZE; this->buf = new T[size]; } template<class T> stack<T>::stack(int size) { this->size = size; this->buf = new T[this->size]; top = -1; } template<class T> void stack<T>::push(T x) { this->top = this->top + 1; this->buf[top] = x; } template<class T> T stack<T>::pop() { if (Empty() == true) { cout << " "; return -1; } else { this->top = this->top - 1; return this->buf[this->top + 1]; } } template<class T> bool stack<T>::Empty() { if (this->top == -1) return true; else return false; } template<class T> T stack<T>::Top() { return this->buf[this->top]; } template<class T> stack<T>::~stack() { delete[] this->buf; } //int main() { // stack<int> a(5); // for (int i = 1; i < 6; i++) { // a.push(i); // } // for (int i = 0; i < 5; i++) { // cout << a.pop(); // } //}
TypeScript
UTF-8
11,685
3.28125
3
[]
no_license
import os = require('os'); import fs = require('fs'); import path = require('path'); import http = require('http'); import async = require('async'); import log = require('./log'); var pidFile; export function isInteger(n:number) { return Number(n) === n && n % 1 === 0; } export function isFloat(n:number) { return n === Number(n) && n % 1 !== 0 } export function createArray(size:number, initValue:any):any[] { var ret = []; for (var i = 0; i < size; i++) { ret.push(initValue); } return ret; } export function isObject(arg) { return typeof arg === 'object' && arg !== null; } export function extend(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; } export function copyObject(obj:any):any { if (typeof obj !== 'object' || obj === null) { return obj; } var result = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { result[key] = copyObject(obj[key]); } } return result; } export function addObject(left:any, right:any):void { for (var key in right) { if (right.hasOwnProperty(key)) { if (isNaN(parseInt(right[key]))) { continue; } if (!left[key]) { left[key] = right[key]; } else { left[key] += right[key]; } } } } export function copyArray(array:Object[]):any[] { var tempArray:any[] = []; array.forEach((item)=> { var temp = copyObject(item); tempArray.push(temp); }); return tempArray; } export function pushArrayInMap(obj:any, key:any, value:any) { if (!obj[key]) obj[key] = Array.isArray(value) ? value : [value]; else if (Array.isArray(value)) value.forEach((val) => {obj[key].push(val);}); else obj[key].push(value); } export function plusValueInMap(obj:any, key:any, value:number|string) { if (!obj[key]) obj[key] = value; else obj[key] += value; } /** * 在预排序数组二分查找search的下界位置 * 说明:查找第一个**大于等于**search的下标 * @param search 查找内容 * @param length 数组长度 * @param getValue 获取比较值方法 * @returns {number} 下界的下标 */ export function lowerBound(search:number, length:number, getValue:(index:number)=>number):number { var left = 0, mid = 0, right = length, value; while (left < right) { mid = Math.floor((left + right) / 2); value = getValue(mid); if (value >= search) { right = mid; } else if (value < search) { left = mid + 1; } } return left; } /** * 在预排序数组二分查找search的上界位置 * 说明: 查找第一个**大于**search的下标 * @param search 查找内容 * @param length 数组长度 * @param getValue 获取比较值方法 * @returns {number} 上界的下标 */ export function upperBound(length:number, search:number, getValue:(index:number)=>number):number { var left = 0, mid = 0, right = length, value; while (left < right) { mid = Math.floor((left + right) / 2); value = getValue(mid); if (value > search) { right = mid; } else if (value <= search) { left = mid + 1; } } return left; } /** * * @param obj * @return {boolean} */ export function isEmpty(obj:any):boolean { // null and undefined are "empty" if (obj === null) { return true; } // Assume if it has a length property with a non-zero value // that that property is correct. if (obj.length > 0) { return false; } if (obj.length === 0) { return true; } // Otherwise, does it have any properties of its own? // Note that this doesn't handle // toString and valueOf enumeration bugs in IE < 9 for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { return false; } } return true; } /** * get random [0, 100] * @return {number} */ export function randChance():number { return Math.floor(Math.random() * 101); } /** * get random float number (high <= low also ok) * Math.random return number [0.0, 1.0) * @param low * @param high * @return {number} */ export function randFloat(low:number, high:number):number { return Math.random() * Math.abs(high - low) + Math.min(low, high); } /** * get random array sequence * @param low * @param high * @return {number} */ export function randInt(low:number, high:number):number { return Math.floor(Math.random() * Math.abs(high - low) + Math.min(low, high)); } /** * get random array sequence * @param array * @param count - if not given, will rand 1 * @return {number[]} */ export function randArray(array:number[], count?:number):number[] { var i, cnt = Math.min(array.length, count || 1), pos = 0, tmp; for (i = 0; i < cnt - 1; i += 1) { pos = randInt(i + 1, array.length); tmp = array[i]; // see more about the performance of swap two values in http://jsperf.com/swap-two-numbers-without-tmp-var/9 array[i] = array[pos]; // use [with a tmp var] for it support not only number value arrays array[pos] = tmp; } return array.slice(0, count); } /** * TODO * @param array * @param count * @param bRepeat ? 暂时没用 * @return {Array} */ export function randByWeight(array:number[], count:number, bRepeat?:boolean):number[] { var i, sum:number = 0, result:number[] = [], repeat:boolean = bRepeat || false, cnt:number = Math.min(array.length, count || array.length), value:number = 0; if (cnt === 0) { return []; } for (i = 0; i < array.length; i += 1) { sum += array[i]; } if (isNaN(sum)) { return []; } var j = 0, used = {}; for (i = 0; i < cnt; i += 1) { value = randInt(0, sum); for (j = 0; j < array.length - i; j += 1) { if (!repeat && used[j]) { continue; } if (array[j] > value) { break; } value -= array[j]; } result.push(j); if (!repeat) { used[j] = true; } } return result; } export function randOneByWeight(array:number[]):number { return array.length === 0 ? null : randByWeight(array, 1, false)[0]; } export function randObjectByWeight(obj:{[key:number]:number}, count:number, bRepeat?:boolean):number[] { var keys = Object.keys(obj), values = []; keys.forEach((key) => { values.push(obj[key]); }); var rand = randByWeight(values, count, bRepeat); var result:number[] = []; rand.forEach((pos) => { result.push(parseInt(keys[pos])); }); return result; } export function randOneObjectByWeight(obj:{[key:number]:number}):number { var result = randObjectByWeight(obj, 1, false); return result.length === 0 ? null : result[0]; } /** * TODO * @param rate * @return boolean */ export function selectByPercent(rate:number):boolean { return rate >= randChance(); } /** * TODO * @param rate * @return boolean */ export function selectByTenThousand(rate:number):boolean { return rate >= randChance(); } /** * @param obj * @return {Array} */ export function objectToArray(obj:any):any[] { var arr = []; for (var key in obj) { arr.push(obj[key]); } return arr; } /** * 注册应用关闭事件 * @param callback */ export function registerProcessEnd(callback:()=>void):void { process.on('cleanup', () => { callback(); }); process.on('beforeExit', () => { console.log('beforeExit'); }); process.on('exit', () => { console.log('exit'); }); process.on('SIGINT', () => { process.emit('cleanup'); log.sInfo('system', 'event signal sigint'); //process.exit(0); }); process.on('uncaughtException', (e:Error) => { log.sFatal('uncaughtException', e.message + ', ' + e['stack']); process.exit(9); }); } export function createPidFile(filename):void { fs.writeFileSync(filename, process.pid); process.on('cleanup', () => { if (fs.existsSync(filename)) { fs.unlink(filename); } }); } export function stringInsert(idx:number, str:string, strAppend:string):string { if(idx > str.length) { log.sError('Util', 'string Append error, idx=%d, str=%s, strAppend=%s', idx, str, strAppend); } else if(idx === str.length) { return (str + strAppend); } else if(idx === 0) { return (strAppend + str); } else { var start = str.substring(0, idx), mid = strAppend, end = str.substring(idx); return (start + mid + end); } } export function stringReverse(str:string):string { return str.split('').reverse().join(''); } export function fetchFileList(path:string, reg?:RegExp):string[] { if (path[path.length - 1] !== '/') { path = path + '/'; } var fileList:string[] = []; var fileNames = fs.readdirSync(path); fileNames.forEach((fileName) => { var fullPath = path + fileName; var stat = fs.statSync(fullPath); if (!stat.isDirectory()) { if (reg) { if (reg.test(fileName)) { fileList.push(fileName); } } else { fileList.push(fileName); } } }); return fileList; } export function httpDownload(url, dest, callback) { var file:fs.WriteStream = fs.createWriteStream(dest); http.get(url, (response) => { if (response.statusCode !== 200) { callback(new Error('http response status code Error: ' + 'code=' + response.statusCode + ', message=' + response.statusMessage)); return ; } response.pipe(file); file.on('finish', () => { //file.closeS(); // close() is async, call cb after close completes. file.end(); callback(null); }); }).on('error', (err) => { // Handle errors fs.unlink(dest); // Delete the file async. (But we don't check the result) if (callback) callback(err.message); }); } export function deleteFileInDir(dir:string, reg:RegExp, callback:(err)=>void):void { if (dir[dir.length - 1] !== '/') { dir = dir + '/'; } fs.readdir(dir, (err, fileNames) => { async.eachSeries(fileNames, (fileName, next) => { var fullPath = dir + fileName; var stat = fs.statSync(fullPath); if (stat.isFile()) { if (reg) { if (reg.test(fileName)) { fs.unlink(fullPath, next); } else { next(null); } } else { fs.unlink(fullPath, next); } } else { next(null); } }, (err) => { callback(err); }); }); } export function parseJSONFile(file:string):any { return JSON.parse(fs.readFileSync(file).toString()); } export function getResponseName(requestName:string):string { if (/\.Request$/.test(requestName)) return requestName.replace(/\.Request$/, '.Response'); return null; }
Java
UTF-8
1,123
2.46875
2
[]
no_license
package com.trongdv.enterpise.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.io.Serializable; import java.time.Instant; @Getter @Setter @NoArgsConstructor public class EmployeeDTO implements Serializable { private long id; private String rollNumber; private String fullName; private String year; private String address; private String email; private String phone; private String identityCard; private Instant createdAt; private Instant updatedAt; private int status; public EmployeeDTO(Employee employee) { this.id = employee.getId(); this.rollNumber = employee.getRollNumber(); this.fullName = employee.getFullName(); this.year = employee.getYear(); this.address = employee.getAddress(); this.email = employee.getEmail(); this.phone = employee.getPhone(); this.identityCard = employee.getIdentityCard(); this.createdAt = employee.getCreatedAt(); this.updatedAt = employee.getUpdatedAt(); this.status = employee.getStatus(); } }
Python
UTF-8
2,422
2.53125
3
[ "MIT" ]
permissive
# An adaptor to create and update state_collections based on delimited files import funtool.adaptor import funtool.group import funtool.state_collection import funtool_common_processes.adaptors.tabular import csv import os # Creates new states from each row in the delimited file. Can create duplicates. def extend_from_delimited_table(adaptor,state_collection, overriding_parameters=None,loggers=None): new_state_collection= create_from_delimited_table(adaptor,state_collection, overriding_parameters,loggers) return funtool.state_collection.join_state_collections(state_collection, new_state_collection ) def create_from_delimited_table(adaptor,state_collection, overriding_parameters=None,loggers=None): adaptor_parameters= funtool.adaptor.get_adaptor_parameters(adaptor, overriding_parameters) if os.path.isfile(adaptor_parameters['file_location']): with open(adaptor_parameters['file_location']) as f: reader = csv.reader(f, **(_delimiter_parameters(adaptor_parameters, f))) state_collection= funtool_common_processes.adaptors.tabular.create_from_config(reader, adaptor_parameters.get('tabular_parameters',{})) group= funtool.group.create_group( 'file', state_collection.states, {}, {'file':adaptor_parameters['file_location']}, {}) state_collection= funtool.state_collection.add_group_to_grouping(state_collection,'file',group, str(adaptor_parameters['file_location'])) return state_collection def _delimiter_parameters( adaptor_parameters, file_handler): params= {} if not (adaptor_parameters.get('newline') is None): params['newline']= adaptor_parameters['newline'] if not (adaptor_parameters.get('decoding') is None): params['decoding']= adaptor_parameters['decoding'] if not (adaptor_parameters.get('delimiter') is None): params['delimiter']= adaptor_parameters['delimiter'] if not (adaptor_parameters.get('quoting') is None): params['quoting']= adaptor_parameters['quoting'] if not (adaptor_parameters.get('dialect') is None): params['dialect']= adaptor_parameters['dialect'] else: sample_text = ''.join(file_handler.readline() for x in range(3)) params['dialect'] = csv.Sniffer().sniff(sample_text) file_handler.seek(0) return params
SQL
UTF-8
2,072
3.1875
3
[ "Apache-2.0" ]
permissive
# ************************************************************ # Sequel Pro SQL dump # Version 4749 # # http://www.sequelpro.com/ # https://github.com/sequelpro/sequelpro # # ************************************************************ /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; SET NAMES utf8mb4; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Dump of table jokes # ------------------------------------------------------------ DROP TABLE IF EXISTS `jokes`; CREATE TABLE `jokes` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `joke` varchar(500) DEFAULT NULL, `answer` varchar(200) DEFAULT NULL, `image` varchar(150) DEFAULT NULL, `button_text` varchar(20) DEFAULT '', `used` tinyint(1) unsigned DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; # Dump of table users # ------------------------------------------------------------ DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT, `first_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL, `last_name` varchar(255) DEFAULT NULL, `profile_pic` varchar(255) DEFAULT NULL, `locale` varchar(5) DEFAULT NULL, `timezone` tinyint(4) DEFAULT NULL, `gender` varchar(10) DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
20,063
2.09375
2
[]
no_license
/** * * Copyright (c) 2002-2008 The P-Grid Team, All Rights Reserved. * * This file is part of the P-Grid package. * P-Grid homepage: http://www.p-grid.org/ * * The P-Grid package is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The P-Grid package 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the P-Grid package. If not, see <http://www.gnu.org/licenses/>. * */ package pgrid.network; import p2p.basic.GUID; import pgrid.Constants; import pgrid.interfaces.basic.PGridP2P; import pgrid.PGridHost; import pgrid.Properties; import pgrid.core.maintenance.identity.IdentityManager; import pgrid.network.protocol.PGridMessage; import java.net.Socket; import java.net.SocketException; import java.util.*; /** * The Communication Manager adminstrates all connection to other hosts. * * @author @author <a href="mailto:Roman Schmidt <Roman.Schmidt@epfl.ch>">Roman Schmidt</a> * @version 1.0.0 */ public class ConnectionManager { /** * Offline period of a host */ //private static final int OFFLINE_PERIOD = 1000*20; // 20s for testes //private static final int OFFLINE_PERIOD = 1000 * 60 * 2; // 5m. /** * Timout to wait for a connection. */ private static final int CONNECT_TIMEOUT = 1000 * 20; // ~ 1m. /** * Timout to wait for a connection. */ private static final int CONNECTING_TIMEOUT = 1000 * 20; // ~ 20. /** * The reference to the only instance of this class (Singleton * pattern). This differs from the C++ standard implementation by Gamma * et.al. since Java ensures the order of static initialization at runtime. * * @see <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip67.html"> * Lazy instantiation - Balancing performance and resource usage</a> */ private static final ConnectionManager SHARED_INSTANCE = new ConnectionManager(); /** * List of connecting connections. */ private Hashtable mConnectings = new Hashtable(); /** * List of waiters on connections. */ private Hashtable mConnectionLock = new Hashtable(); /** * The Message Manager. */ private MessageManager mMsgMgr = null; /** * Hashtable of all PGridP2P connections, indexed by the GUID. */ private Hashtable mConnections = new Hashtable(); /** * true if this peer is behind a firewall */ private boolean mFirewalled = false; /** * Hashtable of all PGridP2P connections, indexed by the GUID. */ private Listener mListener = new Listener(); /** * Hashtable of all Writers, by Host GUID. */ private Hashtable mWriters = new Hashtable(); /** * Hashtable of all timestamp of offline host, by Host GUID. */ //private Hashtable mOfflineHostTimestamps = new Hashtable(); /** * The Identity Manager. */ private IdentityManager mIdentMgr = null; /** * True if connections must be challenged before acceptance */ private boolean mSecuredConnection = false; /** * Number of connection attemps. */ protected int mAttemps; /** * The constructor must be protected to ensure that only subclasses can * call it and that only one instance can ever get created. A client that * tries to instantiate PGridP2P directly will get an error at compile-time. */ protected ConnectionManager() { } /** * This creates the only instance of this class. This differs from the C++ standard implementation by Gamma et.al. * since Java ensures the order of static initialization at runtime. * * @return the shared instance of this class. * @see <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip67.html"> * Lazy instantiation - Balancing performance and resource usage</a> */ public static ConnectionManager sharedInstance() { return SHARED_INSTANCE; } /** * Processes an incoming connection accepted by the CommListener. * * @param socket the socket. */ void accept(Socket socket) { Connection conn = new Connection(socket); conn.setStatus(Connection.STATUS_ACCEPTING); Thread t = new Thread(new Acceptor(conn), "Acceptor - " + conn.getGUID()); t.setDaemon(true); t.start(); } /** * Processes an incoming connection. * * @param socket the socket. * @param greeting the already received greeting. */ public void accept(Socket socket, String greeting) { Connection conn = new Connection(socket); conn.setStatus(Connection.STATUS_ACCEPTING); Thread t = new Thread(new Acceptor(conn, greeting), "Acceptor - " + conn.getGUID()); t.setDaemon(true); t.start(); } /** * The acceptance of an incoming connection is finished. * * @param conn connection. */ public void acceptanceFinished(Connection conn) { Object connectionLock = null; // if host is null, an error has happend in the greating phase. if (conn.getHost() == null) { if (PGridP2P.sharedInstance().isInDebugMode()) { Constants.LOGGER.finest("Incomming connection with host " + conn.getSocket().getInetAddress().getCanonicalHostName() + " failed with status: "+conn.getStatusString()); } return; } // process the acceptance synchronized (mConnectionLock) { connectionLock = mConnectionLock.get(conn.getHost()); // give the coin to only one thread if (connectionLock == null) { connectionLock = new Object(); mConnectionLock.put(conn.getHost(), connectionLock); } } synchronized (connectionLock) { if (conn.getStatus() == Connection.STATUS_CONNECTED) { // check if a connection already exists Connection oldConn = (Connection)mConnections.get(conn.getHost().getGUID()); if (oldConn != null) { // a connection already exists => disconnect new one and return Constants.LOGGER.finer("Additional connection (" + oldConn.getStatusString() + ") to host " + oldConn.getHost().toHostString() + " will be closed later on."); } mConnections.put(conn.getHost().getGUID(), conn); mWriters.put(conn.getHost().getGUID(), new PGridWriter(conn)); PGridReader pr = new PGridReader(conn, mMsgMgr); Thread t = new Thread(pr, "Reader for '" + conn.getHost().toHostString() + "' - " + conn.getGUID()); t.setDaemon(true); t.start(); if (PGridP2P.sharedInstance().isInDebugMode()) Constants.LOGGER.finest("Incomming connection ("+conn.getGUID()+") with host " + (conn.getHost() == null? "\"unknown\"": conn.getHost().toHostString()) + " established."); } else if (PGridP2P.sharedInstance().isInDebugMode()) { Constants.LOGGER.finest("Incomming connection with host " + (conn.getHost() == null? "\"unknown\"": conn.getHost().toHostString()) + " failed with status: "+conn.getStatusString()); } } } /** * Connects the host with the given protocol. * * @param host the host. * @return the connection. */ public Connection connect(PGridHost host) { Constants.LOGGER.finest("Trying to get a connection for host " + host.getGUID()); String connections = ""; for (Enumeration e = mConnections.keys() ; e.hasMoreElements() ;) { GUID g = (GUID)e.nextElement(); connections += g.toString(); try { if(host!=null && host.getGUID() != null){ if (g.toString().equals(host.getGUID().toString())){ connections += " <---- FOUND !!"; } } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.out.println("host(error) :"+host.toHostString()); return null; } connections += "\n"; } Constants.LOGGER.finest("Current available connections (" + mConnections.size() + ") :\n" + connections); Connection conn; Object waiter = null; Object connectingWaiter = null; boolean stop = false; // try to find existing connection, if a PGrid connection is requested and the host is no bootstrap host // create a queue if needed synchronized (mConnectionLock) { connectingWaiter = mConnectionLock.get(host); // give the coin to only one thread if (connectingWaiter == null) { connectingWaiter = new Object(); mConnectionLock.put(host, connectingWaiter); } } synchronized (connectingWaiter) { // if the thread does not have the coin, wait while (!stop) { if ((host != null) && (host.getGUID() != null)) { conn = (Connection)mConnections.get(host.getGUID()); if (conn != null) { return conn; } } waiter = mConnectings.get(host); if (waiter != null) { try { connectingWaiter.wait(CONNECTING_TIMEOUT); } catch (InterruptedException e) { // do nothing here } if (host.getState() != PGridHost.HOST_OK) { return null; } } else { //give the coin to only one thread waiter = new Object(); mConnectings.put(host, waiter); stop = true; } } } if (PGridP2P.sharedInstance().isInDebugMode()) { Constants.LOGGER.finest("Try to establish a new connection for host: " + host.toHostString()); } // establish new connection conn = new Connection(host); conn.setStatus(Connection.STATUS_CONNECTING); Thread t = new Thread(new Connector(conn), "Connect to '" + host.toHostString() + "' - " + conn.hashCode()); t.setDaemon(true); t.start(); // wait for established connection synchronized (waiter) { while(conn.getStatus() == Connection.STATUS_CONNECTING) { try { waiter.wait(CONNECT_TIMEOUT); } catch (InterruptedException e) { } } } synchronized(connectingWaiter) { mConnectings.remove(host); connectingWaiter.notifyAll(); } Connection newConn = null; /*if (host.getGUID() != null) newConn = (Connection)mConnections.get(host.getGUID());*/ return (newConn == null ? conn : newConn); } /** * Establishing a connection has finished. * * @param conn the connection. * @param guid an GUID containing further informations. */ void connectingFinished(Connection conn, pgrid.GUID guid) { boolean challengeSucceeded = true; boolean bootstrap = false; PGridHost host = conn.getHost(); Thread readerThread = null; // if the host uses a temp. GUID (because it was not know before) => set the correct guid // INFO (Roman): I changed it to guid only because the GUID is temp. for bootstrap requests if (host.isGUIDTmp()) { host.setGUID(guid); } // connection has been established if (conn.getStatus() == Connection.STATUS_CONNECTED) { if (host.getGUID() == null) { bootstrap = true; host.setGUID(guid); } mWriters.put(host.getGUID(), new PGridWriter(conn)); PGridReader pr = new PGridReader(conn, mMsgMgr); readerThread = new Thread(pr, "Reader for '" + host.toHostString() + "' - " + conn.getGUID()); readerThread.setDaemon(true); readerThread.start(); if (PGridP2P.sharedInstance().isInDebugMode()) Constants.LOGGER.finer("Connection "+conn.getGUID()+" with host '" + host.toHostString() + "' established with code: "+conn.getStatusString()+"."); if (mSecuredConnection && !bootstrap) { Constants.LOGGER.fine("Challenging host " + host.toHostString() + "..."); if (!mIdentMgr.challengeHost(host, conn)) { host.setState(PGridHost.HOST_STALE); Constants.LOGGER.fine("Challenge failed for host '" + host.toHostString() + "'!"); conn.close(); conn.setStatus(Connection.STATUS_ERROR); challengeSucceeded = false; mWriters.remove(host.getGUID()); } else { host.resetOfflineTime(); Constants.LOGGER.fine("Challenge succeeded for host '" + host.toHostString() + "'!"); } } } // connection has not been established // inform waiting thread that the connection is established Object connectionLock = null; synchronized (mConnectionLock) { connectionLock = mConnectionLock.get(host); // give the coin to only one thread if (connectionLock == null) { connectionLock = new Object(); mConnectionLock.put(host, connectionLock); } } synchronized (connectionLock) { if (conn.getStatus() == Connection.STATUS_CONNECTED) { mConnections.put(host.getGUID(), conn); host.resetMappingAttemps(); } Object t = mConnectings.get(host); if (t != null) { synchronized (t) { t.notifyAll(); } } } } /** * Initializes the Connection Manager. * * @param startListener <tt>true</tt> if the connection listener should be started, <tt>false</tt> otherwise. */ public void init(boolean startListener) { mMsgMgr = MessageManager.sharedInstance(); mSecuredConnection = PGridP2P.sharedInstance().propertyBoolean(Properties.IDENTITY_CHALLENGE); if (mSecuredConnection) mIdentMgr = IdentityManager.sharedInstance(); mAttemps = PGridP2P.sharedInstance().propertyInteger(Properties.IDENTITY_CONNECTION_ATTEMPS); if (startListener) { if (mListener.isListenning()) { Constants.LOGGER.fine("P-Grid Listener is already active. No need to start a new thread."); } else { Thread t = new Thread(mListener, "P-Grid Listener"); t.setDaemon(true); t.start(); } } } /** * Try to reconnect a failed connection by updating the host IPort. * * @param host the host to connect. * @return the established connection or null. */ private Connection reconnect(PGridHost host) { Constants.LOGGER.fine("try to reconnect '" + host.toHostString() + "' ..."); // establish new connection Connection conn = new Connection(host); conn.setStatus(Connection.STATUS_CONNECTING); Connector myConnector = new Connector(conn); //myConnector.run(); Thread t = new Thread(new Connector(conn), "Reconnect to '" + host.toHostString() + "' - " + conn.getGUID()); t.setDaemon(true); t.start(); synchronized (t) { try { t.join(); } catch (InterruptedException e) { } } return conn; } /** * The socket of the delivered connection was closed by the remote host. * * @param conn the connection. */ //FIXME: add a bool to notify connection public void socketClosed(Connection conn) { Object connectionLock = null; synchronized (mConnectionLock) { connectionLock = mConnectionLock.get(conn.getHost()); // give the coin to only one thread if (connectionLock == null) { connectionLock = new Object(); mConnectionLock.put(conn.getHost(), connectionLock); } } synchronized (connectionLock) { if (mConnections.containsValue(conn)) mConnections.remove(conn.getHost().getGUID()); } conn.close(); } /** * The socket of the delivered connection was closed by the remote host. * * @param conn the connection. */ //FIXME: add a bool to notify connection public void socketClosed(Connection conn, boolean lingerSOTimeout) { Object connectionLock = null; if (!lingerSOTimeout) { if (conn.getSocket() != null) { try { conn.getSocket().setSoLinger(false, 0); } catch (SocketException e) { // do nothing } } } socketClosed(conn); } /** * Sends the delivered message to the delivered host. This method is synchroneous. * * @param host the receiving host. * @param msg the message to send. * @return <code>true</code> if the message was sent sucessfull, <code>false</code> otherwise. */ public boolean sendPGridMessage(PGridHost host, PGridMessage msg) { // if the host is offline, don't try to send this message synchronized (host) { if (host.getState() == PGridHost.HOST_OFFLINE) { return false; } } Connection conn = connect(host); if (conn != null && conn.getStatus() == Connection.STATUS_CONNECTED) { PGridWriter writer = (PGridWriter)mWriters.get(host.getGUID()); if (writer != null) { if (writer.sendMsg(msg)) { if (PGridP2P.sharedInstance().isInDebugMode()) { Constants.LOGGER.finest("Message : " + msg.getGUID()+" sent successfully."); } return true; } } else if (PGridP2P.sharedInstance().isInDebugMode()) { Constants.LOGGER.finest("No writer for host: " + host.toHostString()+"."); } } if (PGridP2P.sharedInstance().isInDebugMode()) { Constants.LOGGER.finest("PGrid " + msg.getDescString() + " Message failed to be sent to " + host.toHostString() + (conn != null?" [Connection status: "+conn.getStatusString()+"].":"[Connection is null].")); } /** * NaFT handling */ // Try to send message through a relay PGridHost relay = PGridP2P.sharedInstance().getNaFTManager().getRelay(host); if (relay == null || PGridP2P.sharedInstance().getNaFTManager().isMySelf(relay)) return false; NaFTManager.LOGGER.finest("Trying to send the message for " + host.toHostString() + " via relay host " + relay.toHostString()); msg.getHeader().setSourceHost(msg.getHeader().getHost()); msg.getHeader().setDestinationHost(host); conn = connect(relay); if (conn != null && conn.getStatus() == Connection.STATUS_CONNECTED) { PGridWriter writer = (PGridWriter)mWriters.get(relay.getGUID()); if (writer != null) { if (writer.sendMsg(msg)) { if (PGridP2P.sharedInstance().isInDebugMode()) { NaFTManager.LOGGER.finest("Message : " + msg.getGUID()+" sent successfully."); } return true; } } else if (PGridP2P.sharedInstance().isInDebugMode()) { NaFTManager.LOGGER.finest("No writer for relay host: " + relay.toHostString()+"."); } } return false; } /** * Sends the delivered message to the delivered host through a specific connection. * * @param host the receiving host. * @param conn the connection to the host. * @param msg the message to send. * @return <code>true</code> if the message was sent sucessfull, <code>false</code> otherwise. */ boolean sendPGridMessage(PGridHost host, Connection conn, PGridMessage msg) { if (conn.getStatus() == Connection.STATUS_CONNECTED) { PGridWriter writer = (PGridWriter)mWriters.get(host.getGUID()); if (writer != null) { return writer.sendMsg(msg); } } return false; } /** * Returns the connection for the given host and protocol. * * @param host the host. * @return the connection. */ public Connection getConnection(PGridHost host) { Connection conn = null; // try to find existing connection if (host.getGUID() != null) { conn = (Connection)mConnections.get(host.getGUID()); } return conn; } /** * Returns all connections * * @return all connections. */ public Collection getConnections() { return mConnections.values(); } /** * This method is called by the PGridReader when a timeout occurs. A timeout trigger the disconnection between this * peer and the remote one. * @param conn */ public void connectionTimeout(Connection conn) { long time = System.currentTimeMillis(); if (mConnections.containsValue(conn)) mConnections.remove(conn.getHost().getGUID()); // check if it is time to close the connection if ((time - conn.getLastIOTime()) >= conn.getIOTimeOut() && conn.getStatus() == Connection.STATUS_CONNECTED) { conn.setStatus(Connection.STATUS_CLOSING, "Timeout"); conn.resetIOTimer(); } // if timeout, wait an extra 5s and close connection else if ((time - conn.getLastIOTime()) > 5*1000 && conn.getStatus() != Connection.STATUS_CONNECTED){ conn.setStatus(Connection.STATUS_ERROR, "Closed"); socketClosed(conn); } } /** * Stop listening */ public void stopListening() { mListener.stopListening(); } /** * Restart listening */ public void restartListening() { mListener.restartListening(); } /** * Set the firewall status * @param status the firewall status */ public void setFirewallStatus(boolean status) { mFirewalled = status; } /** * Returns true if this peer is behind a firewall * @return true if this peer is behind a firewall */ public boolean isFirewalled() { return mFirewalled; } }
Go
UTF-8
2,909
2.515625
3
[]
no_license
package network import ( MQTT "github.com/eclipse/paho.mqtt.golang" "fmt" "strconv" "time" "github.com/sirupsen/logrus" "sync" "github.com/chikong/ordersystem/model" "github.com/chikong/ordersystem/manager" "github.com/garyburd/redigo/redis" "github.com/chikong/ordersystem/constant" "github.com/chikong/ordersystem/configs" ) type MqttManager interface { Publish(msg *model.Message) Subscribe(topic string) RegisterCallback(func(message MQTT.Message)) } type mqttManager struct { mqttClient MQTT.Client // 回调列 callbackList []func(message MQTT.Message) } var instance *mqttManager var once sync.Once func GetMqttInstance() MqttManager { once.Do(func() { instance = &mqttManager{} instance.initClient() }) return instance } // 订阅通用业务topic func (m *mqttManager) subscribeCommon(){ m.Subscribe(MqttProject+"/+/+"+TopicChat) } // 连接mqtt func (m *mqttManager) initClient() { if !configs.GetConfig().Mqtt.Open { return } opts := MQTT.NewClientOptions() opts.AddBroker(MqttUrl) opts.SetConnectTimeout(5*time.Second) opts.SetAutoReconnect(true) opts.SetClientID(fmt.Sprintf("system_%s", strconv.FormatInt(time.Now().Unix(), 10))) //opts.SetUsername(*user) //opts.SetPassword(*password) //opts.SetCleanSession(*cleansess) opts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) { key := fmt.Sprintf("%s_%s",msg.Topic(),string(msg.Payload())) exist, _ := redis.Bool(manager.GetRedisConn().Do(manager.RedisExists,key)) if exist { logrus.Warnf("重复消息. topic= %s", msg.Topic()) return } manager.GetRedisConn().Do(manager.RedisSet,key,"",manager.RedisEx,constant.TimeCacheMsgDuplicate) for _, value := range m.callbackList { value(msg) } }) client := MQTT.NewClient(opts) logrus.Infof("连接mqtt. %s", MqttUrl) if token := client.Connect(); token.Wait() && token.Error() != nil { logrus.Errorf("mqtt连接失败: %s",token.Error()) return } logrus.Info("连接mqtt成功") m.mqttClient = client m.subscribeCommon() } // 发送消息 func (m *mqttManager) Publish(msg *model.Message) { if m.mqttClient == nil || !m.mqttClient.IsConnected() { logrus.Warn("发送消息失败.mqtt未连接") go m.initClient() return } m.mqttClient.Publish(msg.Topic, byte(msg.Qos), false, msg.Payload) logrus.Infof("发送 %s 消息: %s, %s",msg.Desc,msg.Topic,msg.Payload) } // 订阅topic func (m *mqttManager) Subscribe(topic string) { if m.mqttClient == nil || !m.mqttClient.IsConnected() { logrus.Warn("发送消息失败.mqtt未连接") go m.initClient() return } if token := m.mqttClient.Subscribe(topic, byte(1), nil); token.Wait() && token.Error() != nil { logrus.Infof("订阅topic失败. %s", topic) } logrus.Infof("订阅topic成功. %s", topic) } func (m *mqttManager) RegisterCallback(fun func(message MQTT.Message)) { m.callbackList = append(m.callbackList, fun) }
C++
UTF-8
262
2.515625
3
[ "MIT" ]
permissive
#include "StarLinkWithTolls.h" StarLinkWithTolls::StarLinkWithTolls(StarLink* link, TollType toll) : StarLinkWithReverseLink(link), toll_(toll) { }; StarLinkWithTolls::~StarLinkWithTolls() { }; FPType StarLinkWithTolls::getTime() const { return toll_; };
JavaScript
UTF-8
1,389
4.5625
5
[]
no_license
//regular function expression // const calcArea = function (radius) { // return 3.14 * radius ** 2; // }; // ARROW function: don't use the function keyword, bit shorter // when there's only one function parameter, parentheses can be taken away but MORE THAN 1 or NONE = parentheses // when we have a single return on one line, return keyword can be removed and moved up to the same line above and take away the code block curly braces => returning that value // BINDING of the "this" keyword (not covered yet) const calcArea = (radius) => 3.14 * radius ** 2; const area = calcArea(5); console.log("area is:", area); // PRACTICE ARROW FUNCTIONS // const greet = function () { // return "hello world"; // }; const greet = () => "hello world"; const result = greet(); console.log(result); // const bill = function (products, tax) { // let total = 0; // for (let i = 0; i < products.length; i++) { // total += products[i] + products[i] * tax; // } // return total; // }; // cannot be shortened to one line because of the extra logic // function keyword has been removed and arrow has been added const bill = (products, tax) => { let total = 0; for (let i = 0; i < products.length; i++) { total += products[i] + products[i] * tax; } return total; }; console.log(bill([10, 15, 30], 0.2)); // OR // const wowza = bill([10, 15, 30], 0.2); // console.log(wowza);
Shell
UTF-8
198
3.265625
3
[]
no_license
#!/usr/bin/env bash set -e shift cmd="$@" until curl -f http://backend:3001; do >&2 echo "Server is unavailable - sleeping" sleep 1 done >&2 echo "Server is up - executing command" exec $cmd
Python
UTF-8
599
3.578125
4
[]
no_license
# -*- coding:utf-8 -*- author = 'haibo' time = '2018-7-28' """ 内置方法:__getitem__ 重定向到字典,返回的是字段的值 """ class MyGetitem: def __getitem__(self, key): if key == 'haibo': return '90' elif key == 'dingli': return '85' elif key == 'jianguang': return '99' else: return 'goodbye' if __name__=="__main__": mygetitem = MyGetitem() print mygetitem['haibo'] print mygetitem['dingli'] print mygetitem['jianguang'] print mygetitem['xianwei'] print mygetitem[' ']
JavaScript
UTF-8
981
2.78125
3
[]
no_license
function articles(state = [], action) { switch (action.type) { case 'LIKE_ARTICLE' : console.log("Incrementing Likes!!"); return state.map((article, index) => { if (index === action.index) { return Object.assign({}, article, { likes: article.likes + 1, }); } return article; }); case 'ADD_ARTICLE' : console.log("Adding articles"); // console.log(action); return [ ...state, { id: action.id, likes: 0, text: action.text, title: action.title, }, ]; case 'REMOVE_ARTICLE' : console.log("Adding articles"); // console.log(action); return [ ...state.slice(0, action.index), ...state.slice(action.index + 1), ]; default: return state; } } export default articles;
JavaScript
UTF-8
1,106
2.859375
3
[]
no_license
function timeDifference(date1,date2) { var difference = date1.getTime() - date2.getTime(); var _daysDifference = Math.floor(difference/1000/60/60/24); difference -= _daysDifference*1000*60*60*24 var _hoursDifference = Math.floor(difference/1000/60/60); difference -= _hoursDifference*1000*60*60 var _minutesDifference = Math.floor(difference/1000/60); difference -= _minutesDifference*1000*60 var _secondsDifference = Math.floor(difference/1000); return [{daysDifference:_daysDifference,hoursDifference:_hoursDifference,minutesDifference:_minutesDifference,secondsDifference:_secondsDifference}]; } function raizN(number, n) { return Math.exp(Math.log(number) / n); } function showModal(headingText,bodyText){ $('#headingModal').text(headingText); $('#bodyModal').text(bodyText); $('#myModal').modal('show'); } function showMenu(id){ if(id.indexOf("2")!=-1){ ViewModel.byStockVisibility(false); ViewModel.generalCalculusVisibility(true); }else if (id.indexOf("1")!=-1){ ViewModel.byStockVisibility(true); ViewModel.generalCalculusVisibility(false); } }
C++
GB18030
1,047
3.25
3
[]
no_license
// DataStructuresAndAlgorithms.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" int BinarySearch(int *in_aNum, int in_nLen, int in_nTargetNum); int _tmain(int argc, _TCHAR* argv[]) { int aNum[] = {1, 2, 3, 4, 5, 6}; int aNum2[] = {1, 2, 3, 4, 5, 6, 7}; int nIndex = BinarySearch(aNum, 6, 4); printf("nIndex : %d\n", nIndex); int nIndex2 = BinarySearch(aNum2, 7, 4); printf("nIndex2 : %d\n", nIndex2); getchar(); return 0; } int BinarySearch(int *in_aNum, int in_nLen, int in_nTargetNum) { int nIndex = -2; if (NULL == in_aNum) { printf("in_aNum is NULL. \n"); return nIndex; } int nLowIndex = 0; int nHighIndex = in_nLen - 1; do { int nMidIndex = (nLowIndex + nHighIndex) /2; if (in_aNum[nMidIndex] == in_nTargetNum) { nIndex = nMidIndex; break; } if (in_aNum[nMidIndex] > in_nTargetNum) { nHighIndex = nMidIndex - 1; } else if (in_aNum[nMidIndex] < in_nTargetNum) { nLowIndex = nMidIndex + 1; } } while (nLowIndex <= nHighIndex); return nIndex; };
Markdown
UTF-8
2,084
3.109375
3
[ "MIT" ]
permissive
# React Pagination Component [![NPM version][npm-image]][npm-url] [![Build Status](https://travis-ci.org/amadormf/react-pag.svg?branch=master)](https://travis-ci.org/amadormf/react-pag) [![npm download][download-image]][download-url] [npm-image]: http://img.shields.io/npm/v/react-pag.svg?style=flat-square [npm-url]: http://npmjs.org/package/react-pag [download-image]: https://img.shields.io/npm/dm/react-pag.svg?style=flat-square [download-url]: https://npmjs.org/package/react-pag Simple pagination component for use with React. You can view an online example in [http://amadormf.github.io/react-pag/](http://amadormf.github.io/react-pag/) ## Install `npm install --save react-pag` ## Example ```javascript <Pagination totalResults={100} resultsPerPage={10} urlPattern="search" /> ``` The result of this code is: ![example](http://amadormf.github.io/react-pag/example-pagination.png) ## Props |Props Name | Type | Default | Description | |-----------|--------------|:--------:|----------------| |totalResults |Number | |Number of results for paginate| |resultsPerPage|Number | |Number of results per page| |actualPage |Number | |Force the actual page of pagination| |maxPagination|Number | |Max number of buttons to show | |onChangePage|Function | |Function to call when the page change| |showBeginingEnd|Bool |false |Show buttons to move to the beginning and go to the end| |showPreviousNext|Bool |false |Show previous and next button| |urlPattern |String | |Path to use in href of pagination, you can get more info in [https://github.com/amadormf/pagination-template](https://github.com/amadormf/pagination-template)| |preventNavigate|Bool |true |You can control the navigation over pages with onChangePage, if you prefer you can give the control to navigator setting this parameter to false| |className |String | |You can use a custom className| |initialPage |Number | 1 |Initial page|
Shell
UTF-8
351
3.46875
3
[]
no_license
#!/bin/sh # usage: ask question default # asking in stderr ask() { local ans echo -n "${1} [${2}]: " >&2 read ans [ -n "${ans}" ] && echo "${ans}" || echo "${2}" } ROOT=$(ask 'rootfs' 'zroot/ROOT') POOL=$(ask 'pool' $(echo $ROOT|cut -d/ -f1)) INIT=$(ask 'init' '/sbin/init') cat >vars <<EOF ROOT="${ROOT}" POOL="${POOL}" INIT="${INIT}" EOF
Go
UTF-8
535
2.953125
3
[]
no_license
package main import ( "encoding/asn1" "fmt" "os" ) // func Marshal(val interface{}) ([]byte, error) // func Unmarshal(val interface{}, b []byte) (rest []byte, err error) func main() { val := 13 fmt.Println("Before marshal/unmarshal:", val) mdata, err := asn1.Marshal(val) checkError(err) var n int _, err1 := asn1.Unmarshal(mdata, &n) checkError(err1) fmt.Println("After marshal/unmarshal:", n) } func checkError(err error) { if err != nil { fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) os.Exit(1) } }
Markdown
UTF-8
444
2.8125
3
[]
no_license
# TestingForms This web app sets up a simple form that allows a user to enter an id and a username. This data is then routed to the appropriate method in MainController.java. Thymeleaf is used to marshall the data to a Greeting object, where it is automagically stored in fields that correspond to special parameters in the html file. The data is then sent back from the server to the web page, again using Thymeleaf, where it is displayed.
JavaScript
UTF-8
622
3.140625
3
[]
no_license
$(function() { $("form").submit(function(e) { e.preventDefault(); var $form = $(this); var num_1 = +$form.find("#num_1").val(); var num_2 = +$form.find("#num_2").val(); var operator = $form.find("#operator").val(); var result = calculate(operator, num_1, num_2); $("#result").text(result); function calculate(operator, num_1, num_2) { switch (operator) { case "+": return num_1 + num_2; case "-": return num_1 - num_2; case "*": return num_1 * num_2; case "/": return num_1 / num_2; } } }); });
C++
UTF-8
1,609
3.828125
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class LISSolution { public: int lis(const vector<int>& inputArray) { if (inputArray.empty()) return 0; vector<int> log(inputArray.size(), 1); for (int index = 1; index < inputArray.size(); ++index) { for(int start=0; start < index; ++start) { if (inputArray[index] > inputArray[start]) { log[index] = std::max(log[index], 1 + log[start]); } } } int maxLis = inputArray[0]; for(int index = 1; index < inputArray.size(); ++index) { maxLis = std::max(maxLis, log[index]); } return maxLis; } int lisUsingPatienceSorting(const vector<int>& inputArray) { if (inputArray.empty()) return 0; vector<int> pile; pile.push_back(inputArray.front()); for (int index = 1; index < inputArray.size(); ++index) { const int currentElement = inputArray[index]; if (currentElement > pile.back()) { pile.push_back(currentElement); } else { auto itr = std::upper_bound(pile.begin(), pile.end(), currentElement); *itr = currentElement; } } return pile.size(); } }; int main(int argc, char** argv) { std::vector<int> v{ 2, 5, 3, 7, 11, 8, 10, 13, 6 }; cout << LISSolution().lis(v) << endl; cout << LISSolution().lisUsingPatienceSorting(v) << endl; return 0; } // // Time complexity: // 1) Naive Approach [call to lis()] : O(n^2) // 2) Using Patience Sorting [call to lisUsingPatienceSorting()]: O(n log n) // -> log (n) because we will have to do binary search each time //
C
UTF-8
1,946
2.515625
3
[]
no_license
/* tplot.c ======= Author: R.J.Barnes */ /* (c) 2010 JHU/APL & Others - Please Consult LICENSE.superdarn-rst.3.2-beta-4-g32f7302.txt for more information. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <math.h> #include "tplot.h" int tplotset(struct tplot *ptr,int nrang) { void *tmp=NULL; if (ptr==NULL) return -1; if (ptr->qflg==NULL) tmp=malloc(sizeof(int)*nrang); else tmp=realloc(ptr->qflg,sizeof(int)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(int)*nrang); ptr->qflg=tmp; if (ptr->gsct==NULL) tmp=malloc(sizeof(int)*nrang); else tmp=realloc(ptr->gsct,sizeof(int)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(int)*nrang); ptr->gsct=tmp; if (ptr->p_l==NULL) tmp=malloc(sizeof(double)*nrang); else tmp=realloc(ptr->p_l,sizeof(double)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(double)*nrang); ptr->p_l=tmp; if (ptr->p_l_e==NULL) tmp=malloc(sizeof(double)*nrang); else tmp=realloc(ptr->p_l_e,sizeof(double)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(double)*nrang); ptr->p_l_e=tmp; if (ptr->v==NULL) tmp=malloc(sizeof(double)*nrang); else tmp=realloc(ptr->v,sizeof(double)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(double)*nrang); ptr->v=tmp; if (ptr->v_e==NULL) tmp=malloc(sizeof(double)*nrang); else tmp=realloc(ptr->v_e,sizeof(double)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(double)*nrang); ptr->v_e=tmp; if (ptr->w_l==NULL) tmp=malloc(sizeof(double)*nrang); else tmp=realloc(ptr->w_l,sizeof(double)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(double)*nrang); ptr->w_l=tmp; if (ptr->w_l_e==NULL) tmp=malloc(sizeof(double)*nrang); else tmp=realloc(ptr->w_l_e,sizeof(double)*nrang); if (tmp==NULL) return -1; memset(tmp,0,sizeof(double)*nrang); ptr->w_l_e=tmp; return 0; }
Java
UTF-8
7,673
2.46875
2
[]
no_license
package com.boc.bocsoft.mobile.bocmobile.buss.specializedservice.overseaszone.base; import android.text.SpannableString; import android.text.Spanned; import android.text.TextPaint; import android.text.style.BackgroundColorSpan; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.view.View; /** * 作者:lq7090 * 创建时间:2016/10/27. * 用途:SpannableString 的一些处理 */ public class SpannableStringUtils { /** * 设置部分可点击 * * @param s * @param l 点击监听 * @param start 点击部分起点 * @param end 点击部分终点 * @return spanableInfo */ public static SpannableString getClickableSpan(String s, View.OnClickListener l, int start, int end) { SpannableString spanableInfo = new SpannableString(s); spanableInfo.setSpan(new ClickSpan(l), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spanableInfo.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spanableInfo.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//粗体 return spanableInfo; } /** * 设置部分可点击及背景 * * @param s * @param l 点击监听 * @param start 起点 * @param end 终点 * @param color 背景 * @return spanableInfo */ public static SpannableString getClickableBackSpan(String s, View.OnClickListener l, int start, int end, int color) { SpannableString spanableInfo = new SpannableString(s); spanableInfo.setSpan(new ClickSpan(l), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//设置可点击区域 spanableInfo.setSpan(new BackgroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 spanableInfo.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//粗体 return spanableInfo; } /** * 设置部分可点击及字体颜色 * * @param s * @param l 点击监听 * @param start 点击起点 * @param end 点击终点 * @param color 字体颜色 * @return spanableInfo */ public static SpannableString getClickableForeSpan(String s, View.OnClickListener l, int start, int end, int color) { SpannableString spanableInfo = new SpannableString(s); spanableInfo.setSpan(new ClickSpan(l), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//设置可点击区域 spanableInfo.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 spanableInfo.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//粗体 return spanableInfo; } /** * 设置可点击部分字体颜色 * * @param s * @param l 点击监听 * @param fcolor 字体颜色 * @param bcolor 背景色 * @param start 起点 * @param end 终点 * @return spanableInfo */ public static SpannableString getClickableBackForeSpan(String s, View.OnClickListener l, int start, int end, int bcolor, int fcolor) { SpannableString spanableInfo = new SpannableString(s); spanableInfo.setSpan(new ClickSpan(l), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//设置可点击区域 spanableInfo.setSpan(new BackgroundColorSpan(bcolor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 spanableInfo.setSpan(new ForegroundColorSpan(fcolor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 return spanableInfo; } /** * 设置部分字体背景颜色 * * @param s * @param color 颜色 * @param start 起点 * @param end 终点 * @return spanableInfo */ public static SpannableString getBackColorSpan(String s, int color, int start, int end) { SpannableString spanableInfo = new SpannableString(s); spanableInfo.setSpan(new BackgroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 return spanableInfo; } /** * 设置部分字体颜色 * * @param s * @param color 颜色 * @param start 起点 * @param end 终点 * @return spanableInfo */ public static SpannableString getForeColorSpan(String s, int color, int start, int end) { SpannableString spanableInfo = new SpannableString(s); spanableInfo.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 return spanableInfo; } /** * @param s 用‘;’ 分割的的多处部分可点击字符串 * @param l 点击监听 * @param style 可点击部分字体 * @param color 可点击部分字体颜色 * @return spanableInfo */ public static SpannableString getClickableForeSpan(String s, View.OnClickListener l, int style, int color) { String[] tmp = s.split(";"); if (tmp != null && tmp.length == 2) { StringBuilder sb = new StringBuilder(); sb.append(tmp[0]); sb.append(tmp[1]); SpannableString spanableInfo = new SpannableString(sb); spanableInfo.setSpan(new ClickSpan(l), tmp[0].length(), sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//设置可点击区域 spanableInfo.setSpan(new ForegroundColorSpan(color), tmp[0].length(), sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 spanableInfo.setSpan(new StyleSpan(style), tmp[0].length(), sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//粗体 return spanableInfo; } else { return new SpannableString(s); } } /** * @param s 不可点击String * @param c 可点击String * @param l 点击监听 * @param style 点击部分字体 * @param color 点击部分字体颜色 * @return spanableInfo */ public static SpannableString getClickableForeSpan(String s, String c, View.OnClickListener l, int style, int color) { StringBuilder sb = new StringBuilder(); sb.append(s); sb.append(c); String st = sb.toString(); SpannableString spanableInfo = new SpannableString(st); spanableInfo.setSpan(new ClickSpan(l), s.length(), sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//设置可点击区域 spanableInfo.setSpan(new ForegroundColorSpan(color), s.length(), sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//为可点击部分设置背景色 spanableInfo.setSpan(new StyleSpan(style), s.length(), sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//可点击部分字体 return spanableInfo; } } /** * 通过此类设定SpannableString 的点击监听 */ class ClickSpan extends ClickableSpan implements View.OnClickListener { private final View.OnClickListener mListener; public ClickSpan(View.OnClickListener l) { mListener = l; } @Override public void onClick(View v) { mListener.onClick(v); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); // ds.setColor(Color.WHITE); //设置文件颜色 ds.setUnderlineText(false); //设置下划线 } }
JavaScript
UTF-8
2,275
3.03125
3
[]
no_license
import { useState, useEffect } from "react"; const useStats = statMessages => { // state const [scoreTotal, setScoreTotal] = useState(0); const [neutralTotal, setNeutralTotal] = useState(0); const [positiveTotal, setPositiveTotal] = useState(0); const [negativeTotal, setNegativeTotal] = useState(0); const [neutralAvg, setNeutralAvg] = useState(0); const [positiveAvg, setPositiveAvg] = useState(0); const [negativeAvg, setNegativeAvg] = useState(0); useEffect(() => { const getScoreTotal = () => { let sum = 0; statMessages.map(message => { sum = sum += message.result; return setScoreTotal(sum); }); }; getScoreTotal(); }, [statMessages]); useEffect(() => { const getNeutralTotal = () => { const neutralMessages = statMessages.filter(message => message.result === 0); setNeutralTotal(neutralMessages.length); }; getNeutralTotal(); }, [statMessages]); useEffect(() => { setNeutralAvg(Math.round(neutralTotal / statMessages.length * 100)); }, [neutralAvg, neutralTotal, statMessages.length]); useEffect(() => { const getPositiveTotal = () => { const positiveMessages = statMessages.filter(message => message.result > 0); setPositiveTotal(positiveMessages.length); }; getPositiveTotal(); }, [statMessages]); useEffect(() => { setPositiveAvg(Math.round(positiveTotal / statMessages.length * 100)); }, [positiveAvg, positiveTotal, statMessages.length]); useEffect(() => { const getNegativeTotal = () => { const negativeMessages = statMessages.filter(message => message.result < 0); setNegativeTotal(negativeMessages.length); } getNegativeTotal(); }, [statMessages]); useEffect(() => { setNegativeAvg(Math.round(negativeTotal / statMessages.length * 100)); }, [negativeAvg, negativeTotal, statMessages.length]); return [ scoreTotal, neutralTotal, positiveTotal, negativeTotal, neutralAvg, positiveAvg, negativeAvg ]; }; export default useStats;
Python
UTF-8
538
2.546875
3
[]
no_license
import pyrebase config = { "apiKey": "AIzaSyD6F67UAfUxa0RjO8sgQtLR9InLifIA578", "authDomain": "robotani-path-storage.firebaseapp.com", "databaseURL": "https://robotani-path-storage.firebaseio.com", "storageBucket": "robotani-path-storage.appspot.com" } firebase = pyrebase.initialize_app(config) db = firebase.database() def main(path, type): if type==0: data = {"manual": path} else: data = {"auto": path} db.child("path").set(data) users = db.child("path").get() print(users.val()) #main()
Java
UTF-8
1,204
2.0625
2
[]
no_license
package com.usco.esteban.agenda_procesos.app.models.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.usco.esteban.agenda_procesos.app.models.dao.IJuzgadoDao; import com.usco.esteban.agenda_procesos.app.models.entity.Especialidad; import com.usco.esteban.agenda_procesos.app.models.entity.Juzgado; @Service public class JuzgadoServiceImpl implements IJuzgadoService { @Autowired private IJuzgadoDao juzgadoDao; @Override @Transactional(readOnly = true) public List<Juzgado> findAll() { return juzgadoDao.findAll(); } @Override @Transactional public void save(Juzgado juzgado) { juzgadoDao.save(juzgado); } @Override @Transactional(readOnly = true) public Juzgado findOne(Long id) { return juzgadoDao.findById(id).orElse(null); } @Override @Transactional public void delete(Long id) { juzgadoDao.deleteById(id); } @Override @Transactional(readOnly = true) public List<Juzgado> findByEspecialidad(Especialidad especialidad) { return juzgadoDao.findByEspecialidad(especialidad); } }
C#
UTF-8
3,660
3.171875
3
[ "MIT" ]
permissive
using System.IO; using System.Text; namespace Gsemac.IO { public class UnbufferedStreamReader : TextReader { // Public members public static new UnbufferedStreamReader Null => new UnbufferedStreamReader(null); public Stream BaseStream => stream; public Encoding CurrentEncoding => encoding; public bool EndOfStream => endOfStream; public UnbufferedStreamReader(Stream stream) : this(stream, Encoding.UTF8) { } public UnbufferedStreamReader(Stream stream, Encoding encoding) { this.stream = stream; this.encoding = encoding; } public override void Close() { base.Close(); stream.Close(); } public override int Peek() { return PeekNextCharacter(); } public override int Read() { return ReadNextCharacter(); } public override int Read(char[] buffer, int index, int count) { int bytesRead = 0; for (int i = index; i < index + count; ++i) { int nextChar = Read(); if (nextChar < 0) break; buffer[index] = (char)nextChar; ++bytesRead; } return bytesRead; } public override string ReadLine() { // Read until we hit "\n", "\r", or "\r\n". // The newline sequence we encounter is consumed, but not returned. if (EndOfStream) return string.Empty; StringBuilder sb = new StringBuilder(); while (!EndOfStream) { int nextChar = ReadNextCharacter(); if (nextChar == '\n') break; if (nextChar == '\r') { // Consume the following newline, if present. nextChar = PeekNextCharacter(); if (nextChar == '\n') ReadNextCharacter(); break; } if (nextChar >= 0) sb.Append((char)nextChar); } return sb.ToString(); } public override string ReadToEnd() { // Since we're reading the entire stream, using a buffer is the same as not. using (StreamReader sr = new StreamReader(stream, encoding)) return sr.ReadToEnd(); } // Private members private readonly Stream stream; private readonly Encoding encoding; private readonly char[] buffer = new char[1]; private bool endOfStream = false; private bool isBufferEmpty = true; private int PeekNextCharacter() { // The stream will be read one character at a time with the current encoding. if (!isBufferEmpty) return buffer[0]; Decoder decoder = encoding.GetDecoder(); int nextByte; while ((nextByte = stream.ReadByte()) != -1) { int decodedCharCount = decoder.GetChars(new[] { (byte)nextByte }, 0, 1, buffer, 0); if (decodedCharCount > 0) { isBufferEmpty = false; return buffer[0]; } } // If we reach this point, no chars were read. endOfStream = true; return -1; } private int ReadNextCharacter() { int nextChar = PeekNextCharacter(); isBufferEmpty = true; return nextChar; } } }
SQL
UTF-8
841
4.125
4
[]
no_license
ERROR: type should be string, got "\nhttps://www.hackerrank.com/challenges/what-type-of-triangle/problem\n\nWrite a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table:\n\nEquilateral: It's a triangle with sides of equal length.\nIsosceles: It's a triangle with sides of equal length.\nScalene: It's a triangle with sides of differing lengths.\nNot A Triangle: The given values of A, B, and C don't form a triangle.\n\nSELECT CASE\nWHEN A+B <=C OR A+C<=B OR B+C<=A THEN 'Not A Triangle'\nWHEN A=B AND B=C THEN 'Equilateral'\nWHEN A=B OR B=C OR A=C THEN 'Isosceles'\nELSE 'Scalene'\nEND\nFROM TRIANGLES;\n \n \n OR \n \n SELECT IF(A+B>C AND A+C>B AND B+C>A, IF(A=B AND B=C, 'Equilateral', IF(A=B OR B=C OR A=C, 'Isosceles', 'Scalene')), 'Not A Triangle') FROM TRIANGLES;\n\n \n \n\n\n\n\n"
C++
UTF-8
230
2.796875
3
[]
no_license
#pragma once #include <cstdint> union Data { int32_t i; float f; explicit Data(int32_t i) { this->i = i; } explicit Data(float f) { this->f = f; } Data() { i = -1; } };
Java
UTF-8
126
1.585938
2
[]
no_license
package dao; import modelo.PedidoCliente; public interface PedidoClienteDAO extends DAO<PedidoCliente, Long>{ }
Python
UTF-8
1,071
3.75
4
[]
no_license
first_name = input("what is your name?") print("hi", first_name, "that sounds like a nice name.") place = input("where are you from?") print("wow I wish I could visit", place, ", it sounds like a great place") favorite_number = input("what is your favorite number?") print("did you know your favorite number divided by my favorite number is", float(favorite_number)/7) dream_car = input("what is your dream car?") print( "ooooooohhh yeah ive heard good things about those" ) cost_of_dream_car = input("how much does it cost?") print("yikes that's quite a pricey car") yearly_interest_on_the_car = input("whats the yearly interest on a car like that?") years = input("if you had to take a loan to buy the "+ dream_car+ " how many years would you take the loan out for?") r = float(yearly_interest_on_the_car)/100/12 n = int(years)*12 print("if you had bought the", dream_car,"you would have a monthly payment of $",(r*float(cost_of_dream_car))/(1-(1+r)**-n), ",hopefully that's reasonable for your budget that's a total of $",(r*float(cost_of_dream_car))/(1-(1+r)**-n)*60)
Markdown
UTF-8
10,249
2.5625
3
[ "MIT" ]
permissive
## Browser &amp; Mobile detection package for Laravel 4. *** ** If you testing the 1.0.*pre releases check out the new readme on the dev-develop-1 branch.** *** The packages collects and wrap together the best user-agent identifier packages for Laravel, and uses it's strength. + Determine **browser** informations. + Determine **operating system** informations. + Determine device kind (**phone,tablet,desktop**) and family, model informations. + Define **mobile grades** for phone and tablet devices. + Determine the browser's **CSS version support**. + Identify **bots**. + Handle Internet Explorer versions. + Uses your application **Cache** without any codeing. + Minimalized cache useage, only a very thin array will be cached without named keys or any extra informations. + Personal configurations. ## Installation. *** First add the following package to your composer: ```json { "require": { "hisorange/browser-detect": "0.9.*" } } ``` After the composer update/install add the service provider to your app.php: ```php 'providers' => array( // ... 'hisorange\browserdetect\Providers\BrowserDetectServiceProvider', // ... ) ``` Add the alias to the aliases in your app.php: ```php 'aliases' => array( // ... 'BrowserDetect' => 'hisorange\browserdetect\Facades\BrowserDetect', ) ``` You can use personal configurations just publish the package's configuration files. ``` php artisan config:publish hisorange/browser-detect ``` Finaly, enjoy :3 **At the first use the Browscap will download the most recent browscap.ini and will create a cached copy from it, this may take several seconds.** ## Performance. *** + On my test server without cacheing the first analization took 40ms and 5-7ms each different agent after that. + With cache the first analization took 3ms and 0-1ms each different agent after that. ## Examples. *** The package created for the Laravel 4 application, and tries to follow the laravelKindOfPrograming. ```php // You can always get the Info object from the facade if you wish to operate with it. BrowserDetect::getInfo(); // return Info object. // But the requests are mirrored to the Info object for easier use. BrowserDetect::browserVersion(); // return '3.6' string. // Supporting human readable formats. BrowserDetect::browserName(); // return 'Firefox 3.6' string. // Or can be objective. BrowserDetect::browserFamily(); // return 'Firefox' string. ``` #### Operate with different headers. *** If you do not set any agent for the BrowserDetect it will use the current $_SERVER['HTTP_USER_AGENT'], but you can change user agent on the fly. ```php // Get my current browser name. BrowserDetect::browserName(); // Chrome 23 // Analize a different header in the same run. BrowserDetect::setAgent('Opera/9.63 (Windows NT 6.0; U; nb) Presto/2.1.1')->browserName(); // Opera Opera 9.63 // Many time as you want... BrowserDetect::setAgent('Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)')->browserVersion(); // 10 ``` #### Fetched informations. *** The Info class always provides a fix information schema, which containing the following datas. ```php print_r(BrowserDetect::getInfo()); // Will result. hisorange\browserdetect\Info Object ( [data] => Array ( [userAgentString] => Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 [isMobile] => 1 [isTablet] => 0 [isDesktop] => 0 [isBot] => 0 [browserFamily] => Safari [browserVersionMajor] => 5 [browserVersionMinor] => 0 [browserVersionPatch] => 2 [osFamily] => iOS [osVersionMajor] => 4 [osVersionMinor] => 3 [osVersionPatch] => 2 [deviceFamily] => Apple [deviceModel] => iPhone [cssVersion] => 3 [mobileGrade] => A ) ) ``` #### Manage user agents. *** Can analize other then the current visitor's user-agent on the fly. ```php // Set a different user agent then the current. (will be processed only when an information getting requested) BrowserDetect::setAgent('Opera/9.99 (Windows NT 5.1; U; pl) Presto/9.9.9'); // Get the currently processed user agent. BrowserDetect::getAgent(); // Same as BrowserDetect::getAgent(); BrowserDetect::userAgentString(); ``` #### Determine the device kind. *** Can determine if the device is a mobile phone, tablet or desktop computer. ```php // Is the device a mobile? BrowserDetect::isMobile(); // return true : false; // Is the device a tablet? BrowserDetect::isTablet(); // return true : false; // Is the device a desktop computer? BrowserDetect::isDesktop(); // return true : false; ``` #### A bot visiting my page? *** If you wish to ban bots from your webpage: ```php if (BrowserDetect::isBot()) { exit('Sorry, humans only <3'); } ``` #### Browser software informations. *** The package determine the browser family and its semantic version. ```php // Get the browser family. BrowserDetect::browserFamily(); // return 'Internet Explore', 'Firefox', 'Googlebot', 'Chrome'... // Get the browser version. BrowserDetect::browserVersionMajor(); // return '5' integer. BrowserDetect::browserVersionMinor(); // return '2' integer. BrowserDetect::browserVersionPatch(); // return '0' integer. // Get the human friendly version. BrowserDetect::browserVersion(); // return '5.2' string, cuts the unecessary .0 or .0.0 from the end of the version. // Even more love for humans.. BrowserDetect::browserName(); // return 'Internet Explorer 10' string, merges the family and it's version. ``` #### Operating system informations. *** The package determine the Operating system family and its version. ```php // Get the os family. BrowserDetect::osFamily(); // return 'Windows' string. // Get the browser version. BrowserDetect::osVersionMajor(); // return 'XP' string or integer if the os uses semantic versioning like Android OS. BrowserDetect::osVersionMinor(); // return '0' integer. BrowserDetect::osVersionPatch(); // return '0' integer. // Get the human friendly version. BrowserDetect::osVersion(); // return '2.3.6' string, for Android OS 2.3.6 BrowserDetect::osVersion(); // return '8' integer, for Windows 8 BrowserDetect::osVersion(); // return 'Vista' string, for Windows Vista BrowserDetect::osVersion(); // return 'XP' string, for Windows XP // Even more love for humans.. BrowserDetect::osName(); // return 'Windows 7' string, merges the family and it's version. ``` #### Device informations. *** Can determine the device family e.g: 'Apple' and the device model e.g: 'iPhone'. This function only works with tablet and mobile devices yet, since the request to the server do not containing informations about the desktop computers. ```php // Get device family. BrowserDetect::deviceFamily(); // return 'Apple' string. Nokia, Samsung, BlackBerry, etc... // Get device model. BrowserDetect::deviceModel(); // return 'iPad' string. iPhone, Nexus, etc.. ``` #### CSS version support. *** The Browscap package can determine many browser's css version support. ```php // Get the supported css version. BrowserDetect::cssVersion(); // return '3' integer. Possible values null = unknown, 1, 2, 3 ``` #### Mobile grades. *** The mobile grading function inherited from the Mobile_Detect and works as it defines it. For desktop computers this value will be null. ```php // Get a tablet's or phone's mobile grade in scale of A,B,C. BrowserDetect::mobileGrade(); // returns 'A'. Values are always capitalized. ``` #### Internet Explorer support. *** The package contains some helper functions to determine if the browser is an IE and it's version is equal or lower to the setted. ```php // Determine if the browser is an Internet Explorer? BrowserDetect::isIE(); // return 'true'. // Send out alert for old IE browsers. if (BrowserDetect::isIEVersion(6)) { echo 'Your browser is a shit, watch the Jersey Shore instead of this page...'; } // true for IE 6 only. BrowserDetect::isIEVersion(6); // true for IE 9 or lower. BrowserDetect::isIEVersion(9, true); ``` #### Export & Import datas. Since (**0.9.1**) *** You can export & import the Info object data's into a simple array or a compact string. This function useful when you wish to store a user agent info in a database field, the compact string format will only contain the analization results so it can be between 30-200 chr which fits perfectly in your database char field. ```php // Export info object to a compact string. echo BrowserDetect::exportToString(); // Will produce '1|0|0|0|Safari|5|0|2|iOS|4|3|2|Apple|iPhone|3|A' // Import info from a compact string. BrowserDetect::importFromString('1|0|0|0|Safari|5|0|2|iOS|4|3|2|Apple|iPhone|3|A'); // Will generate a normal info object. // Export info object to an array. $infoArray = BrowserDetect::exportToArray(); // Will produce a simple array with the info object data values. // Import info from an array. // if you pass a numeric keyed array to the function that will sniff it out and combine the schema keys and the imported data values to the object. BrowserDetect::importFromArray($infoArray); // Will revert every informations. ``` ## Configurations. *** + Can turn on / off the cacheing. + Can set how long the cache keep the results. + Can change the cache key prefix to avoid conflicts. + Can change the browscap package's file cache path. ## Used packages. *** + [garetjax/phpbrowscap](https://github.com/GaretJax/phpbrowscap) Provides the most accurate informations about the browser. + [yzalis/ua-parser](https://github.com/yzalis/UAParser) Parses the user agent and provides accurate version numbers, os name, browser name, etc... + [mobiledetect/mobiledetectli](https://github.com/serbanghita/Mobile-Detect) The famous Mobile_Detect, identifies the device kind and model perfectly! <3 Thank's them too. Those packages are included to the composer and not source mirrored so can find them in your vendor. ## Plans: + Extend the device informations when the MobileDetect 3 will be released. + Create more extended setting for phpbrowscap. + New release with PHP 5.4 traits. + Flexible plugin support.
Java
UTF-8
1,728
2.15625
2
[]
no_license
package dto; // Generated 15/06/2015 12:32:14 PM by Hibernate Tools 4.3.1 import javax.persistence.Column; import javax.persistence.Embeddable; /** * CreditosRemesasId generated by hbm2java */ @Embeddable public class CreditosRemesasId implements java.io.Serializable { private int remesasIdRemesa; private int creditosIdCredito; public CreditosRemesasId() { } public CreditosRemesasId(int remesasIdRemesa, int creditosIdCredito) { this.remesasIdRemesa = remesasIdRemesa; this.creditosIdCredito = creditosIdCredito; } @Column(name="remesas_id_remesa", nullable=false) public int getRemesasIdRemesa() { return this.remesasIdRemesa; } public void setRemesasIdRemesa(int remesasIdRemesa) { this.remesasIdRemesa = remesasIdRemesa; } @Column(name="creditos_id_credito", nullable=false) public int getCreditosIdCredito() { return this.creditosIdCredito; } public void setCreditosIdCredito(int creditosIdCredito) { this.creditosIdCredito = creditosIdCredito; } public boolean equals(Object other) { if ( (this == other ) ) return true; if ( (other == null ) ) return false; if ( !(other instanceof CreditosRemesasId) ) return false; CreditosRemesasId castOther = ( CreditosRemesasId ) other; return (this.getRemesasIdRemesa()==castOther.getRemesasIdRemesa()) && (this.getCreditosIdCredito()==castOther.getCreditosIdCredito()); } public int hashCode() { int result = 17; result = 37 * result + this.getRemesasIdRemesa(); result = 37 * result + this.getCreditosIdCredito(); return result; } }
Java
UTF-8
619
2.59375
3
[]
no_license
package org.peontopia.models; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; /** * Created by axel on 2016-11-10. */ public class Tile implements Tile { int idx; Set<Peon> peons; Optional<Building> building = Optional.empty(); Tile(int idx) { this.idx = idx; peons = new HashSet(); } @Override public Optional<Building> building() { return building; } @Override public Optional<Road> road() { return Optional.empty(); } @Override public Set<Peon> peons() { return Collections.unmodifiableSet(peons); } }
Java
UTF-8
1,111
2.453125
2
[]
no_license
package br.mackenzie.ws; /** * * @author Joaquim Pessôa Filho * */ import io.dropwizard.Application; import io.dropwizard.Configuration; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; public class RestApp extends Application<Configuration> { @Override public void initialize(final Bootstrap<Configuration> bootstrap) { //Mapeia a pasta "src/html" para a url "http://localhost:8080/" e // por padrao abre o arquivo index.html quando um recurso especifico // nao for informado bootstrap.addBundle(new AssetsBundle("/html", "/", "index.html")); } public static void main(String[] args) throws Exception { new RestApp().run(new String[] { "server" }); } @Override public void run(Configuration configuration, Environment environment) { environment.jersey().register(new ProfessorResource()); // Mapeia todos os WebServices para a rota base // "http://localhost:8080/api/" environment.jersey().setUrlPattern("/api/*"); } }
Swift
UTF-8
8,586
2.796875
3
[]
no_license
import SpriteKit class StartScreen: SKScene, ButtonNodeDelegate, SegmentedControlDelegate { var highScoreLabel = SKLabelCustom(name: Consts.Names.LabelNames.highScore) var gameManager = GameManager.shared override init() { super.init(size: Consts.Graphics.screenResolution) createSceneContent() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func createSceneContent() { //Background let background = SKSpriteNode(color: UIColor.white, size: Consts.Graphics.size) background.position = CGPoint(x: size.width/2, y: size.height/2) background.size = CGSize(width: self.frame.width, height: self.frame.height) background.zPosition = Z.background addChild(background) //Title let title = SKLabelNode(text: Consts.Texts.title) title.fontSize = 120 title.position = Positions.titleLabel title.fontName = "Noteworthy-Bold" title.fontColor = UIColor.orange scene?.addChild(title) //Play var buttonData = ButtonData(texture: Consts.Names.ButtonImageNames.play, name: Consts.Names.NodesNames.play, size: Consts.Sizes.squareButton, position: Positions.playButton, zPosition: Z.buttons) let playButtonNode = ButtonNode(imageNamed: buttonData.normalTexture, for: .normal) playButtonNode.delegate = self playButtonNode.setup(buttonData: buttonData) var labelData = LabelData(name: Consts.Names.LabelNames.play, text: Consts.Texts.play, position: nil, zPosition: Z.buttonLabels, fontSize: 80, fontColor: nil) let playAccessibilityLabel = SKLabelCustom(name: labelData.name) playAccessibilityLabel.setup(labelData: labelData) playAccessibilityLabel.setText(text: Consts.Texts.play) playAccessibilityLabel.fontName = "Noteworthy-Bold" playAccessibilityLabel.alpha = 0.01 playButtonNode.addChild(playAccessibilityLabel) scene?.addChild(playButtonNode) //Settings buttonData = ButtonData(texture: Consts.Names.ButtonImageNames.settings, name: Consts.Names.NodesNames.settings, size: Consts.Sizes.bigRectangleButton, position: Positions.settingsButton, zPosition: Z.buttons) let settingsButtonNode = ButtonNode(imageNamed: buttonData.normalTexture, for: .normal) settingsButtonNode.delegate = self settingsButtonNode.setup(buttonData: buttonData) labelData = LabelData(name: Consts.Names.LabelNames.discover, text: Consts.Texts.discover, position: nil, zPosition: Z.buttonLabels, fontSize: 120, fontColor: nil) let discoverAccessibilityLabel = SKLabelCustom(name: labelData.name) discoverAccessibilityLabel.setup(labelData: labelData) discoverAccessibilityLabel.setText(text: Consts.Texts.discover) // discoverAccessibilityLabel.fontName = "Noteworthy-Bold" discoverAccessibilityLabel.alpha = 0.01 settingsButtonNode.addChild(discoverAccessibilityLabel) scene?.addChild(settingsButtonNode) createNote(name: Consts.Names.NodesNames.redNote, index: 0) createNote(name: Consts.Names.NodesNames.yellowNote, index: 1) createNote(name: Consts.Names.NodesNames.blueNote, index: 2) //diffucylty labelData = LabelData(name: Consts.Names.LabelNames.normalDifficulty, text: Consts.Texts.normalDifficulty, position: nil, zPosition: Z.buttonLabels, fontSize: 65, fontColor: UIColor.yellow) buttonData = ButtonData(texture: checkStatus(difficulty: .normal), name: Consts.Names.NodesNames.difficultyNormal, size: Consts.Sizes.rectangleButton, position: Positions.difficultyNormalButton, zPosition: Z.buttons) createSegmentedControl(buttonData: buttonData, labelData: labelData) labelData = LabelData(name: Consts.Names.LabelNames.hardDifficulty, text: Consts.Texts.hardDifficulty, position: nil, zPosition: Z.buttonLabels, fontSize: 65, fontColor: UIColor.yellow ) buttonData = ButtonData(texture: checkStatus(difficulty: .hard), name: Consts.Names.NodesNames.difficultyHard, size: Consts.Sizes.rectangleButton, position: Positions.difficultyHardButton, zPosition: Z.buttons) createSegmentedControl(buttonData: buttonData, labelData: labelData) } func checkStatus(difficulty: Difficulty) -> String { return UserDefaults.difficulty == difficulty ? Consts.Names.ButtonImageNames.difficultySelected : Consts.Names.ButtonImageNames.difficultyNotSelected } func createNote(name: String, index: Int) { let note = SKSpriteNode(imageNamed: name) note.position = Positions.notesPosition[index] note.size = Consts.Sizes.littleSquareButton note.zPosition = Z.sprites let goDown = SKAction.moveBy(x: 0, y: 75, duration: 0.7) let goUp = SKAction.moveBy(x: 0, y: -75, duration: 0.7) var seq = SKAction.sequence([goDown,goUp]) if index % 2 == 1 { note.position.y = note.position.y + 75 seq = SKAction.sequence([goUp,goDown]) } let infiniteSeq = SKAction.repeatForever(seq) note.run(infiniteSeq) addChild(note) } func createSegmentedControl(buttonData: ButtonData, labelData: LabelData) { let button = SegmentedControl(imageNamed: buttonData.normalTexture, for: .normal) button.delegateSegContr = self button.setup(buttonData: buttonData) // button.setScale(Consts.Graphics.scale) let label = SKLabelCustom(name: labelData.name) label.setup(labelData: labelData) label.setText(text: labelData.text) label.fontName = "Noteworthy-Bold" label.fontSize = labelData.fontSize ?? 70 button.addChild(label) self.addChild(button) } func SegmentedControlTapped(_ sender: SegmentedControl) { buttonNodeTapped(sender) if let name = sender.name { switch name { case Consts.Names.NodesNames.difficultyNormal: changeDifficulty(difficulty: .normal, sender: sender, nonSelectedNodeName: Consts.Names.NodesNames.difficultyHard) guard let thirdGestureButton = scene?.childNode(withName: Consts.Names.NodesNames.hapticButtonsInSettings.last!) as! ButtonNode? else {return} thirdGestureButton.isHidden = true case Consts.Names.NodesNames.difficultyHard: changeDifficulty(difficulty: .hard, sender: sender, nonSelectedNodeName: Consts.Names.NodesNames.difficultyNormal) guard let thirdGestureButton = scene?.childNode(withName: Consts.Names.NodesNames.hapticButtonsInSettings.last!) as! ButtonNode? else {return} thirdGestureButton.isHidden = false default: break } } } func changeDifficulty(difficulty: Difficulty, sender: SegmentedControl, nonSelectedNodeName: String) { if gameManager.difficulty != difficulty { guard let nonSelectedNode = self.childNode(withName: nonSelectedNodeName) as! SegmentedControl? else { return } gameManager.difficulty = difficulty switchButtonTexture(sender: sender, notSelected: nonSelectedNode) highScoreLabel.text = Consts.Texts.highScore + "\(UserDefaults.highScore)" } } func switchButtonTexture(sender: SegmentedControl, notSelected: SegmentedControl) { sender.changeTextures(texture: Consts.Names.ButtonImageNames.difficultySelected) notSelected.changeTextures(texture: Consts.Names.ButtonImageNames.difficultyNotSelected) } func buttonNodeTapped(_ sender: ButtonNode) { let transition:SKTransition = SKTransition.fade(withDuration: 1) if let name = sender.name { switch name { case Consts.Names.NodesNames.play: if GameManager.shared.isCompletitionComplete { let scene:SKScene = GameScreen() self.view?.presentScene(scene, transition: transition) } case Consts.Names.NodesNames.settings: let scene:SKScene = SettingsScreen() self.view?.presentScene(scene, transition: transition) default: break } } } }
Python
UTF-8
1,672
3.28125
3
[]
no_license
from __future__ import absolute_import, division, print_function from collections import defaultdict def explore(file_name): ''' :param file_name: :return: ''' print(file_name) seg_dict = defaultdict(int) # segment to count seg_tags = defaultdict(lambda: defaultdict(int)) # segment to unique set of tags { 'A':{ 'NN','Verb'}, 'B':{'NN"}} lines = None with open(file_name, 'r') as f: lines = f.read().splitlines() for i, line in enumerate(lines): # skip empty lines (between sentences kept empty on purpose) if len(line) == 0: continue splitted = line.split('\t') seg = splitted[0] tag = splitted[1] seg_dict[seg] += 1 # unique tag set per segment seg_tags[seg][tag] += 1 print('unigram segments instancecount=', sum(seg_dict.values())) print('unigram segments unique types=', len(seg_dict)) # value:{NN:3, VB:2} --map a dict to it's sum --> 5 print('seg-tag pairs instance count=', sum(map(lambda dic: sum(dic.values()), seg_tags.values()))) # value:{NN:3, VB:2} --map a dict to number of keys --> 5 segtag_pairs_uniques = sum((map(len, seg_tags.values()))) print('seg-tag pairs unique count=', segtag_pairs_uniques) # cool usage of map : [{NN, VB},{VB}] -- map to length of sets --> [2,1] , then just sum print('ambiguousness = average different tag types per segment={:.4}'.format(segtag_pairs_uniques / len(seg_tags))) if __name__ == "__main__": files = ['../exps/isha/isha.gold', '../exps/heb-pos.train', '../exps/heb-pos.gold'] for f in files: print('\n') explore(f)
Java
UTF-8
612
2.015625
2
[]
no_license
package containers; import jade.core.Profile; import jade.core.ProfileImpl; import jade.core.Runtime; import jade.util.leap.Properties; import jade.wrapper.AgentContainer; import jade.wrapper.ControllerException; public class MyMainContainer { public static void main(String[] args) throws ControllerException { Runtime runtime = Runtime.instance(); Properties properties = new Properties(); properties.setProperty(Profile.GUI, "true"); ProfileImpl profile = new ProfileImpl(properties); AgentContainer mainContainer = runtime.createMainContainer(profile); mainContainer.start(); } }
C++
UTF-8
646
3.046875
3
[ "Apache-2.0" ]
permissive
#ifndef __EVENT_H_ #define __EVENT_H_ #include <fstream> #include "..\Defs.h" using namespace std; class Restaurant; //Forward declation //The base class for all possible events in the system (abstract class) class Event { protected: int EventTime; //Timestep when this event takes place int OrderID; //each event is related to certain order Restaurant* pRest; public: Event(int eTime, int ordID, Restaurant* pR); Event(Restaurant* pR); int getEventTime(); int getOrderID(); virtual void ReadEvent(ifstream& fin) = 0; virtual ~Event(); virtual void Execute()=0; ////a pointer to "Restaurant" and events need it to execute }; #endif
PHP
UTF-8
2,900
2.59375
3
[]
no_license
<?php class RecommendationsCest { public function GetRecommendationsWithLimit(ApiTester $I) { $I->am('client'); $I->wantTo("get recommendations - limited count"); $I->haveHttpHeader('Content-Type', 'application/json'); $sku ='LO019EMJGZ27'; $limit = 5; $I->sendPOST('get_product_product_recommendations',['sku'=>$sku, 'limit'=>$limit]); $I->seeResponseCodeIs(200); $response = json_decode($I->grabResponse(), true); //преобразуем json в массив $I->assertTrue(count($response)==$limit, "there are $limit recommendations in response"); //в ответе запрошенное количество рекомендаций /* * Для каждого продукта проверяем наличие поля sku и формат значения в поле - строка из англ. букв и цифр длиной 12 символов */ for ($i=0; $i<count($response); $i++) { $I->seeResponseJsonMatchesJsonPath("$.[$i].product.sku"); $I->seeResponseMatchesJsonType(['sku'=>'string:regex(/^[a-zA-Z0-9]{12}$/)'],"$.[$i].product"); } } public function GetRecommendationsDefaultLimit(ApiTester $I) //падает, приходит 20 шт { $I->am('client'); $I->wantTo("get recommendations - default limit"); $I->haveHttpHeader('Content-Type', 'application/json'); $sku ='LO019EMJGZ27'; $I->sendPOST('get_product_product_recommendations',['sku'=>$sku]); $I->seeResponseCodeIs(200); $response = json_decode($I->grabResponse(), true); //преобразуем json в массив $I->assertTrue(count($response)==12, "there are 12 recommendations in response"); //в ответе 12 рекомендаций } public function GetRecommendationsNullSku(ApiTester $I) { $I->am('client'); $I->wantTo("see error message when try to get recommendations with null SKU provided"); $I->haveHttpHeader('Content-Type', 'application/json'); $limit = 6; $I->sendPOST('get_product_product_recommendations',['sku'=>null, 'limit'=>$limit]); $I->seeResponseCodeIs(400); $I->seeResponseContainsJson(['faultcode'=>'Client.ValidationError']); } public function GetRecommendationsInvalidSku(ApiTester $I) { $I->am('client'); $I->wantTo("see error message when try to get recommendations with invalid (long) SKU provided"); $I->haveHttpHeader('Content-Type', 'application/json'); $limit = 6; $sku ='LO019EMJGZ27/'; $I->sendPOST('get_product_product_recommendations',['sku'=>$sku, 'limit'=>$limit]); $I->seeResponseCodeIs(400); $I->seeResponseContainsJson(['faultcode'=>'Client.RECOMMENDATIONS_NOT_AVAILABLE']); } }
Python
UTF-8
5,324
3.640625
4
[]
no_license
#Author: Jashanpreet Singh #Drexel_ID: js4683 #Lab Section: 66 #Purpose: CS172 Homework 2 #Written on: 04/29/2019 from media import Movie, Song, Picture #to import our classes #dictionary with objects of each class and sorted by the type of object media = { 'Movies': [ Movie('Movie', 'Batman: The Dark Knight', 10, 'Christopher Nolan', 152), Movie('Movie', 'Avengers', 9.4, 'Anthony Russo and Joe Russo', 160), Movie('Movie','Superman', 9.8, 'Richard Donner', 188), Movie('Movie', 'The Conjuring 2', 8.2, 'James Wan', 134), Movie('Movie', 'Jaws', 8.8, 'Steven Spielberg', 130) ], 'Songs': [ Song('Song', 'Thriller', 9.9, 'Micheal Jackson', 'Thriller'), Song('Song', 'Old Town Road', 5.6, 'Lil Nas X', 'Old Town Road'), Song('Song','XO Tour Llif3', 10, 'Lil Uzi Vert', 'Luv Is Rage 2'), Song('Song', "God's Plan", 3.5, 'Drake', 'Scorpion'), Song('Song', "Sanguine Paradise", 9.9, 'Lil Uzi Vert', 'Eternal Atake') ], 'Pictures': [ Picture('Picture', 'Joseph', 5.8, 300), Picture('Picture', 'CS', 9.5, 250), Picture('Picture', 'Photo', 6.8, 450), Picture('Picture','Image', 7.6, 500), Picture('Picture','Hello', 8.7, 212) ] } def allfunction(userInpLower): #a function which will list all of the items in each key mediaKey = '' #variable which will be the key #sets the variable according to the user input if userInpLower == 'all songs': mediaKey = 'Songs' elif userInpLower == 'all movies': mediaKey = 'Movies' else: mediaKey = 'Pictures' print('\nThese are the {} in the libray.'.format(mediaKey)) #a title which tells the user which option they picked print('----------------------------------') counter = 1 #variable to number each item in the key when listed for item in media[mediaKey]: #to get each item in the key the user selected by typing in a specifc command print(str(counter) + '.', item) counter += 1 print('') print('Welcome to the Media Player')#welcome message print('---------------------------') while True: #a loop which keeps the program running and validates the input until the user quits userInp = input("\n Enter 'All' to display all items in the library. \n Enter 'All songs' to only display songs. \n Enter 'All movies' to only display movies. \n Enter 'All pictures' to only display pictures. \n Enter 'song' to play a song. \n Enter 'movie' to play a movie. \n Enter 'picture' to display a picture. \n Enter 'quit' to quit the program \n") userInpLower = userInp.lower() #to get rid of the nuances of a string literal if userInpLower == 'all': #handles if the user decides to display all of the files for key, value in media.items(): #a for loop to loop through each key and its values print('\n' + key) #prints the title of the objects it is about to display, which is songstored in the key print('') for item in value: #loops through each value stored in each keys print(item) elif userInpLower == 'all songs' or userInpLower == 'all movies' or userInpLower == 'all pictures': #handles if the input is to display only one type of files allfunction(userInpLower) #calls the function to list the user's selection elif userInpLower == 'song' or userInpLower == 'movie': #handles if the user decided to play a specific movie or song mediaKey = userInpLower #sets the mediakey to the user input which is the type of media they want to play userInp2 = 'all ' + userInpLower + 's' allfunction(userInp2) #call to function to list all the items of the category selected available in the library userInp2 = input('Enter the name of the {} you want to play:\n'.format(mediaKey)) #asks for the name of the specific media file they want to play mediaKey = userInpLower.capitalize() + 's' #adds an "s" as the input will now match the keys stored for item in media[mediaKey]: #loops through each item in the key selected if userInp2.lower() == item.getName().lower(): #if the second input matches the name of an item stored then play item.play() print('') break else: #handles if the media file is not in the library print( userInp2 + ' is not in the media library.') print('') elif userInpLower == 'picture': #if the user decides to see a specific picture allfunction(userInpLower) mediaKey = userInpLower #gets rid of the nuances userInp2 = input('Enter the name of the {} you want to see:\n'.format(mediaKey)) #asks for the name of the picture mediaKey = 'Pictures' for item in media[mediaKey]: #loops through the pictures key if userInp2.lower() == item.getName().lower(): #if the name matches one of the items then show item.show() print('') break else: #handles if the media file is not in the library print( userInp2 + ' is not in the media library.') print('') elif userInpLower == 'quit': #if the user decides to quit break else: #handles if input is not of the options listed print('\nInvalid Response') print("Let's try again.\n")
Markdown
UTF-8
791
3.546875
4
[]
no_license
## 함수 함수(function)란 하나의 로직을 재실행 할 수 있도록 하는 것으로 코드의 재사용성을 눂여준다. function 함수명([인자...[,인자]]) { 코드내용 return 반환값 } 1. 함수의 출력 - 출력은 return 이라는 기호를 쓴다. 2. 함수의 입력 - 취지에 따라 출력 값이 달라져야 한다. ``` <script> //arg는 매개변수, 영어로 parameter function get_argument(arg) { return arg*1000; } //인자, argument console.log(get_argument(1)); console.log(get_argument(2)); </script> ``` 3. 함수의 정의 정의와 호출 동시에, 익명함수, 바로 실행해야하는 경우, (function (){ i = 0; while(i < 10) { document.write(i); i += 1; } })();
Swift
UTF-8
9,240
2.546875
3
[]
no_license
// // NamesTableViewController.swift // CoreDataTuto // // Created by Mrabti Idriss on 03.12.17. // Copyright © 2017 Mrabti Idriss. All rights reserved. // import UIKit import CoreData import SwiftRecord class ContactsTableViewController: UITableViewController { var contacts: [[Contact]] = [] var contactSections: [String] = [] var filteredContacts: [Contact] = [] var selectedRowToEdit: IndexPath? var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() self.searchController = UISearchController(searchResultsController: nil) self.searchController.searchResultsUpdater = self self.searchController.searchBar.delegate = self self.searchController.dimsBackgroundDuringPresentation = false self.searchController.searchBar.scopeButtonTitles = ContactType.allValuesSearch.map({t in t.rawValue}) self.searchController.searchBar.placeholder = "Search Contacts" self.searchController.searchBar.tintColor = UIColor.white self.navigationItem.searchController = searchController definesPresentationContext = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (contacts.isEmpty) { // load all contacts from database let allContacts = Contact.all() as! [Contact] // Group contacts by section for contactType in ContactType.allValues { let dataForSection = allContacts.filter({ $0.type == contactType.rawValue }) if dataForSection.count > 0 { contacts.append(dataForSection) contactSections.append(contactType.rawValue) } } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { if searchController.isActive { return 1 } else { return contactSections.count } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive { return self.filteredContacts.count } else { return contacts[section].count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if searchController.isActive { return nil } else { return contactSections[section] } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return !searchController.isActive; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? ContactTableViewCell else { fatalError("The dequeued cell is not an instance of ContactTableViewCell.") } // Choose between contact or filteredContacts depending if the user is searching let dataModel: [Contact] = searchController.isActive ? filteredContacts : contacts[indexPath.section] cell.fullName.text = dataModel[indexPath.row].name cell.email.text = dataModel[indexPath.row].email cell.phoneNumber.text = dataModel[indexPath.row].phoneNumber if let picture = dataModel[indexPath.row].picture { cell.contactAvatar(UIImage(data: picture)!) } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .normal, title: "Delete") { action, index in // Remove contact from the model self.contacts[indexPath.section][indexPath.row].delete() self.contacts[indexPath.section].remove(at: index.row) // Remove the contact from the TableView tableView.deleteRows(at: [indexPath], with: .automatic) if self.contacts[indexPath.section].isEmpty { self.contacts.remove(at: indexPath.section) self.contactSections.remove(at: indexPath.section) // Remove the section from the TableView tableView.deleteSections(IndexSet(integer: indexPath.section), with: .automatic) } let _ = Contact.save() } delete.backgroundColor = UIColor.red let edit = UITableViewRowAction(style: .normal, title: "Edit") { action, index in self.selectedRowToEdit = index self.performSegue(withIdentifier: "EditContact", sender: self.contacts[index.section][index.row]) } return [edit, delete] } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let navigationController = segue.destination as! UINavigationController let editNameController = navigationController.viewControllers.first as! EditContactViewController if segue.identifier == "EditContact" { if let selectedContact = sender as? Contact { editNameController.addOrEditContact = selectedContact } } } // MARK: - Actions @IBAction func unwindToContactContactList(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? EditContactViewController, let contact = sourceViewController.addOrEditContact { if let selectedIndexPath = selectedRowToEdit { if (contactSections[selectedIndexPath.section] != contact.type) { if let section = contactSections.index(where: { $0 == contact.type }) { contacts[selectedIndexPath.section].remove(at: selectedIndexPath.row) contacts[section].append(contact) // Update TableView tableView.moveRow(at: selectedIndexPath, to: IndexPath(row: contacts[section].count - 1, section: section)) } else { contacts[selectedIndexPath.section].remove(at: selectedIndexPath.row) contactSections.append(contact.type!) contacts.append([contact]) // Update the TableView tableView.reloadData() } } if contacts[selectedIndexPath.section].isEmpty { contacts.remove(at: selectedIndexPath.section) contactSections.remove(at: selectedIndexPath.section) // Update TableView tableView.deleteSections(IndexSet(integer: selectedIndexPath.section), with: .automatic) } selectedRowToEdit = nil } else { if let section = contactSections.index(where: { $0 == contact.type }) { contacts[section].append(contact) tableView.insertRows(at: [IndexPath(row: contacts[section].count - 1, section: section)], with: .automatic) } else { // Add new Section and insert the row let newSectionIndex = contactSections.count contactSections.append(contact.type!) contacts.append([contact]) // Update the TableView tableView.insertSections(IndexSet(integer: newSectionIndex), with: .automatic) } } } } // MARK : - Other functions func filterContacts(_ searchText: String, scope: String = "All") { filteredContacts = contacts.joined().filter { (contact: Contact) -> Bool in let doesTypeMatch = (scope == "All") || (contact.type == scope) if searchBarIsEmpty() { return doesTypeMatch } else { return doesTypeMatch && contact.name!.lowercased().contains(searchText.lowercased()) } } tableView.reloadData() } func searchBarIsEmpty() -> Bool { return searchController.searchBar.text?.isEmpty ?? true } } extension ContactsTableViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { filterContacts(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope]) } } extension ContactsTableViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { let searchBar = searchController.searchBar let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] filterContacts(searchController.searchBar.text!, scope: scope) } }
Java
UTF-8
2,092
2.109375
2
[]
no_license
package com.handsome.projectnz.View.Home.MaterialHandling; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.handsome.module_engine.E.BaseTemplate.BaseActivity; import com.handsome.projectnz.Adapter.Home.MaterialHandling.MaterialIORecordAdapter; import com.handsome.projectnz.Module.MaterialIORecord; import com.handsome.projectnz.R; import java.util.ArrayList; import java.util.List; public class MaterialInputRecordActivity extends BaseActivity{ private ListView lv_record; private List<MaterialIORecord> records; private MaterialIORecordAdapter adapter; @Override public int getLayoutId() { return R.layout.activity_material_io_record; } @Override public void initViews() { lv_record=findView(R.id.lv); } @Override public void initListener() { } @Override public void initData() { setTitleCanBack(); setTitle("入库记录"); records=new ArrayList<>(); MaterialIORecord record=new MaterialIORecord(); record.setDate("2018-11-23"); record.setCount(3); record.setHandler("Diko"); record.setBelong("初期"); records.add(record); MaterialIORecord record1=new MaterialIORecord(); record1.setDate("2018-11-23"); record1.setCount(3); record1.setHandler("adah."); record1.setBelong("初期"); records.add(record); adapter=new MaterialIORecordAdapter(this,records); lv_record.setAdapter(adapter); lv_record.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i=new Intent(MaterialInputRecordActivity.this,MaterialInputRecordDetailActivity.class); i.putExtra("record",records.get(position)); startActivity(i); } }); } @Override public void processClick(View v) { } }
Markdown
UTF-8
974
2.875
3
[]
no_license
# Udacity Restaurant Reviews App This is the fifth project of Udacity Front-End NanoDegree Programm. ## Project Overview For the Restaurant Reviews projects, you will incrementally convert a static webpage to a mobile-ready web application. In Stage One, you will take a static design that lacks accessibility and convert the design to be responsive on different sized displays and accessible for screen reader use. You will also add a service worker to begin the process of creating a seamless offline experience. ## Installition 1. Clone/Download the project repository [here](https://github.com/Raghad72/Restaurant-Reviews-App.git). 2. Download and install python. 3. In the project directory open terminal and start local server with "$ python -m http.server" 4. Open App in Browser: http://localhost:8000 ## Resources & Tools - [Udacity's starter code](https://github.com/udacity/mws-restaurant-stage-1.git) - [MapBox API key](https://account.mapbox.com/)
Shell
UTF-8
168
2.796875
3
[]
no_license
#!/bin/bash if [[ ! $(who) && ! $(netstat -natp | grep -e 3389.*ESTABLISHED) ]]; then echo "This client is currently not used and will be shut down now." poweroff fi
Java
UTF-8
3,619
1.890625
2
[]
no_license
package org.onebusaway.nyc.webapp.actions.admin; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.validation.SkipValidation; import org.onebusaway.users.model.User; import org.onebusaway.users.model.UserIndex; import org.onebusaway.users.model.UserIndexKey; import org.onebusaway.users.services.UserIndexTypes; import org.onebusaway.users.services.UserPropertiesService; import org.onebusaway.users.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.onebusaway.nyc.webapp.actions.OneBusAwayNYCActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator; import com.opensymphony.xwork2.validator.annotations.Validations; @Result(type = "redirectAction", name = "list", params = {"actionName", "api-keys"}) public class ApiKeysAction extends OneBusAwayNYCActionSupport implements ModelDriven<ApiKeyModel> { private static final long serialVersionUID = 1L; @Autowired private UserService _userService; @Autowired private UserPropertiesService _userPropertiesService; private List<ApiKeyModel> _apiKeys; private ApiKeyModel _model = new ApiKeyModel(); @Override public ApiKeyModel getModel() { return _model; } public List<ApiKeyModel> getApiKeys() { return _apiKeys; } @Override @SkipValidation public String execute() { _apiKeys = new ArrayList<ApiKeyModel>(); List<String> apiKeys = _userService.getUserIndexKeyValuesForKeyType(UserIndexTypes.API_KEY); for(String key : apiKeys) { ApiKeyModel m = new ApiKeyModel(); m.setApiKey(key); m.setMinApiRequestInterval(_userService.getMinApiRequestIntervalForKey(key, true)); _apiKeys.add(m); } return SUCCESS; } @Validations(requiredStrings = {@RequiredStringValidator(fieldName = "model.apiKey", message = "Error")}) public String saveOrUpdate() { if(_model.getMinApiRequestInterval() == null) _model.setMinApiRequestInterval(100L); saveOrUpdateKey(_model.getApiKey(), _model.getMinApiRequestInterval()); return "list"; } @Validations(requiredStrings = {@RequiredStringValidator(fieldName = "model.apiKey", message = "Error")}) public String delete() { UserIndexKey key = new UserIndexKey(UserIndexTypes.API_KEY, _model.getApiKey()); UserIndex userIndex = _userService.getUserIndexForId(key); if (userIndex == null) return INPUT; User user = userIndex.getUser(); _userService.removeUserIndexForUser(user, key); if (user.getUserIndices().isEmpty()) _userService.deleteUser(user); // Clear the cached value here _userService.getMinApiRequestIntervalForKey(_model.getApiKey(), true); return "list"; } @SkipValidation public String generate() { _model.setApiKey(UUID.randomUUID().toString()); _model.setMinApiRequestInterval(100L); return saveOrUpdate(); } /**** * Private Methods ****/ private void saveOrUpdateKey(String apiKey, Long minApiRequestInterval) { UserIndexKey key = new UserIndexKey(UserIndexTypes.API_KEY, apiKey); UserIndex userIndex = _userService.getOrCreateUserForIndexKey(key, "", true); _userPropertiesService.authorizeApi(userIndex.getUser(), minApiRequestInterval); // Clear the cached value here _userService.getMinApiRequestIntervalForKey(apiKey, true); } }
JavaScript
UTF-8
2,894
2.96875
3
[]
no_license
mainModule.factory('defaultFactory', function($http) { var factory = {}; var users = []; factory.getActivity = function(loc) { return $http.get("http://terminal2.expedia.com/x/activities/search?location="+ loc +"&apikey=KvTSobGaExiwiazfRdtoMYpNaRhBk2E9") .then(function(returned_data_from_server){ // console.log(returned_data_from_server); return returned_data_from_server; }); } factory.getActivityDetails = function(id) { return $http.get("http://terminal2.expedia.com/x/activities/details?activityId="+ id +"&apikey=KvTSobGaExiwiazfRdtoMYpNaRhBk2E9") .then(function(returned_data_from_server1){ // console.log(returned_data_from_server1); // console.log("1"); return returned_data_from_server1; }); } factory.getWeather = function(data) { return $http.get("http://api.openweathermap.org/data/2.5/weather?q="+ data +"&APPID=485450c2da837aceda525ff9a4165fe1") .then(function(returned_data_from_server2){ // console.log(returned_data_from_server2); return returned_data_from_server2; }); } factory.getAllUsers = function(callback){ var title = ""; var image = ""; var price = ""; var detail = ""; var weather = ""; var wDescript = ""; var id = ""; var lat = ""; var lon = ""; var activity = []; var obj = {}; // console.log("Factory - getAllUsers"); // console.log("Executing $http.get getAllUsers"); //get TTDs $http.get('http://terminal2.expedia.com/x/activities/search?location=London&apikey=KvTSobGaExiwiazfRdtoMYpNaRhBk2E9') .then(function(returned_data_from_server){ console.log("Server responded with: ", returned_data_from_server); //callback(returned_data_from_server); for (var i = 0; i < 10; i++) { activity = returned_data_from_server.data.activities[i]; // id = returned_data_from_server.activities[0].id; // console.log(id); id = activity.id; title = activity.title; image = activity.imageUrl; price = activity.fromPrice; //get TTD description $http.get("http://terminal2.expedia.com/x/activities/details?activityId="+ id +"&apikey=KvTSobGaExiwiazfRdtoMYpNaRhBk2E9") .then(function(returned_data_from_server1){ console.log("Server responded with: ", returned_data_from_server1); detail = returned_data_from_server1.data.metaDescription; lat = returned_data_from_server1.data.latLng.split(","); lon = lat[1]; lat = lat[0]; //get Location weather $http.get("http://api.openweathermap.org/data/2.5/weather?lat="+ lat +"&lon="+ lon +"&APPID=485450c2da837aceda525ff9a4165fe1") .then(function(returned_data_from_server2){ // console.log("Server responded with: ", returned_data_from_server2); weather = returned_data_from_server2.data.weather[0].main; wDescript = returned_data_from_server2.data.weather[0].description; }); }); console.log(title + "\n" +image + "\n" +price + "\n" +detail + "\n" +weather + "\n" +wDescript + "\n"); } }); } return factory; });
Python
UTF-8
343
3.34375
3
[]
no_license
def f(S): res = [1] cnt = 1 for i in range(1, len(S)): if S[i] > S[i-1]: cnt += 1 else: cnt = 1 res.append(cnt) return ' '.join([str(x) for x in res]) T = int(input()) for t in range(1, T + 1): N = int(input()) S = input() res = f(S) print(f"Case #{t}: {res}")
Java
UTF-8
2,619
3.140625
3
[]
no_license
package com.meng.juc; import org.junit.Test; import java.util.concurrent.*; public class testxianhaolaing { /* * dountwatchdown test * * */ @Test public void test1() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(3); /*所有线程都运行完成才继续主线程*/ for (int i = 0; i < 3; i++) { new Thread(() -> { countDownLatch.countDown(); }).start(); } countDownLatch.await(); System.out.println("over"); } public static void test2() throws BrokenBarrierException, InterruptedException { CyclicBarrier cyclicBarrier = new CyclicBarrier(3); for (int i = 0; i < 2; i++) { new Thread(() -> { try { System.out.println(1); Thread.sleep(2000); cyclicBarrier.await(); System.out.println("好"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } new Thread(() -> { try { System.out.println("last"); Thread.sleep(5000); System.out.println("我来晚了抱歉我"); cyclicBarrier.await(); System.out.println("see you"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); System.out.println("main结束"); } public static void main(String[] args) throws BrokenBarrierException, InterruptedException { test3(); } public static void test3() { /*信号量*/ Semaphore semaphore=new Semaphore(3); for (int j=0;j<4;j++) { new Thread(() -> { for (int i = 0; i < 3; i++) { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "come in"); TimeUnit.SECONDS.sleep(10); semaphore.release(); System.out.println(Thread.currentThread().getName() + "come out"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } }
Python
UTF-8
235
3.3125
3
[]
no_license
def iterate(iterable): while True: for i in iterable: yield i def cycle(iterable): for i in iterate(iterable): print(i) def main(): cycle(range(0, 5)) if __name__ == '__main__': main()