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
Python
UTF-8
1,328
2.890625
3
[]
no_license
from requests_html import HTMLSession class Website: __proto = 'HTTP' def __init__(self, url): self.url = url self.domain = url.split('/')[2] def print_something(self): print('AAAAAAAAAAAAAAA') print('This is Website!') def print_title(self): with HTMLSession() as session: self.response = session.get(self.url) print('TITLE: ', self.response.html.xpath('//title')[0].text) class Shop(Website): def print_price(self): print('PRICE: ', 100500) def print_something(self): print('00000000000000000000') print('00000000000000000000') print('00000000000000000000') print('00000000000000000000') class SearchEngine(Website): def position(self, keyword, domain): with HTMLSession() as session: resp = session.get( f'{self.url}/search?q={keyword}&num=100&hl=en') links = resp.html.xpath('//div[@class="r"]/a[1]/@href') for position, url in enumerate(links, start=1): if domain in url: print(f'Position for keyword: {keyword} ({domain}) is {position}') py4you = Website('https://py4you.com/') rozetka = Website('https://py4you.com/') moyo = Shop('https://moyo.ua/') google = SearchEngine('https://google.com.ua/')
Markdown
UTF-8
10,202
2.859375
3
[]
no_license
--- MySQL基础 --- 1. ## MySQL基本概念 1. #### MySQL驱动是什么东西? 1. 访问数据库则进行网络连接 2. 这个网络连接则需要由MySQL驱动创建 3. 基于网络连接建立各种CRUD操作 2. #### 数据库连接池解决了什么问题? 1. 当并发过高时候,如果此时只有一个数据库连接,多个线程抢占一个数据库连接,肯定会导致效率低下 2. 如果每个请求去访问数据库都创建一个连接,使用后进行销毁,那么创建和销毁线程的开销过大,会导致程序效率低下 3. 故引进连接池,需要的时候从池里取,不需要的时候放回池里 3. #### 数据库连接池是用来干什么的? 1. 维护了server与DB之间的多个连接 2. 进行权限校验和验证 2. ### MySQL架构设计 ![](../imgs/MySQL基础架构.png) 1. ##### 用户发送请求到Tomcat过程 1. Tomcat收到请求后,获取连接池,将SQL通过连接池发送给MySQL 2. 把MySQL当黑盒来执行 MySQL的网络连接必须由线程来处理 2. ##### 有线程监听网络请求 3. ##### 取出网络请求的参数,交由SQL接口 4. ##### SQL接口 负责处理接口收到的SQL 5. ##### 查询解析器 让MySQL的储存引擎能够看得懂SQL 6. ##### 查询优化器: 1. 查询一个最优的查询路径 2. 针对编写的SQL生成查询路径树 3. 从里面选择一条最优查询路径 7. ##### 调用存储引擎接口,执行真正的SQL语句: 1. 数据库服务并不知道数据库是存放在哪里,数据管理都是由存储引擎进行控制的。 2. 故需要引入存储引擎: 按照要求、步骤去查询内存和缓存的数据,更新磁盘数据等。 8. ##### 执行器 1. 根据执行计划调用存储引擎接口 2. 根据优化器生成的一套执行计划,然后不停地调用存储引擎的各种接口,去执行SQL语句 ### InnoDB存储引擎的架构 #### InnoDB的存储结构 ![](../imgs/InnoDB写入流程.png) 1. ##### InnoDB会先查询数据是否存在,如果存在,直接加独占锁。如果不存在,则将磁盘里的数据读取到Buffer Pool进行缓存,并加独占锁 2. ###### undo日志文件,万一事务执行失败,还原数据: 保存了原始的数据,可以让事务执行失败的时候进行事务混滚 3. ##### 更新Buffer Pool中的缓存数据 1. 完成1、2两步之后,则开始更新缓冲池中的数据 2. 此时由于只更新了缓冲池中的数据,并未更新数据库文件中的数据,所以为脏数据 4. ##### Redo Log Buffer 万一系统宕机,避免数据丢失 1. 此时内存中的数据修改了,但文件中的未进行修改,宕机了怎么办? 2. 把内存中的修改写入一个Redo Log Buffer中去,也是一个内存缓冲区 5. ##### 事务未提交就宕机了怎么办? 此时如若宕机,由于数据仅写入了内存中,未写入文件磁盘中,所以此时宕机是无光紧要的。 6. ##### 提交事务的时候,将redo日志写入磁盘中 1. 此时会根据一定的策略把redo日志从redo log buffer中刷入文件系统里去,是通过innodb_flush_log_tx_commit这个参数要控制的. 2. 提交日志成功,redo日志肯定会出现在磁盘上,所以如果此时宕机,buffer pool的数据刷入失败,InnoDB也可以从redo日志中导入恢复数据 3. 如果此值是2,提交的时候会把redo日志先写入磁盘文件对应的系统缓存(OS Cache)中去,可能隔一秒或数秒才刷入磁盘中去。 4. 如果此值是1,则代表事务提交得立即刷入磁盘中 5. 值是0,则代表不写入磁盘 7. #### binlog日志是什么东西? 1. ##### 日志分类 - 重做日志: 对哪个数据也的什么记录,做了个什么修改,如redo日志。 - 归档日志:记录的是偏向逻辑型的日志,如对name做了更新操作,值是xx。 2. MySQL属于自己的日志文件,不是属于存储引擎 3. 存储引擎在提交日志的时候,同时会写入binlog日志 8. #### 执行器的作用以及顺序 1. 将磁盘数据加载数据到Buffer Pool,并加独占锁 2. 将数据写入undo log日志,更新Buffer Poo 3. 将更新写入redo log buffer中,并根据配置刷入磁盘中 4. 写入binlog日志 9. #### binlog日志的刷盘策略 1. 有个sync_binlog参数,默认值是0 2. 为0的情况下,为先写入os cache,再刷入磁盘中 3. 为1的情况下,会在踢脚事务的时候,强制写入磁盘中去 10. #### 基于bin log日志和redo log日志完成事务的提交 1. 完成binlog日志写入后,就会完成最终的事务提交,此时会把本次更新对应的binlog文件名和更新binlog日志的位置,都写入到redo log文件里去。 2. 然后给redo log文件加上commit标识符 3. commit标识符是用来表示redo log日志和binlog日志的一致性的,仅有redo log和binlog都写入成功了,且数据都为一致性的,才代表成功了。 11. #### 后台随机讲内存的脏数据刷入到磁盘中 1. MySQL后台有一定的线程,会随机讲修改后的数据刷入到磁盘中 2. 在刷入前宕机: 重启后会根据redo日志恢复之前提交的事务,将做过的修改加载到内存中去 ### MySQL生产环境部署 1. #### 一般需要什么环境的机器? 1. 如果只有几百上千人的系统,那么什么机器影响不大。 2. Java服务器,如果4C8G,每秒大概能承受500左右并发量。只是个大概,与每个请求的请求时间有关。 3. MySQL通常使用8C16G,甚至使用16C32G机器 4. Java系统的主要压力和负担都是集中在MySQL数据库上,所以数据库往往是负载最高的。 5. 8C16G通常扛一两千并发是没问题 6. 16C32G通常扛三四千并发是没问题 7. 磁盘最好为SSD 2. #### 互联网公司的生产需求? 1. ##### 应该首先要进行数据库规划,清楚大概有多少压力 2. ##### MySQL应该让DBA去安装,DBA会增加一些MySQL调优参数、Linux内核调优参数等。 3. ##### 应该进行压测 需要进行基准测试,如模拟1000请求,观察机器cpu负载、磁盘IO、网络负载、内存负载情况等。 4. ##### QPS和TPS 1. QPS: Query Per Second 即数据库每秒可以处理多少个请求,大致理解为数据库每秒能处理多少个SQL 对于一个由多个服务组成的系统,每秒能接收的并发数为QPS 2. TPS Transaction Per Second 即每秒处理的事务量,即提交+回滚的事务,一般一个事务包含多个SQL 每秒能完成多少笔交易为TPS的概念,一个请求多个子系统的请求调用 5. ##### IO压测性能的指标: 1. IOPS: 机器随机IO并发能力,即随机读写能力(太慢影响随机输啊盘速度) 2. 吞吐量 磁盘存储每秒可读多少字节的数据量。(影响事务提交的时候redo日志的顺序读写) 3. Latency往磁盘写入一条数据的延时 提交时需顺序写入redo log,故写入时间延迟与事务时间正相关 6. ##### 其他性能指标 1. CPU负载 2. 网络负载 3. 内存负载 3. ### 数据库压测 1. #### 压测工具: sysbench功能 1. 帮助构造大量数据 2. 模拟几千个线程并发访问数据库 3. 包括模拟出各种事务提交到数据库的场景 4. 可以模拟出几十万TPS的压测场景 2. #### 压测模式 1. oltp_read_only模式: 只读性能测试 2. oltp_read_writer模式: 综合性能测试 3. oltp_delete模式: 删除性能测试 4. oltp_update_index模式: 更新使用索引性能测试 5. oltp_update_none_index模式: 更新不使用索引性能测试 6. oltp_insert: 插入性能测试 7. oltp_write_only: 写入性能测试 3. #### 线程: 1. 初始的时候可用10,然后逐渐地增加线程数,让其承载更高的QPS,一直到极限 4. #### 机器的其他性能, 在逐渐的加大线程时,查看硬件性能指标 5. #### 如何观察硬件性能指标? 1. ##### CPU性能: TOP命令的第一行 top - 15:00:00 up 42:35 , 1 user , load average : 0.15 , 0.05 , 0.01 - 42:35 -> 机器的运行时间 - 1 user -> 一个用户在使用 - load average 0.15 , 0.05 , 0.01 第一个数值代表CPU在一分钟的负载情况 , 第二个是五分钟,第三个是15分钟 。此值是最大值为 cpu的核心数 2. ##### 内存负载情况: 也为TOP命令 Men: 3G total , 2G userd , 1.2G free , 0.3G buffers - total -> 总内存空间 - userd -> 已使用内存空间 - free -> 空闲空间 - buffers -> os内核缓冲区空间 3. ##### 磁盘IO情况: dstat -d 命令或 dstat -r 命令 -ask/total | read | writer | | ---- | ------ | | 103k | 211k | | 0 | 11k | 上述数据代表每秒读103K ,写211k -io/total | read | write | | ---- | ----- | | 0.25 | 31.9 | | 0 | 253 | 上述代表读的IOPS和写的IOPS 4. ##### 网卡流量使用情况: dstat -n命令 -net/total | recv | send | | ---- | ---- | | 16k | 17k | 每秒网卡接收到流量有多少k,发送多少k。 千兆网卡一般传输速度在100M左右 6. #### 生产环境数据库部署方案: 1. ### 不能让数据库裸奔 需对数据库进行监控,如cpu、内存、网络、磁盘IO、慢查询、QPS等 2. ### 可视化监控平台 - Promethus: 监控数据采集系统 - Grafana: 将采集后的数据组成一些报表,供可视化监控展示
Java
UTF-8
331
2.78125
3
[]
no_license
package com.demo; public class Employee { private String name; private int age; public Employee(String name, int age){ this.name = name; this.age = age; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { return true; } }
Java
UTF-8
1,121
2.28125
2
[]
no_license
package com.hcl.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hcl.dao.TskRepository; import com.hcl.exception.FailedDatabaseActionException; import com.hcl.model.Task; @Service public class TaskService { @Autowired private TskRepository repo; public boolean saveTask(Task tsk) throws FailedDatabaseActionException { try { repo.save(tsk); return true; } catch (Exception e) { throw new FailedDatabaseActionException("Couldn't insert to database... check your connection", e); } } public List<Task> findAllTasks() { return (List<Task>) repo.findAll(); } public Optional<Task> findTaskById(long id) { return repo.findById(id); } public boolean deleteTask(Task tsk) throws FailedDatabaseActionException { try { repo.delete(tsk); return true; } catch (Exception e) { throw new FailedDatabaseActionException("Couldn't delete from database... check your connection", e); //System.out.println("Couldn't delete"); //return false; } } }
Python
UTF-8
1,016
4.5
4
[]
no_license
""" While Loop Disadvantage: infinite loop! """ #start, condition-boundary, manage! l=list(range(10)) for number in l: if number%2==0: print("\tNumber ",number," is Even") else: print("\tNumber ",number," is ODD") print("For ended!! ",number) #---------- number=0 while number <= 10: #performs the Loop until given condition is satisfied print("Number : ",number) if number%2==0: print("\tNumber ",number," is Even") else: print("\tNumber ",number," is ODD") number= number+1 #number+=1 print("While ended!! ",number) #Infinite Loop with while print("\n Enter 'quit' to terminate the Loop") condition = True attempt=1 while condition: #true print("Attempt No:",attempt) name = input("\tEnter your Name : ") if name=='quit': print("\n\t Loop is Ending now..."); condition = False # can use 'break' else: print("\tName Entered : ",name) attempt+=1 else: #While Else print("Completed While")
Markdown
UTF-8
2,425
2.5625
3
[]
no_license
xState ====== A state machine editot and runtime. Can be used to model simple workflow # 简介 xState编辑器是一个允许开发人员创建状态机的编辑器,通过通用直观的解决方案。 ![overview](https://oscimg.oschina.net/oscnet/up-77a64e69d1d009af7b0731da86f5957c5c5.png) # 适用场景 状态机用处极其广泛,适用于订单,用户,任务等等具有确定状态的领域模型 # 特点 1. 结合模型和代码 1. 可以创建仅包含状态和变迁的状态机 1. 也可以提供状态变迁时的触发器 # 状态转移触发器 1. EntryAction 1. ExitAction 1. TransitionAction ## 状态转移校验 1. TransitionGuard ![event](https://oscimg.oschina.net/oscnet/up-0a97e778c0ff0e6ccab32610baf42ae17ca.png) # 使用范例 模型可以被工具用于在运行时触发状态转移 ![sample](https://oscimg.oschina.net/oscnet/up-9d8a27d0b887bbe2ee3bcbd018ea2a9cea5.png) # 如何传递业务属性 有些时候需要传递业务信息给状态机的各个触发器做判断,虽然缺省的Event类里面没有这些属性,但由于Event 是个普通类,用户可以自定义自己的Event子类,在子类里面定义需要的业务属性。允许时可以在各个Action里面cast 标准的Event 为你自定义的Event类即可获得额外的属性。 # 如何恢复状态机之前的状态 有时需要保存状态机的当前状态,并在之后恢复。可以通过调用StateMachine的restore(String id),传入需要恢复的状态id实现。 # 如何重置状态机 在状态机没有处于End状态的情况下,可以通过调用reset()方法重置状态机的状态。 # 集成说明 [参考样例POM](https://github.com/hejiehui/xState/blob/master/com.xrosstools.xstate.sample/pom.xml) Depenency <dependency> <groupId>com.xrosstools</groupId> <artifactId>xstate</artifactId> <version>${latest}</version> </dependency> # Demo project [Demo](https://github.com/hejiehui/xState/tree/master/com.xrosstools.xstate.sample) # 实际案例 ## 简单状态机 ![uc1](https://oscimg.oschina.net/oscnet/up-4350f7ca0b4c7e41f9eff16246453d58e52.png) ## 复杂状态机 ![uc2](https://oscimg.oschina.net/oscnet/up-106c0d586ba63d2a3dadf7b8310dfc4bc19.png) ## 携程金服案例 [基于xstate实现携程金服业务流程动态化](https://my.oschina.net/hejiehui/blog/1574335)
Java
UTF-8
1,782
2.46875
2
[]
no_license
package persistence.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.postgis.PGgeometry; import persistence.hibernate.HibernateConfig; import persistence.util.Coordinates; public class SpatialQueries { private Connection dbConn; private double distance; public SpatialQueries(){ this.distance = 0.018045289547661728; try { dbConn = ConnectionFactory.newConnection(); } catch (SQLException e) { e.printStackTrace(); } } public int qteOfNearPOIByType(Coordinates coordenates, String type) throws SQLException{ int qte = 0; qte += qteNear(coordenates, type, "points"); qte += qteNear(coordenates, type, "lines"); qte += qteNear(coordenates, type, "polygons"); return qte; } public void setDistance(double distance){ this.distance = distance; } private int qteNear(Coordinates coordenates, String type, String table) throws SQLException{ String pointString = "POINT(" + coordenates.getLatitude() + " " + coordenates.getLongitude() + ")"; String query = "SELECT location " + "FROM larbc_db." + HibernateConfig.getCurrentSchema() + "." + table + " p " + "WHERE ST_Distance(location, GeomFromText('" + pointString + "', -1)) <= "+ distance + " AND " + "p.type = '" + type + "' AND NOT equals(p.location, GeomFromText('" + pointString + "', -1));"; PreparedStatement s = dbConn.prepareStatement(query); ResultSet rs = s.executeQuery(); List<PGgeometry> pgGeometries = new ArrayList<PGgeometry>(); while(rs.next()){ pgGeometries.add((PGgeometry) (rs.getObject("location"))); } return pgGeometries.size(); } }
Java
UTF-8
2,540
2.265625
2
[]
no_license
package au.com.carsguide.pages; import au.com.carsguide.utility.Utility; import com.cucumber.listener.Reporter; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class SearchCarsPage extends Utility { private static final Logger log = LogManager.getLogger(SearchCarsPage.class.getName()); @FindBy(xpath = "//select[@id='makes']") WebElement _selectMake; @FindBy(xpath = "//option[@data-gtm-label = \"make\"]") WebElement _make; @FindBy(xpath = "//select[@id='models']") WebElement _selectModels; @FindBy(xpath = "//select[@id='locations']") WebElement _selectLocation; @FindBy(xpath = "//select[@id='priceTo']") WebElement _selectPrice; @FindBy(xpath = "//input[@id='search-submit']") WebElement _submitFindMyNextCar; //This method will select car brand public void selectMakeOfCar(String carMaker) { Reporter.addStepLog("Select car brand : " + _selectMake.toString() + "<br>"); log.info("Select car brand : " + _selectMake.toString()); selectByValueFromDropDown(_selectMake, carMaker); } //This method will select car model public void selectModelOfCar(String carModel) { Reporter.addStepLog("Select car model : " + _selectModels.toString() + "<br>"); log.info("Select car model : " + _selectModels.toString()); selectByValueFromDropDown(_selectModels, carModel); } //This method will select location of searched car public void selectLocationOfCar(String location) { Reporter.addStepLog("Select car location : " + _selectLocation.toString() + "<br>"); log.info("Select car location : " + _selectLocation.toString()); selectByValueFromDropDown(_selectLocation, location); } //This method will select maximum price of car you wish to buy public void selectPriceOfCar(String price) { Reporter.addStepLog("Select maximum price : " + _selectPrice.toString() + "<br>"); log.info("Select car maximum price : " + _selectPrice.toString()); selectByVisibleTextFromDropDown(_selectPrice, price); } //This method will submit your search criteria of car public void submitFindMyNextCar() { Reporter.addStepLog("Submit search criteria : " + _submitFindMyNextCar.toString() + "<br>"); log.info("Submit search criteria : " + _submitFindMyNextCar.toString()); clickOnElement(_submitFindMyNextCar); } }
JavaScript
UTF-8
4,064
2.9375
3
[]
no_license
var player; var intv; var slider; //Init //////////////////////////// window.onload = function() { document.getElementById('btnPlay').addEventListener('click', playMusic, false); document.getElementById('btnPause').addEventListener('click', pauseMusic, false); document.getElementById('btnStop').addEventListener('click', stopMusic, false); document.getElementById('btnVolUp').addEventListener('click', volUp, false); document.getElementById('btnVolDown').addEventListener('click', volDown, false); player = document.getElementById('player'); slider = document.getElementById('sliderTime'); slider.addEventListener('change', reposition, false); getMusicList(); } function reposition() { player.currentTime = slider.value; } //Volume Controls // 0.0 Silent - 1.0 Full Volume ///////////////////////////// function volUp() { if(player.volume < 1) { player.volume += 0.1; console.log(player.volume); } else { player.volume = 1; } } function volDown() { if(player.volume > 0) { player.volume -= 0.1; console.log(player.volume); } else { player.volume = 0; } } //Music Play Controls /////////////////////////// function playMusic() { player.play(); intv = setInterval(update, 100); slider.max = player.duration; } function update() { document.getElementById('songTime').innerHTML = millisToMins(player.currentTime); slider.value = player.currentTime; } function millisToMins(seconds) { var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60); var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60; if (numseconds >= 10) { return "Time Elapsed: " + numminutes + ":" + Math.round(numseconds); } else { return "Time Elapsed: " + numminutes + ":0" + Math.round(numseconds); } } function pauseMusic() { player.pause(); clearInterval(intv); } function stopMusic() { player.pause(); player.currentTime = 0; clearInterval(intv); } function getMusicList() { var parser = new DOMParser(); xmlDocument = parser.parseFromString(xml, "text/xml"); var elementsArray = xmlDocument.documentElement.getElementsByTagName('composition'); var arrayLength = elementsArray.length; var output= "<table>"; for(var i=0; i < arrayLength; i++) { var title = elementsArray[i].getElementsByTagName('title')[0].firstChild.nodeValue; var composer = elementsArray[i].getElementsByTagName('composer')[0].firstChild.nodeValue; var time = elementsArray[i].getElementsByTagName('time')[0].firstChild.nodeValue; var fileName = elementsArray[i].getElementsByTagName('filename')[0].firstChild.nodeValue; output += "<tr>"; output += ("<td onclick='songSelect(\"" + fileName + "\")'>" + title + "; By: " + composer + "; </td>"); output += "</tr>" } output += "</table>"; document.getElementById('musicList').innerHTML = output; } function songSelect(fn) { //console.log(fn); document.getElementById('player').src = fn; playMusic(); } function floatLeft() { document.getElementById("sliderTime").style.cssFloat = "left"; }
Markdown
UTF-8
4,762
2.875
3
[]
no_license
#includ<stdio.h> void main(){ InitStack(S); InitQueue(Q); printf(" \n"); printf(" \n"); printf(" 欢迎进入停车场系统\n"); printf(" **********************************************\n"); printf(" 1 新车到来 \n"); printf(" 2 车离开 \n"); printf(" 3 查看车场信息 \n"); printf(" 4 查看便道信息 \n"); printf(" # 退出 \n"); printf(" 计科高职13-3:齐工合伙人 \n"); printf(" **********************************************\n"); char cc; cc=' '; while(cc!='#'){ printf("请选择操作: "); cc=getchar(); getchar(); switch (cc){ case'1': Car_Come(S,Q);break; case'2': Car_leave(S,Q);break; case'3': seeStack(S);break; case'4': seeQueue(Q);break; case'#': break; default:{printf("选择不正确!请重新选择!\n"); continue; } } } } void seeStack(SqStack S){ if(StackEmpty(S)==-1){ printf("站内没有车! \n"); return; } else{ while(StackEmpty(S)!=-1){ Pop(S,tempCar); printf("%d 位置:%-10s 进站时间:%d\n",S.top,tempCar.carLicense,tempCar.time); } } printf("------------------------------------------- \n"); } void seeQueue(LinkQueue Q){ if(QueueEmpty(Q)==-1){ printf("便道内没有车! \n"); return; } else{ InitQueue(tempQ); printf("便道内车辆: \n"); while(QueueEmpty(Q)!=-1){ DeQueue(Q,tempCar); printf(" %s \n",tempCar.carLicense); EnQueue(tempQ,tempCar.carLicense); } //重新进队列 while(QueueEmpty(tempQ)!=-1){ DeQueue(tempQ,tempCar); EnQueue(Q,tempCar.carLicense); } } printf("------------------------------------------- \n"); void Car_Come(SqStack &S,LinkQueue &Q){ printf("新车到来:\n"); printf("输入车牌号:"); scanf("%s",&tempCar.carLicense); if(StackFull(S)==-1){ EnQueue(Q,tempCar.carLicense); printf("此车辆已进入便道!\n"); } else{ printf("输入车进入停车场时间:"); scanf("%d",&tempCar.time); getchar(); Push(S,tempCar.carLicense,tempCar.time); printf("在停车场中的位置: %d\n",(S.top-1)); } printf("----------------------------"); } void Car_leave(SqStack &S,LinkQueue &Q) { int d,come_time=0; char car_license[15]; printf("车辆离开车站:"); printf("请输入要离开车辆的位置:"); scanf("%d",&d); if(StackEmpty(S)==-1){ return; } else{ if(d<S.top){ InitStack(tempS); while(S.top!=(d+1)){ Pop(S,tempCar); Push(tempS,tempCar.carLicense,tempCar.time); } Pop(S,tempCar); come_time=tempCar.time; printf("输入车离开时间:"); scanf("%d",&tempCar.time); printf("%s 已经离开!\n",tempCar.carLicense); printf("离开时间:%d\n",tempCar.time); printf("费用:%d \n",unit_price*(tempCar.time-come_time)); //重新进栈 while(StackEmpty(tempS)!=-1){ Pop(tempS,tempCar); Push(S, tempCar.carLicense,tempCar.time); } if(QueueEmpty(Q)==-1){ return; } else{ DeQueue(Q,tempCar); printf("%s 进站\n",tempCar.carLicense); printf("输入车进站时间:"); scanf("%d",&tempCar.time); Push(S,tempCar.carLicense,tempCar.time); printf("在停车场中的位置: %d\n",(S.top-1)); } } printf("----------------------------"); } void InitStack(SqStack &S){ S.elem=(CarType *)malloc((N+1)*sizeof(CarType)); if(S.elem==NULL) return; S.top=0; } int StackEmpty(SqStack S){ if(S.top==0) return -1; } int StackFull(SqStack S){ if(S.top==N) return -1; } void GetTop(SqStack S,CarType &e){ if(S.top==0) return; e=S.elem[S.top-1]; } void Push(SqStack &S,char *ch,int time){ if(S.top<N+1){ strcpy(S.elem[S.top].carLicense,ch); S.elem[S.top].time=time; S.top++; } } void Pop(SqStack &S,CarType &eCar){ if(S.top==0) return; --S.top; strcpy(eCar.carLicense,S.elem[S.top].carLicense); eCar.time=S.elem[S.top].time; } void InitQueue(LinkQueue &Q){ Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode)); if(Q.front==NULL) return; Q.front->next=NULL; }li int QueueEmpty(LinkQueue Q){ if(Q.front==Q.rear) return -1; } void EnQueue(LinkQueue &Q,char *ch){ p=(QueuePtr)malloc(sizeof(QNode)); if(p==NULL) return; strcpy(p->data.carLicense,ch); p->next=NULL; Q.rear->next=p; Q.rear=p; } void DeQueue(LinkQueue &Q,CarType &eCar){ if(Q.front==Q.rear) return; p=Q.front->next; strcpy(eCar.carLicense,p->data.carLicense); Q.front->next=p->next; if(Q.rear==p) Q.rear=Q.front; free(p); }
Python
UTF-8
2,312
3.21875
3
[]
no_license
import csv from utils import settings def get_features(): with open(settings.BALABIT_FEATURES_INPUT, 'r') as csv_file: data_reader = csv.reader(csv_file, delimiter=',') user_ids = ['7', '9', '12', '15', '16', '20', '21', '23', '29', '35'] row = next(data_reader) row = next(data_reader) data = [] for i in range(0, len(user_ids)): user_id = user_ids[i] counter = 0 traveled_distance = 0 elapsed_time = 0 length_of_line = 0 largest_deviation = 0 while row[-1] == user_id: counter += 1 traveled_distance += float(row[1]) elapsed_time += float(row[2]) length_of_line += float(row[3]) largest_deviation += float(row[4]) try: row = next(data_reader) except StopIteration: data_row = [user_id, counter, traveled_distance / counter, elapsed_time / counter, length_of_line / counter, largest_deviation / counter] data.append(data_row) return data print(counter) print(elapsed_time) print('travel' + str(traveled_distance/counter)) data_row = [user_id, counter, elapsed_time/60, traveled_distance/counter, length_of_line/counter, largest_deviation/counter] data.append(data_row) return data def create_table(data): with open(settings.BALABIT_FEATURES_OUTPUT, 'w', newline='') as csv_file: data_writer = csv.writer(csv_file, delimiter=',') header = ['Felhasználó', 'Műveletek száma', 'Átlagos eltelt idő', 'Átlagos megtett út', 'Átlagos vonalhossz', 'Átlagos legnagyobb eltérés'] header = ['Felhasznalo', 'Muveletek szama', 'Eltelt ido', 'Atlagos megtett ut', 'Atlagos vonalhossz', 'Atlagos legnagyobb elteres'] data_writer.writerow(header) for i in range(len(data)): row = data[i] data_writer.writerow(row) def main(): data = get_features() print(data) print(len(data)) create_table(data) main()
Java
UTF-8
3,377
2.546875
3
[]
no_license
package pangame; import Display.Visual; import Graphic.Assests; import Graphic.Camera; import Input.Keymanager; import Input.MouseManager; import State.State; import State.GameState; import State.Menu; import State.Endgame; import java.awt.*; import java.awt.image.BufferStrategy; public class Game implements Runnable { private Thread thread; private Visual visual; private Boolean running = false; private BufferStrategy bs; private Graphics g; public State gamestate; public State MenuState; public State endgame; private Keymanager keyManager; private Camera camera; private Handler handler; private MouseManager mousemanager; public Game() { keyManager = new Keymanager(); mousemanager = new MouseManager(); } private void init() { visual = new Visual(); Assests.init(); handler = new Handler(this); camera = new Camera(handler,0,0); visual.getjframe().addKeyListener(keyManager); visual.getjframe().addMouseListener(mousemanager); visual.getjframe().addMouseMotionListener(mousemanager); visual.getcanvas().addMouseListener(mousemanager); visual.getcanvas().addMouseMotionListener(mousemanager); gamestate = new GameState(handler); MenuState = new Menu(handler); endgame = new Endgame(handler); MenuState.setman(); State.setstate(MenuState); } private void tick() { keyManager.tick(); if (State.getstate() != null) { State.getstate().tick(); } } private void render() { bs = visual.getcanvas().getBufferStrategy(); if (bs == null) { visual.getcanvas().createBufferStrategy(3); return; } g = bs.getDrawGraphics(); g.clearRect(0,0, 800, 600); if (State.getstate() != null) { State.getstate().render(g); } bs.show(); g.dispose(); } public void run(){ init(); int fps = 60; double timepertick = 1000000000/fps; double delta = 0; long now; long lasttime = System.nanoTime(); while(running) { now = System.nanoTime(); delta += (now - lasttime)/timepertick; lasttime = now; if (delta >= 1) { tick(); render(); delta--; } } stop(); } public synchronized void start() { if (running) { return; } running = true; thread = new Thread(this); thread.start(); } public synchronized void stop(){ if (!running) { return; } try { thread.join();; } catch (InterruptedException e) { e.printStackTrace(); } } public Keymanager getKeyManager() { return keyManager; } public MouseManager getMousemanager() { return mousemanager;} public Camera getCamera() { return camera;} public int getwidth() { return visual.getcanvas().getWidth(); } public int getheight() { return visual.getcanvas().getHeight();} public GameState getgamestate() { return (GameState) gamestate; } private String sep = System.getProperty("file.separator"); }
Java
UTF-8
920
1.976563
2
[]
no_license
package com.forezp.phoenix.service; import com.forezp.phoenix.dao.ProcessDataMapper; import com.forezp.phoenix.domain.ProcessData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by fangzhipeng on 2017/4/20. */ @Service public class ProcessDataService { @Autowired private ProcessDataMapper processDataMapper; public List<ProcessData> findByRowKey(String rowkey) { return processDataMapper.findByKey(rowkey); } public List<ProcessData> findByCondition(String lineNo,String cabNo,String cellNo,String channelNo,String time1,String time2){ return processDataMapper.findByMultipleConditions(lineNo,cabNo,cellNo,channelNo,time1,time2); } public List<ProcessData> findByTime(String time1,String time2){ return processDataMapper.findByTime(time1,time2); } }
Markdown
UTF-8
7,892
3.03125
3
[]
no_license
九二 曾国藩面无表情地听着,这些事他早已看得很清楚,一点都不感到意外。但这的确是一件棘手的事。这些首功将官们自恃功大,要价很高,朝廷的封赏既不能全部满足他们的欲望,又只是空衔而无实惠,现在要把他们围攻两三年,自以为靠性命换来的财产再掏出来,这无异于挖他们的心肝。真的闹起事来,后果不堪设想。“老九,你要说服他们顾全大局,不管多少都要拿出一些,一则好向朝廷交代,二则也要堵塞天下悠悠之口。” “杀人放火,我可以指挥他们干,要他们拿出自己的性命钱,我做不到。况且我也不干,我的银子就已经运走了。” “九帅,你一碗水没有端平!” 曾国荃正要说下去,门口突然传进一声雷似的吼叫,只见焕字营营官朱洪章喝得醉醺醺地满口吐着白沫,两眼红通通地睁得如铜铃般大,跌跌撞撞地冲了进来,后面跟着几个亲兵。 “焕文!”曾国藩拉长着脸,十分不快地对朱洪章说,“你看你醉成什么样子!” “中堂大人。”朱洪章这时才发觉曾国藩也在,顿时清醒了点,“第一个冲进城的,不是李臣典,而是我朱某人!” “这话怎讲?”曾国藩感到奇怪,都说康福死后,李臣典是第一个冲进金陵城的,为何又变成了朱洪章? “中堂大人。”朱洪章用手抹去嘴边的白沫,两脚也站直了些,以略为恭顺的态度说,“六月十六日上午,龙脖子地道第二次挖成,点火前,九帅集合各营营官,议决谁为攻城先锋,大家都畏葸不敢领命,是我出队领下了先锋之命,并立了军令状,这事九帅应该还记得。后来我率焕字营一千五百兄弟从城墙缺口冲入,第一个进了金陵,九帅还称赞我有能耐。” “照这样说,应当是焕文第一个进城了。”曾国藩问弟弟。 “是的。”曾国荃点头。 “那又为何是李臣典呢?”曾国藩大惑不解。 “中堂大人,事情是这样的。”朱洪章抢着说,“龙脖子地道是信字营挖的,李臣典虽未第一个进城,但却是最先打到天王宫,说李臣典是第一号功臣,我并没有意见,但现在萧孚泗倒排在我的前面,抢得了男爵,这能使我服气吗?娘的,攻城时他向后退,领赏时他往前冲,他聪明,老子是蠢崽。” 朱洪章又喷出白沫来,他死命地吐了一口痰,愤愤不平地嚷道,“九帅,你这样压我,难道因为我朱洪章是贵州人,不是湘乡人吗?” “朱洪章,你在放狗屁!”曾国荃猛地从床上跳起,“哪个因你不是湘乡人压了你,我是把你列在萧孚泗前面的。” “那又是谁把我的名字排到后头去了呢?这个狗日的,害得我得不到爵位。”朱洪章大叫起来,气焰更足了。 “明告诉你吧!那是中堂大人手下起草折子的彭寿颐改动的。”曾国荃说着,顺手将桌上一把腰刀甩到朱洪章的脚边。 腰刀与砖相碰,发出刺耳的撞击声,“你用这把腰刀把他杀了吧!” 朱洪章被这个突如其来的举动弄得不知所措,一时呆住了。 “你去杀呀!”曾国荃冲到朱洪章面前,像一头狂怒的饿虎,要把朱洪章一口吞下,“还站在这里干什么?不敢杀,你就给老子滚出去,狗杂种!”曾国荃的暴怒把朱洪章的气焰压了下去。他耷拉着脑袋,嘴里嘟嘟囔囔地出了门。 “大哥,你看看,就是这班人进了城!”望着朱洪章的背影,曾国荃气仍未消,“若不是刚才这一手,他几乎要坐到我和大哥的头上拉屎拉尿了。只有一个朱洪章还好对付,若是朝廷真的要追查金银,那就会有成千上万个朱洪章跳出来,你看怎么办?” 这个意外的插曲使得曾国藩又惊又恼。“湘军已经腐败了。”他在心里得出了结论。 “大哥。”曾国荃小声而神秘地呼唤,曾国藩觉得有点异样,“依我看,新的大乱就要到来,我们得先下手为强。” “你说什么?”新侯爵已觉察到新伯爵的反常。 “我们学他。”曾国荃伸出左手掌,右手在掌心上划出一个字来。曾国藩顺着他的手势看着看着,不觉屏息静气,最后紧张得连大气都不敢出一口。 原来,曾国荃在掌心上划出的是一个“赵”字。毫无疑问,这指的是陈桥兵变黄袍加身的宋朝开国皇帝赵匡胤。 “沅甫,你疯了!”曾国藩冷冷地看着因情绪激昂而红了脸的弟弟,生气地说。 “大哥。”曾国荃压低声音,焦急地说,“这桩事,打下安庆后我就想过了。我也晓得润芝、雪琴以及左宗棠都旁敲侧击试探过你,大哥那时不同意是对的,因为时机不到,而现在时机到了。吉字大营攻下长毛盘踞十多年的老巢,军威无敌于天下,所有八旗、绿营都不是我们的对手。现在朝廷要追查金银下落,吉字营上下怨声载道,正是我们利用的好时候。吉字大营五万,雪琴、厚庵水师两万,还有鲍春霆的两万,张运兰、萧启江的三万,这十二万人是大哥的心腹力量,再加上李少荃的淮军,只要大哥登台一呼,大家都会死心塌地跟着干。左宗棠要是不从,就干掉他!大哥,你把这支人马交给我,不出两年,我保证叫天下所有的人都向大哥拱手称臣。”曾国荃越说越得意忘形,曾国藩越听脸色越阴沉。曾国荃心想,大哥素来谨慎,这样的大事,他怎么会轻易作出决定,不做声,便是在心中盘算。他进一步撩拨,“大哥,大清立国以来,只有吴三桂、耿精忠几个汉人手里有过军队,这些军队一直是朝廷的眼中钉。后人都说吴三桂不安分造反,其实他们哪里知道,那是朝廷逼出来的。” 曾国藩心里猛一惊,觉得弟弟的话有道理,过去自己也是指责吴三桂的。也可能事实真的如沅甫所言,吴三桂造反是逼出来的。 “朝廷也在逼我们了。”曾国荃气得咬牙切齿,“走了一千多号人,与打下金陵相比算得了什么?如此声色俱厉地训斥,居心何在?口口声声追查长毛金银的下落,无非是说我们私吞了,好为将来抄家张本。大哥,这十二万湘军在你的手里,朝廷是食不甘味、寝不安神呀!飞鸟尽,良弓藏,狡兔死,走狗烹,想不到今日轮到我们兄弟了。”曾国荃长叹一声粗气后,恶狠狠地对着曾国藩说,“大哥,我们这是何苦来!百战沙场,九死一生,难道就是要做别人砧板上的鱼肉吗?盛四昨日对我讲,家里起新屋上大梁时,木匠们都唱:两江总督太细哩,要到北京做皇帝。又说当年太公梦的不是蟒蛇,而是一条龙,因怕官府追查,才谎说是蟒蛇。大哥。”曾国荃扯着曾国藩的衣袖口,紧张得说不出话来,好一会才慢慢地吐出,“满人气数已尽,你才是真正的真龙天子呀!” 曾国藩坐在对面,听着弟弟这一番令人毛骨悚然的心里话,仿佛觉得阴风阵阵,浑身发冷。他突然意识到不能让他无休止地说下去,这里面只要有一句话被人告发,就可能立即招来灭族惨祸。此时自己已被搅得心烦意乱,难以说服他。 办法只有一个,便是马上离开。 “老九,你今天情绪有点失常,可能是湿毒引起心里烦躁的缘故。你静下心来,好好躺着,我叫人来给你看看病。”说罢,不等曾国荃回答,便匆匆地走了。
Python
UTF-8
88
3.140625
3
[]
no_license
N=int(input()) k=int(input()) sum=0 for N in range(0:4): sum=sum+N print(N)
Java
UTF-8
586
2.421875
2
[]
no_license
package com.example.alexmao.tp2final.firebase; import java.util.ArrayList; import java.util.List; /** * Created by filou on 01/04/16. */ public class Events { private List<MeetingFinalChoice> meetings; public Events() { meetings = new ArrayList<>(); } public List<MeetingFinalChoice> getMeetings() { return meetings; } public void setMeetings(List<MeetingFinalChoice> meetings) { this.meetings = meetings; } public void addMeeting(MeetingFinalChoice meetingFinalChoice) { meetings.add(meetingFinalChoice); } }
Python
UTF-8
4,774
3.015625
3
[]
no_license
#!/usr/bin/env python from optparse import OptionParser import glob, sys import numpy as np from mirnylib import h5dict ########################################################################################### # get_interaction_matrix.py # # Hi-C data is binned into 40 kb sequences and there is an interaction matrix defined for # each bin. This script finds the bin any given feature of a BED file belongs to and prints # the interaction matrix associated with that bin. # # Currently, I am dividing each chromosome into bins and then finding the bin corresponding # to a particular feature by iteration. This isn't the optimal way to do things. Changing # this will substantially improve speed. ########################################################################################### def main(): usage = 'usage:%prog [options] <bed_file> <chrom_sizes> <normalized_matrices>' parser = OptionParser(usage) parser.add_option('-o', dest='out_file', default='bed_hi_c_matrices.txt', help='Output file to print normalized hi-c matrices for features in BED file [Default: %default]') parser.add_option('-b', dest='bin_size', type='int', default=40000, help='Bin Size used for calculating interaction matrices [Default: %default]') (options, args) = parser.parse_args() if len(args)!=3: parser.error('Must provide a BED file of features, sizes of the chromosomes and directory with the normalized matrices\n %s' %(usage)) else: bed_file = args[0] chrom_sizes = args[1] normalized_matrices = args[2] bin_size = options.bin_size out_file = open(options.out_file, 'w') if normalized_matrices[-2:] == 'hm': extract_from_heatmap(bed_file, normalized_matrices, out_file, bin_size) else: extract_from_matrices(bed_file, normalized_matrices, bin_size, out_file) def extract_from_heatmap(bed_file, normalized_matrices, out_file): heatmap = h5dict.h5dict(normalized_matrices, 'r') bin_size = heatmap['resolution'] for line in open(bed_file, 'r'): a = line.strip().split('\t') heatmap_key = '22 22' elif a[0] == 'chrY': heatmap_key = '23 23' elif a[0] == 'chrM': heatmap_key = '24 24' else: chrom_num = int(a[0][3:]) heatmap_key = ' '.join([str(chrom_num - 1), str(chrom_num - 1)]) start, end = int(a[1]), int(a[2]) bin_number = 1 pos = 1 while pos < end: bin_start = pos bin_end = pos + resolution - 1 pos += resolution bin_number += 1 print >> out_file, '\t'.join(map(str, list(heatmap[heatmap_key][bin_number]))) def extract_from_matrices(bed_file, normalized_matrices, bin_size, out_file): chrom_bins = make_chrom_bins(chrom_sizes, bin_size) print >> sys.stderr, 'Divided each chromosome into bins of %i bps' %(bin_size) interaction_matrices = get_interaction_matrices(normalized_matrices, bin_size) print >> sys.stderr, 'Finished storing all the interaction matrices into a hash table' print >> sys.stderr, 'Extracting normalized matrix for each feature in the bed file' print >> sys.stderr, 'This step is quite slow right now. Please wait...' for line in open(bed_file): a = line.strip().split() chrom, start, end = a[0], int(a[1]), int(a[2]) for bin_name in chrom_bins[chrom].keys(): bin_start = chrom_bins[chrom][bin_name][0] bin_end = chrom_bins[chrom][bin_name][1] bin_range = range(bin_start, bin_end + 1) if start in bin_range or end in bin_range: feature_bin = bin_name feature_matrix = interaction_matrices[chrom][feature_bin] print >> out_file, '\t'.join(feature_matrix) out_file.close() def make_chrom_bins(chrom_sizes, bin_size): chrom_bins = {} for line in open(chrom_sizes): a = line.strip().split() chrom = a[0] chrom_size = int(a[1]) chrom_bins[chrom] = {} i = 1 pos = 1 while pos < chrom_size: bin_name = 'bin_' + str(i) i += 1 bin_start = pos bin_end = pos + (bin_size - 1) pos += bin_size chrom_bins[chrom][bin_name] = [bin_start, bin_end] return chrom_bins def get_interaction_matrices(normalized_matrices, bin_size): interaction_matrices = {} if normalized_matrices[-1] == '/': normalized_matrices_files = glob.glob(normalized_matrices + '*.*') else: normalized_matrices_files = glob.glob(normalized_matrices + '/*.*') for file_name in normalized_matrices_files: a = file_name.strip().split('/')[-1].split('.') chrom = a[1] interaction_matrices[chrom] = {} i = 1 for line in open(file_name): bin_name = 'bin_' + str(i) bin_matrix = line.strip().split()[1:] interaction_matrices[chrom][bin_name] = bin_matrix i += 1 return interaction_matrices ########################################################################################### # main() ########################################################################################### if __name__ == '__main__': main()
Java
UTF-8
1,633
2.921875
3
[]
no_license
package com.zjkhzgm.echo; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; /** * @author zgm * @Description: * @Date 2018/10/7 9:37 */ public class EchoServerHandler extends ChannelHandlerAdapter { /** * 这里我们覆盖了chanelRead()事件处理方法。 每当从客户端收到新的数据时, 这个方法会在收到消息时被调用 * 这个例子中,收到的消息的类型是ByteBuf * * @param ctx 通道处理的上下文信息 * @param msg 接收的消息 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ctx.write(msg); ctx.flush(); } /** * 这个方法会在发生异常时触发 * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { /** * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用,即当 Netty 由于 IO * 错误或者处理器在处理事件时抛出的异常时。在大部分情况下,捕获的异常应该被记录下来 并且把关联的 channel * 给关闭掉。然而这个方法的处理方式会在遇到不同异常的情况下有不 同的实现,比如你可能想在关闭连接之前发送一个错误码的响应消息。 */ // 出现异常就关闭 cause.printStackTrace(); ctx.close(); } }
Markdown
UTF-8
3,026
2.9375
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "流程审批系统测试经验" subtitle: "" date: 2016-06-27 author: "Tesla9527" header-img: "img/home-bg-o.jpg" catalog: true tags: - 工作 --- > 从去年开始一直测试流程审批系统,也算是对流程系统的测试有了一些经验,总结了下,如果能做好以下几点,能够让测试 工作做的更加高效和自信。 ## 需求整理 #### 需求文档管理(OneDrive) 文档真的是一个蛮贵重的东西,OneDrive提供30G的免费空间,用来管理文档是再好不过的。而且能实时备份到云端,防止文档丢失。 #### 需求疑问点整理(Teambition) 其实就在对应的需求文档里写出疑问点也可以,但是如果文档一多,再去找用户确认需求的时候难免会遗忘一些东西。如果用Teambition 来集中管理疑问点,这些疑问点得到客户的回复后,再将这些答复在对应的需求文档里面做记录,就会比较好。这样就做到了需求 的正确性,而且也做到了需求集中管理,需求疑问点集中管理。 ## 测试用例设计和执行 对于流程审批系统,最关键的2点是流程走向和表单字段验证。有一段时间我觉得用Excel来管理这些用例会比较好,因为能清晰地将测试步骤 整体地展示。但是现在觉得还是用TFS来管理用例的设计比较好,每一个流程建立一个测试套件,然后再在里面分流程走向和表单验证这2大类 来管理。流程走向中在标题上将用例场景描述清楚,步骤中将每一步审批写好,类似于流程审批记录。用例执行完之后也能很方便地看出整体的测试结果。 每一个流程在设计时,可以用Excel把各种条件组合画出来,决定有几种走向,这样再回过头来看这个流程设计的时候,能够一下子了解到覆盖的场景。 ## Bug管理 微软在软件测试方面做的确实不错,用了这么多bug管理工具,个人觉得还是用TFS来管理bug最好,一方面能集中的根据项目来管理bug,另外一方面也能 通过Charts一目了然地了解到Bug走势以及当前bug状态。需要记住的一点是,在做项目的过程中,不论是客户提的bug还是开发发现的bug,都要整理后统一记录 到TFS里面来,要不然过后很容易忘记,而且有一个实实在在的bug单,能更好地促进开发去修复bug。 下面是自己建的几个chart,效果感觉还不错。 ![img](/img/in-post/Tfs-Bug-Charts.jpg) ## 提高测试效率的一些SQL 流程被审批之后,审批路径比较长,在验证一些问题的时候,需要重新发起申请并走到这个节点,这样非常浪费时间。如果这个时候能够 利用SQL查出来对应的审批记录,并将审批状态回退,这样就能节省大量的时间。另外也需要一个查询审批记录的存储过程,这样也能很方便的查询 出每一步的审批状态,方便测试审批。
Java
UTF-8
153
1.953125
2
[]
no_license
package drawing.commands; /** * Interface for a command * * @author paude * */ public interface ICommand { public void execute(); }
Python
UTF-8
3,033
2.734375
3
[]
no_license
# coding=utf8 """Demo download views.""" from cStringIO import StringIO from os.path import abspath, dirname, join from django.core.files.storage import FileSystemStorage from django_downloadview.files import VirtualFile from django_downloadview import views from demoproject.download.models import Document # Some initializations. #: Directory containing code of :py:module:`demoproject.download.views`. app_dir = dirname(abspath(__file__)) #: Directory containing files fixtures. fixtures_dir = join(app_dir, 'fixtures') #: Path to a text file that says 'Hello world!'. hello_world_path = join(fixtures_dir, 'hello-world.txt') #: Storage for fixtures. fixtures_storage = FileSystemStorage(location=fixtures_dir) # Here are the views. #: Pre-configured download view for :py:class:`Document` model. download_document = views.ObjectDownloadView.as_view(model=Document) #: Same as download_document, but streamed inline, i.e. not as attachments. download_document_inline = views.ObjectDownloadView.as_view(model=Document, attachment=False) #: Pre-configured view using a storage. download_fixture_from_storage = views.StorageDownloadView.as_view( storage=fixtures_storage) #: Direct download of one file, based on an absolute path. #: #: You could use this example as a shortcut, inside other views. download_hello_world = views.PathDownloadView.as_view(path=hello_world_path) #: Direct download of one file, based on an absolute path, not as attachment. download_hello_world_inline = views.PathDownloadView.as_view( path=hello_world_path, attachment=False) class CustomPathDownloadView(views.PathDownloadView): """Example of customized PathDownloadView.""" def get_path(self): """Convert relative path (provided in URL) into absolute path. Notice that this particularly simple use case is covered by :py:class:`django_downloadview.views.StorageDownloadView`. .. warning:: If you are doing such things, make the path secure! Prevent users to download files anywhere in the filesystem. """ path = super(CustomPathDownloadView, self).get_path() return join(fixtures_dir, path) #: Pre-configured :py:class:`CustomPathDownloadView`. download_fixture_from_path = CustomPathDownloadView.as_view() class StringIODownloadView(views.VirtualDownloadView): """Sample download view using StringIO object.""" def get_file(self): """Return wrapper on StringIO object.""" file_obj = StringIO(u"Hello world!\n".encode('utf-8')) return VirtualFile(file_obj, name='hello-world.txt') #: Pre-configured view that serves "Hello world!" via a StringIO. download_generated_hello_world = StringIODownloadView.as_view() download_http_hello_world = views.HTTPDownloadView.as_view( url=u'https://raw.github.com/benoitbryon/django-downloadview/master/demo/demoproject/download/fixtures/hello-world.txt', basename=u'hello-world.txt')
Python
UTF-8
755
3.171875
3
[]
no_license
import sys def stack_push(inp): stack_data.append(inp) def stack_pop(): if stack_empty(): return -1 else: return stack_data.pop() def stack_empty(): return 1 if len(stack_data) == 0 else 0 def stack_top(): if stack_empty(): return -1 else: return stack_data[-1] def stack_size(): return len(stack_data) cmd_dict={'push': stack_push, 'top': stack_top, 'size': stack_size, 'empty': stack_empty, 'pop': stack_pop} stack_data=[] N = int(sys.stdin.readline()) for i in range(N): cmd_str = sys.stdin.readline() if len(cmd_str.split()) > 1: # push명령어 cmd_dict[cmd_str.split()[0]](cmd_str.split()[1]) else: print(cmd_dict[cmd_str.split()[0]]())
Python
UTF-8
888
2.53125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
from telegram.ext.dispatcher import Dispatcher from telegram import TelegramError from threading import Event class BlockDispatcher(Dispatcher): def __init__(self, updater, user_manager): # Build a new dispatcher based on the same settings as we get from the # updater. # TODO Probably shouldn't hard code workers but eh. super().__init__(updater.bot, updater.update_queue, 4, Event()) self.um = user_manager # Replace the updater's dispatcher with this one updater.dispatcher = self def processUpdate(self, update): # An error happened while polling if isinstance(update, TelegramError): self.dispatchError(None, update) if self.um.is_blocked(update): return super().processUpdate(update)
Java
UTF-8
2,321
2.265625
2
[]
no_license
package com.eurodyn.qlack2.fuse.mailing.impl.monitor; import com.eurodyn.qlack2.fuse.mailing.api.MailQueueMonitorClock; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.aries.blueprint.annotation.config.ConfigProperty; import org.ops4j.pax.cdi.api.OsgiServiceProvider; import java.util.logging.Level; import java.util.logging.Logger; @Singleton @OsgiServiceProvider(classes = {MailQueueMonitorClock.class}) public class MailQueueMonitorClockImpl implements MailQueueMonitorClock, Runnable { /** * Logger reference */ private static final Logger LOGGER = Logger.getLogger(MailQueueMonitorClockImpl.class.getName()); private Thread thread; @ConfigProperty("${interval}") private long interval; @Inject private MailQueueMonitor monitor; @Override @PostConstruct public void start() { if (thread != null) { LOGGER.log(Level.FINE, "Mail queue monitor is started."); return; } LOGGER.log(Level.FINE, "Mail queue monitor starting ..."); thread = new Thread(this, "Mail queue monitor thread"); thread.start(); } @Override @PreDestroy public void stop() { if (thread == null) { LOGGER.log(Level.FINE, "Mail queue monitor is stopped."); return; } LOGGER.log(Level.FINE, "Mail queue monitor stopping ..."); thread.interrupt(); thread = null; } @Override public void status() { LOGGER.log(Level.FINE, "Checking mail queue monitor status ..."); if (thread != null && thread.isAlive()) { LOGGER.log(Level.FINE, "Mail queue monitor is running."); } else { LOGGER.log(Level.FINE, "Mail queue monitor is stopped."); } } @Override public void run() { try { Thread current = Thread.currentThread(); while (!current.isInterrupted()) { tick(); Thread.sleep(interval); } } catch (InterruptedException ex) { LOGGER.log(Level.FINEST, "Mail queue monitor interrupted."); } } private void tick() { try { LOGGER.log(Level.FINEST, "Mail queue monitor executing ..."); monitor.checkAndSendQueued(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Mail queue processing produced an error.", e); } } }
C++
UTF-8
376
2.84375
3
[]
no_license
#include<bits/stdc++.h> //#define max 100 //int memo[max]; int fib(int n,int *memo){ if(memo[n-1]!=0){ return memo[n-1]; } else if(n==1||n==2){ return 1; } else{ int f=fib(n-1,memo)+fib(n-2,memo); memo[n-1]=f; return f; } } using namespace std; int main(){ int n; cin>>n; int memo[n]={0}; int result=fib(n,memo); cout<<"Ans: "<<result<<endl; return 0; }
Java
UTF-8
2,975
2.3125
2
[]
no_license
package com.demo.jfinal.util; import com.demo.jfinal.controller.LoginController; import com.demo.jfinal.controller.TestController; import com.demo.jfinal.model.db._MappingKit; import com.demo.jfinal.shiro.ShiroInterceptor; import com.demo.jfinal.shiro.ShiroPlugin; import com.jfinal.config.*; import com.jfinal.kit.Prop; import com.jfinal.kit.PropKit; import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import com.jfinal.plugin.c3p0.C3p0Plugin; import com.jfinal.render.ViewType; public class TestConfig extends JFinalConfig { /** * 供Shiro插件使用。 */ private Routes routes; /** * //此方法用来配置JFinal的常量值 * * @param constants */ @Override public void configConstant(Constants constants) { Prop p = PropKit.use("SystemConfig.txt");//PropKit 工具类用来操作外部配置文件 // 开发者模式,正式部署时关闭 constants.setDevMode(p.getBoolean("devMode")); constants.setBaseViewPath("/WEB-INF/views");//配置页面访问主路径,webapp下 constants.setViewType(ViewType.JSP);//设置视图类型为Jsp,否则默认为FreeMarker } /** * //配置JFinal访问路由 * * @param me */ @Override public void configRoute(Routes me) { this.routes = me; me.add("/test", TestController.class, "/");//路由,指定调用哪个controller,访问地址是/controllerKey/viewPath/方法名(index()是默认方法,不需要加方法名) me.add("/", LoginController.class, "/"); } /** * //用来配置JFinal的Handler * * @param handlers */ @Override public void configHandler(Handlers handlers) { } /** * //用来配置JFinal的Interceptor * * @param interceptors */ @Override public void configInterceptor(Interceptors interceptors) { interceptors.add(new ShiroInterceptor());//shiro拦截器 // interceptors.add(new Filter());//配置拦截器 } /** * //用来配置JFinal的Plugin,C3P0数据库连接池插件,ActiveRecordPlugin数据库访问插件 * * @param me */ @Override public void configPlugin(Plugins me) { //加载数据库配置文件 Prop p = PropKit.use("SystemConfig.txt"); //创建c3p0连接 C3p0Plugin c3p0Plugin = new C3p0Plugin(p.get("jdbcUrl"), p.get("user"), p.get("password")); ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin); arp.setShowSql(true); arp.setDevMode(true); // 方式一: 直接配置数据表映射 // arp.addMapping("GB_DRIVER", "ID", GbDriver.class); // 方式二:配置数据表映射写到一个文件中 _MappingKit.mapping(arp); me.add(c3p0Plugin); me.add(arp); //shiro ShiroPlugin shiroPlugin = new ShiroPlugin(this.routes); me.add(shiroPlugin); } }
Markdown
UTF-8
1,120
3.375
3
[ "MIT" ]
permissive
# Reddit To Twitter Bot Bot that takes reddit posts from subreddit of your choosing and tweets them. The bot also has the option of only selecting specific posts based on keywords of your choosing from your chosen subreddit. ## Things you will need: 1. "Client ID" & "Client Secret" from your reddit account. [Instructions](https://github.com/reddit-archive/reddit/wiki/OAuth2) 2. "Consumer Key","Consumer Secret", "Access Token" & "Access Token Secret" from the twitter account that your bot will be using. [Instructions](https://developer.twitter.com/en/docs/basics/authentication/guides/access-tokens.html) ## Program Instructions: 1. Clone repository. 2. Download packages Tweepy & Praw. ``` pip install tweepy pip instal praw ``` 3. Enter the API keys into there approriate places. 4. Enter your chosen subreddit. 5. (Optional) Enter keywords for specific posts you are looking for in the keyword list. 6. Run the program on any IDE or on the command line. ``` py reddit_to_twitter.py ``` If you run into any problems please [file an issue](https://github.com/princeali909/reddit-to-twitter-bot/issues).
Python
UTF-8
4,573
3.140625
3
[ "Apache-2.0" ]
permissive
import numbers import six from ...cereal import serializable from ..core import typecheck_promote from ..primitives import Int, Float, Str, Bool from ..containers import Struct, Tuple from .timedelta import Timedelta def _binary_op_casts_to(a, b): if isinstance(a, Datetime) and isinstance(b, Timedelta): return Datetime elif isinstance(a, Datetime) and isinstance(b, Datetime): return Timedelta elif isinstance(a, Timedelta) and isinstance(b, Datetime): return Datetime else: # pragma: no cover return type(a) DatetimeStruct = Struct[ { "year": Int, "month": Int, "day": Int, "hour": Int, "minute": Int, "second": Int, "microsecond": Int, } ] @serializable(is_named_concrete_type=True) class Datetime(DatetimeStruct): """ Proxy Datetime object, similar to Python's datetime. Note: Datetimes are always in UTC. """ _doc = { "month": "1 <= month <= 12", "day": "1 <= day <= number of days in the given month and year", "hour": "0 <= hour < 24", "minute": "0 <= minute < 60", "second": "0 <= second < 60", "microsecond": "0 <= microsecond < 1000000", } _constructor = "datetime.from_components" def __init__(self, year, month=1, day=1, hour=0, minute=0, second=0, microsecond=0): "Construct a `Datetime` from a components. All parts are optional besides ``year``." super(Datetime, self).__init__( year=year, month=month, day=day, hour=hour, minute=minute, second=second, microsecond=microsecond, ) @classmethod def _promote(cls, obj): try: return cls.from_string(obj.isoformat()) except AttributeError: if isinstance(obj, six.string_types): return cls.from_string(obj) if isinstance(obj, numbers.Number): return cls.from_timestamp(obj) return super(cls, cls)._promote(obj) @classmethod @typecheck_promote((Int, Float)) def from_timestamp(cls, seconds): return cls._from_apply("datetime.from_timestamp", seconds) @classmethod @typecheck_promote(Str) def from_string(cls, string): return cls._from_apply("datetime.from_string", string) @typecheck_promote(Timedelta) def __add__(self, other): return self._from_apply("add", self, other) @typecheck_promote(lambda: (Timedelta, Datetime)) def __sub__(self, other): return _binary_op_casts_to(self, other)._from_apply("sub", self, other) @typecheck_promote(Timedelta) def __mod__(self, other): """Difference (`Timedelta`) between this `Datetime` and the nearest prior interval of the given `Timedelta`. Example ------- >>> dt = Datetime(2016, 4, 15, 18, 16, 37, 684181) # doctest: +SKIP >>> td = dt % Timedelta(seconds=60) # doctest: +SKIP >>> td.compute() # doctest: +SKIP datetime.timedelta(0, 37, 684181) """ return Timedelta._from_apply("mod", self, other) @typecheck_promote(Timedelta) def __floordiv__(self, other): """This `Datetime`, floored to the nearest prior interval of the given `Timedelta`. Example ------- >>> dt = Datetime(2016, 4, 15, 18, 16, 37, 684181) # doctest: +SKIP >>> dt_quotient = dt // Timedelta(seconds=60) # doctest: +SKIP >>> dt_quotient.compute() # doctest: +SKIP datetime.datetime(2016, 4, 15, 18, 16) """ return self._from_apply("floordiv", self, other) @typecheck_promote(Timedelta) def __divmod__(self, other): return Tuple[type(self), Timedelta]._from_apply("divmod", self, other) @typecheck_promote(lambda: Datetime) def __eq__(self, other): return Bool._from_apply("eq", self, other) @typecheck_promote(lambda: Datetime) def __ge__(self, other): return Bool._from_apply("ge", self, other) @typecheck_promote(lambda: Datetime) def __gt__(self, other): return Bool._from_apply("gt", self, other) @typecheck_promote(lambda: Datetime) def __le__(self, other): return Bool._from_apply("le", self, other) @typecheck_promote(lambda: Datetime) def __lt__(self, other): return Bool._from_apply("lt", self, other) @typecheck_promote(lambda: Datetime) def __ne__(self, other): return Bool._from_apply("ne", self, other)
Python
UTF-8
2,490
4.0625
4
[]
no_license
# Sorting Algorithm # Insertion Sort # Time: O(n^2) # Space: O(1) # pick each item insert to the right place def insertionSort(alist): for i in range(1,len(alist)): cur = alist[i] pos = i while pos > 0 and alist[pos - 1] > cur: alist[pos] = alist[pos - 1] pos -= 1 alist[pos] = cur return alist # Bubble Sort # Time: O(n^2) # Space: O(1) # exachange btw every two items def BubbleSort(alist): for i in range(len(alist) - 1, 0, -1): for j in range(i): if alist[j] > alist[j + 1]: temp = alist[j] alist[j] = alist[j + 1] alist[j + 1] = temp return alist # Selection Sort # Time: O(n^2) # Space: O(1) # select the largest to put it in the last def selectionSort(alist): for i in range(len(alist) - 1, 0, -1): maxIndex = 0 for j in range(i + 1): if alist[j] > alist[maxIndex]: maxIndex = j alist[i], alist[maxIndex] = alist[maxIndex], alist[i] return alist # Merge Sort # Time: O(nlogn) # Space: O(n) # select the largest to put it in the last def mergeSort(alist): if len(alist) < 2: return alist mid = len(alist) / 2 left = alist[:mid] right = alist[mid:] mergeSort(left) mergeSort(right) l = r = 0 for i in range(len(alist)): lval = left[l] if l < len(left) else None rval = right[r] if r < len(right) else None if (lval and rval and lval < rval) or rval is None: alist[i] = lval l += 1 elif (lval and rval and lval >= rval) or lval is None: alist[i] = rval r += 1 return alist # Quick Sort # Time: O(nlogn) # Space: O(log(n)) # https://www.youtube.com/watch?v=MZaf_9IZCrc def quickSort(alist, left, right): if left < right: q = partition(alist, left, right) quickSort(alist, left, q - 1) quickSort(alist, q + 1, right) return alist def partition(alist, left, right): pivot = alist[right] i = left - 1 for j in range(left, right): if alist[j] < pivot: i += 1 alist[i], alist[j] = alist[j], alist[i] alist[i + 1], alist[right] = alist[right], alist[i + 1] return i + 1 sample = [54,26,93,17,77,31,44,55,20] #print insertionSort(sample) #print BubbleSort(sample) #print selectionSort(sample) #print mergeSort(sample) print quickSort(sample, 0, len(sample) - 1)
Markdown
UTF-8
1,264
3.1875
3
[]
no_license
# Sequence Labeling The problem here is: Given a sequence of tokens, infer the most probable sequence of lables for these tokens. Examples are: * Part of Speech Tagging (POS Tagging) * Named Entity Recognition (NER) For POS tagging we can use tags from the "Universal Dependencies Project". So here we want to understand for example who is the subject, what is the verb, what is the object, and this is in practice part of speech tagging, so giving a label to parts of the speech. On the other hand, named entities recognition is related to the detection of any real-world object which may have a proper name, like: * Persons * Organizations * Locations * ... Sometimes they also usually include: * Dates and Times * Amounts * Units In order to solve the sequence labeling tasks either POS or NER we have different approaches: 1. Rule-Based Models (example: EngCG tagger) 2. Separate label classifiers for each token (e.g., Naive Bayes, or Logistic Regression and so on used at each position) 3. Sequence Models (HMM, MEMM, CRF) 4. Neural Networks ## Neural Language Modeling Neural networks are the state of the art for the previously discussed tasks such as Language Modeling, POS tagging and NER. Here we use RNN, specifically LSTM generally.
Markdown
UTF-8
1,932
3.40625
3
[]
no_license
--- title: "算法 - 最好、最坏、平均复杂度" author: "颇忒脱" tags: ["ARTS-A"] date: 2019-02-13T20:24:48+08:00 --- <!--more--> [极客时间 - 数据结构与算法之美 - 04 | 复杂度分析(下):浅析最好、最坏、平均、均摊时间复杂度][1] ## 最好、最坏时间复杂度 略,比较容易分析。 ## 平均时间复杂度 需考虑概率来计算。 概率论中的**加权平均值**,也叫作**期望值**,所以平均时间复杂度的全称应该叫**加权平均时间复杂度**或者**期望时间复杂度**。 ## 均摊时间复杂度 均摊时间复杂度及对应的摊还分析法。 对一个数据结构进行一组连续操作中,大部分情况下时间复杂度都很低,只有个别情况下时间复杂度比较高,而且这些操作之间存在前后连贯的时序关系,这个时候,我们就可以将这一组操作放在一块儿分析,看是否能将较高时间复杂度那次操作的耗时,平摊到其他那些时间复杂度比较低的操作上。而且,在能够应用均摊时间复杂度分析的场合,一般均摊时间复杂度就等于最好情况时间复杂度。 ```java // 全局变量,大小为 10 的数组 array,长度 len,下标 i。 int array[] = new int[10]; int len = 10; int i = 0; // 往数组中添加一个元素 void add(int element) { if (i >= len) { // 数组空间不够了 // 重新申请一个 2 倍大小的数组空间 int new_array[] = new int[len*2]; // 把原来 array 数组中的数据依次 copy 到 new_array for (int j = 0; j < len; ++j) { new_array[j] = array[j]; } // new_array 复制给 array,array 现在大小就是 2 倍 len 了 array = new_array; len = 2 * len; } // 将 element 放到下标为 i 的位置,下标 i 加一 array[i] = element; ++i; } ``` [1]: https://time.geekbang.org/column/article/40447
Java
UTF-8
754
3.203125
3
[]
no_license
package com.learning.net; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerListener implements Runnable { int port; ServerSocket server; Socket client; public ServerListener(int port) { this.port = port; } public void run() { try { server = new ServerSocket(port); client = server.accept(); DataInputStream input = new DataInputStream( new BufferedInputStream(client.getInputStream())); String line = ""; while (line != "Over") { line = input.readUTF(); System.out.println('\n'+line); } input.close(); server.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
UTF-8
464
2.953125
3
[]
no_license
package com.myspringprojects.rnd.mockitolearning.testdoubles.spy; public class BookRepositorySpy implements BookRepository { int saveCalled = 0; Book lastAddedBook = null; @Override public void save(Book book) { this.saveCalled++; this.lastAddedBook = book; } public int timesCalled() { return this.saveCalled; } public boolean calledWith(Book book) { return lastAddedBook.equals(book); } }
Python
UTF-8
1,322
3.3125
3
[]
no_license
import talib as ta import pandas as pd import numpy as np # This funciton can be replaced by your trading strategy. # The function must one of the following three # 1 - BUY # 0 - HOLD # -1 - SELL def trading_strategy(inputs): # This demo trading strategy is build on cross over of moving averages of 5 and 20 periods (data points) . df = pd.DataFrame(inputs) sma5_list = ta.SMA(df['close'] , 5) ema20_list = ta.EMA(df['close'] , 20) arr = np.array(sma5_list) df['sma5'] = arr.tolist() arr = np.array(ema20_list) df['ema20'] = arr.tolist() sma5 = df['sma5'].iloc[-1] ema20 = df['ema20'].iloc[-1] last_sma5 = df['sma5'].iloc[-2] last_ema20 = df['ema20'].iloc[-2] if ~np.isnan(last_sma5) and ~np.isnan(last_ema20): if (last_sma5 < last_ema20 and sma5 >= ema20): return 1 # buy elif (last_sma5 > last_ema20 and sma5 <= ema20): return -1 # sell else: return 0 # do nothing def trading_strategySD(inputs): df = pd.DataFrame(inputs) current_std = df['close'][-3:len(df)].std() # std of last 3 prices past_std = df['close'][-15:-3].std() if df['close'].iloc[-1] > df['close'][-15:-3].max() and current_std > 1.5 * past_std: return 1 # buy elif df['close'].iloc[-1] < df['close'][-15:-3].min() and current_std > 1.5 * past_std: return 1 # sell else: return 0
Markdown
UTF-8
2,632
2.828125
3
[ "CC0-1.0" ]
permissive
--- layout: post title: "Shooting Star Chase&#58; Sunrise Walk - 1 June 2014" permalink: /archives/2014/03/shooting_star_chase_sunrise_walk_1_june_2014.html commentfile: 2014-03-21-shooting_star_chase_sunrise_walk_1_june_2014 category: around_town date: 2014-03-21 22:03:08 image: "/assets/images/2014/SHOOTIGN_sunrise-walk_thumb.jpg" excerpt: | Shooting Star Chase is a leading children's hospice charity caring for babies, children and young people with life-limiting conditions, and their families. Whether lives are measured in days, weeks, months or years, we are here to make every moment count. We support families from diagnosis to end of life and throughout bereavement with a range of nursing, practical, emotional and medical care. --- <a href="/assets/images/2014/SHOOTIGN_sunrise-walk.jpg" title="See larger version of - sunrise walk"><img src="/assets/images/2014/SHOOTIGN_sunrise-walk_thumb.jpg" width="150" height="150" alt="sunrise walk" class="photo right" /></a> Shooting Star Chase is a leading children's hospice charity caring for babies, children and young people with life-limiting conditions, and their families. Whether lives are measured in days, weeks, months or years, we are here to make every moment count. We support families from diagnosis to end of life and throughout bereavement with a range of nursing, practical, emotional and medical care. Our Sunrise Walk is a great way to get together with your family, friends and colleagues. The 13 mile walk is open to both men and women. Dogs and children are of course also welcome on the walk. The walk will start before sunrise so don't forget your torch! Last year our first sunrise walk saw 300 walkers raising £48,000 for Shooting Star Chase. This year we're looking for 400 walkers to take part and we aim to raise over £60,000. Sign up today to be a part of something special! No matter what your fitness level you can take part and raise vital funds to support local families with babies, children and young people with life-limiting conditions. The walk takes place on Sunday 1<sup>st</sup> June at 4:30am. We're looking to attract walkers from all backgrounds, not just experienced walkers, but families with children who are looking for something different and exciting to take part in. The route will take you past some picturesque sights including Richmond Park, Richmond Hill, The Thames, Ham Common, Bushy Park and Home Park near Hampton Court Palace. We're looking for 400 walkers to take part. Are you up for the challenge? [www.shootingstarchase.org.uk/sunrisewalk](http://www.shootingstarchase.org.uk/sunrisewalk)
Markdown
UTF-8
6,621
3.21875
3
[]
no_license
## FLock(), IsFLocked(), IsRLocked(), Sys(2011) FLOCK() locks all records in a table, preventing any other user from obtaining a lock on the file. Records are still visible for others to view, browse and report on. SYS(2011) can be used to detect the status of the current record, without attempting to actually place a lock on the record. The Is?Locked() functions return a logical rather than SYS(2011)'s localizable string, for easier internationalization. ### Usage ```foxpro lResult = FLOCK( [ nWorkArea | cAlias ] ) ``` <table border cellspacing=0 cellpadding=0 width=100%> <tr> <td width=32% valign=top> <p><b>Parameter</b></p> </td> <td width=23% valign=top> <p><b>Value</b></p> </td> <td width=45% valign=top> <p><b>Meaning</b></p> </td> </tr> <tr> <td width=32% rowspan=2 valign=top> <p>nWorkArea</p> </td> <td width=23% valign=top> <p>Integer</p> </td> <td width=45% valign=top> <p>Specifies the work area of the table to be locked.</p> </td> </tr> <tr> <td width=33% valign=top> <p>Omitted</p> </td> <td width=67% valign=top> <p>If cAlias is also omitted, the file lock is attempted in the current work area.</p> </td> </tr> <tr> <td width=32% rowspan=2 valign=top> <p>cAlias</p> </td> <td width=23% valign=top> <p>Character</p> </td> <td width=45% valign=top> <p>Specifies the alias of the table to be locked.</p> </td> </tr> <tr> <td width=33% valign=top> <p>Omitted</p> </td> <td width=67% valign=top> <p>If nWorkArea is also omitted, the file lock is attempted in the current work area.</p> </td> </tr> <tr> <td width=32% rowspan=2 valign=top> <p>lResult</p> </td> <td width=23% valign=top> <p>.T.</p> </td> <td width=45% valign=top> <p>The lock was placed successfully.</p> </td> </tr> <tr> <td width=33% valign=top> <p>.F.</p> </td> <td width=67% valign=top> <p>No lock was placed, either because others have locks on the table, or because there's no table open in the specified area or with the supplied alias.</p> </td> </tr> </table> You can use FLOCK() to ensure that changes to all records will be performed, say, before issuing a REPLACE ALL command. We try to avoid using this command, unless all records must be locked, since it must be manually released with UNLOCK ALL and doesn't scale well into client-server environments. Instead, we try to use table buffering and multi-locks to lock only those records we want to affect. Use BEGIN TRANSACTION, ROLLBACK and END TRANSACTION to ensure that all or none of the updates are made to the tables. ### Example ```foxpro ? FLOCK("Customer") ``` ### Usage ```foxpro cReturn = SYS(2011) lLock = ISFLOCKED( [ nWorkArea | cAlias ] ) lLock = ISRLOCKED( [ nRecNo, [ nWorkArea | cAlias ] ]) ``` <table border cellspacing=0 cellpadding=0 width=100%> <tr> <td width=32% valign=top> <p><b>Parameter</b></p> </td> <td width=23% valign=top> <p><b>Value</b></p> </td> <td width=45% valign=top> <p><b>Meaning</b></p> </td> </tr> <tr> <td width=32% rowspan=4 valign=top> <p>cReturn</p> </td> <td width=23% valign=top> <p>&quot;Exclusive&quot;</p> </td> <td width=45% valign=top> <p>The current table is opened exclusively.</p> </td> </tr> <tr> <td width=33% valign=top> <p>&quot;Record Unlocked&quot;</p> </td> <td width=67% valign=top> <p>The current record is not locked by this workstation.</p> </td> </tr> <tr> <td width=33% valign=top> <p>&quot;Record Locked&quot;</p> </td> <td width=67% valign=top> <p>The current record is locked by this workstation.</p> </td> </tr> <tr> <td width=33% valign=top> <p>Empty String</p> </td> <td width=67% valign=top> <p>There is no table open in the current work area.</p> </td> </tr> <tr> <td width=32% valign=top> <p>nRecno</p> </td> <td width=23% valign=top> <p>Integer</p> </td> <td width=45% valign=top> <p>The record number whose lock is tested.</p> </td> </tr> <tr> <td width=32% rowspan=2 valign=top> <p>lLock</p> </td> <td width=23% valign=top> <p>.T.</p> </td> <td width=45% valign=top> <p>The file or record is already locked.</p> </td> </tr> <tr> <td width=33% valign=top> <p>.F.</p> </td> <td width=67% valign=top> <p>The file or record is not locked, or, if you specified a work area, no table is open in that work area.</p> </td> </tr> </table> SYS(2011) has confused a number of developers, who think this function tells them whether or not they will be able to lock the record. It doesn't. This function just reports whether the local FoxPro application has the record locked. In order to determine if someone else has the record or file locked, the application must attempt to lock the record. This function is missing a second, optional parameter, allowing the developer to specify the alias or work area of the record of concern. It is notable by its absence. Like all SYS() functions, SYS(2011) won't give you an error if you supply too many parameters, so don't think that SYS(2011, lcAlias) is actually working on the alias you specify. SYS(2011) returns the localized lock status as text, such as "File Locked," "Exclusive," "Record Locked" or "Record Unlocked." This is almost useless in an application that might run on several different localized runtimes. So, in VFP 5, Microsoft introduced the two IS functions, which return a logical result, regardless of the language in use. Unlike SYS(2011), however, you may not get the whole picture. If a table is open exclusively, ISFLOCKED() reports .T., while ISRLOCKED() reports .F. So, to get the full story on whether a REPLACE can be sure to work, you need to check ISEXCLUSIVE() OR ISFLOCKED() OR ISRLOCKED(). <table border=0 cellspacing=0 cellpadding=0 width=100%> <tr> <td width=17% valign=top> <b><img width=95 height=78 src="Bug.gif"></b></p> </td> <td width=83%> <p>Even more confusing, the IS functions return .F. if the work area you specify has no table open. If, on the other hand, you supply a bogus alias, you get the error &quot;Alias not found.&quot; These functions should consistently do one or the other.</p> </td> </tr> </table> ### Example ```foxpro ? SYS(2011) lSafeToSave = ISEXCLUSIVE() OR ISFLOCKED() OR ISRLOCKED() ``` ### See Also [Begin Transaction](s4g336.md), [CursorSetProp()](s4g348.md), [IsExclusive()](s4g371.md), [Lock](s4g204.md), [Unlock](s4g204.md)
PHP
UTF-8
1,361
2.59375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Spires\Contracts\Core; use Spires\Contracts\Container\Container; interface Core extends Container { /** * Get the version number of the application. * * @return string */ public function version(); /** * Get the base path of the Laravel installation. * * @return string */ public function basePath(); /** * Register a service provider with the application. * * @param \Spires\Core\ServiceProvider|string $provider * @param array $config * @param bool $force * @return \Spires\Core\ServiceProvider */ public function register($provider, array $config = [], $force = false); /** * Register all of the base service providers. * * @return void */ public function registerBaseServiceProviders(); /** * Get the service providers that have been loaded. * * @return array */ public function getLoadedProviders(); /** * Get all plugins. * * @return array */ public function getPlugins(); /** * Boot the application's service providers. * * @return void */ public function boot(); /** * Determine if the application has booted. * * @return bool */ public function isBooted(); }
Python
UTF-8
948
3.265625
3
[]
no_license
# -*- coding: utf-8 -*- class find_code: def __init__(self): self.words_dict = {} self.input_word = '' self.out_string = 'Human Rights' def open_file(self, file='filtered_words.txt'): with open(file) as f: for line in f: if not self.words_dict.has_key(line.strip()): self.words_dict[line.strip()] = True def user_input(self): self.input_word = raw_input('请输入要校验的句子:') def find_word(self): for w in self.words_dict.keys(): if self.input_word.find(w) != -1: self.out_string = 'Freedom' break print self.out_string go_on = True if __name__ == '__main__': while go_on: find = find_code() find.open_file() find.user_input() find.find_word() go_on = False if raw_input('是否继续(输入N退出):') == 'N' else True
Python
UTF-8
1,460
2.921875
3
[]
no_license
#!/usr/bin/env python # encoding:utf8 import pika # 建立到达RabbitMQ Server的connection # 此处RabbitMQ Server位于本机-localhost connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() # 声明queue,确认要从中接收message的queue # queue_declare函数是幂等的,可运行多次,但只会创建一次 # 若可以确信queue是已存在的,则此处可省略该声明,如producer已经生成了该queue # 但在producer和consumer中重复声明queue是一个好的习惯 # 但是实际的情况确实,我在3.6.1的版本中, 这里如果再declare的话, 会报错 channel.queue_declare(queue='hello') print ' [*] Waiting for messages. To exit press CTRL+C' # 定义回调函数 # 一旦从queue中接收到一个message回调函数将被调用 # ch:channel # method: # properties: # body:message def callback(ch, method, properties, body): print " [x] Received %r" % (body,) # 从queue接收message的参数设置 # 包括从哪个queue接收message,用于处理message的callback,是否要确认message # 默认情况下是要对消息进行确认的,以防止消息丢失。 # 此处将no_ack明确指明为True,不对消息进行确认。 channel.basic_consume(callback, queue='hello', no_ack=True) # 始循环从queue中接收message并使用callback进行处理 channel.start_consuming()
Shell
UTF-8
252
2.640625
3
[]
no_license
#!/bin/bash function nsrequest() { ./nsrequest/DerivedData/nsrequest/Build/Products/Release/nsrequest $1 } tempfile=$(mktemp -t rules.pac) yaml2pac data/rules.yaml > $tempfile echo "File path: $tempfile" yaml2pac data/rules.yaml -t $tempfile
Java
GB18030
1,057
3.609375
4
[]
no_license
package javaSourceDemo; import java.util.Scanner; public class ShoppingCart { public static void main(String[] args) { Scanner input = new Scanner(System.in); double price; // Ʒ int count; // Ʒ double total = 0; // ܼ // 1.Ʒĵۺ System.out.print("MacBook Proĵ:"); price = input.nextDouble(); System.out.print("Ʒ"); count = input.nextInt(); total += price * count; System.out.print("iPhoneXS MAXĵ:"); price = input.nextDouble(); System.out.print("Ʒ"); count = input.nextInt(); total += price * count; System.out.print("AirPods Proĵ:"); price = input.nextDouble(); System.out.print("Ʒ"); count = input.nextInt(); total += price * count; // 2.жǷ if (total >= 50000) total *= 0.7; else total *= 0.9; // 3.ۺļ۸ System.out.println("ۺļ۸Ϊ" + total); } }
Ruby
UTF-8
887
2.609375
3
[]
no_license
require 'base64' module Kodi # Use the HTTP JSON-RPC API of Kodi to refresh the Kodi DB # # @param [String] login_pass # The 'login:pass' pair to use to access Kodi's HTTP API # @param [String] host # The host to use to access Kodi's HTTP API # @param [Int] port # The port to use to access Kodi's HTTP API # def self.refresh(login_pass, host, port) json_body = '{ "jsonrpc":"2.0","method":"VideoLibrary.Scan","id":"AliScript" }' headers = { 'Content-Type' => 'application/json' } headers['Authorization'] = 'Basic ' + Base64.encode64(login_pass) if login_pass req = Net::HTTP.new(host, port) resp, _ = req.post('/jsonrpc', json_body, headers) if resp.code.to_i == 200 Log::success('Kodi Database update started') else Log::error("Failed to trigger Kodi Database update (#{resp.code})") end end end
C
UTF-8
475
3.515625
4
[]
no_license
#include <stdio.h> #include <time.h> #include <stdlib.h> double get_pi(int n) { int k = 0; int i; double x; double y; srand(time(NULL)); for (i = 0; i < n; i++) { x = (double)rand() / RAND_MAX; y = (double)rand() / RAND_MAX; if (x * x + y * y <= 1.0) { k++; } } return 4.0 * k / n; } int main() { printf("%lf\n", get_pi(100)); printf("%lf\n", get_pi(10000)); printf("%lf\n", get_pi(1000000)); printf("%lf\n", get_pi(100000000)); return 0; }
Java
UTF-8
478
2.171875
2
[]
no_license
package com.example.cassa.entrainementprojettut.geometry.setGeometry; import com.example.cassa.entrainementprojettut.geometry.figure.Figure; import java.util.Random; public class SetGeometryLV3 implements I_SetGeometry { public SetGeometryLV3(){ } @Override public String getFalsePropertie(Figure f) { return f.getFalsePropertieLV3(); } @Override public String getTruePropertie(Figure f) { return f.getPropertieLV3(); } }
SQL
UTF-8
1,843
3.734375
4
[]
no_license
----------------------------------------------------------------- -- Version 0.3.0 ----------------------------------------------------------------- -- Fix to some column character sets alter table characters modify column cname varchar(20) character set latin1; alter table character_owners modify column pname varchar(20) character set latin1; alter table profiles modify column pname varchar(20) character set latin1; alter table profiles modify column pwd varchar(40) character set latin1; alter table profiles modify column email varchar(50) character set latin1; alter table profiles modify column sid varchar(32) character set latin1; -- Add DM flag to profile alter table profiles add ( dm varchar(1) not null default 'N' ); -- Add campaign id and owner to characters alter table characters add ( campaign integer null, owner varchar(20)); update characters set owner = editedby, lastedited = lastedited; -- Alter character_owners to remove owners. alter table character_owners add ( coid int(11) ); set @rownum = 1; update character_owners set coid = @rownum:=@rownum+1; update characters, character_owners set coid = 0 where id = cid and owner = pname; delete from character_owners where coid = 0; alter table character_owners drop column coid; -- Create campaign table create table campaign ( id integer primary key auto_increment, name varchar(40) not null, owner varchar(20) not null, active varchar(1) not null default 'Y', open varchar(1) not null default 'N', website varchar(250), pc_level varchar(250), description text, pc_alignment varchar(250), max_players integer); -- Create campaign join status table create table campaign_join( campaign_id integer not null, char_id integer not null, status enum ('RJ','IJ','DI','DJ') not null);
Python
UTF-8
4,618
2.6875
3
[]
no_license
from DGM import GraphMatrix import numpy as np ''' All bees leave hive and search for a path. Then they return and we keep for exapmle top 10%. Each bee follows one of these other bees based on waggle dance. ''' class Forager(GraphMatrix): def __init__(self, filename): GraphMatrix.__init__(self, filename) self.S = [] # the open set self.T = [] # the tour list of the bee self.V = np.zeros(shape=self.n+2, dtype=int) # the visited set self.current_op = 0 self.profitability_rating = 0 self.preferred_tour_indicator = 0 # whether a forager follows another forager or not self.preferred_tour = [] self.r = 0 # probability of following a waggle dance self.global_op_count = 0 def set_preferred_tour(self, T): self.preferred_tour = T def move(self, j): ''' j: operation moves from i == self.current_op to j moves from i to j and updates - remove j from Unk(i) (and vice versa) - add j to Suc(i) - add i to Pre(j) - add i to self.V (the visited_set) - append i to self.T (the tour list) - adds new op if j is not last operation in sequence - removes j in `self.S` (the open list) returns None ''' i = self.current_op if i != 0: self.remove_unknown(i, j), self.remove_unknown(j, i) self.add_successor(i, j) self.add_predecessor(j, i) self.V[i] = 1 self.T.append(i) self.current_op = j self.S.remove(j) self.global_op_count+=1 # increment op count # j in n+2 --> reduce by one and get the job_no and seq_no seq_no = (j-1) % self.n_machines if seq_no != self.n_machines - 1: self.S.append(j+1) # it's not the last operation --> append else: self.global_op_count = 0 # reset op count since we have reached the end def select_next_op(self, alpha, beta): ''' p_ij is the rating of edge between i and j alpha is the value assigned to the preferred path Need to add heuristic to choose nodes :return: ''' #i = self.current_op k = len(self.S) m = self.preferred_tour_indicator # need to add check to see if action is the same as the action in preferred path p = [] # ratings of edges between current node and all available nodes Probs = [] # probability to branch from node i to j durations = [] for each in self.S: i = (each-1) % self.n_machines j = (each-1) // self.n_machines durations.append(self.P[j][i]) if ((m != k) and (m<k)): for each in self.S: if ((m==1) and (self.preferred_tour[self.global_op_count+1] == each)): p.append((1-m*0.1)/(k-m)) else: p.append(1/k) else: for each in self.S: p.append(0.1) # if there is no waiting time for every action # then we're indifferent in choosing different actions if sum(p) == 0: action = np.random.choice(self.S) else: numerator = 0 for j in range(len(self.S)): numerator += (p[j])*((1/durations[j])) for j in range(len(self.S)): Probs.append(((p[j])*((1/durations[j]))) / numerator) Probs = np.array(Probs) / sum(Probs) action = np.random.choice(self.S, p=Probs) if self.preferred_tour_indicator == 1: if action != self.preferred_tour[self.global_op_count+1]: self.preferred_tour_indicator = 0 self.preferred_tour = [] return action def calculate_tour_length(self): #Find makespan for current bee C = np.zeros([self.n_jobs, self.n_machines]) ops = np.array(self.T) seq_nos, job_nos = (ops-1) % self.n_machines, (ops-1) // self.n_machines m_nos, m_times = self.M[job_nos, seq_nos], self.P[job_nos, seq_nos] for op, j_idx, s_idx, m_idx, T in zip(ops, job_nos, seq_nos, m_nos, m_times): if op == 0: continue earliest_start = max(C[:, m_idx].max(), C[j_idx, :].max()) C[j_idx, m_idx] = earliest_start + T return C.max() def update_profitability_rating(self): ''' updates profitability rating with the formula 1/C_max ''' C_max = self.calculate_tour_length() self.profitability_rating = float(1)/C_max
Java
UTF-8
3,464
2
2
[]
no_license
package py.com.excelsis.sicca.entity; // Generated 14/10/2011 09:15:23 AM by Hibernate Tools 3.4.0.Beta1 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.validator.Length; import org.hibernate.validator.NotNull; /** * SinPro generated by hbm2java */ @Entity @Table(name = "sin_pro", schema = "sinarh") public class SinPro implements java.io.Serializable { private Integer idPro; private Integer aniAniopre; private Integer nenCodigo; private Integer entCodigo; private Integer tipCodigo; private Integer proCodigo; private String funCodigo; private String proNombre; private String proNomabr; private String proDescrip; public SinPro() { } public SinPro(Integer idPro, Integer aniAniopre, Integer nenCodigo, Integer entCodigo, Integer tipCodigo, Integer proCodigo, String funCodigo, String proNombre, String proNomabr, String proDescrip) { this.idPro = idPro; this.aniAniopre = aniAniopre; this.nenCodigo = nenCodigo; this.entCodigo = entCodigo; this.tipCodigo = tipCodigo; this.proCodigo = proCodigo; this.funCodigo = funCodigo; this.proNombre = proNombre; this.proNomabr = proNomabr; this.proDescrip = proDescrip; } @Id @Column(name = "id_pro", unique = true, nullable = false) public Integer getIdPro() { return this.idPro; } public void setIdPro(Integer idPro) { this.idPro = idPro; } @Column(name = "ani_aniopre", nullable = false) public Integer getAniAniopre() { return this.aniAniopre; } public void setAniAniopre(Integer aniAniopre) { this.aniAniopre = aniAniopre; } @Column(name = "nen_codigo", nullable = false) public Integer getNenCodigo() { return this.nenCodigo; } public void setNenCodigo(Integer nenCodigo) { this.nenCodigo = nenCodigo; } @Column(name = "ent_codigo", nullable = false) public Integer getEntCodigo() { return this.entCodigo; } public void setEntCodigo(Integer entCodigo) { this.entCodigo = entCodigo; } @Column(name = "tip_codigo", nullable = false) public Integer getTipCodigo() { return this.tipCodigo; } public void setTipCodigo(Integer tipCodigo) { this.tipCodigo = tipCodigo; } @Column(name = "pro_codigo", nullable = false) public Integer getProCodigo() { return this.proCodigo; } public void setProCodigo(Integer proCodigo) { this.proCodigo = proCodigo; } @Column(name = "fun_codigo", nullable = false) @NotNull public String getFunCodigo() { return this.funCodigo; } public void setFunCodigo(String funCodigo) { this.funCodigo = funCodigo; } @Column(name = "pro_nombre", nullable = false, length = 200) @NotNull @Length(max = 200) public String getProNombre() { return this.proNombre; } public void setProNombre(String proNombre) { this.proNombre = proNombre; } @Column(name = "pro_nomabr", nullable = false, length = 100) @NotNull @Length(max = 100) public String getProNomabr() { return this.proNomabr; } public void setProNomabr(String proNomabr) { this.proNomabr = proNomabr; } @Column(name = "pro_descrip", nullable = false, length = 200) @NotNull @Length(max = 200) public String getProDescrip() { return this.proDescrip; } public void setProDescrip(String proDescrip) { this.proDescrip = proDescrip; } }
C++
BIG5
704
3.734375
4
[]
no_license
# include <iostream> # include <stdlib.h> using namespace std; int rFibonacci(int n); int main(void){ while(true){ cout << "пJwpFibonacciƦCĴX(J0Y)G"; int arr_length = 0; cin >> arr_length; if (arr_length == 0) break; cout << "==>fib(" << arr_length << ") = " << rFibonacci(arr_length) << "\n\n\n"; } return 0; } int rFibonacci(int n){ int arr_fibon[n]; if (n == 1) arr_fibon[0]= 0; else if (n == 2){ arr_fibon[0]= 0; arr_fibon[1]= 1; }else if (n > 2){ arr_fibon[0]= 0; arr_fibon[1]= 1; for (int i = 2 ; i < n; i++){ arr_fibon[i] = arr_fibon[i-1] + arr_fibon[i-2]; } } return arr_fibon[n-1]; }
SQL
UTF-8
1,208
3.546875
4
[ "BSD-2-Clause" ]
permissive
use progettok19; drop TABLE IF EXISTS LOT; drop TABLE IF EXISTS BID; drop TABLE IF EXISTS USER; drop TABLE IF EXISTS TIMER; drop TABLE IF EXISTS AUCTION; CREATE TABLE USER ( username CHAR(20), pass CHAR(40), loggedstatus BOOLEAN, PRIMARY KEY(username)); CREATE TABLE AUCTION ( id INTEGER AUTO_INCREMENT, closingdate DATETIME, higheroffer INTEGER, closed BOOLEAN, PRIMARY KEY(id)); CREATE TABLE LOT ( title CHAR(20), vendor CHAR(20), winner CHAR(20), baseprice INTEGER, auctionid INTEGER AUTO_INCREMENT, PRIMARY KEY(auctionid), FOREIGN KEY (vendor) REFERENCES USER(username), FOREIGN KEY (winner) REFERENCES USER(username), FOREIGN KEY (auctionid) REFERENCES AUCTION(id)); CREATE TABLE BID ( id INTEGER AUTO_INCREMENT, offerer CHAR(20), amount INTEGER, auctionid INTEGER, PRIMARY KEY (id), FOREIGN KEY (offerer) REFERENCES USER(username), FOREIGN KEY(auctionid) REFERENCES AUCTION(id)); CREATE TABLE TIMER ( id INTEGER, millis LONG, PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES AUCTION(id)); SET @@global.time_zone = '+02:00'; SET @@session.time_zone = '+02:00'; ALTER DATABASE `progettok19` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
Markdown
UTF-8
1,456
2.640625
3
[ "MIT" ]
permissive
--- guide: User Guide section: Overview overview: true menu: getting-started --- **Lita** is a [chat bot](https://en.wikipedia.org/wiki/Chatterbot) written in [Ruby](https://www.ruby-lang.org/) with persistent storage provided by [Redis](http://redis.io/). It uses a plugin system to connect to different chat services and to provide new behavior. The plugin system uses the familiar tools of the Ruby ecosystem: [RubyGems](https://rubygems.org/) and [Bundler](http://bundler.io/). <h3 id="features">Features</h3> * Can connect to any chat service * Simple installation and setup * Easily extendable with plugins * Data persistence with Redis * Built-in web server and routing * Event system for behavior triggered in response to arbitrary events * Support for outgoing HTTP requests * Group-based authorization * Internationalization * Configurable logging * Generators for creating new plugins <h3 id="coming-from-hubot">Coming from Hubot</h3> Lita draws much inspiration from GitHub's fantastic [Hubot](https://hubot.github.com/), but has a few key differences and strengths: * It's written in Ruby. * It exposes the full power of Redis rather than using it to serialize JSON. * It's easy to develop and test plugins for with the provided [RSpec](https://github.com/rspec/rspec) extras. Lita strongly encourages thorough testing of plugins. * It uses the Ruby ecosystem's standard tools (RubyGems and Bundler) for plugin installation and loading.
Python
UTF-8
890
2.796875
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- from __future__ import division import numpy as np import scipy.spatial.distance as distance """ This module contains routines for managing and validating kCSD parameters. """ def check_for_duplicated_electrodes(elec_pos): """ **Parameters** elec_pos : np.array **Returns** has_duplicated_elec : Boolean """ unique_elec_pos = np.vstack({tuple(row) for row in elec_pos}) has_duplicated_elec = unique_elec_pos.shape == elec_pos.shape return has_duplicated_elec def min_dist(elec_pos): """ Returns minimal distance between any electrodes """ min_distance = 0.0 dim = len(elec_pos[0]) if dim > 1: min_distance = distance.pdist(elec_pos).min() else: flat_elec = elec_pos.flatten() min_distance = distance.pdist(flat_elec[:, None], 'cityblock').min() return min_distance
JavaScript
UTF-8
7,370
3.171875
3
[]
no_license
// Displays day at top of the page var today = moment(); $('#currentDay').text(today.format('dddd')); console.log(today); // .css? .attr? Add or remove class? $("#hour-9").parent().css("background-color", "yellow !important"); const inpKey = document.getElementById("inpKey"); const btnInsert = document.getElementById("btnInsert"); const btnInsert10 = document.getElementById("btnInsert10"); const btnInsert11 = document.getElementById("btnInsert11"); const btnInsert12 = document.getElementById("btnInsert12"); const btnInsert1 = document.getElementById("btnInsert1"); const btnInsert2 = document.getElementById("btnInsert2"); const btnInsert3 = document.getElementById("btnInsert3"); const btnInsert4 = document.getElementById("btnInsert4"); const btnInsert5 = document.getElementById("btnInsert5"); const btnInsert6 = document.getElementById("btnInsert6"); const btnInsert7 = document.getElementById("btnInsert7"); const btnInsert8 = document.getElementById("btnInsert8"); const btnInsert9pm = document.getElementById("btnInsert9pm"); const btnInsert10pm = document.getElementById("btnInsert10pm"); renderLastRegistered(); function renderLastRegistered() { // var notes = localStorage.getItem("inpKey"); // inpKey.textContent = notes; $("#hour-9").val(localStorage.getItem("to-do")); $("#hour-10").val(localStorage.getItem("hour10")); $("#hour-11").val(localStorage.getItem("hour11")); $("#hour-12").val(localStorage.getItem("hour12")); $("#hour-1").val(localStorage.getItem("hour1")); $("#hour-2").val(localStorage.getItem("hour2")); $("#hour-3").val(localStorage.getItem("hour3")); $("#hour-4").val(localStorage.getItem("hour4")); $("#hour-5").val(localStorage.getItem("hour5")); $("#hour-6").val(localStorage.getItem("hour6")); $("#hour-7").val(localStorage.getItem("hour7")); $("#hour-8").val(localStorage.getItem("hour8")); $("#hour-9pm").val(localStorage.getItem("hour9pm")); $("#hour-10pm").val(localStorage.getItem("hour10pm")); } btnInsert.addEventListener("click", function(event) { event.preventDefault(); var notes = document.querySelector('#hour-9').value; localStorage.setItem("to-do", notes); renderLastRegistered(); } ); ; btnInsert10.addEventListener("click", function(event) { event.preventDefault(); var notes10 = document.querySelector('#hour-10').value; localStorage.setItem("hour10", notes10); renderLastRegistered(); } ); ; btnInsert11.addEventListener("click", function(event) { event.preventDefault(); var notes11 = document.querySelector('#hour-11').value; localStorage.setItem("hour11", notes11); renderLastRegistered(); } ); ; btnInsert12.addEventListener("click", function(event) { event.preventDefault(); var notes12 = document.querySelector('#hour-12').value; localStorage.setItem("hour12", notes12); renderLastRegistered(); } ); ; btnInsert1.addEventListener("click", function(event) { event.preventDefault(); var notes1 = document.querySelector('#hour-1').value; localStorage.setItem("hour1", notes1); renderLastRegistered(); } ); ; btnInsert2.addEventListener("click", function(event) { event.preventDefault(); var notes2 = document.querySelector('#hour-2').value; localStorage.setItem("hour2", notes2); renderLastRegistered(); } ); ; btnInsert3.addEventListener("click", function(event) { event.preventDefault(); var notes3 = document.querySelector('#hour-3').value; localStorage.setItem("hour3", notes3); renderLastRegistered(); } ); ; btnInsert4.addEventListener("click", function(event) { event.preventDefault(); var notes4 = document.querySelector('#hour-4').value; localStorage.setItem("hour4", notes4); renderLastRegistered(); } ); ; btnInsert5.addEventListener("click", function(event) { event.preventDefault(); var notes5 = document.querySelector('#hour-5').value; localStorage.setItem("hour5", notes5); renderLastRegistered(); } ); ; btnInsert6.addEventListener("click", function(event) { event.preventDefault(); var notes6 = document.querySelector('#hour-6').value; localStorage.setItem("hour6", notes6); renderLastRegistered(); } ); ; btnInsert7.addEventListener("click", function(event) { event.preventDefault(); var notes7 = document.querySelector('#hour-7').value; localStorage.setItem("hour7", notes7); renderLastRegistered(); } ); ; btnInsert8.addEventListener("click", function(event) { event.preventDefault(); var notes8 = document.querySelector('#hour-8').value; localStorage.setItem("hour8", notes8); renderLastRegistered(); } ); ; btnInsert9pm.addEventListener("click", function(event) { event.preventDefault(); var notes9pm = document.querySelector('#hour-9pm').value; localStorage.setItem("hour9pm", notes9pm); renderLastRegistered(); } ); ; btnInsert10pm.addEventListener("click", function(event) { event.preventDefault(); var notes10pm = document.querySelector('#hour-10pm').value; localStorage.setItem("hour10pm", notes10pm); renderLastRegistered(); } ); ; // $(document).ready(function () { // // listen for save button clicks // $('.saveBtn').on('click', function () { // // get nearby values // var value = $(this).siblings('.description').val(); // var time = $(this).parent().attr('id'); // // save in localStorage // localStorage.setItem(time, value); // // Show notification that item was saved to localStorage by adding class 'show' // $('.notification').addClass('show'); // // Timeout to remove 'show' class after 5 seconds // setTimeout(function () { // $('.notification').removeClass('show'); // }, 5000); // }); // function hourUpdater() { // // get current number of hours // var currentHour = moment().hours(); // // loop over time blocks // $('.time-block').each(function () { // var blockHour = parseInt($(this).attr('id').split('-')[1]); // // check if we've moved past this time // if (blockHour < currentHour) { // $(this).addClass('past'); // } else if (blockHour === currentHour) { // $(this).removeClass('past'); // $(this).addClass('present'); // } else { // $(this).removeClass('past'); // $(this).removeClass('present'); // $(this).addClass('future'); // } // }); // } // hourUpdater(); // // set up interval to check if current time needs to be updated // var interval = setInterval(hourUpdater, 15000); // // load any saved data from localStorage // $('#hour-9 .description').val(localStorage.getItem('hour-9')); // $('#hour-10 .description').val(localStorage.getItem('hour-10')); // $('#hour-11 .description').val(localStorage.getItem('hour-11')); // $('#hour-12 .description').val(localStorage.getItem('hour-12')); // $('#hour-13 .description').val(localStorage.getItem('hour-13')); // $('#hour-14 .description').val(localStorage.getItem('hour-14')); // $('#hour-15 .description').val(localStorage.getItem('hour-15')); // $('#hour-16 .description').val(localStorage.getItem('hour-16')); // $('#hour-17 .description').val(localStorage.getItem('hour-17')); // // display current day on page // });
Markdown
UTF-8
283
2.875
3
[]
no_license
# BFS-Pacman A self-solving pacman console game, where according to several variables (The initial position of the "Pacman", the exit and the position of the walls) the pacman is able to perform a BFS through all the possible paths, selecting the shortest one and moving through it.
Java
UTF-8
1,201
2.1875
2
[ "MIT" ]
permissive
package com.gtc.tradinggateway.service.huobi.dto; import com.google.common.collect.ImmutableMap; import com.gtc.model.gateway.data.OrderDto; import com.gtc.model.gateway.data.OrderStatus; import lombok.Data; import java.math.BigDecimal; import java.util.Map; /** * Created by mikro on 01.04.2018. */ @Data public class HuobiOrderDto { private static final Map<String, OrderStatus> MAPPER = ImmutableMap.<String, OrderStatus>builder() .put("pre-submitted", OrderStatus.NEW) .put("submitting", OrderStatus.NEW) .put("submitted", OrderStatus.NEW) .put("partial-filled", OrderStatus.PARTIALLY_FILLED) .put("filled", OrderStatus.FILLED) .put("canceled", OrderStatus.CANCELED) .build(); private Number id; private String symbol; private BigDecimal price; private BigDecimal amount; private String state; public OrderDto mapTo() { return OrderDto.builder() .orderId(symbol + "." + id.toString()) .size(amount) .price(price) .status(MAPPER.getOrDefault(state, OrderStatus.UNMAPPED)) .build(); } }
Markdown
UTF-8
767
2.765625
3
[]
no_license
- Do a little more each day than you think you possibly can. - The ability to speak is a short cut to distinction. It puts a man in the limelight, raises him head and shoulders above the crowd. - In Istanbul I met a man who said he knew beyond a doubt that God was a cat. I asked why he was so sure, and the man said, “When I pray to him, he ignores me.” - Separately there was only wind, water, sail, and hull, but at my hand the four had been given purpose and direction. - The man who can speak acceptably is usually given credit for an ability out of all proportion to what he really possesses. - After the age of 80, everything reminds you of something else. - The secret of my vigor and activity is that I have managed to have a lot of fun. 7 quotes
Java
UTF-8
617
3.1875
3
[]
no_license
package tree.problems.easy; public class IsSumProperty { public static int isSumProperty(Node root) { if (root == null || (root.left == null && root.right == null)) { return 1; } int left = 0, right = 0; if (root.left != null) { left = root.left.data; } if (root.right != null) { right = root.right.data; } if (root.data == (left + right) && isSumProperty(root.left) == 1 && isSumProperty(root.right) ==1 ) { return 1; } return 0; } }
JavaScript
UTF-8
974
2.59375
3
[ "MIT" ]
permissive
var fs = require('fs') var path = require('path') var Canvas = require('..') var canvas = new Canvas(150, 150) var ctx = canvas.getContext('2d') ctx.fillRect(0, 0, 150, 150) // Draw a rectangle with default settings ctx.save() // Save the default state ctx.fillStyle = '#09F' // Make changes to the settings ctx.fillRect(15, 15, 120, 120) // Draw a rectangle with new settings ctx.save() // Save the current state ctx.fillStyle = '#FFF' // Make changes to the settings ctx.globalAlpha = 0.5 ctx.fillRect(30, 30, 90, 90) // Draw a rectangle with new settings ctx.restore() // Restore previous state ctx.fillRect(45, 45, 60, 60) // Draw a rectangle with restored settings ctx.restore() // Restore original state ctx.fillRect(60, 60, 30, 30) // Draw a rectangle with restored settings canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'state.png')))
Python
UTF-8
1,979
3.703125
4
[]
no_license
import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8') # https://wikidocs.net/7033 # for문과 range 구문을 사용해서 0~99까지 한 라인에 하나씩 순차적으로 출력하는 프로그램을 작성하라. ''' for i in range(100): print(i) ''' # 월드컵은 4년에 한 번 개최된다. range()를 사용하여 2002~2050년까지 중 월드컵이 개최되는 연도를 출력하라. # 2002 # 2006 # 2010 # ... # 2042 # 2046 # 2050 # 참고) range의 세번 째 파라미터는 증감폭을 결정합니다. # >> print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8] ''' for i in range(2002, 2051, 4): print(i) ''' # 1부터 30까지의 숫자 중 3의 배수를 출력하라. ''' for i in range (3, 31, 3): print(i) ''' # 99부터 0까지 1씩 감소하는 숫자들을, 한 라인에 하나씩 출력하라. ''' for i in range(99, -1, -1): print(i) ''' # for문을 사용해서 아래와 같이 출력하라. # 0.0 # 0.1 # 0.2 # 0.3 # 0.4 # 0.5 # ... # 0.9 ''' for i in range(10): print(i / 10) ''' # 구구단 3단을 출력하라. ''' for i in range(1, 10): print(3, "x", i, "=", i * 3) ''' # 구구단 3단을 출력하라. 단 홀수 번째만 출력한다. ''' for i in range(1, 10): if i % 2 != 0: print(3, "x", i, "=", i * 3) ''' # 1~10까지의 숫자에 대해 모두 더한 값을 출력하는 프로그램을 for 문을 사용하여 작성하라. ''' a = 0 for i in range(11): a += i print(a) ''' # 1~10까지의 숫자 중 모든 홀수의 합을 출력하는 프로그램을 for 문을 사용하여 작성하라. ''' a = 0 for i in range(11): if i % 2 != 0: a += i print(a) ''' # 1~10까지의 숫자를 모두 곱한 값을 출력하는 프로그램을 for 문을 사용하여 작성하라. ''' a = 1 for i in range(1, 11): a *= i print(a) '''
Python
UTF-8
853
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- ''' Created on 06/12/2012 @author: User ''' from django.db import models escolhas = ( ('A','Ativada'), ('D','Desativada') ) class Noticia(models.Model): class Meta: verbose_name = 'Nova Notícia' verbose_name_plural = 'Notícias' ordering = ('-data',) titulo = models.CharField('Título', max_length=100) conteudo = models.TextField('Conteúdo') fonte_url = models.URLField('URL da Fonte', max_length=100, null=True, blank=True, help_text='Exemplo: http://www.nomedosite.com.br/') data = models.DateField() status = models.CharField(max_length=1, choices=escolhas) def __unicode__(self): return self.titulo @models.permalink def get_absolute_url(self): return ('manaia.views.VerNoticias', [str(self.id)])
C#
UTF-8
1,735
2.59375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum GameState { Play, Pause } public class GameController : MonoBehaviour { private GameState state; static private GameController _instance; private int score; int dragonHitScore; int dragonKillScore; [SerializeField] float maxHealth; public static GameController Instance { get { return _instance; } } public float MaxHealth { get { return maxHealth; } set { maxHealth = value; } } private void Awake() { _instance = this; state = GameState.Play; } public void Hit(IDestructable victim) { if (victim.GetType() == typeof(Dragon)) { { HUD.Instance.HealthBar.value = victim.Health; } if (victim.Health > 0) { Score += dragonHitScore; } else { Score += dragonKillScore; } Debug.Log("Dragon hit.Current score " + score); } } private int Score { get { return score; } set { if (value != score) { score = value; HUD.Instance.SetScore(score.ToString()); } } } void Start() { HUD.Instance.HealthBar.maxValue = maxHealth; HUD.Instance.HealthBar.value = maxHealth; HUD.Instance.SetScore(Score.ToString()); } // Update is called once per frame void Update() { } }
Java
UTF-8
1,822
2.953125
3
[]
no_license
package Basico; public class Generator { public static int IFGOTO = -35; public static int GOTO = -36; public static int LABEL = -37; private static int indiceTemp = 0; private static int indiceLabel = 0; public static String nuevaTemp() { return "_t" + indiceTemp++; } public static String nuevaLabel() { return "L" + indiceLabel++; } public static void salida(int inst, String arg1, String arg2, String res) { if (inst == sym.MAS) { PLC.out.println("\t" + res + " = " + arg1 + " + " + arg2 + ";"); } else if (inst == sym.MENOS) { PLC.out.println("\t" + res + " = " + arg1 + " - " + arg2 + ";"); } else if (inst == sym.POR) { PLC.out.println("\t" + res + " = " + arg1 + " * " + arg2 + ";"); } else if (inst == sym.PRINT) { PLC.out.println("\t" + "print " + res + ";"); } else if (inst == sym.AND) { PLC.out.println(res + "=" + arg1 + "&&" + arg2); } else if (inst == IFGOTO) { PLC.out.println("\tif (" + arg1 + arg2 + ") goto " + res + ";"); } else if (inst == GOTO) { PLC.out.println("\tgoto " + res + ";"); } else if (inst == LABEL) { PLC.out.println(res + ":"); } else if (inst == sym.ELSE) { PLC.out.println(res + "=" + arg1 + "/" + arg2); } else if (inst == sym.MINUS) { PLC.out.println("\t" + res + " = -" + arg1 + ";"); } else if (inst == sym.ENTERO) { PLC.out.println("\t" + res + " = " + arg1); } else if (inst == sym.IDENT) { PLC.out.println("\t" + res + " = " + arg1 + ";"); } else if (inst == sym.DIV) { PLC.out.println("\t" + res + " = " + arg1 + " / " + arg2 + ";"); } } }
Markdown
UTF-8
1,662
2.78125
3
[]
no_license
title: Python 连接 Mysql 数据库 date: 2016-03-14 15:01:19 tags: - Python - Mysql - MySQLdb - 数据库 - database --- ## 连接 mysql 数据库 使用 MySQLdb 来做为连接 mysql 数据库。 ``` python import MySQLdb   try: # host 表示主机类型 # user 登录的用户 # passwd 登录密码 # db 登录的数据库 # port 端口号,在本地情况下可以不用写     conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306) # 连接数据库     cur=conn.cursor() # 获取数据库的指针     cur.execute('select * from user') # 数据库操作     cur.close() # 关闭数据库的指针     conn.close() # 关闭数据库 except MySQLdb.Error,e: # 数据库连接失败。       print "Mysql Error %d: %s" % (e.args[0], e.args[1]) ``` ## 问题 如果出现了这种情况 ``` python Traceback (most recent call last): File "db_test.py", line 1, in <module> import MySQLdb ImportError: No module named MySQLdb ``` 说明没有安装相应的库 ## 安装 MySQLdb [Python下的Mysql模块MySQLdb安装详解](http://www.jb51.net/article/48827.htm) [下载Mysql模块MySQLdb](https://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz/download) ## 参考链接 - [python操作MySQL数据库](http://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html) - [Python下的Mysql模块MySQLdb安装详解](http://www.jb51.net/article/48827.htm) - [MySQL-python-1.2.3.tar.gz](https://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz/download)
PHP
UTF-8
4,644
2.875
3
[]
no_license
<?php if ( ! class_exists( 'ProSites_Helper_Session' ) ) { class ProSites_Helper_Session { private static $token = 'prosites_'; private static $add_time = '+1 hour'; /** * IMPORTANT: Only works for logged in users. * * To use this for registration, create the user first and login immediately * * @param $key * @param null $value * @param bool $unset * @param bool $duration * @param bool $force_session * @param bool $token_update * * @return bool|null|string */ public static function session( $key = true, $value = null, $unset = false, $duration = false, $force_session = false, $token_update = false ) { $session_value = null; // Make sure session is started if ( ! session_id() ) { session_start(); } // WordPress 4.0+ only if ( class_exists( 'WP_Session_Tokens' ) && is_user_logged_in() && ( ! $force_session || ( $force_session && $token_update ) ) ) { $user_id = get_current_user_id(); $session = WP_Session_Tokens::get_instance( $user_id ); $token_parts = explode( '_', self::$token ); $token_parts = (int) array_pop( $token_parts ); self::$token = empty( $token_parts ) ? self::$token . $user_id : self::$token; if ( empty( $duration ) ) { // Default 1 hr $duration = strtotime( self::$add_time, time() ); } $session_data = $session->get( self::$token ); if ( empty( $session_data ) ) { $session_data = array( 'expiration' => $duration, ); } if ( null === $value && ! $unset ) { if ( is_array( $key ) ) { $session_value = self::_get_val( $session_data, $key ); } else if( true !== $key ){ $session_value = isset( $session_data[ $key ] ) ? $session_data[ $key ] : null; } else { $session_value = isset( $session_data ) ? $session_data : null; } } else { if ( ! $unset ) { if ( is_array( $key ) ) { self::_set_val( $session_data, $key, $value ); } else { $session_data[ $key ] = $value; } } else { if ( is_array( $key ) ) { self::_unset_val( $session_data, $key ); } else { unset( $session_data[ $key ] ); } } $session->update( self::$token, $session_data ); $session_value = $value; } } else { // Pre WordPress 4.0 // Rely on $_SESSION vars. May require some plugins or server configuration // to work properly. if ( null === $value && ! $unset ) { if ( is_array( $key ) ) { $session_value = self::_get_val( $_SESSION, $key ); } else if( true !== $key ) { $session_value = isset( $_SESSION[ $key ] ) ? $_SESSION[ $key ] : null; } else { $session_value = isset( $_SESSION ) ? $_SESSION : null; } } else { if ( ! $unset ) { if ( is_array( $key ) ) { self::_set_val( $_SESSION, $key, $value ); } else { $_SESSION[ $key ] = $value; } } else { if ( is_array( $key ) ) { self::_unset_val( $_SESSION, $key ); } else { unset( $_SESSION[ $key ] ); } } $session_value = $value; } } // Try from $_SESSION then attempt to update token if( ! $force_session && empty( $session_value ) && null === $value ) { $session_value = self::session( $key, $value, $unset, $duration, true ); // Update token if we can self::session( $key, $session_value, $unset, $duration, true, true ); } return $session_value; } public static function unset_session( $key ) { // Attempt to clear token... self::session( $key, null, true ); // And $_SESSION if it still exists unset( $_SESSION[ $key ] ); } private static function _get_val( $arr, $index ) { $value = false; if ( is_array( $index ) ) { $key = array_shift( $index ); if ( isset( $arr[ $key ] ) ) { $value = $arr[ $key ]; if ( count( $index ) ) { $value = self::_get_val( $value, $index ); } } else { return null; } } return $value; } private static function _set_val( &$data, $path, $value ) { $temp = &$data; foreach ( $path as $key ) { $temp = &$temp[ $key ]; } $temp = $value; return $value; } private static function _unset_val( &$data, $path ) { $temp = &$data; $kill = $path[ count($path) - 1 ]; foreach ( $path as $key ) { if ( $kill != $key ) { $temp = &$temp[ $key ]; } else { unset( $temp[ $key ] ); } } } public static function attempt_force_sessions() { // Activate Sessions by putting in a false var ProSites_Helper_Session::session('psts_sessions_active', true); } } }
SQL
UTF-8
877
3.9375
4
[ "Apache-2.0" ]
permissive
/********* FIELD_IS_STANDARD_VALID_CONCEPT all standard concept id fields are standard and valid Parameters used in this template: cdmDatabaseSchema = @cdmDatabaseSchema cdmTableName = @cdmTableName cdmFieldName = @cdmFieldName **********/ SELECT num_violated_rows, CASE WHEN denominator.num_rows = 0 THEN 0 ELSE 1.0*num_violated_rows/denominator.num_rows END AS pct_violated_rows FROM ( SELECT COUNT_BIG(violated_rows.violating_field) AS num_violated_rows FROM ( SELECT '@cdmTableName.@cdmFieldName' AS violating_field, t.* FROM @cdmDatabaseSchema.@cdmTableName t join @cdmDatabaseSchema.CONCEPT c ON t.@cdmFieldName = c.CONCEPT_ID WHERE c.CONCEPT_ID != 0 AND (c.STANDARD_CONCEPT != 'S' OR c.INVALID_REASON IS NOT NULL ) ) violated_rows ) violated_row_count, ( SELECT COUNT_BIG(*) AS num_rows FROM @cdmDatabaseSchema.@cdmTableName ) denominator ;
PHP
UTF-8
2,029
2.5625
3
[]
no_license
<?php namespace Admin\Controller; use Think\Controller; class CommonController extends Controller{ public function __construct(){ header("Content-Type: text/html; charset=utf-8"); parent::__construct(); // 检测当前访问者是否登录了。 $this->checkLogin(); // 检测当前管理员是否具有访问当前[控制器-方法]的权限 $this->checkAuth(); } // 登录检测 protected function checkLogin(){ // 验证用户的登录状态[ 因为 ACTION_NAME直接接收地址栏的方法名,所以会有大小写的情况 ] // $action = array('index/login','index/code'); $action = array('index/login'); $res = !in_array( strtolower( CONTROLLER_NAME.'/'.ACTION_NAME ), $action ); if( $res && session('is_login') != 1 ){ $this->error( '您尚未登录!',U('Admin/index/login') ); } } // 权限检测 protected function checkAuth(){ // 先获取当前访问的控制器 和 方法名 $auth_key = CONTROLLER_NAME .'-'. ACTION_NAME; // 获取当前登录的管理员的角色ID $role_id = session('role_id'); // 根据得到的角色ID,到角色表中获取当前角色所拥有的权限 $role_info = D('Role')->find($role_id); // 判断当前权限 $auth_key 是否在当前管理员所拥有的权限范围内 // 下面数组的方法都不应该验证权限 $allow = array( 'index/index', // 后台首页 'index/top', // 后台顶部 'index/left', // 后台菜单 'index/main', // 后台主页 'index/login', // 后台登录页面 'index/logout', // 后台退出页面 'index/code', // 后台登录页面的验证码 ); $res = !in_array( strtolower( CONTROLLER_NAME.'/'.ACTION_NAME ), $allow ); if($res && strpos($role_info['role_auth_ac'], $auth_key ) === false ){ $this->error('您不具备当前操作的权限');die; } } }
C
UTF-8
546
3.765625
4
[]
no_license
#include <stdio.h> #define INVALID -1 int sumup(int v[]) { int i; int sum = 0; for(i = 0; v[i] != INVALID; i++) sum += v[i]; return sum; } int main(void) { int i; int a[128]; int na = sizeof(a) / sizeof(a[0]); printf("input %d elements (end element : -1).\n", na - 1); for(i = 0; i < na - 1; i++) { printf("a[%d] : ", i); scanf("%d", &a[i]); if(a[i] == INVALID) break; } if(i == na - 1) a[i] = INVALID; printf("sum : %d\n", sumup(a)); return 0; }
C++
GB18030
875
3.03125
3
[]
no_license
//ءɢ롢ռ #ifndef MONEY_H #define MONEY_H #include<iostream> #include<cstdlib> #include<cmath> using namespace std; namespace Space1 { class Money { public: Money(); Money(double amount); Money(int theDollars,int theCents); double getAmount() const; int getDollars()const; int getCents()const; void input(); void output() const; void operator=(const Money& amount2); private: int dollars; int cents; int dollarsPart(double amount)const; int centsPart(double amount)const; int round(double number)const; }; const Money operator +(const Money& amount1,const Money& amount2); const Money operator -(const Money& amount1,const Money& amount2); bool operator ==(const Money& amount1,const Money& amount2); const Money operator -(const Money& amount1); //const Money operator=(const Money& amount1,const Money& amount2); } #endif
C
UTF-8
2,591
3.546875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <stdarg.h> #include <unistd.h> #include <fcntl.h> void strTrim(char* str) { int readIndex = 0; int writeIndex = 0; while (str[readIndex] == ' ') { //loop past all leading spaces readIndex++; } while (str[readIndex] != '\0') { //loop till end of string if (str[readIndex] == ' ' //if there is a space, check.. && (str[readIndex + 1] == ' ' //if the next character is also a space || str[readIndex + 1] == '\0' //if the next character is the end of the string || str[writeIndex - 1] == '<' //if the previous character was a < || str[writeIndex - 1] == '>' //if the previous charater was a > ) ) { //do nothing //skip extra whitespace } else{ //if no rules were violated str[writeIndex] = str[readIndex]; //copy read to write writeIndex++; } readIndex++; } str[writeIndex] = '\0'; //end string with null character } int main(int argc, char* argv[], char* env[]) { /* char* cmd = "/bin/echo"; char* argVector [] = { "echo", "hello", "world", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ /* char* cmd = "/usr/bin/gcc"; char* argVector[] = { "gcc", "t.c", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ //o_wronly requires file to exist /* close(1); open("outfile", O_WRONLY, 0644); char* cmd = "/bin/echo"; char* argVector[] = { "echo", "hello", "world", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ /* FILE* fp = fopen("outfile", "w"); // fopen a FILE stream for fclose(fp); close(1); open("outfile", O_WRONLY, 0644); char* cmd = "/bin/echo"; char* argVector[] = { "echo", "hello", "world", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ /* close(1); open("outfile", O_WRONLY|O_CREAT, 0644); char* cmd = "/bin/echo"; char* argVector[] = { "echo", "hello", "world", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ /* close(1); open("outfile", O_WRONLY|O_CREAT|O_APPEND, 0644); char* cmd = "/bin/echo"; char* argVector[] = { "echo", "hello", "world", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ /* close(0); open("infile", O_RDONLY); char* cmd = "/bin/cat"; char* argVector[] = { "cat", NULL }; int r = execve(cmd, argVector, env); printf("didnt work\n"); */ char input[] = " test this function > to see>if > it >> works < very well "; printf("|%s|\n", input); strTrim(input); printf("strTrim()\n|%s|\n", input); }
Markdown
UTF-8
1,493
2.546875
3
[]
no_license
--- authors: - admin bio: My teaching interests are data science, statistics, and science communication. education: courses: - course: PhD in Environmental Science and Management institution: Bren School, UC Santa Barbara year: 2012 - course: MS in Mechanical Engineering institution: UC Santa Barbara year: 2007 - course: BS in Chemical Engineering institution: UC Santa Barbara year: 2005 email: "ahorst@ucsb.edu" interests: - Statistics - Data analysis - Environmental science - Science communication - Art name: Allison Horst organizations: - name: Bren School of Environmental Science and Management url: "http://bren.ucsb.edu/" role: Lecturer social: - icon: envelope icon_pack: fas link: '#contact' - icon: twitter icon_pack: fab link: https://twitter.com/allison_horst - icon: github icon_pack: fab link: https://github.com/allisonhorst superuser: true user_groups: - Researchers - Visitors --- Hi everyone, I'm Allison! I'm a continuing lecturer at the Bren School of Environmental Science and Management at UC Santa Barbara, where I teach statistics, data analysis, and science communication. I'm also the current RStudio Artist-in-Residence, and you can find some of my R- and stats-related artwork [here](https://github.com/allisonhorst/stats-illustrations). When I'm not teaching or painting, I can often be found wandering through the oak forests and sagebrush of the Los Padres and Inyo National Forests with my partner Greg and our dog, Teddy.
Python
UTF-8
2,038
4.0625
4
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2019/12/9 9:50 下午 # @Author : lihm # @File : sort.py import random def quicksort(seq): if len(seq) < 2: return seq else: base = seq[0] left = [elem for elem in seq[1:] if elem < base] right = [elem for elem in seq[1:] if elem > base] return quicksort(left) + [base] + quicksort(right) def bouble_sourt(seq): # 冒泡排序(顺序形式),从左向右,两两比较,如果左边元素大于右边,就交换两个元素的位置。 # 其中,每一轮排序,序列中最大的元素浮动到最右面。也就是说,每一轮排序,至少确保有一个元素在正确的位置。 # 这样接下来的循环,就不需要考虑已经排好序的元素了,每次内层循环次数都会减一。 # 其中,如果有一轮循环之后,次序并没有交换,这时我们就可以停止循环,得到我们想要的有序序列了。 seq = seq[:] n = len(seq) - 1 i = j = 0 flag = 1 # 遍历所有数组元素 while i < n: j = 0 # Last i elements are already in place while j < n - i - 1: if seq[j] > seq[j + 1]: seq[j], seq[j + 1] = seq[j + 1], seq[j] flag = 0 j += 1 if flag: break i += 1 return seq def find_min_index(seq): min_elem = seq[0] count = 0 min_leem_index = count for elem in seq[1:]: count += 1 if elem < min_elem: elem, min_elem = min_elem, elem min_leem_index = count return min_leem_index def select_sort(seq): # 选择排序 seq = seq[:] length = len(seq) for i in range(length): index = find_min_index(seq[i:]) seq[index + i], seq[i] = seq[i], seq[index + i] return seq if __name__ == '__main__': seq = [9, 1, 2, 5, 4, 3, 2, 1, 4] random.shuffle(seq) print(quicksort(seq)) print(bouble_sourt(seq)) print(select_sort(seq))
Python
UTF-8
530
3.34375
3
[]
no_license
import sys from collections import Counter N = int(sys.stdin.readline()) nums = [] for n in range(N): num = int(sys.stdin.readline()) nums.append(num) print(int(round((sum(nums) / N), 0))) # 1 nums.sort() answer4 = max(nums) - min(nums) print(nums[N // 2]) # 2 if len(nums) == 1: # 3 print(nums[0]) else: counter = Counter(nums) tuple_list = counter.most_common() if tuple_list[0][1] == tuple_list[1][1]: print(tuple_list[1][0]) else: print(tuple_list[0][0]) print(answer4) # 4
C++
UTF-8
1,382
3.109375
3
[]
no_license
// we have defined the necessary header files here for this problem. // If additional header files are needed in your program, please import here. #include<vector> int main() { // please define the C++ input here. For example: int a,b; cin>>a>>b;; // please finish the function body here. // please define the C++ output here. For example:cout<<____<<endl; int n; while(cin>>n){ vector<vector<int>> arr = vector(n,vector<int>(n,0)); int num = 1; for(int i=0;i<n;++i){ switch(i%3){ case 0: for(int j=i/3;j<n-1-i/3*2;++j){ arr[i/3][j] = num++; } break; case 1: for(int j=i/3;j<n-i/3*2;++j){ arr[j][n-j-1-i/3] = num++; } break; case 2: for(int j=n-i/3*2-2;j>i/3;--j){ arr[j][i/3] = num++; } break; } } if(n%3==1){ arr[n/3][n/3] = (1+n)*n/2; } for(auto l:arr){ for(int i=0;i<n;++i){ if(i==0) cout<<l[i]; else if(l[i]!=0) cout<<" "<<l[i]; } cout<<endl; } } return 0; }
Java
UTF-8
313
1.835938
2
[]
no_license
package universetournament.shared.logic.gamemode.events; import universetournament.shared.events.SubType; /** * * @author Bernd Marbach * */ public enum GameModeSubType implements SubType { SET_TIME, PLAYER_JOINED, PLAYER_LEFT, PLAYER_SCORE_CHANGED, TEAM_SCORE_CHANGED, PLAYER_KILLED, PLAYER_DIED; }
SQL
UTF-8
1,941
3
3
[]
no_license
CREATE OR REPLACE PACKAGE "GUIUTILS" AS TYPE CURSOR_TYPE IS REF CURSOR; PROCEDURE GETKEYCONTAINERATTRIBUTES (pContainerIDList IN varchar2:=NULL, pContainerBarcodeList IN varchar2:=NULL, O_RS OUT CURSOR_TYPE); PROCEDURE GETKEYPLATEATTRIBUTES (pPlateIDList IN varchar2:=NULL, pPlateBarcodeList IN varchar2:=NULL, O_RS OUT CURSOR_TYPE); PROCEDURE DISPLAYCREATEDCONTAINERS (p_Containerlist IN varchar2:=NULL, O_RS OUT CURSOR_TYPE); FUNCTION GETLOCATIONPATH (pLocationID IN inv_locations.location_id%type) return varchar2; FUNCTION GETRACKLOCATIONPATH (pLocationID IN inv_locations.location_id%type) return varchar2; FUNCTION GETFULLRACKLOCATIONPATH (pLocationID IN inv_locations.location_id%type) return varchar2; PROCEDURE GETRECENTLOCATIONS(pContainerID IN inv_containers.container_id%type, pNumRows in integer:=5, O_RS OUT CURSOR_TYPE); FUNCTION GETPARENTPLATEIDS (pPlateID inv_plates.plate_id%TYPE) RETURN varchar2; FUNCTION GETPARENTPLATEBARCODES (pPlateID inv_plates.plate_id%TYPE) RETURN varchar2; FUNCTION GETPARENTPLATELOCATIONIDS(pPlateID inv_plates.plate_id%TYPE) RETURN varchar2; FUNCTION GETPARENTWELLIDS (pWellID inv_wells.well_id%TYPE) RETURN varchar2; FUNCTION GETPARENTWELLLABELS (pWellID inv_wells.well_id%TYPE) RETURN varchar2; FUNCTION GETPARENTWELLNAMES (pWellID inv_wells.well_id%TYPE) RETURN varchar2; FUNCTION GETPARENTPLATEIDS2 (pWellID inv_wells.well_id%TYPE) RETURN varchar2; FUNCTION GETPARENTPLATELOCATIONIDS2(pWellID inv_wells.well_id%TYPE) RETURN varchar2; FUNCTION GETPARENTPLATEBARCODES2 (pWellID inv_wells.well_id%TYPE) RETURN varchar2; /* Returns the sum of qty_available for all child containers of the given container */ FUNCTION GETBATCHAMOUNTSTRING (pContainerID inv_containers.container_id%TYPE, p_DryWeightUOM VARCHAR2) RETURN varchar2; END GUIUTILS; / show errors;
C#
UTF-8
41,119
2.796875
3
[]
no_license
using PetAdopt.DTO; using PetAdopt.DTO.Animal; using PetAdopt.Models; using PetAdopt.Utilities; using System; using System.Collections.Generic; using System.Data.Entity; using System.IO; using System.Linq; namespace PetAdopt.Logic { /// <summary> /// 動物Logic /// </summary> public class AnimalLogic : _BaseLogic { /// <summary> /// 認養動物Logic /// </summary> /// <param name="operation">操作者資訊</param> public AnimalLogic(Operation operation) : base(operation) { } /// <summary> /// 取得動物列表 /// </summary> /// <param name="page">第幾頁(1是第一頁)</param> /// <param name="take">取幾筆</param> /// <param name="query">標題查詢</param> /// <param name="isLike">模糊比對</param> /// <param name="areaId">Area.Id</param> /// <param name="classId">Class.Id</param> /// <param name="statusId">Status.Id</param> /// <param name="userId">User.Id</param> /// <returns></returns> public AnimalList GetAnimalList(int page = 1, int take = 10, string query = "", bool isLike = true, int areaId = -1, int classId = -1, int statusId = -1, int userId = -1) { var log = GetLogger(); log.Debug("page:{0}, take:{1}, query={2}, isLike={3}, areaId={4}, classId={5}, statusId={6}, userId={7}", page, take, query, isLike, areaId, classId, statusId, userId); if (page < 1) page = 1; if (take < 1) take = 10; List<AnimalItem> list; var count = 0; // 查全部 if (string.IsNullOrWhiteSpace(query)) { var animals = PetContext.Animals .OrderByDescending(r => r.Id) .Select(r => new { r.Id, r.CoverPhoto, r.Title, r.Introduction, r.OperationInfo, r.Area, r.Class, r.Status }); // 指定誰發佈的 if (userId != -1) { animals = animals .Where(r => r.OperationInfo.UserId == userId); } // 指定地區 if (areaId != -1) { animals = animals .Where(r => r.Area.Id == areaId); } // 指定分類 if (classId != -1) { animals = animals .Where(r => r.Class.Id == classId); } // 指定狀態 if (statusId != -1) { animals = animals .Where(r => r.Status.Id == statusId); } var templist = animals .Select(r => new { r.Id, r.CoverPhoto, r.Title, r.Introduction, r.OperationInfo.Date, Area = r.Area.Word, Classes = r.Class.Word, Status = r.Status.Word }) .Skip((page - 1) * take) .Take(take) .ToList(); list = templist .Select(r => new AnimalItem { Id = r.Id, Photo = string.IsNullOrWhiteSpace(r.CoverPhoto) ? r.CoverPhoto : r.CoverPhoto.StartsWith("http://") ? r.CoverPhoto : r.CoverPhoto.StartsWith("https://") ? r.CoverPhoto : "../../Content/uploads/" + r.CoverPhoto, Title = r.Title, Introduction = r.Introduction, Date = r.Date.ToString() + " UTC", Area = r.Area, Classes = r.Classes, Status = r.Status }) .ToList(); count = animals.Count(); } // 查特定標題 else { // 查完全命中的 if (isLike == false) { var animals = PetContext.Animals .Where(r => r.Title == query) .OrderByDescending(r => r.Id) .Select(r => new { r.Id, r.CoverPhoto, r.Title, r.Introduction, r.OperationInfo, r.Area, r.Class, r.Status }); // 指定誰發佈的 if (userId != -1) { animals = animals .Where(r => r.OperationInfo.UserId == userId); } // 指定地區 if (areaId != -1) { animals = animals .Where(r => r.Area.Id == areaId); } // 指定分類 if (classId != -1) { animals = animals .Where(r => r.Class.Id == classId); } // 指定狀態 if (statusId != -1) { animals = animals .Where(r => r.Status.Id == statusId); } var templist = animals .Select(r => new { r.Id, r.CoverPhoto, r.Title, r.Introduction, r.OperationInfo.Date, Area = r.Area.Word, Classes = r.Class.Word, Status = r.Status.Word }) .Skip((page - 1) * take) .Take(take) .ToList(); list = templist .Select(r => new AnimalItem { Id = r.Id, Photo = string.IsNullOrWhiteSpace(r.CoverPhoto) ? r.CoverPhoto : r.CoverPhoto.StartsWith("http://") ? r.CoverPhoto : r.CoverPhoto.StartsWith("https://") ? r.CoverPhoto : "../../Content/uploads/" + r.CoverPhoto, Title = r.Title, Introduction = r.Introduction, Date = r.Date.ToString() + " UTC", Area = r.Area, Classes = r.Classes, Status = r.Status }) .ToList(); count = animals.Count(); } // 查包含的 else { var animals = PetContext.Animals .Where(r => r.Title.Contains(query)) .Select(r => new { r.Id, r.CoverPhoto, r.Title, r.Introduction, r.OperationInfo, r.Area, r.Class, r.Status }); // 指定誰發佈的 if (userId != -1) { animals = animals .Where(r => r.OperationInfo.UserId == userId); } // 指定地區 if (areaId != -1) { animals = animals .Where(r => r.Area.Id == areaId); } // 指定分類 if (classId != -1) { animals = animals .Where(r => r.Class.Id == classId); } // 指定狀態 if (statusId != -1) { animals = animals .Where(r => r.Status.Id == statusId); } var templist = animals .OrderByDescending(r => r.Id) .Select(r => new { r.Id, r.CoverPhoto, r.Title, r.Introduction, r.OperationInfo.Date, Area = r.Area.Word, Classes = r.Class.Word, Status = r.Status.Word }) .Skip((page - 1) * take) .Take(take) .ToList(); list = templist .Select(r => new AnimalItem { Id = r.Id, Photo = string.IsNullOrWhiteSpace(r.CoverPhoto) ? r.CoverPhoto : r.CoverPhoto.StartsWith("http://") ? r.CoverPhoto : r.CoverPhoto.StartsWith("https://") ? r.CoverPhoto : "../../Content/uploads/" + r.CoverPhoto, Title = r.Title, Introduction = r.Introduction, Date = r.Date.ToString() + " UTC", Area = r.Area, Classes = r.Classes, Status = r.Status }) .ToList(); count = animals.Count(); } } var result = new AnimalList { List = list, Count = count }; return result; } /// <summary> /// 取得動物資訊 /// </summary> /// <param name="id">Animal.Id</param> /// <returns></returns> public IsSuccessResult<GetAnimal> GetAnimal(int id) { var log = GetLogger(); log.Debug("id: {0}", id); var animal = PetContext.Animals .Include(r => r.Class) .Include(r => r.Status) .Include(r => r.Area) .Include(r => r.OperationInfo.User) .SingleOrDefault(r => r.Id == id); if (animal == null) return new IsSuccessResult<GetAnimal>("找不到此認養動物資訊"); return new IsSuccessResult<GetAnimal> { ReturnObject = new GetAnimal { Photo = animal.CoverPhoto, Title = animal.Title, Introduction = animal.Introduction, Address = animal.Address, AreaId = animal.AreaId, ClassId = animal.ClassId, SheltersId = animal.SheltersId, StatusId = animal.StatusId, Area = animal.AreaId.HasValue ? animal.Area.Word : null, Class = animal.Class.Word, Shelters = animal.SheltersId.HasValue ? animal.Shelter.Name : null, Status = animal.Status.Word, Phone = animal.Phone, StartDate = animal.StartDate.ToString() + " UTC", EndDate = animal.EndDate.HasValue ? animal.EndDate.Value.ToString() + " UTC" : null, Age = animal.Age, Date = animal.OperationInfo.Date.ToString() + " UTC", UserDisplay = animal.OperationInfo.User.Display } }; } /// <summary> /// 取得留言列表 /// </summary> /// <param name="id">Animal.Id</param> /// <param name="page">第幾頁(1是第一頁)</param> /// <param name="take">取幾筆資料</param> /// <returns></returns> public AnimalMessageList GetMessageList(int id, int page = 1, int take = 10) { var log = GetLogger(); log.Debug("page:{0}, take:{1}, id:{2}", page, take, id); if (page <= 0) page = 1; if (take < 1) take = 10; var messages = PetContext.Animals .Where(r => r.Id == id) .SelectMany(r => r.Messages); var temp = messages.Select(r => new { r.Id, Message = r.Message1, r.OperationInfo.Date, r.OperationInfo.User.Account }) .OrderByDescending(r => r.Id) .Skip((page - 1) * take) .Take(take) .ToList(); var list = temp.Select(r => new AnimalMessageItem { Id = r.Id, Message = r.Message, Date = r.Date.ToString() + " UTC", Account = r.Account }) .ToList(); var count = messages.Count(); return new AnimalMessageList { List = list, Count = count }; } /// <summary> /// 刪除動物 /// </summary> /// <param name="path">圖片路徑</param> /// <param name="id">Animal.Id</param> /// <param name="userId">User.Id</param> /// <returns></returns> public IsSuccessResult DeleteAnimal(string path, int id, int userId) { var log = GetLogger(); log.Debug("path: {0}, id: {1}, userId: {2}", path, id, userId); var result = new IsSuccessResult(); var animal = PetContext.Animals.SingleOrDefault(r => r.Id == id); if (animal == null) { result.IsSuccess = false; result.ErrorMessage = "找不到此動物資訊"; return result; } //檢查權限 var user = PetContext.Users.SingleOrDefault(r => r.Id == userId); if (user == null || user.IsDisable) { result.IsSuccess = false; result.ErrorMessage = "沒有權限"; return result; } if (user.IsAdmin == false && animal.OperationInfo.UserId != userId) { result.IsSuccess = false; result.ErrorMessage = "沒有權限"; return result; } if (animal.Blogs.Any()) { result.IsSuccess = false; result.ErrorMessage = "有關於此動物的文章,無法刪除"; return result; } // 有上傳圖片,就把圖片刪掉 if (string.IsNullOrWhiteSpace(animal.CoverPhoto) == false) { File.Delete(path + "//" + animal.CoverPhoto); } try { PetContext.Messages.RemoveRange(animal.Messages); PetContext.Animals.Remove(animal); PetContext.SaveChanges(); return result; } catch (Exception ex) { log.Error(ex); result.IsSuccess = false; result.ErrorMessage = "發生不明錯誤,請稍候再試"; return result; } } /// <summary> /// 刪除留言 /// </summary> /// <param name="id">Animal.Id</param> /// <param name="messageId">Message.Id</param> /// <param name="userId">User.Id</param> /// <returns></returns> public IsSuccessResult DeleteMessage(int id, int messageId, int userId) { var log = GetLogger(); log.Debug("id: {0}, messageId: {1}, userId: {2}", id, messageId, userId); var result = new IsSuccessResult(); var animal = PetContext.Animals.SingleOrDefault(r => r.Id == id); if (animal == null) { result.IsSuccess = false; result.ErrorMessage = "找不到此問與答"; return result; } //檢查權限 var user = PetContext.Users.SingleOrDefault(r => r.Id == userId); if (user == null || user.IsDisable) { result.IsSuccess = false; result.ErrorMessage = "沒有權限"; return result; } if (user.IsAdmin == false) { result.IsSuccess = false; result.ErrorMessage = "沒有權限"; return result; } var message = animal.Messages.SingleOrDefault(r => r.Id == messageId); if (message == null) { result.IsSuccess = false; result.ErrorMessage = "找不到此留言"; return result; } try { PetContext.Messages.Remove(message); PetContext.SaveChanges(); return result; } catch (Exception ex) { log.Error(ex); result.IsSuccess = false; result.ErrorMessage = "發生不明錯誤,請稍候再試"; return result; } } /// <summary> /// 新增認養動物 /// </summary> /// <param name="data">動物資訊</param> /// <returns></returns> public IsSuccessResult<AnimalItem> AddAnimal(CreateAnimal data) { var log = GetLogger(); log.Debug("photo: {0}, title: {1}, introduction:{2}, areaId:{3}, address:{4}, phone:{5}, classId:{6}, shelters:{7}, startDate:{8}, endDate:{9}, statusId:{10}, age:{11}", data.Photo, data.Title, data.Introduction, data.AreaId, data.Address, data.Phone, data.ClassId, data.Shelters, data.StartDate, data.EndDate, data.StartDate, data.Age); if (string.IsNullOrWhiteSpace(data.Title)) return new IsSuccessResult<AnimalItem>("請輸入標題"); data.Title = data.Title.Trim(); if (string.IsNullOrWhiteSpace(data.Introduction)) return new IsSuccessResult<AnimalItem>("請輸入介紹"); data.Introduction = data.Introduction.Trim(); if (data.EndDate.HasValue) { if (data.EndDate < data.StartDate) return new IsSuccessResult<AnimalItem>("安樂死日期不得在認養日期之前"); } var hasClass = PetContext.Classes.Any(r => r.Id == data.ClassId); if (hasClass == false) return new IsSuccessResult<AnimalItem>("請選擇正確的分類"); var hasStatus = PetContext.Status.Any(r => r.Id == data.StatusId); if (hasStatus == false) return new IsSuccessResult<AnimalItem>("請選擇正確的狀態"); int? sheltersId = 0; if (string.IsNullOrWhiteSpace(data.Shelters) == false) { data.Shelters = data.Shelters.Trim(); sheltersId = PetContext.Shelters .Where(r => r.Name == data.Shelters) .Select(r => r.Id) .SingleOrDefault(); if (sheltersId == 0) { if (string.IsNullOrWhiteSpace(data.Address)) return new IsSuccessResult<AnimalItem>("找不到此收容所,請輸入正確名稱"); } } else { if (data.AreaId.HasValue == false) return new IsSuccessResult<AnimalItem>("請選擇地區"); else { var hasArea = PetContext.Areas.Any(r => r.Id == data.AreaId); if (hasArea == false) return new IsSuccessResult<AnimalItem>("請選擇正確的地區"); } } if (string.IsNullOrWhiteSpace(data.Photo) == false) data.Photo = data.Photo.Trim(); var isAny = PetContext.Animals.Any(r => r.Title == data.Title); if (isAny) return new IsSuccessResult<AnimalItem>(string.Format("已經有 {0} 這個認養資訊了", data.Title)); try { var animal = PetContext.Animals.Add(new Animal { CoverPhoto = data.Photo, Title = data.Title, Introduction = data.Introduction, Address = data.Address, AreaId = data.AreaId, ClassId = data.ClassId, SheltersId = sheltersId == 0 ? null : sheltersId, Phone = data.Phone, StartDate = data.StartDate.ToUniversalTime(), EndDate = data.EndDate.HasValue ? data.EndDate.Value.ToUniversalTime() : data.StartDate.AddDays(12), Age = data.Age, StatusId = data.StatusId, OperationInfo = new OperationInfo { Date = data.StartDate != null ? data.StartDate.ToUniversalTime() : DateTime.UtcNow, UserId = GetOperationInfo().UserId } }); PetContext.SaveChanges(); return new IsSuccessResult<AnimalItem> { ReturnObject = new AnimalItem { Id = animal.Id, Title = animal.Title, } }; } catch (Exception ex) { log.Error(ex); return new IsSuccessResult<AnimalItem>("發生不明錯誤,請稍候再試"); } } /// <summary> /// 修改認養動物資訊 /// </summary> /// <param name="data">修改動物資訊</param> /// <param name="userId">User.Id</param> /// <returns></returns> public IsSuccessResult EditAnimal(EditAnimal data, int userId) { var log = GetLogger(); log.Debug("photo: {0}, title: {1}, introduction: {2}, areaId: {3}, address: {4}, phone: {5}, classId: {6}, shelters: {7}, startDate: {8}, endDate: {9}, statusId: {10}, age: {11}, id: {12}, user: {13}", data.Photo, data.Title, data.Introduction, data.AreaId, data.Address, data.Phone, data.ClassId, data.Shelters, data.StartDate, data.EndDate, data.StartDate, data.Age, data.Id, userId); var animal = PetContext.Animals.SingleOrDefault(r => r.Id == data.Id); if (animal == null) return new IsSuccessResult("找不到此認養動物資訊"); if (string.IsNullOrWhiteSpace(data.Title)) return new IsSuccessResult<AnimalItem>("請輸入標題"); data.Title = data.Title.Trim(); if (string.IsNullOrWhiteSpace(data.Introduction)) return new IsSuccessResult<AnimalItem>("請輸入介紹"); data.Introduction = data.Introduction.Trim(); //檢查權限 var user = PetContext.Users.SingleOrDefault(r => r.Id == userId); if (user == null || user.IsDisable) return new IsSuccessResult<AnimalItem>("沒有權限"); if (user.IsAdmin == false && animal.OperationInfo.UserId != userId) return new IsSuccessResult<AnimalItem>("沒有權限"); if (data.EndDate.HasValue) { if (data.EndDate < data.StartDate) return new IsSuccessResult<AnimalItem>("安樂死日期不得在認養日期之前"); } var hasClass = PetContext.Classes.Any(r => r.Id == data.ClassId); if (hasClass == false) return new IsSuccessResult<AnimalItem>("請選擇正確的分類"); var hasStatus = PetContext.Status.Any(r => r.Id == data.StatusId); if (hasStatus == false) return new IsSuccessResult<AnimalItem>("請選擇正確的狀態"); int? sheltersId = 0; if (string.IsNullOrWhiteSpace(data.Shelters) == false) { data.Shelters = data.Shelters.Trim(); sheltersId = PetContext.Shelters .Where(r => r.Name == data.Shelters) .Select(r => r.Id) .SingleOrDefault(); if (sheltersId == 0) return new IsSuccessResult<AnimalItem>("找不到此收容所,請輸入正確名稱"); } else { if (data.AreaId.HasValue == false) return new IsSuccessResult<AnimalItem>("請選擇地區"); else { var hasArea = PetContext.Areas.Any(r => r.Id == data.AreaId); if (hasArea == false) return new IsSuccessResult<AnimalItem>("請選擇正確的地區"); } } if (string.IsNullOrWhiteSpace(data.Photo) == false) data.Photo = data.Photo.Trim(); var isAny = PetContext.Animals.Any(r => r.Title == data.Title && r.Id != data.Id); if (isAny) return new IsSuccessResult<AnimalItem>(string.Format("已經有 {0} 這個認養資訊了", data.Title)); if (animal.CoverPhoto == data.Photo && animal.Title == data.Title && animal.Introduction == data.Introduction && animal.Address == data.Address && animal.AreaId == data.AreaId && animal.ClassId == data.ClassId && animal.SheltersId == sheltersId && animal.Phone == data.Phone && animal.StartDate == data.StartDate.ToUniversalTime() && animal.EndDate == (data.EndDate.HasValue ? data.EndDate.Value.ToUniversalTime() : data.EndDate) && animal.Age == data.Age && animal.StatusId == data.StatusId) return new IsSuccessResult(); try { animal.CoverPhoto = data.Photo; animal.Title = data.Title; animal.Introduction = data.Introduction; animal.Address = data.Address; animal.AreaId = data.AreaId; animal.ClassId = data.ClassId; animal.SheltersId = sheltersId == 0 ? null : sheltersId; animal.Phone = data.Phone; animal.StartDate = data.StartDate.ToUniversalTime(); animal.EndDate = (data.EndDate.HasValue ? data.EndDate.Value.ToUniversalTime() : data.EndDate); animal.Age = data.Age; animal.StatusId = data.StatusId; PetContext.SaveChanges(); return new IsSuccessResult(); } catch (Exception ex) { log.Error(ex); return new IsSuccessResult("發生不明錯誤,請稍候再試"); } } /// <summary> /// 留言 /// </summary> /// <param name="id">Animal.Id</param> /// <param name="message">留言內容</param> /// <returns></returns> public IsSuccessResult AddMessage(int id, string message) { var log = GetLogger(); log.Debug("id: {0}, message: {1}", id, message); if (string.IsNullOrWhiteSpace(message)) return new IsSuccessResult("請輸入留言"); message = message.Trim(); var animal = PetContext.Animals.SingleOrDefault(r => r.Id == id); if (animal == null) return new IsSuccessResult("找不到此待認養動物,暫時無法留言"); var userId = GetOperationInfo().UserId; if (userId == 0) return new IsSuccessResult("請先登入後再進行留言"); try { animal.Messages.Add(new Message { Message1 = message, IsRead = false, OperationInfo = new OperationInfo { Date = DateTime.UtcNow, UserId = userId } }); PetContext.SaveChanges(); return new IsSuccessResult(); } catch (Exception ex) { log.Error(ex); return new IsSuccessResult("發生不明錯誤,請稍候再試"); } } /// <summary> /// 取得認養動物的自動完成 /// </summary> /// <param name="title">認養文章標題</param> /// <returns></returns> public List<Suggestion> GetAnimalSuggestion(string title) { if (string.IsNullOrWhiteSpace(title)) return new List<Suggestion>(); title = title.Trim(); var animalList = PetContext.Animals .Where(r => r.Title.Contains(title)) .Take(10) .Select(r => new Suggestion { Display = r.Title, Value = r.Id.ToString() }) .ToList(); return animalList; } /// <summary> /// 取得輪播的資訊 /// </summary> /// <returns></returns> public List<Carousel> GetCarouselList() { var temp = PetContext.Animals .OrderByDescending(r => r.Id) .Take(100) .Select(r => new { r.Id, r.CoverPhoto, r.EndDate, r.Title }); var rnd = new Random(); int skip = rnd.Next(temp.Count() - 5); var data = temp.Skip(skip).Take(5).ToList(); var result = new List<Carousel>(); // 沒取到半筆,就回傳一個空的list回去 if (data.Any() == false) { result.Add(new Carousel { Link = "/Shelters/New", Photo = "../../Content/Images/news.jpg", Title = "發佈收容所資訊.", Detail = "發表全台各地的收容所,中途之家訊息,讓民眾可以前往認養!!", Alt = "發佈收容所資訊", Class = "item", ButtonText = "前往發佈" }); result.Add(new Carousel { Link = "/Animal/New", Photo = "../../Content/Images/adopt.jpg", Title = "送養動物.", Detail = "發佈等待好心人認養的動物,幫牠們尋找一個溫暖的家!!", Alt = "送養動物", Class = "item", ButtonText = "前往發佈" }); result.Add(new Carousel { Link = "/Help/New", Photo = "../../Content/Images/activity.jpg", Title = "即刻救援.", Detail = "有動物急需要幫忙,發佈上來讓更多人知道這個消息!!", Alt = "即刻救援", Class = "item", ButtonText = "前往發佈" }); result.Add(new Carousel { Link = "/Blog/New", Photo = "../../Content/Images/using.jpg", Title = "牠與他的故事.", Detail = "發表你與家中小寶貝的溫馨故事,讓其他人羨慕一下!!", Alt = "牠與他的故事", Class = "item", ButtonText = "前往發佈" }); result.Add(new Carousel { Link = "/Knowledge/New", Photo = "../../Content/Images/about.jpg", Title = "相關知識.", Detail = "提供與動物有關的相關知識,讓新手也能輕鬆了解怎麼養小狗、小貓~~", Alt = "相關知識", Class = "item", ButtonText = "前往發佈" }); } else { result = data .Select(r => new Carousel { Link = "/Animal/Detail?id=" + r.Id, Photo = string.IsNullOrWhiteSpace(r.CoverPhoto) ? r.CoverPhoto : r.CoverPhoto.StartsWith("http://") ? r.CoverPhoto : r.CoverPhoto.StartsWith("https://") ? r.CoverPhoto : "../../Content/uploads/" + r.CoverPhoto, Title = "處死日:", EndDate = r.EndDate.ToString() + " UTC", Detail = "", Alt = "即將安樂死動物", Class = "item", ButtonText = "立即認養" }) .ToList(); } result.First().Class += " active"; return result; } public int AddAnimalFromOpenData() { var newAnimalCount = 0; var client = new Client(); var animalList = client.GetAnimalInfo() .Where(r => (string.IsNullOrWhiteSpace(r.animal_createtime) ? DateTime.UtcNow : Convert.ToDateTime(r.animal_createtime)) > DateTime.UtcNow.AddMonths(-6)) .OrderBy(r => r.animal_createtime); foreach (var item in animalList) { try { // convert status Enum.StatusType myStatus; System.Enum.TryParse(item.animal_status, true, out myStatus); short statusId = 0; switch (myStatus) { case PetAdopt.Enum.StatusType.NONE: statusId = PetContext.Status.Where(r => r.Word == "其他").Select(r => r.Id).SingleOrDefault(); break; case PetAdopt.Enum.StatusType.OPEN: statusId = PetContext.Status.Where(r => r.Word == "開放認養").Select(r => r.Id).SingleOrDefault(); break; case PetAdopt.Enum.StatusType.ADOPTED: statusId = PetContext.Status.Where(r => r.Word == "已認養").Select(r => r.Id).SingleOrDefault(); break; case PetAdopt.Enum.StatusType.OTHER: statusId = PetContext.Status.Where(r => r.Word == "其他").Select(r => r.Id).SingleOrDefault(); break; case PetAdopt.Enum.StatusType.DEAD: statusId = PetContext.Status.Where(r => r.Word == "已安樂死").Select(r => r.Id).SingleOrDefault(); break; default: statusId = PetContext.Status.Where(r => r.Word == "其他").Select(r => r.Id).SingleOrDefault(); break; } // convert class var animalClass = PetContext.Classes.Where(r => r.Word.Contains(item.animal_kind)).FirstOrDefault(); if (animalClass == null) animalClass = PetContext.Classes.Where(r => r.Word == "其他").SingleOrDefault(); var sex = "公"; if (item.animal_sex == "F") sex = "母"; var sterilization = "是"; if (item.animal_sterilization == "N") sterilization = "否"; var bacterin = "是"; if (item.animal_bacterin == "N") bacterin = "否"; // combine information var introduction = "動物編號:" + item.animal_subid + " (請將此編號告知收容所,以便快速找到此浪浪)\n"; introduction += "性別:" + sex + "\n"; introduction += "體型:" + item.animal_bodytype + "\n"; introduction += "毛色:" + item.animal_colour + "\n"; introduction += "年紀:" + item.animal_age + "\n"; introduction += "是否已絕育:" + sterilization + "\n"; introduction += "是否已施打狂犬病疫苗:" + bacterin + "\n"; introduction += "備註:" + item.animal_remark + "\n"; var newAnimal = new PetAdopt.DTO.Animal.CreateAnimal { Photo = item.album_file, Title = string.IsNullOrWhiteSpace(item.animal_title) ? item.animal_id + " " + item.shelter_name : item.animal_title, Shelters = item.shelter_name, AreaId = Convert.ToInt16(item.animal_area_pkid), ClassId = animalClass.Id, StatusId = statusId, Address = item.animal_place, StartDate = Convert.ToDateTime(item.animal_createtime).ToUniversalTime(), Introduction = introduction }; var result = AddAnimal(newAnimal); if (result.IsSuccess == false) { var animal = PetContext.Animals.SingleOrDefault(r => r.Title == newAnimal.Title); if (animal == null) continue; var editAnimal = new PetAdopt.DTO.Animal.EditAnimal { Id = animal.Id, Photo = item.album_file, Title = string.IsNullOrWhiteSpace(item.animal_title) ? item.animal_id + " " + item.shelter_name : item.animal_title, Shelters = item.shelter_name, AreaId = Convert.ToInt16(item.animal_area_pkid), ClassId = animalClass.Id, StatusId = statusId, Address = item.animal_place, StartDate = Convert.ToDateTime(item.animal_createtime).ToUniversalTime(), Introduction = introduction }; EditAnimal(editAnimal, GetOperationInfo().UserId); } else newAnimalCount++; } catch (Exception) { } } return newAnimalCount; } /// <summary> /// 刪除半年外的動物 /// </summary> public int DeleteAnimals() { var sql = @"delete from Animal where StartDate < DateAdd(""m"", -6, GetDate())"; return PetContext.Database.ExecuteSqlCommand(sql); } } }
Python
UTF-8
2,551
2.796875
3
[]
no_license
from matplotlib import pyplot as plt import numpy as np from tkinter import * from tkinter import ttk def m2py(fom): fom = fom.replace("^","**") fom = fom.replace("sin","np.sin") fom = fom.replace("cos","np.cos") fom = fom.replace("tan","np.tan") fom = fom.replace("pi","np.pi") fom = fom.replace("e","np.e") return fom def graph(): # Graphs the function formula = m2py(str(eqnERY.get())) x = np.arange(eval(x_minERY.get()),eval(x_maxERY.get()),0.01) y = eval(formula) ax = plt.gca() ax.set_ylim([eval(y_minERY.get()),eval(y_maxERY.get())]) plt.axhline(linewidth=2, y=0, color='black') plt.axvline(linewidth=2, x=0, color='black') if 'x' not in formula: plt.axhline(y=eval(formula)) else: utol = 100. ltol = -100. y[y>utol] = np.inf y[y<ltol] = -np.inf plt.plot(x,y) plt.grid(linestyle="--") plt.show() def useDefault(): # Fills default values for the domain and range x_minERY.delete(0,END) x_maxERY.delete(0,END) y_minERY.delete(0,END) y_maxERY.delete(0,END) x_minERY.insert(0,-10) x_maxERY.insert(0,10) y_minERY.insert(0,-10) y_maxERY.insert(0,10) root = Tk() root.title("Graphing Calculator") root.option_add("*Font", "courier 36") root.resizable(False, False) style = ttk.Style() style.configure('TButton', font = ('courier', 28, 'bold')) eqnLBL = ttk.Label(root,text="y =") eqnERY = ttk.Entry(root) defaultBTN = ttk.Button(root, text="Use Default Limits", command=useDefault) x_minLBL = ttk.Label(root, text="x min:") x_minERY = ttk.Entry(root, width=5) x_maxLBL = ttk.Label(root, text="x max:") x_maxERY = ttk.Entry(root, width=5) y_minLBL = ttk.Label(root, text="y min:") y_minERY = ttk.Entry(root, width=5) y_maxLBL = ttk.Label(root, text="y max:") y_maxERY = ttk.Entry(root, width=5) button = ttk.Button(root, text="PLOT", style="TButton", command=graph) # Place all widgets on the grid eqnLBL.grid(row=1,column=0, pady=10) eqnERY.grid(row=1,column=1, pady=10) defaultBTN.grid(row=0, column=0, columnspan=2, sticky=N, pady=(0,15)) button.grid(row=6,column=0, columnspan=2,sticky=N+S+W+E, pady=(30,0)) x_minLBL.grid(row=2,column=0, pady=10) x_minERY.grid(row=2,column=1, sticky=W, pady=10) x_maxLBL.grid(row=3,column=0, pady=10) x_maxERY.grid(row=3,column=1, sticky=W, pady=10) y_minLBL.grid(row=4,column=0, pady=10) y_minERY.grid(row=4,column=1, sticky=W, pady=10) y_maxLBL.grid(row=5,column=0, pady=10) y_maxERY.grid(row=5,column=1, sticky=W, pady=10) root.mainloop()
PHP
UTF-8
269
3.59375
4
[]
no_license
<?php class Person { public $firstName = "Samuel Langhorne"; public $lastName = "Clement"; public $yearBorn = 1899; } $myObject = new Person(); echo $myObject->firstName . "\n"; // accessing the properties $myObject->firstName = 'S.L.'; echo $myObject->firstName;
C++
UTF-8
875
3.140625
3
[]
no_license
//Leetcode 1175 class Solution { public: int MOD; int numPrimeArrangements(int n) { MOD = 1000000007; vector<int> is_prime(n+1, true); is_prime[1] = false; for(int i=2;i<=n;++i) { for(int m=2;;++m) { int v=i*m; if(v>n) break; is_prime[v] = false; } } int prime_num = 0, not_num = 0; for(int i=1;i<=n;++i) { if(is_prime[i]) ++prime_num; else ++not_num; } return (permutate_num(prime_num) * permutate_num(not_num)) % MOD; } long long permutate_num(int c) { long long res = 1; //long long防止int溢出,尽管有MOD求余,但是res*i有可能会超出int范围 for(int i=2;i<=c;++i) res = (res * i) % MOD; return res; } };
Python
UTF-8
3,049
4.4375
4
[]
no_license
#https://leetcode.com/problems/flatten-nested-list-iterator/ ''' Given a list of lists, design an iterator that implements a next() and hasNext() function Inp: [[1,1],2,[1,1]] Out: [1, 1, 2, 1, 1] Inp: [1,[4,[6]]] Out: [1, 4, 6] ''' #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] We initialize the data structure with a list (masquerading as stack). The list is filled with a single nestedList and a location. This question is exactly similar to the manner in which the Flatten Lists Iterator is done. In that question, the hasNext() moves the pointers to the next available position. The next() just returns the number at that location. Once it returns the next number, it perturbs the locations so that the next call of hasNext() moves the pointers back to another appropriate position. """ self.st = [[nestedList, 0]] #Note: We use a list rather than a tuple since we want to make changes to the position attribute (li[1]) def next(self): ''' In case the appropriate nestedLists haven't been discovered, we call the self.hasNext() just to make sure that we are at appropriate nestedInteger''' if self.hasNext(): li, pos = self.st[-1] #Returning the nested integer that hasNext finds as the next appropriate self.st[-1][1] += 1 #perturbing the positions so that hasNext knows to move the pointers forward again. return li[pos].getInteger() raise Exception('No more Elements in NestedList') def hasNext(self): st = self.st while st: #If nothing on stack, return False li, pos = st[-1] # If end of current nestedList has been reached, pop it out of stack. if pos == len(li): st.pop() continue # If current nestedInteger is an integer, then return True (since we have arrived at the appropriate position) if li[pos].isInteger(): return True nesList = li[pos].getList() st[-1][1] += 1 #Forwarding the position pointers of the current list level. st.append([nesList, 0]) #Adding the current list onto the stack return False
TypeScript
UTF-8
3,561
3.046875
3
[]
no_license
import { types, getParent, destroy, flow, getSnapshot } from "mobx-state-tree" import { createHistory } from './History' export type ITodoItem = typeof TodoItem.Type; export type ITodoStore = typeof TodoStore.Type; // A TodoItem contains the information describing a Task export const TodoItem = types .model("Todo", { userId: types.optional(types.number, 1), id: types.number, title: types.string, completed: types.optional(types.boolean, false) }) .actions(self => ({ // Change title given a new title changeLabel(newLabel: string) { self.title = newLabel; }, // Change the completed value given a new completed value changeComplete(newValue: boolean) { self.completed = newValue; }, // Navigate up dependence tree two levels and remove self from tree remove() { // Level 1 = array of todos // Level 2 = todo store getParent(self, 2).remove(self); }, // Use mobx generator function to create synchronous async action // Similiar to async / await // This method mocked for reference only - never used in the app save: flow(function* save() { try { yield window.fetch(`https://jsonplaceholder.typicode.com/todos/1`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(getSnapshot(self)) }) } catch (ex) { console.warn("Unable to save todo", ex) } }) })) // A TodoStore's primary responsibility is to store an array of TodoItems // This model is composed of the typical stuff (models, actions, views) // But also a generic history class that allows undo and redo actions export const TodoStore = types.compose(types .model("TodoStore", { todos: types.optional(types.array(TodoItem), []), loading: types.optional(types.boolean, false) }) .actions(self => ({ // Add todo to todo array add(todo: ITodoItem) { self.todos.push(todo); }, // Remove todo from todo array remove(todo: ITodoItem) { destroy(todo); }, // Load contrived todo suggestions into todo array // Adding randomized id to avoid React 'key' errors getSuggestions: flow(function* getSuggestions(count: number) { self.loading = true; try { const response = yield window.fetch('data/todos.json'); const todos = yield response.json(); // Grab requested number since service returns 200 records const slice = todos.slice(0, count); // Randomize the ID slice.map((item: ITodoItem) => { item.id = Math.floor(Math.random() * 100000000) }) self.todos.push(...slice); self.loading = false; } catch (ex) { console.error("Error while loading suggestions:", ex); self.loading = false; } }) })) .views(self => { // View functions wrapped in literal to allow referencing // internal properties from within other functions // Only works if accessed property is a getter using 'get' // Other options found here: https://github.com/mobxjs/mobx-state-tree#lifecycle-hooks-for-typesmodel const vx = { get todoCount() { return self.todos.length; }, get completedCount() { return self.todos.filter(todo => todo.completed == true).length; }, get completedPct() { if (vx.todoCount == 0) return 0; return Math.floor((vx.completedCount / vx.todoCount) * 100); } } return vx; }), createHistory(["/loading"]) )
Markdown
UTF-8
1,202
3.203125
3
[]
no_license
--- layout: post title: 行ごとに異なるインデックスに” 1 ”を持つ numpy 配列を作成するには date: 2018-10-29 05:36:59 categories: python numpy --- <p>タイトルのような配列を作成したいのですが、効率の良いプログラムが思い浮かばないので<br> 質問させてください。<br> 作成したい配列は、例えば0行目は 0, 2, 4 列目、1行目は 1, 3, 4 列目成分に"1"を持ちそれ以外は"0"を持つといった配列をpythonのfor文を用いずに作成したいです。例で上げた行列は、</p> ``` array = [[1,0,1,0,1], [0,1,0,1,1]] ``` <p>といった行列です。各行でどの列成分に"1"を配置するかを指定する行×1の個数のサイズ<br> (上の例で言えば 2×3 の行列)はすでにあるものとして、効率よく配列を作成する方法があれば<br> 教えていただきたいです。<br> for文を使った場合のコードは以下のようになりました。</p> ``` import numpy as np list_1_index = np.array[[0,2,4],[1,3,4]] array_0_1 = np.zeros(2*5).reshape(2,5) for i in range(len(list_1_index)): array_0_1[i,list_1_index[i,:]] = 1 ```
C
UTF-8
3,280
3.328125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "storage_mgr.h" #include "dberror.h" #include "test_helper.h" RC readBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){ if(pageNum>=1&&pageNum<=totalNumPages){ fseek(fHandle->mgmtInfo, (pageNum-1)*PAGE_SIZE , SEEK_SET); //printf("seeked"); fread(memPage, 1, PAGE_SIZE, fHandle->mgmtInfo); //printf("read") return RC_OK; } else{ return RC_FILE_NOT_FOUND; } } int getBlockPos (SM_FileHandle *fHandle) { return fHandle->curPagePos; //returns current position of the pointer in the file } RC readFirstBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ readBlock(1, fHandle, memPage); //returns the first block = 1 } RC readPreviousBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ readBlock(fHandle->curPagePos-1, fHandle, memPage); // returns the previous block } RC readCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ readBlock(fHandle->curPagePos, fHandle, memPage); //returns the current block } RC readNextBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ readBlock(fHandle->curPagePos+1, fHandle, memPage); // returns the next block } RC readLastBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ readBlock(fHandle->totalNumPages, fHandle, memPage); //returns the last block } RC writeBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){ /* to check the number of pages lies inbetween the pagenumbers available and then add information */ if(pageNum>0 && pageNum<=totalNumPages){ fseek(fHandle->mgmtInfo,(pageNum-1)*PAGE_SIZE, SEEK_SET); fwrite(memPage,PAGE_SIZE,1,fHandle->mgmtInfo); pageNum = pageNum + 1; totalNumPages = totalNumPages + 1; return RC_OK; } /* to create NULL pages and add more information */ else if(pageNum>totalNumPages){ ensureCapacity(pageNum-totalNumPages,fHandle); fseek(fHandle->mgmtInfo,(pageNum-1)*PAGE_SIZE, SEEK_SET); fwrite(memPage,PAGE_SIZE,1,fHandle->mgmtInfo); pageNum = pageNum + 1; totalNumPages = totalNumPages + 1; return RC_OK; } else{ return RC_FAILED_WRITE } } RC writeCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ // to write in the current block writeBlock(fHandle->curPagePos, fHandle, memPage); } RC appendEmptyBlock (SM_FileHandle *fHandle){ //create an empty block with value = NULL ('/0') int i=0; char emptyString[PAGE_SIZE]; for(i=0;i<PAGE_SIZE;i++){ emptyString[i]='\0'; } //find the last page fseek(fHandle->mgmtInfo,fHandle->totalNumPages*PAGE_SIZE,SEEK_SET); //write the empty block fwrite(emptyString,PAGE_SIZE,1,fHandle->mgmtInfo); return RC_OK; fHandle->curPagePos=lastPage; fHandle->totalNumPages = lastPage+1; } RC ensureCapacity (int numberOfPages, SM_FileHandle *fHandle){ /*if there are lesser number of pages => totalNUmPages < numberOfPages appendEmptyBlock numofblocksadded = totalNumPages-numberOfPages location = curPagePos */ int i=0; if(numberOfPages>totalNumPages){ for(i=fHandle->totalNumPages;i<numberOfPages;i++){ appendEmptyBlock(fHandle); } return RC_OK //printf("capacity ensured") } else{ return RC_FAILED_WRITE } }
Java
UTF-8
926
3.015625
3
[]
no_license
package co.edu.unicauca.facade.access; import co.edu.unicauca.facade.domain.order.Order; import java.util.ArrayList; import java.util.List; /** * Esta clase representa la lista de pedidos en la cual se almacenan en dicha lista * * @author Jefferson Eduardo Campo, Hector Esteban Coral */ public class OrderRepositoryList implements IOrderRepository { /** * Array List de pedidos */ private static List<Order> orders; /** * Constructor */ public OrderRepositoryList(){ orders = new ArrayList<Order>(); } /** * método que guarda las ordenes en la lista * @param order Orden se agrega a la lista */ @Override public void createOrder(Order order) { orders.add(order); } /** * Método para obtener la lista de ordenes o pedidos * @return retorna la lista. */ @Override public List<Order> list() { return orders; } }
C++
UTF-8
763
2.828125
3
[]
no_license
//hashTable.h // Author: Benjamin Fogiel #include<iostream> #include<cstring> #include<climits> #include<fstream> #include "minHeap.h" #ifndef HASHTABLE_H #define HASHTABLE_H using namespace std; // A class for Min Heap class HashTable { private: vector<Node> htarr; int numElm; int cap; int tableLen; MinHeap* h; public: bool isPrime(int n); int nextPrime(int N); string st1; // Constructor HashTable(int size, string st); // Destructor //~HashTable(); // Search for element returns index or -1 if not found int search(string s); // Insert void insertHash(string s); // Delete Element void deleteElm(string s); //print heap ascending order void writeHeap(string file); }; #endif
Java
UTF-8
3,702
1.992188
2
[]
no_license
package com.ejemplo.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ejemplo.dto.InfoAuditoria; import com.ejemplo.model.Estudiante; import com.ejemplo.model.EstudianteCurso; import com.ejemplo.repository.EstudianteCursoRepository; import com.ejemplo.repository.EstudianteRepository; import com.ejemplo.service.IEstudianteCursoService; import com.ejemplo.util.InformacionAuditoriaComponent; import com.ejemplo.util.JasperReportComponent; import com.ejemplo.dto.JasperData; @Service public class EstudianteCursoServiceImpl implements IEstudianteCursoService{ @Autowired private EstudianteCursoRepository estudianteCursoRepository=new EstudianteCursoRepository(); @Autowired private InformacionAuditoriaComponent informacionAuditoriaComponent; @Autowired private JasperReportComponent jasperComponent; @Autowired private EstudianteRepository estudianteRepo; @Override public void insert(EstudianteCurso estudiantecurso, HttpServletRequest request) { llenarDatosAuditoria(estudiantecurso, request); estudianteCursoRepository.insert(estudiantecurso); } @Override public List<EstudianteCurso> listarCursosPorEstudiante(Integer estudiante) { return estudianteCursoRepository.listarCursosPorEstudiante(estudiante); } @Override public void update(EstudianteCurso estudianteCurso, HttpServletRequest request) { llenarDatosAuditoria(estudianteCurso, request); estudianteCursoRepository.update(estudianteCurso); } @Override public void delete(EstudianteCurso estudianteCurso, HttpServletRequest request) { llenarDatosAuditoria(estudianteCurso, request); estudianteCursoRepository.delete(estudianteCurso); } @Override public List<EstudianteCurso> listar(Integer codigo) { return estudianteCursoRepository.listar(codigo); } @Override public void cursosPdf(HttpServletResponse response,Integer codigo) { // List<TotalExperiencia> lstTotalExp = tiempoIndividual(); List<EstudianteCurso> lstCursos = listarCursosPorEstudiante(codigo); Estudiante estudiante= estudianteRepo.listarPorCodigo(codigo); JasperData jasper = new JasperData(); Map<String, Object> dataSource = new HashMap<>(); dataSource.put("materias", lstCursos); dataSource.put("codigo", codigo); dataSource.put("nombre", estudiante.getPersona().getNombre()); jasper.setPathJrxml("/static/reporte/pdf/reporte2.jrxml"); jasper.setResponse(response); jasper.setDataSource(dataSource); try { jasperComponent.exportToPdf(jasper); } catch (Exception e) { e.printStackTrace(); } } private void llenarDatosAuditoria(EstudianteCurso estudianteCurso, HttpServletRequest request) { InfoAuditoria infoAuditoria = informacionAuditoriaComponent.getInfoAuditoria(request); estudianteCurso.setCliente(infoAuditoria.getCliente()); estudianteCurso.setIp(infoAuditoria.getIp()); estudianteCurso.setUsuario(infoAuditoria.getUsuario()); } @Override public void notasPdf(HttpServletResponse response, Integer codigo) { List<EstudianteCurso> lstCursos = listarCursosPorEstudiante(codigo); JasperData jasper = new JasperData(); Map<String, Object> dataSource = new HashMap<>(); dataSource.put("estudiante", lstCursos); jasper.setPathJrxml("/static/reportes/pdf/notas.jrxml"); jasper.setResponse(response); jasper.setDataSource(dataSource); try { jasperComponent.exportToPdf(jasper); } catch (Exception e) { e.printStackTrace(); } } }
C++
GB18030
373
2.859375
3
[]
no_license
#include<iostream> #include<string.h> using namespace std; int a[]={2,5,5}; int b[]={2,2,3,5,5,7}; int main() { int cnt=0; int i=0,j=0; while(i<3&&j<6) { if(a[i]==b[j]) { cout<<a[i]<<" "; cnt++; i++,j++; } else if(a[i]<b[j]) { i++; cnt++; } else if(a[i]>b[j]) { j++; cnt++; } } cout<<endl<<"ȽϴΪ"<<cnt<<endl; return 0; }
Java
UTF-8
1,147
2.6875
3
[]
no_license
package com.zhua.spring.webserver.controller; import com.zhua.spring.webserver.publish.service.MyWebService; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.URL; /** * @ClassName JdkWsClient * @Description jdk原生调用(需要获取服务接口文件) * @Author zhua * @Date 2020/8/13 12:42 * @Version 1.0 */ public class JdkWsClient { /** * 启动报错就注释调 pom.xml 的 axis jar包引用 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { URL url = new URL("http://127.0.0.1:11008/webService?wsdl"); // 指定命名空间和服务名称 QName qName = new QName("http://service.zhua.web.com/wsdl", "webService"); Service service = Service.create(url, qName); // 通过getPort方法返回指定接口 MyWebService myServer = service.getPort(new QName("http://service.zhua.web.com/wsdl", "myWebService"), MyWebService.class); // 调用方法 获取返回值 String result = myServer.sayHello("admin"); System.out.println(result); } }
Java
UTF-8
318
1.648438
2
[]
no_license
package com.hmetrix1.dao.imp; import com.hmetrix1.dao.ClusterComponentsDAO; import com.hmetrix1.dto.ClusterComponentDTO; public class ClusterComponentsDAOImp implements ClusterComponentsDAO{ @Override public ClusterComponentDTO accessClusterComponent() { // TODO Auto-generated method stub return null; } }
Java
UTF-8
676
2.234375
2
[]
no_license
package service.faultWarning; import dao.LineDataDao; import bll.predict.PredictInput; import tool.highcharts.LineData; import tool.highcharts.LineDataBuilder; public class WarnViewService { private PredictInput input; public WarnViewService(String tableName, Long time, String ID) { input = LineDataDao.read(tableName, ID,time); } public LineData getComparison(String name) { double[] x=new double[input.getTime().length] ; for (int i = 0; i < input.getTime().length; ++i) { x[i] = Double.parseDouble(input.getTime()[i])*1000; } return LineDataBuilder.createBuilder("", "", name) .addSeries("实测值", x,input.getData()).build(); } }
Swift
UTF-8
2,652
2.515625
3
[]
no_license
// // StartViewController.swift // Math // // Created by William Peroche on 23/06/18. // Copyright © 2018 William Peroche. All rights reserved. // import Foundation import UIKit class StartViewController : UIViewController { @IBOutlet var firstTextField: UITextField! @IBOutlet var operationTextField: UITextField! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var value = [Int]() var operation = [String]() for i in 1...10 { if let button = view.viewWithTag(i) as? UIButton { if button.isSelected { value.append(i) } } } for i in 100...103 { if let button = view.viewWithTag(i) as? UIButton { if button.isSelected { operation.append(button.titleLabel!.text!) } } } guard let destination = segue.destination as? TestViewController else { return } destination.firstArray = value destination.operationArray = operation } @IBAction func startAction() { var value = [Int]() var operation = [String]() for i in 1...10 { if let button = view.viewWithTag(i) as? UIButton { if button.isSelected { value.append(i) } } } for i in 100...103 { if let button = view.viewWithTag(i) as? UIButton { if button.isSelected { operation.append(button.titleLabel!.text!) } } } if value.count == 0 || operation.count == 0 { validateAlert() return } performSegue(withIdentifier: "start", sender: nil) } @IBAction func numberSelection(_ sender: UIButton) { sender.isSelected = !sender.isSelected } @IBAction func operationSelection(_ sender: UIButton) { sender.isSelected = !sender.isSelected } func validateAlert() { view.endEditing(true) let alertController = UIAlertController(title: "Make sure that numbers and operations are selected ", message: "", preferredStyle: UIAlertControllerStyle.alert) let saveAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { alert -> Void in }) alertController.addAction(saveAction) self.present(alertController, animated: true, completion: nil) } }
Java
UTF-8
355
1.703125
2
[]
no_license
package org.mis.bean; import org.hibernate.Session; import org.sky.test.HibernateSessionFactory; /** * Data access object (DAO) for domain model * @author MyEclipse Persistence Tools */ public class BaseHibernateDAO implements IBaseHibernateDAO { public Session getSession() { return HibernateSessionFactory.getSession(); } }
JavaScript
UTF-8
2,297
2.59375
3
[ "MIT" ]
permissive
import mongoose from 'mongoose'; import Follower from '../models/follower'; /** * This function is responsible for returning list * of users that user specified by req.id is following * * @param {Object} req - Router request object * @param {Object} res - Router response object */ export const getFollowers = (req, res, next) => { // Determing if user wants to receive his followers or // users he's following // If req.query.followers is specified followers of given user // will be returned. const condition = req.query.followers ? { populate: 'follower', query: { following: req.params.id }} : { populate: 'following', query: { follower: req.params.id }}; Follower.find(condition.query) .populate(condition.populate, ['_id', 'meta.firstname', 'meta.lastname', 'meta.avatar']) .then(pairs => res.status(200).json(pairs.map(pair => pair[condition.populate]))) .catch(err => next(err)); } /** * Use this function to create new follower pair. * User specified as :id in route param will be assigned * as a follower of req.body.user * * @param req * @param res */'' export const createFollower = (req, res) => { Follower.findOne({ follower: req.params.id, following: req.body.user }) .then(follower => { if(follower) { res.status(400).json({ message: 'You are already following this user'}); throw 'Already following'; } return Follower.findOneAndUpdate( { follower: req.params.id, following: req.body.user }, { follower: req.params.id, following: req.body.user }, { new: true, upsert: true, runValidators: true, setDefaultsOnInsert: true }) .populate('follower', ['_id', 'meta.firstname', 'meta.lastname', 'meta.avatar']) }) .then(pair => res.status(200).json(pair.follower)) .catch(err => next(err)); } /** * Use this function to unfollow certain user. * User specified by :id in route param will no longer * be following req.body.user * * @param req * @param res */ export const deleteFollower = (req, res) => { Follower.deleteOne({ follower: req.params.id, following: req.query.user }) .then(deleted => res.status(200).json(deleted)) .catch(err => next(err)); }
PHP
UTF-8
1,757
2.59375
3
[]
no_license
<?php if(!checklogin()){ exit(); } if($_POST){ //if user did input $studentno=$_SESSION['studentno']; $PostID = (@$_GET['PostID'] ? $_GET['PostID'] : $_POST['PostID']); // if get is null then get post $text = $_POST['text']; //filter $text=addslashes(htmlspecialchars($text)); // PostID is the id of Post to reply // but if PostID==1 that means this is comment. $PostID=intval($PostID); $change = array("\n", "\r\n", "\r"); $text = str_replace($change, '<br>', $text); $time= date("Y/n/j \a\\t g:ia"); //date format: 2014/12/25 at 2:00am //write into sql if(!@mysql_query("INSERT INTO storytelling_report (postid, studentno, text , time)VALUES( $PostID, $studentno, '$text', '$time')")) die( mysql_error ()); echo "<script>alert(\"report success! Thanks for your report.\");"; echo "window.location.href=\"?p=storytelling\"</script>"; } ?> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type"content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="<?php echo $Template ?>storytelling/ext/storytelling.css"> </head> <body> <div id="container"> <form id="Postbox" method="post" action="?p=st_report" enctype="multipart/form-data"> <input id="PostID" type="hidden" value="<?php echo $_GET['PostID'] ?>" name="PostID"> <textarea id="textInput" name="text" placeholder="reason to report this post..." onkeydown="if(event.ctrlKey&&event.keyCode==13){ this.parentNode.buttonSubmit.click(); return false}; "></textarea> <br> <input id="buttonSubmit" type="submit" value="Post (ctrl+enter)" onclick="chkPostingStatus()"> </form> </div> </body> </html>
C
UTF-8
359
3.625
4
[]
no_license
#include <stdio.h> /* 1-11/12: Write a program that prints its input one word per line */ #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ #if defined EOF # undef EOF # define EOF '^' #endif main() { char c; while ( (c = getchar()) != EOF) { if (c == '\t' || c == ' ') putchar('\n'); else putchar(c); } }
PHP
UTF-8
2,939
3.03125
3
[]
no_license
<!-- Programmed By: DJ Booker June 15, 2021 This program will demonstrate 2d arrays --> <html> <head> <style> .error { color: red; } </style> <title> Lab 6 </title> </head> <body> <?php $search = $searchMSG = ""; function validate_input($input) { $input = trim($input); $input = htmlspecialchars($input); return $input; } if ($_POST["submit"]) { $search = validate_input($_POST["search"]); if (empty($search)) $searchMSG = "Search box is required!"; } ?> <!--<div style="background-color:pink;width:60%;margin:auto;text-align:center;">--> <div style="width:60%;margin:auto;"> <h1>City Info Query System</h1> <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <p><span class="error">*required field.</span></p> Query by: <select name="query"> <option value="City" <?php if ($query == "City") echo "selected"; ?>>City</option> <option value="State" <?php if ($query == "State") echo "selected"; ?>>State</option> <option value="Income" <?php if ($query == "Income") echo "selected"; ?>>Income</option> </select> <br /><br /> Type the State, City Name or Income that you want to search: <input type="text" name="search" value="<?php echo $search; ?>"> <span style="color:red;">*<?php echo $searchMSG; ?></span> <br /><br /> <input type=submit name=submit value=submit> </form> <hr /> <?php $CitiInfo = array( array("New York", "NY", 8008278, 103246, 12345), array("Los Angeles", "CA", 3694820, 100000, 12346), array("Chicago", "IL", 2896016, 93591, 12347), array("Houston", "TX", 1953631, 98174, 12348), array("Philadelphia", "PA", 1517550, 91083, 12349), array("Phoenix", "AZ", 1321045, 83412, 29874), array("San Diego", "CA", 1223400, 99247, 29875), array("Dallas", "TX", 1188580, 90111, 29876), array("San Antonio", "TX", 1144646, 89925, 29877), array("Detroit", "MI", 951270, 80188, 29878) ); $found = 0; if ($_POST["submit"]) { if (empty($search)) echo "<br/>"; else { echo "<table border = 1>"; echo "<tr><td>City</td><td>State</td><td>Population</td><td>Income</td> <td>Zipcode</td></tr>"; foreach ($CitiInfo as $search) { if ($_POST["query"] == "City" && $_POST["search"] == $search[0]) { foreach ($search as $value) echo "<td>" . $value . "</td>"; $found++; } else if ($_POST["query"] == "State" && $_POST["search"] == $search[1]) { echo "<tr>"; foreach ($search as $value) echo "<td>" . $value . "</td>"; $found++; echo "<tr>"; } else if ($_POST["query"] == "Income" && $_POST["search"] <= $search[3]) { echo "<tr>"; foreach ($search as $value) echo "<td>" . $value . "</td>"; $found++; echo "</tr>"; } } echo "</table>"; echo "We found " . $found . " results matching your search.</br>"; } } ?> </div> </body> </html>
Java
UTF-8
2,753
2.53125
3
[ "Apache-2.0" ]
permissive
package com.tinkerpop.gremlin.util.optimizers; import com.tinkerpop.blueprints.Compare; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.tinkergraph.TinkerFactory; import com.tinkerpop.gremlin.Gremlin; import com.tinkerpop.gremlin.oltp.filter.HasPipe; import com.tinkerpop.gremlin.oltp.map.GraphQueryPipe; import com.tinkerpop.gremlin.util.optimizers.GraphQueryOptimizer; import org.junit.Test; import static org.junit.Assert.*; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class GraphQueryOptimizerTest { @Test public void shouldPutHasParametersIntoGraphQueryBuilder() { Gremlin<Vertex, Vertex> gremlin = (Gremlin) Gremlin.of(TinkerFactory.createClassic()); gremlin.getOptimizers().clear(); gremlin.V().has("age", 29); assertEquals(2, gremlin.getPipes().size()); assertTrue(gremlin.getPipes().get(0) instanceof GraphQueryPipe); assertTrue(gremlin.getPipes().get(1) instanceof HasPipe); assertEquals("age", ((HasPipe) gremlin.getPipes().get(1)).hasContainer.key); assertEquals(Compare.EQUAL, ((HasPipe) gremlin.getPipes().get(1)).hasContainer.predicate); assertEquals(29, ((HasPipe) gremlin.getPipes().get(1)).hasContainer.value); assertEquals("marko", gremlin.next().<String>getValue("name")); assertFalse(gremlin.hasNext()); gremlin = (Gremlin) Gremlin.of(TinkerFactory.createClassic()); gremlin.getOptimizers().clear(); gremlin.registerOptimizer(new GraphQueryOptimizer()); gremlin.V().has("age", 29); assertEquals(1, gremlin.getPipes().size()); assertTrue(gremlin.getPipes().get(0) instanceof GraphQueryPipe); assertEquals("age", ((GraphQueryPipe) gremlin.getPipes().get(0)).queryBuilder.hasContainers.get(0).key); assertEquals(Compare.EQUAL, ((GraphQueryPipe) gremlin.getPipes().get(0)).queryBuilder.hasContainers.get(0).predicate); assertEquals(29, ((GraphQueryPipe) gremlin.getPipes().get(0)).queryBuilder.hasContainers.get(0).value); assertEquals("marko", gremlin.next().<String>getValue("name")); assertFalse(gremlin.hasNext()); } @Test public void shouldReturnTheSameResultsAfterOptimization() { Gremlin a = (Gremlin) Gremlin.of(TinkerFactory.createClassic()); a.getOptimizers().clear(); a.V().has("age", 29); assertTrue(a.hasNext()); Gremlin b = (Gremlin) Gremlin.of(TinkerFactory.createClassic()); b.getOptimizers().clear(); b.registerOptimizer(new GraphQueryOptimizer()); b.V().has("age", 29); assertTrue(b.hasNext()); assertEquals(a, b); assertFalse(a.hasNext()); assertFalse(b.hasNext()); } }
Markdown
UTF-8
3,388
2.84375
3
[ "Unlicense" ]
permissive
# نتنياهو: لن نسمح أبداً لإيران بتطوير أسلحة نووية Published at: **2019-11-06T00:00:00+00:00** Author: **** Original: [الشرق الأوسط](https://aawsat.com/home/article/1978641/%D9%86%D8%AA%D9%86%D9%8A%D8%A7%D9%87%D9%88-%D9%84%D9%86-%D9%86%D8%B3%D9%85%D8%AD-%D8%A3%D8%A8%D8%AF%D8%A7%D9%8B-%D9%84%D8%A5%D9%8A%D8%B1%D8%A7%D9%86-%D8%A8%D8%AA%D8%B7%D9%88%D9%8A%D8%B1-%D8%A3%D8%B3%D9%84%D8%AD%D8%A9-%D9%86%D9%88%D9%88%D9%8A%D8%A9?utm_source=dlvr.it&utm_medium=twitter) أكد رئيس الوزراء الإسرائيلي المنتهية ولايته بنيامين نتنياهو أن إسرائيل لن تسمح لإيران أبداً بتطوير أسلحة نووية.وقال نتنياهو الليلة الماضية: «في ضوء الجهود الإيرانية الرامية لتوسيع برنامجها لتطوير الأسلحة النووية ولتوسيع تخصيب اليورانيوم الذي يهدف إلى تصنيع القنابل النووية، أقول وأكرر مرة أخرى: لن نسمح أبداً لإيران بتطوير الأسلحة النووية».وأضاف: «هذا ليس من أجل ضمان أمننا ومستقبلنا فحسب، ولكن أيضاً من أجل ضمان مستقبل الشرق الأوسط والعالم كله».جاء هذا رداً على إعلان الرئيس الإيراني حسن روحاني أمس أن بلاده ستبدأ من اليوم الخطوة الرابعة في خفض التزاماتها بموجب الاتفاق النووي.وكان رئيس منظمة الطاقة الذرية الإيرانية علي أكبر صالحي، قد أعلن أمس أن طهران ستبدأ اليوم (الأربعاء) تخصيب اليورانيوم إلى نسبة خمسة في المائة بمنشأتها النووية تحت الأرض في فوردو، مضيفاً أن طهران لديها قدرة تخصيب اليورانيوم إلى 20 في المائة إذا لزم الأمر.ونقلت وكالة أنباء الطلبة عن صالحي قوله: «غداً سنخصب اليورانيوم إلى خمسة في المائة بفوردو... لدينا الآن ما يكفي من اليورانيوم المخصب حتى 20 في المائة، لكن يمكننا إنتاجه إذا اقتضت الضرورة».وكانت الولايات المتحدة قد انسحبت العام الماضي بصورة أحادية من الاتفاق النووي الذي كان يهدف لمنع طهران من الحصول على ترسانة نووية مقابل تقديم مزايا اقتصادية لها.وتمارس الولايات المتحدة حالياً ضغوطاً قصوى على إيران لإجبارها على التفاوض على اتفاق أوسع يتجاوز برنامجها النووي، إلا أن طهران تؤكد أنها لن تدخل في أي مفاوضات مع الولايات المتحدة ما لم تظهر واشنطن «حسن نية».وأدخلت إيران خفضاً واسعاً على الالتزامات المنصوص عليها في الاتفاق من أجل الضغط على الدول الأخرى الأطراف به لاتخاذ خطوات ملموسة لضمان المزايا الاقتصادية المنصوص عليها في الاتفاق لصالح إيران.
TypeScript
UTF-8
418
3
3
[]
no_license
export type ProcessMessage = {type: string, data: any} export type IListener = (msg: any) => void export default class Process { constructor() { } public exit: number = 0 private listeners:Array<IListener> = [] async wait(exit: Promise<void>) { try { await exit } catch(e) { this.handleUncaughtError(e) this.exit = 1 } } handleUncaughtError(e) { console.error(e) } }
Java
UTF-8
437
2.015625
2
[]
no_license
package com.example.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.entity.Board; public interface BoardRepository extends JpaRepository<Board, Long> { /* insert -> save(엔티티 객체) select -> findById(키 타입), getOne(키 타입) update -> save(엔티티 타입) delete -> deleteById(키 타입), delete(엔티티 객체) */ }
Java
UTF-8
900
1.953125
2
[]
no_license
package cn.flyrise.android.protocol.entity.knowledge; import java.util.List; import cn.flyrise.feep.core.network.request.ResponseContent; import cn.flyrise.feep.knowledge.model.SearchFile; /** * Created by klc on 2016/9/23. */ public class SearchFileResponse extends ResponseContent { public Result result; public Result getResult() { return result; } public class Result { private String pageNo; private String pageSize; private List<SearchFile> doc; private String numFound; public int getPageNo() { return Integer.valueOf(pageNo); } public int getPageSize() { return Integer.valueOf(pageSize); } public List<SearchFile> getDoc() { return doc; } public int getNumFound() { return Integer.valueOf(numFound); } } }