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
|
---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 595 | 2.625 | 3 |
[] |
no_license
|
using Calculator.Common.Entities;
using Calculator.Loggers;
namespace Calculator.Web.Services
{
public class ResultSenderService : IResultSenderService
{
private readonly IActivityLogger activityLogger;
public ResultSenderService(IActivityLogger logger)
{
activityLogger = logger;
}
public void SendResultByEmail(Operation operation, double? result)
{
activityLogger.Info($"SendResultByEmail: your operation '{operation.OperationString()}' was calculated, result = {result}");
}
}
}
|
JavaScript
|
UTF-8
| 3,581 | 3.140625 | 3 |
[] |
no_license
|
"use strict";
const intersectAni = function () {
const sections = document.querySelectorAll("section");
const sectionPic = document.querySelector(".section-picture");
const sectionDesc = document.querySelector(".section-description");
const fadeIn = function (entries) {
const [entry] = entries;
if (!entry.isIntersecting) return;
entry.target.classList.remove("section--hide");
if (entry.target === sectionPic) {
sectionDesc.classList.remove("section--hide");
secObs.unobserve(sectionDesc);
}
secObs.unobserve(entry.target);
};
const secObs = new IntersectionObserver(fadeIn, {
root: null,
threshold: 0.3,
});
sections.forEach((s) => {
s.classList.add("section--hide");
secObs.observe(s);
});
};
const slider = function () {
let windowWidth;
console.log(windowWidth);
const slides = document.querySelectorAll(".slide");
const btnLeft = document.querySelector(".slider__btn--left");
const btnRight = document.querySelector(".slider__btn--right");
const dot = document.querySelector(".dots");
let curSlide = 0,
timer,
pause;
const maxSlides = slides.length;
const createDots = function () {
slides.forEach((_, i) => {
dot.insertAdjacentHTML(
"beforeend",
`<button class="dots__dot" data-num="${i}"> </button>`
);
console.log("hello");
});
};
const goToSlide = function (slide) {
slides.forEach((s, i) => {
s.style.transform = `translateX(${100 * (i - slide)}%)`;
});
};
const activeDot = function (curSlide) {
document
.querySelectorAll(".dots__dot")
.forEach((d) => d.classList.remove("dots__dot--active"));
document
.querySelector(`.dots__dot[data-num="${curSlide}"]`)
.classList.add("dots__dot--active");
};
const timeSlide = function () {
const timer = setInterval(function () {
if (curSlide === maxSlides - 1) {
curSlide = 0;
} else {
curSlide++;
}
goToSlide(curSlide);
activeDot(curSlide);
}, 3000);
return timer;
};
const resetTime = function (sec) {
if (pause) clearTimeout(pause);
clearInterval(timer);
pause = setTimeout(() => (timer = timeSlide()), sec * 1000);
return pause;
};
const goToNext = function () {
if (curSlide === maxSlides - 1) {
curSlide = 0;
} else {
curSlide++;
}
goToSlide(curSlide);
activeDot(curSlide);
resetTime(3);
};
const goToPrev = function () {
if (curSlide === 0) {
curSlide = maxSlides - 1;
} else {
curSlide--;
}
goToSlide(curSlide);
activeDot(curSlide);
resetTime(3);
};
const dotClick = function (e) {
if (!e.target.closest(".dots__dot")) return;
console.log("hello");
const dotNum = +e.target.dataset.num;
goToSlide(dotNum);
activeDot(dotNum);
resetTime(3);
};
const init = function () {
createDots();
goToSlide(0);
activeDot(0);
timer = timeSlide();
};
init();
btnRight.addEventListener("click", goToNext);
btnLeft.addEventListener("click", goToPrev);
dot.addEventListener("click", dotClick);
window.addEventListener("resize", function () {
windowWidth = window.innerWidth;
if (windowWidth < 1138) {
clearInterval(timer);
clearTimeout(pause);
slides.forEach((s, i) => {
s.style.transform = ``;
});
} else {
goToSlide(0);
activeDot(0);
dot.innerHTML === "" && createDots();
resetTime(3);
}
});
};
slider();
intersectAni();
|
Ruby
|
UTF-8
| 910 | 2.84375 | 3 |
[] |
no_license
|
class Product < ActiveRecord::Base
validates_uniqueness_of :name
validates_presence_of :name
has_many :costs
def set_cost #second validate it into sql with setcost
if costs.nil?
@costs=Array.new
end
@costs << Cost.new(:valid_from => Time.now,
:amount => @cost,
:product_id => @id)
self.save
end
def cost=(amount) #first put the cost in @cost
@cost = amount #todo validate the amount as a float
end
def cost
cost_at_date(Time.now)
end
def cost_at_date(date)
if costs.empty?
return 0
else
current_cost = @costs.first
for cost in @costs
if cost.valid_from<=date && cost.valid_from>=current_cost.valid_from
current_cost = cost
end
end
return current_cost.amount
end
end
def decrease_stock()
self.stock = self.stock-1
save
end
end
|
Markdown
|
UTF-8
| 2,139 | 3.90625 | 4 |
[] |
no_license
|
## Navigation
- [Chapter 1](#Chapter-1)
- [Chapter 2](#Chapter-2)
## Chapter 1
Strings and Arrays
### 1.1
Implement an algorithm to determine if a string has all unique characters. What if you
cannot use additional data structures?
### 1.2
Given two strings, write a method to decide if one is a permutation of the
other.
### 1.3
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.)
### 1.4
Given a string, write a function to check if it is a permutation of a palindrome.
A palindrome is a word or phrase that is the same forwards and backwards. A permutation
is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
### 1.5
There are three types of edits that can be performed on strings: insert a character,
remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
### 1.6
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
### 1.7
Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
### 1.8
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column are set to 0.
### 1.9
Assume you have a method isSubstringwhich checks if one word is a substring
of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat").
[back to top](#Navigation)
## Chapter 2
[back to top](#Navigation)
|
Markdown
|
UTF-8
| 26,628 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
一直在金融行业里做软件项目,见识了各种形形色色的企业软件开发框架,就像见多了摄影的美景后自己也想去那走一走,所以JEA诞生了。<br>
JEA定位为面向服务的企业级分布式开发集成框架,要完全发挥JEA的各项特性,需要准备多台服务器分别部署应用和支撑系统,如果要商用,相对来说大中型企业可能会更适合些。主要特点如下:<br>
1、分布式远程过程调用:随着SOA越来越深入人心,软件的整体设计可能也会像传统工业社会一样,慢慢向流水线方向发展。曾经接触过很多类似这样的产品:它们独力完成了所有的业务工作,不需要和其它业务系统进行协同工作,随着时间的推移,它们越来越庞大,越来越难维护,而且还会发现一个很神奇的现象,产品里的很多业务功能总是能在同家公司的其它产品里发现。解决这个问题的有效办法是对业务系统进行拆解,根据不同的业务节点拆解成多个子系统,一笔交易通过远程调用的方式由各个子系统协同完成,这样可以很好的控制各子系统的复杂度,同时也能提升业务重用。JEA的分布式远程过程调用是通过Storm的DRPC来实现的,由Spring做IOC容器管理,很容易做横向扩展,开发方面符合Spring通用开发模式,通过Maven生成发布包发布到Storm上,之后即可通过dispatch(String callback, String facadeId, Object... objs)调用,JEA在处理时会首先通过Kryo将对象序列化,然后发送到DRPC服务器,转交给Topology后由Bolt进行反序列化并调用Facade来完成交易。而对于实效性要求不高的异步交易,JEA同样通过ActiveMQ队列方式提供了支持,JEA将对象序列化后发送到相应的队列后结束本次交易,而Storm服务器的MQTopology会定时从队列里轮询,发现有新消息后调用Facade来完成交易。<br>
2、二级缓存和双重缓存(很容易扩展成多级缓存和多重缓存):鉴于分布式多服务器部署的考虑,JEA的缓存服务器只支持Memcached和Redis这二种,同时通过配置可使其支持二级缓存和双重缓存。双重缓存,在往L1缓存数据时会同时往L2缓存一份数据,此时L2将作为L1的备份缓存,如果L1缓存失效,会自动从L2缓存里去获取数据,避免缓存雪崩的发生。二级缓存,Memcached和Redis都是性能优越的缓存服务器,但它们都有各自的特色,相互之间并不能完全替代,有条件的情况下,建议打开JEA的L1缓存和L2缓存,然后往缓存服务器新增或更新缓存数据时,根据实际的业务情况制定缓存策略,决定是将业务数据缓存在L1缓存还是缓存在L2缓存,通过调用CacheContext.set(String cacheLevel, String key, Object value, int seconds)将数据缓存在指定级别的缓存器上。<br>
3、面向服务体系结构:每一个基于JEA进行构建的系统,它即是一个服务提供者,同时它也可以作为服务消费者。向外部系统提供服务时,除了通过Storm和ActiveMQ队列这二种不同时效要求的方式外,JEA还支持更通用的基于WebService的REST服务或者SOAP服务,鉴于性能、稳定性和横向扩展等需要,在企业内部构建SOA服务体系,建议基于Storm+MQ来构建整套服务体系,如果需要提供服务供外部机构调用,再在其基础上额外提供更通用的REST服务或SOAP服务。而向外部系统消费服务时,主要基于外部系统所提供的服务接口方式调用不同的消费方式来获得服务的请求结果,目前允许的消费方式有:ActiveMQ、Storm、REST、SOAP这四种,如果服务提供方提供的是REST服务,此时数据默认将按JSON的方式组织发送。<br>
4、JEA整体是基于Spring进行容器管理,通过Maven进行构建,同时又集成了Hibernate和Mybatis这二大开源ORM框架,所以通过JEA很容易构建出一套SpringMVC系统,系统分层结构:Web->Bridge->Facade->Service->Dao(Integration,对外消费服务),其中Web可以单独部署成Web服务器,Bridge及之后各分层组成StormTopology服务发布到DRPC服务器上,另外在Dao层通过AbstractBaseDAO所提供的各个方法,很容易完成DB层面的CRUD操作,只是需要注意,JEA要求所有的DB事务管理统一交由Hibernate进行管理,所以所有涉及会引发DB数据变化的操作都由Hibernate来完成,而查询操作则交由Mybatis来完成(后续将引入自定义的缓存机制,使Hibernate和Mybatis能够共享缓存内容)。<br>
<br>
JEA使用手册(样例参看:https://github.com/yiyongfei/jea-demo)<br>
1、配置文件jea-core.properties,放在项目Classpath下<br>
#sync mode[SPRING or STORM.LOCAL or STORM.REMOTE]<br>
配置项:sync.mode<br>
说明:实时模式,1)SPRING,通过BeanFactory获取Bean对象,直接执行默认方法完成业务调用;2)STORM.LOCAL,开启STORM本地模式,通过Topology完成业务调用;3)STORM.REMOTE,开启STORM远程模式,通过调用远程注册的Topology完成业务调用;<br>
#db info<br>
配置项:db.driver<br>
说明:数据库驱动<br>
配置项:db.url<br>
说明:数据库连接<br>
配置项:db.username<br>
说明:数据库用户<br>
配置项:db.password<br>
说明:数据库密码<br>
配置项:db.validation<br>
说明:用于校验数据库连接是否有效的SQL(如select 1 from dual)<br>
配置项:db.hibernate.dialect<br>
说明:如org.hibernate.dialect.MySQLDialect<br>
#configure files<br>
配置项:storm.configure.file<br>
说明:指定storm的配置文件名(如storm.properties)<br>
配置项:mq.configure.file<br>
说明:指定MQ的配置文件名(如mq.properties)<br>
配置项:cache.configure.file<br>
说明:指定缓存的配置文件名(如cache.properties)<br>
配置项:topology.context.file<br>
说明:指定Appserver的配置文件名(如applicationContext-appserver.xml),该文件作为业务应用服务器的上下文配置文件<br>
<br>
2、配置文件storm.properties,放在项目Classpath下<br>
[submit.definition](Topology提交类定义,必须有该项内容)<br>
配置项:local<br>
说明:Storm本地模式的Submit提交类<br>
配置项:remote<br>
说明:Storm远程模式的Submit提交类<br>
<br>
[drpc.server](DRPC服务器定义,必须有该项内容)<br>
配置项:host<br>
说明:主机IP地址(如192.168.222.133)<br>
配置项:port<br>
说明:主机端口(如3772)<br>
配置项:timeout<br>
说明:连接超时时间,毫秒(如3000)<br>
<br>
[topology.definition](Topology定义区间,必须有该项内容)<br>
drpc01Topology=com.architecture.example.topology.DrpcTopology<br>
drpc02Topology=com.architecture.example.topology.DrpcTopology<br>
mqTopology=com.architecture.example.topology.MQTopology<br>
mqTopology,自定义Topology在Storm发布时的Topology名<br>
com.architecture.example.topology.MQTopology,对应的Topology类<br>
<br>
[facade.topology.mapping](指定Facade的处理Topology映射,必须有该项内容)<br>
default=drpc01Topology<br>
exampleSaveFacade=drpc02Topology<br>
exampleSaveFacade,在Appserver里定义的Facade对象,由Spring做IOC容器管理<br>
drpc02Topology,在topology.definition定义的Topology名<br>
default,默认处理Topology,如果指定处理的Facade没有映射Topology,则交由默认处理Topology来处理<br>
<br>
3、配置文件cache.properties,放在项目Classpath下<br>
[l1.cache](L1缓存器,必须有该项内容)<br>
配置项:type<br>
说明:缓存类型,1)MEMCACHED;2)REDIS<br>
配置项:activate<br>
说明:是否激活,true表示该缓存器已经激活<br>
配置项:servers<br>
说明:缓存服务器,格式:IP:PORT IP:PORT IP:PORT<br>
配置项:maxTotal<br>
说明:控制一个pool可分配多少个实例<br>
配置项:maxWaitMillis<br>
说明:表示当引入一个实例时,最大的操作等待时间;<br>
配置项:maxConnectMillis<br>
说明:控制一个pool实例超时时间;(只用于Memcached)<br>
配置项:enableHealSession<br>
说明:实例修复开关(设成true时将自动修复失效的连接);(只用于Memcached)<br>
配置项:healSessionInterval<br>
说明:实例修复间隔时间(milliseconds);(只用于Memcached)<br>
配置项:failureMode<br>
说明:(只用于Memcached)<br>
配置项:maxIdle<br>
说明:控制一个pool最多有多少个状态为idle(空闲的)的实例;(只用于Redis)<br>
配置项:testOnBorrow<br>
说明:在引入一个实例时,是否提前进行validate操作;如果为true,则得到的实例均是可用的;(只用于Redis)<br>
配置项:testOnReturn<br>
说明:在return给pool时,是否提前进行validate操作;(只用于Redis)<br>
配置项:lifo<br>
说明:borrowObject返回对象时,是采用DEFAULT_LIFO(last in first out,即类似cache的最频繁使用队列),如果为False,则表示FIFO队列;(只用于Redis)<br>
[l2.cache](L2缓存器,必须有该项内容)<br>
type=见l1.cache说明<br>
activate=见l1.cache说明<br>
servers=见l1.cache说明<br>
maxTotal=见l1.cache说明<br>
maxWaitMillis=见l1.cache说明<br>
maxConnectMillis=见l1.cache说明<br>
enableHealSession=见l1.cache说明<br>
healSessionInterval=见l1.cache说明<br>
failureMode=见l1.cache说明<br>
maxIdle=见l1.cache说明<br>
testOnBorrow=见l1.cache说明<br>
testOnReturn=见l1.cache说明<br>
lifo=见l1.cache说明<br>
<br>
4、配置文件mq.properties,放在项目Classpath下<br>
[mq.server](MQ服务器定义,必须有该项内容)<br>
配置项:host<br>
说明:MQ服务器主机(如tcp://192.168.222.134:61616)<br>
配置项:username<br>
说明:MQ用户名<br>
配置项:password<br>
说明:MQ密码<br>
<br>
[consume.queue.mapping](指定MQ消费者的队列线程,必须有该项内容)<br>
exampleQueue=com.ea.core.achieve.mq.consumer.DefaultConsumer<br>
exampleQueue,自定义的队列名<br>
com.ea.core.achieve.mq.consumer.DefaultConsumer,队列对应的消费线程<br>
<br>
[facade.queue.mapping](指定Facade的处理队列,表示由该队列处理该Facade,必须有该项内容)<br>
default=exampleQueue<br>
default,默认处理队列,如果指定的Facade没有映射队列,则交由默认队列来处理<br>
<br>
5、配置文件applicationContext-appserver.xml,普通的Spring配置文件,唯一需要注意的是该上下文配置文件是应用于业务应用服务器,Web应用服务器将另外提供配置文件,样例如下:<br>
<?xml version="1.0" encoding="UTF-8"?><br>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
default-lazy-init="true"><br>
<description>Spring公共配置 </description> <br>
<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 --><br>
<context:component-scan base-package="com.architecture"></context:component-scan><br>
<context:component-scan base-package="com.ea"></context:component-scan><br>
<context:property-placeholder ignore-resource-not-found="true"
location="classpath*:/jea-core.properties" /><br>
<!-- 配置数据源(连接池,druid) --> <br>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><br>
<property name="driverClassName" value="${db.driver}" /><br>
<property name="url" value="${db.url}" /><br>
<property name="username" value="${db.username}" /><br>
<property name="password" value="${db.password}" /> <br>
<property name="initialSize" value="3" /><br>
<property name="minIdle" value="3" /><br>
<property name="maxActive" value="20" /><br>
<property name="maxWait" value="60000" /><br>
<property name="timeBetweenEvictionRunsMillis" value="60000" /><br>
<property name="minEvictableIdleTimeMillis" value="300000" /><br>
<property name="validationQuery" value="SELECT 'x'" /><br>
<property name="testWhileIdle" value="true" /><br>
<property name="testOnBorrow" value="false" /><br>
<property name="testOnReturn" value="false" /><br>
<property name="poolPreparedStatements" value="true" /><br>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <br>
<property name="filters" value="stat" /><br>
</bean><br>
<!-- 配置Session工厂 --><br>
<bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><br>
<property name="dataSource" ref="dataSource" /><br>
<property name="packagesToScan"><br>
<list><br>
<value>com.architecture</value><br>
</list><br>
</property><br>
<property name="hibernateProperties"><br>
<props><br>
<prop key="hibernate.dialect">${db.hibernate.dialect}</prop><br>
<prop key="hibernate.show_sql">true</prop><br>
<prop key="hibernate.cache.use_second_level_cache">false</prop> <br>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop><br>
</props><br>
</property><br>
</bean><br>
<bean id="mybatisSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><br>
<property name="dataSource" ref="dataSource" /><br>
<property name="configLocation" value="classpath:mybatis.xml" /><br>
<property name="mapperLocations" value="classpath*:/sqlmap/**/*sqlmap-mapping.xml" /><br>
</bean><br>
<!-- 配置SessionTemplate --><br>
<bean id="mybatisSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"><br>
<constructor-arg name="sqlSessionFactory" ref="mybatisSessionFactory" /><br>
</bean><br>
<!-- 配置Hibernate事务管理器 --><br>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"><br>
<property name="sessionFactory" ref="hibernateSessionFactory" /><br>
</bean><br>
<!-- 使用annotation定义事务 --> <br>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" /><br>
</beans><br>
6、Web应用服务器的具体配置见样例,遵循一般的SpringMVC配置即可,若结合Rest或Soap,增加相应的配置文件即可;<br>
7、Web层Controller的开发<br>
1)继承com.ea.core.web.controller.AbstractController,<br>
2)Controller欲调用Facade的业务逻辑时,只需调用父类的方法dispatch(String callback, String facadeId, Object... models)即可;<br>
dispatch方法说明:<br>
参数:callback,调用类型,a)实时调用,WebConstant.CALL_BACK.SYNC;2)准实时调用,WebConstant.CALL_BACK.ASYNC<br>
参数:facadeId,在业务应用服务器定义的Facade的BeanId名称<br>
参数:models,要传递给Facade处理的0到多个的数据对象<br>
返回:Facade的执行结果,如果Facade执行时抛出异常,则Dispatch方法同样抛出相同的异常<br>
<br>
8、Facade层的开发,事务控制统一在Facade层处理<br>
1)如果该Facade不做事务控制,直接继承com.ea.core.facade.AbstractFacade即可<br>
2)如果由该Facade做事务控制,直接继承com.ea.core.facade.AbstractTransactionalFacade即可<br>
3)实现Object perform(Object... obj)方法,在该方法里完成业务逻辑<br>
<br>
9、Service层的开发,Storm必须要求每个注入的类实现序列化接口,定义了公共接口IService<br>
1)实现接口com.ea.core.service.IService<br>
<br>
10、DAO层的开发,完成与DB的交互<br>
1)继承com.ea.core.orm.dao.AbstractBaseDAO<br>
2)通过Hibernate完成单表新增,执行父类的save方法,参数为继承于BasePO的子对象,返回BasePK主键对象<br>
3)通过Hibernate完成单表更新,执行父类的update方法,参数为继承于BasePO的子对象<br>
4)通过Hibernate完成单表删除,执行父类的delete方法,参数为继承于BasePO的子对象<br>
5)通过Hibernate完成单表查看,执行父类的load方法,参数为继承于BasePO的子对象<br>
6)通过Mybatis完成单记录的查询,执行父类的queryOne方法,参数参照sqlmap-mapping.xml里的配置<br>
7)通过Mybatis完成多记录的查询,执行父类的queryMany方法,参数参照sqlmap-mapping.xml里的配置<br>
8)通过Hibernate完成单表单记录的新增、修改、删除,执行父类的executeSQL方法,第1个参数为SQL语句,SQL遵循对应数据库的标准写法,第2个参数为对象数组,按SQL要求的参数次序填充参数内容<br>
9)通过Hibernate完成单表批量记录的新增、修改、删除,执行父类的batchExecuteSQL方法,第1个参数为SQL语句,SQL遵循对应数据库的标准写法,第2个参数为对象数组的集合,按SQL要求的参数次序填充参数内容<br>
<br>
11、Integration层的开发,完成与外部系统的交互,不涉及外部系统的事务<br>
1)如果外部系统提供AcviveMQ服务,继承com.ea.core.integration.bridge.MQIntegration<br>
2)调用方法connect(String host, String username, String password, String queueName, String facadeId, Object... obj)<br>
connect方法说明:<br>
参数:host,远程MQ服务器的主机<br>
参数:username,远程MQ的用户名<br>
参数:password,远程MQ的密码<br>
参数:queueName,要放置的队列名<br>
参数:facadeId,对应的业务FacadeId名称<br>
参数:obj,Facade要使用的参数<br>
<br>
3)如果外部系统提供Storm服务,继承com.ea.core.integration.bridge.StormIntegration<br>
4)调用方法connect(String host, String port, String timeout, String topologyName, String facadeId, Object... obj) <br>
connect方法说明:<br>
参数:host,远程DRPC服务器的主机<br>
参数:port,远程DRPC的端口<br>
参数:timeout,超时时间<br>
参数:topologyName,远程DRPC服务器注册的拓扑名称<br>
参数:facadeId,对应的业务FacadeId名称<br>
参数:obj,Facade要使用的参数<br>
<br>
5)如果外部系统提供Rest服务,继承com.ea.core.integration.bridge.RestIntegration<br>
6)调用方法connect(String host, String httpMethod, String method, Object... obj)<br>
connect方法说明:<br>
参数:host,远程提供REST服务的服务名,如http://127.0.0.1:8080/architecture-demo-web/ws/HelloREST<br>
参数:httpMethod,POST或PUT或GET或DELETE<br>
参数:method,Rest服务对应的方法,如@Path("/update/{id}"),则该方法为update<br>
参数:obj,Rest要使用的参数<br>
<br>
7)如果外部系统提供Soap服务,继承com.ea.core.integration.bridge.SoapIntegration<br>
8)调用方法connect(String host, String method, Object... obj)<br>
connect方法说明:<br>
参数:host,远程提供SOAP服务的服务名,如http://127.0.0.1:8080/architecture-demo-web/ws/HelloSOAP?wsdl<br>
参数:method,SOAP服务对应的方法,如update<br>
参数:obj,SOAP要使用的参数<br>
<br>
12、Bridge层的开发,涉及Storm的开发<br>
1)在architecture-achieve下有部分Storm的默认实现,可以参考实现<br>
2)DRPC的Spout有默认实现,无须开发<br>
3)生成基于DRPC的Bolt,继承com.ea.core.storm.bolt.AbstractDrpcBolt,并实现方法perform(String facadeName, Object... models)<br>
例:<br>
protected Object perform(String facadeName, Object... models) throws Exception {<br>
IFacade facade = (IFacade) AppServerBeanFactory.getBeanFactory().getBean(facadeName);<br>
return facade.facade(models);<br>
}<br>
4)生成基于DRPC的Topology,继承com.ea.core.storm.topology.AbstractDRPCTopology,并实现方法AbstractDrpcBolt setBolt(TopologyBuilder builder, String upStreamId)<br>
例:<br>
protected AbstractDrpcBolt setBolt(TopologyBuilder builder, String upStreamId) {<br>
DefaultDrpcBolt bolt = new DefaultDrpcBolt();<br>
bolt.setBoltName("drpcBolt");<br>
builder.setBolt(bolt.getBoltName(), bolt).noneGrouping(upStreamId);<br>
return bolt;<br>
}<br>
5)非DRPC应用需开发Spout,继承com.ea.core.storm.spout.AbstractRichSpout<br>
6)生成普通Bolt,继承com.ea.core.storm.bolt.AbstractRichBolt<br>
7)生成普通Topology,继承com.ea.core.storm.topology.AbstractTopology,并实现方法AbstractRichBolt setBolt(TopologyBuilder builder, String upStreamId)和IRichSpout initSpout()<br>
例:<br>
protected AbstractRichBolt setBolt(TopologyBuilder builder, String upStreamId) {<br>
MQBolt bolt = new MQBolt();<br>
bolt.setBoltName("mqBolt");<br>
builder.setBolt(bolt.getBoltName(), bolt).noneGrouping(upStreamId);<br>
return bolt;<br>
}<br>
protected IRichSpout initSpout() {<br>
return new MQSpout();<br>
}<br>
8)生成本地模式和远程模式的提交类<br>
本地模式提交类,继承com.ea.core.storm.main.AbstractLocalSubmitTopology<br>
远程模式提交类,继承com.ea.core.storm.main.AbstractSubmitTopology<br>
二者的主要差别在于构造函数:<br>
本地模式:<br>
super();<br>
Config conf = new Config();<br>
......<br>
StormCluster cluster = new StormCluster(new LocalCluster());<br>
super.init(cluster, conf);<br>
远程模式:<br>
super();<br>
Config conf = new Config();<br>
......<br>
StormCluster cluster = new StormCluster(new StormSubmitter());<br>
super.init(cluster, conf);<br>
9)配置storm.properties文件<br>
10)生成远程模式的Main类,如下<br>
public class TopologySubmit {<br>
public static void main(String[] args) throws Exception {<br>
Class<?> className = TopologyDefinition.findSubmitMode(StormConstant.SUBMIT_MODE.REMOTE.getCode());<br>
((ISubmitTopology)className.newInstance()).submitTopology();<br>
}<br>
}<br>
11)通过Maven的maven-assembly-plugin(配置文件内容参见样例项目的assembly.xml),将其打成Jar包,找到以-topology-submit作为后缀的Jar包<br>
12)将该Jar包上传到Storm服务器,进行Topology提交<br>
./storm jar xxx-topology-submit.jar xxx.xxx.TopologySubmit<br>
<br>
13、ActiveMQ队列消费者开发<br>
1)继承com.ea.core.mq.consumer.AbstractConsumer,它是一个线程类,表示从队列里获取一条待处理的消息后,可以另起一个线程来处理,不堵塞<br>
2)实现方法ReceiveDTO deserialize(byte[] aryByte),完成对消息的反序列化工作,返回结果里的requestId,将作为perform的第1个参数,params将作为第2个参数<br>
3)实现方法perform(String facadeId, Object... models)<br>
<br>
14、二级缓存及双重缓存的使用,当前将缓存的上下文交由Spring管理<br>
1)配置好cache.properties<br>
2)通过BeanFactory获取上下文对象CacheContext<br>
3)执行该上下文对象的缓存方法<br>
方法:set(Map<String, Object> map, int seconds)<br>
说明:根据Map对象设置缓存数据,如果Key存在,则会覆盖Value。所有Level的缓存器都会缓存数据。<br>
方法:set(String cacheLevel, Map<String, Object> map, int seconds)<br>
说明:根据Map对象设置缓存数据,如果Key存在,则会覆盖Value。指定Level及后续的缓存器会缓存数据,cacheLevel 缓存级别,如果设置成L2,表明L2及后续的缓存器将缓存数据,但L1不缓存<br>
方法:set(String key, Object value, int seconds)<br>
方法:set(String cacheLevel, String key, Object value, int seconds)<br>
<br>
方法:add(Map<String, Object> map, int seconds)<br>
说明:设置缓存数据,如果Key存在,则缓存不成功.所有Level的缓存器都会缓存数据<br>
方法:add(String cacheLevel, Map<String, Object> map, int seconds)<br>
说明:设置缓存数据,如果Key存在,则缓存不成功。指定Level及后续的缓存器会缓存数据<br>
方法:add(String key, Object value, int seconds)<br>
方法:add(String cacheLevel, String key, Object value, int seconds)<br>
<br>
方法:replace(Map<String, Object> map, int seconds)<br>
说明:设置缓存数据,如果Key不存在,则缓存不成功。所有Level的缓存器都会缓存数据。<br>
方法:replace(String cacheLevel, Map<String, Object> map, int seconds) <br>
说明:设置缓存数据,如果Key不存在,则缓存不成功。指定Level及后续的缓存器会缓存数据<br>
方法:replace(String key, Object value, int seconds)<br>
方法:replace(String cacheLevel, String key, Object value, int seconds)<br>
<br>
方法:Set<String> keys(String pattern, String regexp)<br>
说明:从所有缓存服务器里查找所有指定表达式的Key,不同的缓存服务器里如果存在相同的Key,只返回其中一个。<br>
<br>
方法:expire(String key, int seconds)<br>
说明:设置失效时间,所有Level的缓存器都会设置<br>
<br>
方法:Object get(String key)<br>
说明:根据Key获得缓存数据,从所有Level的缓存器里查找是否符合Key的缓存数据,找到后中止查找直接返回结果<br>
<br>
方法:Boolean exists(String key)<br>
方法:判断Key是否存在<br>
<br>
方法:Map<String, Object> getByRegexp(String pattern, String regexp)<br>
说明:根据正则表达式从所有缓存服务器里获得符合条件的Key和缓存数据<br>
<br>
方法:delete(String key) <br>
说明:根据Key删除缓存数据<br>
<br>
方法:deleteByRegexp(String pattern, String regexp) <br>
说明:根据正则表达式删除符合条件的缓存数据<br>
<br>
|
Markdown
|
UTF-8
| 619 | 2.96875 | 3 |
[] |
no_license
|
---
title: "関数定義の基本"
date: "2003-10-13"
---
Ruby の関数は、下記のように `def` キーワードを使用して定義します。
```Ruby
# メソッドの定義
def add(a, b)
a + b
end
# メソッドの呼び出し
puts add(1, 2)
```
戻り値は `return` を使って明示することができますが、最後に評価した値が関数の戻り値として扱われるので、多くの場合は `return` を省略することができます。
むしろ `return` を省略した方が少しだけ処理が速いらしいです(『Ruby ソースコード完全解説』より)。
|
Java
|
UTF-8
| 5,618 | 3.078125 | 3 |
[] |
no_license
|
package us.fitzpatricksr.cownet.commands.games;
import org.bukkit.plugin.java.JavaPlugin;
import us.fitzpatricksr.cownet.CowNetThingy;
/**
* This class simply manages the state transition changes in the game. It doesn't keep track of
* players, winners, losers or much else. There is a simple callback interface that is used
* to tell clients when the game progresses from one state to the next. The whole class is
* driven by clients calling the getGameState() method.
* <p/>
*/
public class GameGatheringTimer {
private static final int GAME_WATCHER_FREQUENCY = 20 * 1; // 1 second
private static enum GamePhase {
GATHERING, //gathering tributes
LOUNGING, //players are in the arena but can't do anything yet.
IN_PROGRESS, //started but not over yet
ENDED //the game is over
}
public interface Listener {
public void gameGathering();
public void gameLounging();
public void gameInProgress();
public void gameEnded();
public void gameCanceled();
public void announceGather(long time);
public void announceLounging(long time);
public void announceWindDown(long time);
}
@CowNetThingy.Setting
public static long timeToGather = 1 * 60 * 1000; // 1 minute
@CowNetThingy.Setting
public static long timeToLounge = 10 * 1000; // 10 seconds
@CowNetThingy.Setting
public static long timeToRun = 2 * 60 * 1000; // 2 minute game
private Listener listener; // client callback
private long time = System.currentTimeMillis(); // time when the current phase started
private GamePhase gameState = GamePhase.GATHERING; // what stage of the game we're in
private JavaPlugin plugin;
private int gatherTaskId = 0;
public GameGatheringTimer(JavaPlugin plugin, Listener listener) {
this.plugin = plugin;
this.listener = listener;
this.listener.gameGathering();
gatherTaskId = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
gameWatcher();
}
}, GAME_WATCHER_FREQUENCY, GAME_WATCHER_FREQUENCY);
}
public String getGameStatusMessage() {
if (isGathering()) {
long timeToWait = getTimeToGather() / 1000;
return "Game Status: Gathering. The games will start in " + timeToWait + " seconds";
} else if (isGameOn()) {
return "Game Status: IN PROGRESS. " + getTimeUntilEnd() / 1000 + " seconds to go.";
} else {
return "Game Status: Eneded.";
}
}
public boolean isGathering() {
return gameState == GamePhase.GATHERING;
}
public boolean isLounging() {
return gameState == GamePhase.LOUNGING;
}
public boolean isInProgress() {
return gameState == GamePhase.IN_PROGRESS;
}
public boolean isGameOn() {
GamePhase phase = gameState;
return phase == GamePhase.IN_PROGRESS || phase == GamePhase.LOUNGING;
}
public boolean isEnded() {
return gameState == GamePhase.ENDED;
}
private long getTimeToGather() { // private because it is not state aware
return Math.max((timeToGather + time) - System.currentTimeMillis(), 0);
}
private long getTimeToLounge() { // private because it is not state aware
return Math.max((timeToLounge + time) - System.currentTimeMillis(), 0);
}
private long getTimeUntilEnd() { // private because it is not state aware
return Math.max((timeToRun + time) - System.currentTimeMillis(), 0);
}
/* start lounging if we haven't already done so */
public void startLounging() {
if (gameState == GamePhase.GATHERING) {
gameState = GamePhase.LOUNGING;
time = System.currentTimeMillis();
listener.gameLounging();
}
}
/* start the game if it isn't already started */
public void startGame() {
startLounging(); // don't skip lounging phase!
if (gameState == GamePhase.LOUNGING) {
gameState = GamePhase.IN_PROGRESS;
time = System.currentTimeMillis();
listener.gameInProgress();
}
}
public void cancelGame() {
gameState = GamePhase.ENDED;
time = System.currentTimeMillis();
listener.gameCanceled();
}
public void endGame() {
gameState = GamePhase.ENDED;
time = System.currentTimeMillis();
listener.gameEnded();
}
private void gameWatcher() {
if (gameState == GamePhase.GATHERING) {
if (getTimeToGather() <= 0) {
startLounging();
} else {
long timeToWait = getTimeToGather() / 1000;
if (timeToWait % 10 == 0 || timeToWait < 10) {
listener.announceGather(timeToWait);
}
}
}
// we check each state in case some state lasts for 0 time
if (gameState == GamePhase.LOUNGING) {
if (getTimeToLounge() <= 0) {
startGame();
} else {
long timeToWait = getTimeToLounge() / 1000;
listener.announceLounging(timeToWait);
}
}
if (gameState == GamePhase.IN_PROGRESS) {
if (getTimeUntilEnd() <= 0) {
endGame();
} else {
long timeToWait = getTimeUntilEnd() / 1000;
if (timeToWait % 30 == 0 && timeToWait > 10) {
listener.announceWindDown(timeToWait);
} else if (timeToWait <= 10) {
listener.announceWindDown(timeToWait);
}
}
}
if (gameState == GamePhase.ENDED) {
// gamestate here should be ENDED, so kill the timer
if (gatherTaskId != 0) { // gatherTaskId should never be 0 here
plugin.getServer().getScheduler().cancelTask(gatherTaskId);
gatherTaskId = 0;
} else {
// gameWatcher() should only be called by the watcher thread whose ID
// is stored in gatherTaskId. If gatherTaskId == 0, then something
// is calling this method other than the thread or the thread
// wasn't killed properly.
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
|
C++
|
UTF-8
| 203 | 2.75 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main(){
long long a,b,c,d;
cin >> a >> b >> c >> d;
if(b>=c&&d>=a) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
|
PHP
|
UTF-8
| 4,426 | 2.578125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_User extends CI_Model {
public function insert($data)
{
return $this->db->insert('user', $data);
}
public function login($email)
{
//return $this->db->get_where('user', array('username' => $email));
$query = $this->db->query("
SELECT
u.*,
c.NAME as countryName
FROM
user u
JOIN country c ON u.negara = c.iso
WHERE
u.username = '".$email."'
");
return $query;
}
public function update($id, $data)
{
$this->db->where('id', $id);
return $this->db->update('user', $data);
}
public function get()
{
return $this->db->query("
SELECT
u.*,
c.NAME AS countryName
FROM
user u
JOIN country c
WHERE
u.negara = c.iso
");
}
public function getBy()
{
//return $this->db->get_where('user', array('id' => $this->input->get('id')));
return $this->db->query("
SELECT
u.*,
c.NAME AS countryName
FROM
user u
JOIN country c
WHERE
u.negara = c.iso
AND
u.id = ".$this->input->get('id')."
");
}
public function getUsername($username)
{
return $this->db->get_where('user', array('username' => $username));
}
public function delete()
{
return $this->db->delete('user', array('id' => $this->input->get('id')));
}
public function getTotal()
{
$user = $this->db->query("Select count(*) as user from user")->row_array();
$berita = $this->db->query("select count(*) as berita from konten")->row_array();
$isu = $this->db->query("
SELECT
COUNT( * ) as isu
FROM
konten
WHERE
kategori IN ( 'Separatisme', 'Kejahatan Lintas Batas', 'Terorisme', 'PWNI' )
")->row_array();
$bdi = $this->db->query("select count(*) as bdi from konten where kategori = 'BDI'")->row_array();
$bulan = $this->db->query("select count(*) as bulan from konten where kategori = 'Laporan Bulanan'")->row_array();
return [
'total_user' => $user['user'],
'total_berita' => $berita['berita'],
'isu_bersama' => $isu['isu'],
'bdi' => $bdi['bdi'],
'laporan_bulanan' => $bulan['bulan']
];
}
public function resetPass($user)
{
$res = 'Failed';
$config = [
'mailtype' => 'html',
'charset' => 'utf-8',
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com',
'smtp_user' => 'utomoputraw@gmail.com',
'smtp_pass' => 'pusamania94',
'smtp_crypto' => 'ssl',
'smtp_port' => 587,
'crlf' => "\r\n",
'newline' => "\r\n"
];
$data = $this->db->get_where('user', array('username' => $user))->row_array();
$key = $this->generateRandomString();
$updt = array('password' => password_hash($key, PASSWORD_DEFAULT));
$this->load->library('email', $config);
$this->email->from('no-reply@bin.com', 'One Mission');
$this->email->to($data['email']);
$this->email->subject('Reset Password');
$this->email->message("Your new password is: ".$key);
if($this->email->send()){
$this->db->where('id', $data['id']);
$this->db->update('user', $updt);
$res = 'Success';
}
return $this->email->print_debugger();
}
function generateRandomString($length = 10) {
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function editPass($input)
{
$updt = array('password' => password_hash($input['password'], PASSWORD_DEFAULT));
$this->db->where('id', $input['id']);
return $this->db->update('user', $updt);
}
}
?>
|
C++
|
UTF-8
| 1,378 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include "../lib/euler.hpp"
using namespace std;
typedef unsigned long ul;
int main() {
int N = 10000000;
vector<bool> s = sieve(N);
vector<ul> phiArray;
phiArray.resize(N);
// calculate all primes and powers of primes
for (int i = 0; i <= N; ++i) {
if (s[i]) continue;
ul pr = i+2;
ul pr_ = pr, pr__ = pr;
phiArray[pr] = pr-1;
while (pr_*pr <= N) {
pr__ = pr_;
pr_ *= pr;
phiArray[pr_] = pr__*(pr - 1);
}
}
for (int i = 2; i <= N; ++i) {
if (phiArray[i]) continue;
for (int j = 0; j < N; ++j) {
if (s[j] || i % (j+2)) continue;
int i_ = i;
while (i_ % (j+2) == 0)
i_ /= (j+2);
phiArray[i] = phiArray[i_]*phiArray[i/i_];
break;
}
}
double minRatio = 100;
int ans = 0;
for (int i = 2; i <= N; ++i) {
double ratio = double(i)/phiArray[i];
string iStr = to_string(i),
phiStr = to_string(phiArray[i]);
sort(iStr.begin(), iStr.end());
sort(phiStr.begin(), phiStr.end());
if (iStr == phiStr && ratio < minRatio) {
minRatio = ratio;
ans = i;
}
}
cout << ans << endl;
}
|
Java
|
UTF-8
| 210 | 2.5 | 2 |
[] |
no_license
|
package lean.java.example.design.patterns.factory;
/**
* Created by sunyong on 2018-09-06.
*/
public class AudiCar implements Car {
@Override
public String getName() {
return "Audi";
}
}
|
Markdown
|
UTF-8
| 242 | 3.046875 | 3 |
[] |
no_license
|
### Description
Given 2 strings, determine if they are anagrams of each other.
An anagram is a word, phrase, or name formed by rearranging the letters
of one another.
### Examples
cinema > iceman
qwerty > qeywrt
'' > ''
### Input
2 strings
|
Java
|
UTF-8
| 3,530 | 2.421875 | 2 |
[] |
no_license
|
package org.ptolemy.graphiti.generic;
import java.util.Collection;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.ptolemy.graphiti.generic.ActorViewModel.PortKind;
import org.ptolemy.graphiti.generic.EntityViewModel.EntityKind;
public abstract class AbstractViewModel implements NameViewModel {
// from NameViewModel
/**
* Returns the (simple) name of the eObject
* @param eObject
* @return
*/
@Override
public String getName(EObject eObject) {
EStructuralFeature nameFeature = eObject.eClass().getEStructuralFeature("name");
return (nameFeature != null && (! eObject.eIsProxy()) ? (String) eObject.eGet(nameFeature) : null);
}
/**
* Returns the qualified name of the eObject
* @param eObject
* @return
*/
@Override
public String getQualifiedEntityName(EObject eObject) {
StringBuilder buffer = new StringBuilder(getName(eObject));
while (eObject.eContainer() != null) {
eObject = eObject.eContainer();
String name = getName(eObject);
if (name != null) {
buffer.insert(0, ".");
buffer.insert(0, name);
}
}
return buffer.toString();
}
/**
* Returns the owning eObject within which the name must be unique
* @return
*/
@Override
public EObject getNamespace(EObject eObject) {
return eObject.eContainer();
}
// from NameEditModel
/**
* Sets the (simple) name of the eObject to the provided name
* @param eObject
* @param name
* @return
*/
// will @Override if NameEditModel is implemented
public String setName(EObject eObject, String name) {
eObject.eSet(eObject.eClass().getEStructuralFeature("name"), name);
return getName(eObject);
}
protected boolean isUsed(EObject container, String name) {
for (EObject child : container.eContents()) {
String childName = getName(child);
if (name.equals(childName)) {
return true;
}
}
return false;
}
/**
* Returns a unique name in this container, with the provided prefix
* @return
*/
// will @Override if NameEditModel is implemented
public String getUniqueName(EObject eObject, String prefix) {
int count = 1;
while (isUsed(eObject, prefix + count)) {
count++;
}
return prefix + count;
}
// support for ActorViewModel
protected abstract boolean isPort(EObject port, PortKind portKind);
protected void addPorts(Collection<? extends EObject> ports, PortKind portsKind, PortKind[] portKinds, Collection<EObject> allPorts) {
if (portKinds == null || portKinds.length == 0) {
allPorts.addAll(ports);
} else {
for (PortKind portKind : portKinds) {
if (portsKind == null) {
for (EObject port : ports) {
if (isPort(port, portKind)) {
allPorts.add(port);
}
}
} else if (portKind == portsKind) {
allPorts.addAll(ports);
break;
}
}
}
}
protected abstract boolean isEntity(EObject entity, EntityKind entityKind);
protected void addEntities(Collection<? extends EObject> entities, EntityKind entitiesKind, EntityKind[] entityKinds, Collection<EObject> allEntities) {
if (entityKinds == null || entityKinds.length == 0) {
allEntities.addAll(entities);
} else {
for (EntityKind entityKind : entityKinds) {
if (entityKind == null) {
for (EObject entity : entities) {
if (isEntity(entity, entityKind)) {
allEntities.add(entity);
}
}
} else if (entityKind == entitiesKind) {
allEntities.addAll(entities);
break;
}
}
}
}
}
|
PHP
|
UTF-8
| 130 | 2.625 | 3 |
[] |
no_license
|
<?php
class Object implements Serializable{
public function serialize(){
}
public function unserialize($serialized){
}
}
|
Java
|
UTF-8
| 583 | 3.328125 | 3 |
[] |
no_license
|
package objects;
import java.util.Map;
public class ShoppingCart {
private Map<Book, Integer> bookCopies;
public ShoppingCart(Map<Book, Integer> bookCopies) {
this.bookCopies = bookCopies;
}
public Map<Book, Integer> getBookCopies() {
return bookCopies;
}
public void setBookCopies(Map<Book, Integer> bookCopies) {
this.bookCopies = bookCopies;
}
/**
* Assumes that only one copy of a book is always added to the shopping cart.
* @param newBook
*/
public void addBook(Book newBook) {
this.bookCopies.put(newBook, 1);
}
}
|
JavaScript
|
UTF-8
| 1,002 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
/**
* Explanation of the algorithm:
* https://codility.com/media/train/6-Leader.pdf
*/
function solution(A) {
// sort the input
const _A = [...A]
A.sort((a,b) => a - b)
// find the leader (stack method)
let stack = []
for (let x=0; x<A.length; x++) {
if (x == 0) {
stack.push(A[x])
} else {
if (stack.length > 0 && (stack[stack.length-1] != A[x])) {
stack.pop()
} else {
stack.push(A[x])
}
}
}
if (stack.length > 0) {
const cand = stack[0]
// check cardinality of cand
let count = 0
for (let y=0; y<_A.length; y++) {
if (_A[y] == cand) {
count ++
}
}
if (count > _A.length / 2) {
return _A.indexOf(cand)
} else { // cand was not a leader
return -1
}
} else { // no leader
return -1
}
}
module.exports = solution
|
Markdown
|
UTF-8
| 1,416 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
# DBView
DBView is a lightweight tool to view and manage your remotely hosted databases in the browser. While desktop database management software is powerful, it can be overwhelming and require unecessary overhead when your only needs are viewing tables and performing standard tasks (especially for those with limited database experience). On the other hand, CLIs are lightweight, but they are not well suited to viewing data, and using them to build large queries can be frustrating. DBView was created to provide developers an easy way to acesss their databases without any installation. This project is still in the very early stages of development.
## Installation
```
git clone https://github.com/dbviews/dbview
cd dbview
npm install
```
Then run `npm start` to start the local server.
We also provide an npm script to create a sample table in your database. To execute this script, run `npm run fillDB`.
## Running tests
We use [mocha](https://mochajs.org/), [supertest](https://github.com/visionmedia/supertest), and [karma](http://karma-runner.github.io/1.0/index.html) to run tests.
### Server side tests
Located in `test/supertest.js`
```
npm test
```
### Client side tests
It's easiest to run the client side tests if you install the karma CLI globally.
```
npm install -g karma-cli
```
Then, navigate to `dview/` and run the tests:
```
karma start
```
These tests are located in `test/client/`.
|
Python
|
UTF-8
| 3,039 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# coding=utf-8
import os
import unittest
import HTMLTestRunner
from framework.util.Config import Config
from framework.util.Email import Email
from framework.util.Log import Log
TAG = os.path.basename(__file__)
class TestRunner:
_instance = None
def __init__(self):
pass
def setUpTestSuite(self, case_dir):
testsuite = unittest.TestSuite()
testmodules = []
discover = unittest.defaultTestLoader.discover(case_dir, pattern='*.py', top_level_dir=None)
testmodules.append(discover)
if len(testmodules) > 0:
for module in testmodules:
for testcase in module:
testsuite.addTest(testcase)
else:
return None
return testsuite
@classmethod
def _getInstance(cls):
if cls._instance is None:
cls._instance = TestRunner()
return cls._instance
@classmethod
def run(cls, case_dir=os.path.join(os.getcwd(), "testcases")):
instance = cls._getInstance()
Log.i(TAG, "********TEST START********")
fp = None
try:
testsuite = instance.setUpTestSuite(case_dir)
if testsuite is not None:
report_dir = Config.get("REPORT", "dir")
if report_dir is None:
report_dir = os.path.join(os.getcwd(), "result")
else:
if os.path.exists(report_dir) and os.path.isdir(report_dir):
try:
os.removedirs(report_dir)
Log.i(TAG, "remove dir: " + report_dir)
except Exception as e:
Log.e(TAG, "remove failed: " + report_dir + ", exception: " + str(e))
try:
os.mkdir(report_dir)
except Exception as e:
Log.e(TAG, "mkdir failed: " + report_dir + ", exception: " + str(e))
report_file = Config.get("REPORT", "file")
if report_file is None:
report_file = "report.html"
report_path = os.path.join(report_dir, report_file)
fp = open(report_path, 'wb')
runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Report', description='Test Description')
runner.run(testsuite)
else:
Log.i(TAG, "No testcase was found .")
except Exception as ex:
Log.e(TAG, str(ex))
finally:
if fp is not None:
fp.close()
# send test report by email
email_switch = Config.get("EMAIL", "switch")
if email_switch == 'on':
Email.send()
elif email_switch == 'off':
Log.i(TAG, "Do not send report via email")
else:
Log.e(TAG, "Unknow state.")
Log.i(TAG, "********TEST END**********")
if __name__ == "__main__":
TestRunner.run()
|
Java
|
UTF-8
| 2,796 | 2.53125 | 3 |
[] |
no_license
|
package com.bus.hbm;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="firstname")
private String fname;
@Column(name="lastname")
private String lname;
@Column(name="username")
private String username;
@Column(name="emailid")
private String emailId;
public Users(int id, String fname, String lname, String username, String emailId) {
super();
this.id = id;
this.fname = fname;
this.lname = lname;
this.username = username;
this.emailId = emailId;
}
public Users() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Users [id=" + id + ", fname=" + fname + ", lname=" + lname + ", username=" + username + ", emailId="
+ emailId + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((emailId == null) ? 0 : emailId.hashCode());
result = prime * result + ((fname == null) ? 0 : fname.hashCode());
result = prime * result + id;
result = prime * result + ((lname == null) ? 0 : lname.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Users other = (Users) obj;
if (emailId == null) {
if (other.emailId != null)
return false;
} else if (!emailId.equals(other.emailId))
return false;
if (fname == null) {
if (other.fname != null)
return false;
} else if (!fname.equals(other.fname))
return false;
if (id != other.id)
return false;
if (lname == null) {
if (other.lname != null)
return false;
} else if (!lname.equals(other.lname))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
|
TypeScript
|
UTF-8
| 2,751 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import { Readable } from 'stream';
import { FastifyInstance } from 'fastify';
import td from 'testdouble';
import { getArtwork } from '@/api/routes/getArtwork';
import { ArtworksService } from '@/services/ArtworksService';
import { mockToken } from '../mockToken';
import test from '../setupTestServer';
async function setup(server: FastifyInstance): Promise<ArtworksService> {
const artworksService = td.object<ArtworksService>();
await server.register(mockToken());
await server.register(getArtwork({ artworksService }));
return artworksService;
}
test('it should return an error when given an invalid artwork type', async t => {
await setup(t.context.server);
const response = await t.context.server.inject({
method: 'GET',
path: '/artwork/invalid/a3347ad5-8374-4e18-8d94-257b3ca802bb',
});
t.is(response.statusCode, 404);
});
test('it should return an error when given an invalid uuid', async t => {
await setup(t.context.server);
const response = await t.context.server.inject({
method: 'GET',
path: '/artwork/album/a3347ad5',
});
t.is(response.statusCode, 400);
});
test('it should return an error when given an invalid size', async t => {
await setup(t.context.server);
const response = await t.context.server.inject({
method: 'GET',
path: '/artwork/album/a3347ad5-8374-4e18-8d94-257b3ca802bb',
query: {
size: '645',
},
});
t.is(response.statusCode, 400);
});
test('it should return an error when artwork cannot be found', async t => {
const artworksService = await setup(t.context.server);
td.when(
artworksService.createArtworkStream(
'album',
'a3347ad5-8374-4e18-8d94-257b3ca802bb',
96,
),
).thenResolve(Error('not found'));
const response = await t.context.server.inject({
method: 'GET',
path: '/artwork/album/a3347ad5-8374-4e18-8d94-257b3ca802bb',
query: {
size: '96',
},
});
t.is(response.statusCode, 404);
});
test('it should return a stream', async t => {
const artworksService = await setup(t.context.server);
async function* generate() {
yield 'hello ';
yield 'world';
}
const readable = Readable.from(generate());
td.when(
artworksService.createArtworkStream(
'album',
'a3347ad5-8374-4e18-8d94-257b3ca802bb',
96,
),
).thenResolve({
stream: readable,
size: 11,
});
const response = await t.context.server.inject({
method: 'GET',
path: '/artwork/album/a3347ad5-8374-4e18-8d94-257b3ca802bb',
query: {
size: '96',
},
});
t.is(response.statusCode, 200);
t.is(response.headers['content-type'], 'image/jpeg');
t.is(response.headers['content-length'], 11);
t.is(response.body, 'hello world');
});
|
Python
|
UTF-8
| 234 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
def get_average(li):
sum = 0
for num in li:
sum += num
mean = sum / len(li)
return mean
def test_get_average():
num1 = 10
num2 = 20
numbers = [num1, num2, 50]
assert(get_average(numbers)) == 40
|
C++
|
UTF-8
| 4,865 | 2.5625 | 3 |
[] |
no_license
|
#include "SpriteFactory.h"
#include "../Maths/Matrix4.h"
#include "../Graphics/Mesh.h"
#include "../Graphics/VertexBuffer.h"
#include "../Graphics/IndexBuffer.h"
#include "../Graphics/Material.h"
#include "../Graphics/Shader.h"
#include "../Resources/ResourceManager.h"
#include "../Platform/Application.h"
using namespace GLESGAE;
Resources::Locator SpriteFactory::create(const Vector2& scale, const unsigned int u, const unsigned int v, const unsigned int s, const unsigned int t)
{
ResourceManager* resourceManager(Application::getInstance()->getResourceManager());
Resource<Shader> shader;
if (Resources::INVALID != mSettings.shader.bank) { // Shader bank isn't strictly necessary for Fixed Function, so we can safely ignore this.
ResourceBank<Shader>& shaderBank(resourceManager->getBank<Shader>(mSettings.shader.bank, Resources::Shader));
shader = (shaderBank.add(mSettings.shader.group, Resources::Shader, makeSpriteShader()));
}
const unsigned int texWidth(mTexture->getWidth());
const unsigned int texHeight(mTexture->getHeight());
// (0,0) is bottom left, we want it top left so that pixel co-ords match from a graphics editor.
float texU(static_cast<float>(u) / texWidth);
float texV(static_cast<float>(texHeight - v) / texHeight);
float texS(static_cast<float>(s) / texWidth);
float texT(static_cast<float>(texHeight - t) / texHeight);
const float texelOffsetWidth(0.00125F);
const float texelOffsetHeight(0.00125F);
if (u > 0U)
texU += texelOffsetWidth;
if (v > 0U)
texV += texelOffsetHeight;
if (s < texWidth)
texS += texelOffsetWidth;
if (t < texHeight)
texT += texelOffsetHeight;
ResourceBank<Mesh>& meshBank(resourceManager->getBank<Mesh>(mSettings.mesh.bank, Resources::Mesh));
Resource<Mesh>& mesh(meshBank.add(mSettings.mesh.group, Resources::Mesh, makeSprite(scale, shader, texU, texV, texS, texT)));
Resources::Locator locator(mSettings.mesh);
locator.resource = mesh.getId();
return locator;
}
Mesh* SpriteFactory::makeSprite(const Vector2& scale, const Resource<Shader>& shader, const float u, const float v, const float s, const float t)
{
float vertexData[32] = {// Position - 16 floats
-1.0F * scale.x(), 1.0F * scale.y(), 0.0F, 1.0F,
1.0F * scale.x(), 1.0F * scale.y(), 0.0F, 1.0F,
1.0F * scale.x(), -1.0F * scale.y(), 0.0F, 1.0F,
-1.0F * scale.x(), -1.0F * scale.y(), 0.0F, 1.0F,
// Tex Coords - 8 floats
u, v, // bottom left
s, v, // top left
s, t, // top right
u, t}; // bottom right
unsigned int vertexSize = 25 * sizeof(float);
unsigned char indexData[6] = { 0, 1, 2, 2, 3, 0 };
unsigned int indexSize = 6 * sizeof(unsigned char);
ResourceManager* resourceManager(Application::getInstance()->getResourceManager());
ResourceBank<Material>& materialBank(resourceManager->getBank<Material>(mSettings.material.bank, Resources::Material));
ResourceBank<VertexBuffer>& vertexBank(resourceManager->getBank<VertexBuffer>(mSettings.vertex.bank, Resources::VertexBuffer));
ResourceBank<IndexBuffer>& indexBank(resourceManager->getBank<IndexBuffer>(mSettings.index.bank, Resources::IndexBuffer));
Resource<VertexBuffer>& newVertexBuffer(vertexBank.add(mSettings.vertex.group, Resources::VertexBuffer, new VertexBuffer(reinterpret_cast<unsigned char*>(&vertexData), vertexSize)));
newVertexBuffer->addFormatIdentifier(VertexBuffer::FORMAT_POSITION_4F, 4U);
newVertexBuffer->addFormatIdentifier(VertexBuffer::FORMAT_TEXTURE_2F, 4U);
Resource<IndexBuffer>& newIndexBuffer(indexBank.add(mSettings.index.group, Resources::IndexBuffer, new IndexBuffer(reinterpret_cast<unsigned char*>(&indexData), indexSize, IndexBuffer::FORMAT_UNSIGNED_BYTE)));
Resource<Material>& newMaterial(materialBank.add(mSettings.material.group, Resources::Material, new Material));
newMaterial->setShader(shader);
newMaterial->addTexture(mTexture);
return new Mesh(newVertexBuffer, newIndexBuffer, newMaterial);
}
/// Helper function to generate a shader if need be.
Shader* SpriteFactory::makeSpriteShader()
{
std::string vShader =
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord0; \n"
"varying vec2 v_texCoord0; \n"
"uniform mat4 u_mvp; \n"
"void main() \n"
"{ \n"
" gl_Position = u_mvp * a_position; \n"
" v_texCoord0 = a_texCoord0; \n"
"} \n";
std::string fShader =
#ifdef GLES2
"precision mediump float; \n"
#endif
"varying vec2 v_texCoord0; \n"
"uniform sampler2D s_texture0; \n"
"void main() \n"
"{ \n"
" gl_FragColor = texture2D(s_texture0, v_texCoord0); \n"
" gl_FragColor.a = 1.0; \n"
"} \n";
#ifndef GLES1
Shader* newShader(new Shader());
newShader->createFromSource(vShader, fShader);
return newShader;
#else
return 0;
#endif
}
|
Python
|
UTF-8
| 1,584 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
from os import environ
from fastapi.exceptions import HTTPException
from fastapi.security import HTTPBearer
from jwt import decode
from pydantic import BaseModel
from starlette.requests import Request
from starlette.status import HTTP_403_FORBIDDEN
KEY = environ.get("KEY", "secret")
# Authenticate Model
class LazyUser(BaseModel):
"""
A lazy user model.
Args:
BaseModel (pydantic.BaseModel): Base model class.
"""
username: str
password: str
role: str
class LazyAuth(HTTPBearer):
"""
A custom authentication class that uses the JWT token to authenticate the user.
Args:
HTTPBearer (class): The class that handles the authentication.
"""
async def __call__(self, request: Request) -> LazyUser:
"""
The authentication method.
Args:
request (Request): The request object.
Raises:
HTTPException: If the token is invalid.
Returns:
LazyUser: The user object.
"""
cred = await super().__call__(request)
try:
user = decode(cred.credentials, key=KEY, algorithms="HS256")
except Exception as exp:
"""
If the token is invalid, raise an HTTPException.
Raises:
HTTPException: If the token is invalid.
"""
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail=str(exp),
)
return LazyUser(**user)
authentication_lazy = LazyAuth(scheme_name="Bearer", auto_error=False,)
|
Python
|
UTF-8
| 2,370 | 3.09375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
# stdlib
import glob
import os.path
import sys
def public(f):
""""Use a decorator to avoid retyping function/class names.
* Grabbed from recipe by Sam Denton
http://code.activestate.com/recipes/576993-public-decorator-adds-an-item-to-__all__/
* Based on an idea by Duncan Booth:
http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a
* Improved via a suggestion by Dave Angel:
http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8a42e1
"""
all = sys.modules[f.__module__].__dict__.setdefault('__all__', [])
if f.__name__ not in all: # Prevent duplicates if run from an IDE.
all.append(f.__name__)
return f
public(public)
def is_path_under_directory(path, directory):
"""Return True if ``path`` is in ``dir``.
This operates only on paths and does not actually access the filesystem.
"""
# TODO(brownhead): This might not handle unicode correctly...
directory = os.path.abspath(directory) + "/"
path = os.path.abspath(path) + "/"
return path.startswith(directory)
def glob_foreach_list(foreach):
"""Globs a path/paths and return the flattened result.
An IOError will be raised if no results are found for a particular glob.
:param foreach: The path(s) to glob.
:type foreach: list, str, or unicode
:return: The sorted list of paths.
:Example:
>>> glob_foreach_list(["b/*", "a"])
["a", "b/1", "b/2"]
>>> glob_foreach_list("b/*")
["b/1", "b/2"]
>>> glob_foreach_list([])
[]
"""
listified = foreach
if isinstance(foreach, basestring):
listified = [foreach]
# Glob any strings in the list.
globbed_list = []
for i in listified:
if isinstance(i, basestring):
found = glob.glob(i)
if not found:
raise IOError("No files found matching glob {0!r}".format(i))
globbed_list += found
else:
globbed_list.append(i)
return sorted(globbed_list)
def makedirs(path):
try:
os.makedirs(path)
except OSError as e:
# This is a little racey, but does a good job at reducing massive log spam, so definitely
# a net win.
if e.errno != 17 and os.path.isdir(path):
raise
@public
def swap_extension(path, new_extension):
return os.path.splitext(path)[0] + new_extension
|
Java
|
UTF-8
| 2,659 | 2.5625 | 3 |
[] |
no_license
|
package eu.eyan.amoba.gui;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import com.jgoodies.forms.factories.CC;
import com.jgoodies.forms.layout.FormLayout;
public class AmobaTablaView extends JPanel
{
private static final long serialVersionUID = 1L;
private Field jelzo = new Field();
private Field[][] fields = new Field[3][3];
public AmobaTablaView()
{
initTabla();
jelzo.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
initTabla();
}
});
}
private void initTabla()
{
this.removeAll();
this.setLayout(new FormLayout("pref,pref,pref", "pref,pref,pref,pref"));
for (int x = 0; x < fields.length; x++)
{
for (int y = 0; y < fields[x].length; y++)
{
Field mezo = new Field();
fields[x][y] = mezo;
this.add(mezo, CC.xy(x + 1, y + 2));
mezo.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
mezoKlick(e);
}
});
}
}
this.add(jelzo, CC.xy(2, 1));
jelzo.setText("x");
this.revalidate();
}
private void mezoKlick(MouseEvent e)
{
Field mezo = (Field) e.getSource();
if (mezo.getText().equals(""))
{
mezo.setText(jelzo.getText());
if (jelzo.getText().equals("x"))
{
jelzo.setText("o");
}
else
{
jelzo.setText("x");
}
}
checkTable(fields);
}
private void checkTable(Field[][] fields)
{
for (int i = 0; i < fields.length; i++)
{
checkFields(fields[0][i], fields[1][i], fields[2][i]);
checkFields(fields[i][0], fields[i][1], fields[i][2]);
}
checkFields(fields[0][0], fields[1][1], fields[2][2]);
checkFields(fields[2][0], fields[1][1], fields[0][2]);
}
private void checkFields(Field... fields)
{
String first = fields[0].getText();
for (Field field : fields)
{
if (!first.equals(field.getText()) || first.equals(""))
{
return;
}
}
for (Field field : fields)
{
field.setForeground(Color.red);
}
}
}
|
Python
|
UTF-8
| 294 | 2.78125 | 3 |
[] |
no_license
|
for t in range(int(input())):
n, m = map(int, input().split())
a = [list(input().strip()) for _ in range(n)]
ans = 0
for y in range(n-1):
if a[y][m-1] != "D":
ans += 1
for x in range(m-1):
if a[n-1][x] != "R":
ans += 1
print(ans)
|
PHP
|
UTF-8
| 1,977 | 2.875 | 3 |
[] |
no_license
|
<?php
/**
* Classe de entidade Artigo
*/
include_once('Categoria.class.php');
include_once('../../Utilizador/entity/Usuario.class.php');
class Article
{
private $id;
private $titulo;
private $conteudo;
private $dataPublicacao;
private $tags;
private $publicado;
private $imagem;
private $banner;
private $Categoria;
private $user;
function __construct()
{
$Categoria = new Categoria();
$tags = Array();
}
public function setId($id){
$this->id = $id;
}
public function getId(){
return $this->id;
}
public function setTitulo($titulo){
$this->titulo = $titulo;
}
public function getTitulo(){
return self::titulo;
}
public function setConteudo($conteudo){
$this->conteudo = $conteudo;
}
public function getConteudo(){
return $this->conteudo;
}
public function setCategoria($Categoria){
$this->Categoria = $Categoria;
}
public function getCategoria(){
return $this->Categoria;
}
public function setPublicado($publicado){
$this->publicado = $publicado;
}
public function getPublicado(){
return $this->publicado;
}
public function setImagem($imagem){
$this->imagem = $imagem;
}
public function getImagem(){
return $this->imagem;
}
public function setDtPublicacao($dataPublicacao){
$this->dataPublicacao = $dataPublicacao;
}
public function getDtPublicacao(){
return $this->dataPublicacao;
}
public function setTags($tags){
$this->tags = $tags;
}
public function getTags(){
return $this->tags;
}
public function setPublicado($publicado){
$this->publicado = $publicado;
}
public function getPublicado(){
return $this->publicado;
}
public function setBanner($banner){
$this->banner = $banner;
}
public function getBanner(){
return $this->banner;
}
public function setUser($usuario) {
$this->user = $usuario;
}
public function getUser() {
return $this->user;
}
}
?>
|
JavaScript
|
UTF-8
| 676 | 2.609375 | 3 |
[] |
no_license
|
export const getCustomerData = async () => {
const response = await fetch('http://localhost:5000/customer-data');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message);
}
return body;
};
export const postCustomerData = async customers => {
const data = JSON.stringify(customers);
const response = await fetch('http://localhost:5000/customer-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: data
});
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message);
}
return body;
};
|
TypeScript
|
UTF-8
| 2,626 | 2.71875 | 3 |
[] |
no_license
|
import {Component, OnInit, Input, Output} from '@angular/core';
import {Book} from "../shared/book";
import {ActivatedRoute, Router} from "@angular/router";
import {BookStoreService} from "../shared/book-store.service";
import {AuthService} from "../shared/authentication-service";
@Component({
selector: 'bs-book-details',
templateUrl: './book-details.component.html',
styles: []
})
export class BookDetailsComponent implements OnInit {
@Input() book : Book;
constructor(
private bs: BookStoreService,
private router: Router,
private route: ActivatedRoute,
private authService: AuthService
){}
ngOnInit() {
//route gets separeted and saved in an array
const params = this.route.snapshot.params;
// b is the book, and is now an observeable
this.bs.getSingle(params['isbn']).subscribe(
b => this.book = b
);
}
/**
* @desc book is going to be removed from the database
* */
removeBook(){
if (confirm("Buch wirklich löschen?")){
this.bs.remove(this.book.isbn)
.subscribe(res=> this.router.navigate(['../'], {relativeTo: this.route}));
}
}
/**
* @desc adds book to the shoppingCart via localStorage
* */
addToCart(){
//create new Item
let newItem={
book : this.book,
amount: 1,
};
let cart;
//if there is no cart in the localStorage create a new array
if (!localStorage.getItem('cart')) cart = [];
//get cart from the localStorage and save it in an array
else cart = JSON.parse(localStorage.getItem('cart'));
if (!(cart instanceof Array)) cart = [];
//check if the book is already in the shoppingCart
let bookExists = false;
for (let i = 0; i < cart.length; i++) {
if(newItem.book.isbn === cart[i].book.isbn){
bookExists = true;
//change amaount of book, when book already exists in shoppingCart
cart[i].amount++;
let price = this.book.bruttoPrice * cart[i].amount;
cart[i].book.bruttoPrice = price.toFixed(2);
break;
}
}
//push item in cart array when it doesn't already exist
if(bookExists === false){
cart.push(newItem);
}
//set array cart in localStorage
localStorage.setItem('cart', JSON.stringify(cart));
console.log(localStorage);
}
getRating (num: number) {
return new Array(num);
}
}
|
Markdown
|
UTF-8
| 7,489 | 2.640625 | 3 |
[] |
no_license
|
一〇〇
方振远随在那人的身后,进入楼上一间雅室之中。
垂帘起处,只见一个身穿蓝色劲装的少年,端坐房中。
蓝衣少年一见方振远,立刻起身迎了上来,欠身一礼,道:“方老前辈,还记得在下吗?”
方振远仔细看去,只觉似曾相识,但一时之间,却又想不起来,怔了一怔,道:“阁下是……”
蓝衣少年道:“晚辈姓铁。”
方振远道:“原来是铁兄。”
蓝衣少年道:“不敢当,老前辈言重了。”
方振远轻轻咳了一声,道:“铁兄,那封信是你写的吗?”
蓝衣人道:“不错,虎威镖局,正陷入险恶境界之中,晚辈不忍坐视老前辈受害,因此,才传书示警,希望老前辈能够置身事外。”
方振远道:“信上署名报恩人,这就叫在下想不明白了。”
蓝衣人道:“老前辈施恩不望人报,竟早把晚辈忘了。”
方振远道:“这些日子,风波层起,老朽有些糊涂了。”
蓝衣人道:“老前辈在荒祠外,救了一个受人暗算的……”
方振远道:“哦,你就是那骑白马年轻人。”
蓝衣少年道:“晚辈铁梦秋。”
方振远叹息一声道:“铁公子一片好心,在下感激不尽,不过,我不能弃下大哥,独善其身。”
铁梦秋道:“那位大哥是……”
方振远道:“关中岳。”
铁梦秋沉吟了一阵,道:“老前辈性情中人,道义为先,晚辈倒也不便多劝。”
方振远一抱拳,站起身子,道:“多谢美意,在下告辞了。”
铁梦秋轻轻咳了一声道:“老前辈吃杯水酒再走如何?”
方振远摇摇头道:“不!我还要急着回大哥的话。”
铁梦秋道:“关总镖头如若问起在下时,不用把在下描述的很仔细。”
方振远沉吟了片刻,道:“好!老朽遵命。”
举步向外行去。
铁梦秋望着方振远的背影,轻轻叹息一声,摇摇头,道:“择善固执的老人。”
再说方振远一口气走下又一村直奔回局。
关中岳和一众镖师,正聚于厅中商量大事。
方振远一进门,急急对关中岳抱拳一揖,道:“大哥,小弟复命。”
关中岳微微一笑,站起身子,道:“怎的回来得这样快?”
众镖师齐齐起身,施礼相迎。
方振远一面还礼,一面说道:“诸位请坐,”自己先在关中岳的身侧,坐了下来。
关中岳道:“我已经说的很清楚了,希望诸位,一面练习武功,一面小心防守,不论来的人是一个,两个,是强是弱,都要及时传出警讯,便于相互支援。”
众镖师齐齐欠身应遵:“我等记下了。”
关中岳道:“好!诸位请各回已位。”
众镖师应了一声,行出大厅。
关中岳沉声道:“四成,你留下来。”
杨四成缓缓在关中岳的身旁坐下。
关中岳回顾了方振远一眼,道:“兄弟,见着了那人没有?”
方振远道:“见着了。”
关中岳道:“他说些什么?”
方振远道:“他劝小弟离开虎威镖局。”
关中岳哦了一声道:“你问过了他的姓名?”
方振远道:“问过了,他叫铁梦秋,名不见经传,小弟从未听人说过。”
关中岳道:“你一口回绝了他劝你离开镖局子,他的神态如何?”
方振远笑道:“他一点也不坚持,反倒赞我几句,我们谈话不多,小弟就匆匆告辞了。”
关中岳道:“他怎会和你相识?”
方振远道:“是那日荒祠中救的一位年轻人。”
关中岳捋髯沉思道:“铁梦秋,铁梦秋,江湖确没有这一号人物。”
方振远轻轻咳了一声,道:“我瞧他年纪轻轻,纵然是名门正派的弟子,但也不是什么重要人物。”
关中岳笑一笑,道:“他可是穿着一身蓝色疾服劲装?”
方振远道:“不错,大哥也见过?”关中岳未回答方振远的问题却又问道:“他很英俊,佩长剑,有着一股让人不可通视的气势。”
方振远道:“不错。”
关中岳道:“那就是他了。”
方振远奇道:“怎么,大哥认识他了?”
关中岳道:“见过,昨夜之中,我与葛玉郎见过他,葛玉郎对他似有着很大的畏惧,如是那人也和咱们为敌,葛玉郎宁可不和咱们合作。”
方振远啊了一声,道:“有这等事,那人究竟是什么人呢?”
关中岳道:“江湖上,完全没有他的传说,如非兄弟告诉我,他叫铁梦秋,连他的姓名也不知晓。”语声微微一顿,接道:“也许葛玉郎知晓一些内情,但他却未仔细对我说过。”
方振远突然说道:“小弟去请他来咱们镖局,和大哥聊聊。”
关中岳一伸手,拉住了方振远道:“慢着。”
方振远道:“小弟瞧他叫了很多菜,还未开始食用,算时间,他应该还在又一村中。”
关中岳道:“别说他不会来,就算他来了,咱们也不晓得和他谈些什么?”
方振远笑一笑,道:“大哥,你赴那葛玉郎之约回来后,似乎是有些不对,小弟瞧出了你的愁苦,虽然大哥不肯说明。”
关中岳道:“小兄支见葛玉郎,确然发生了很多事,咱们目前的处境,更是险恶万分,连我也无法定下主意。”
方振远道:“咱们周围敌人太多,而来处不明,简直是无法防范。”
方振远道:“既是来处不明,大哥又怎委知晓呢?……”
关中岳道:“我瞧到了他们,一个个身着黑衣,面罩黑纱,叫人无法瞧到他们的真正面目。”
方振远道:“那些人都是和咱们为敌的人。”
关中岳道:“不错,他们都似是要得到那份牧羊图。”
方振远道:“唉!想不到因为一幅牧羊图,闹到这等局面……”沉吟了片刻,接道:“大哥,小弟有句话,不知是当不当讲?”
关中岳道:“不要紧,你尽管说。”
方振远道:“咱们把刘氏父女们,保到开封府就算是交了差,犯不着为那牧羊图的事得罪天下英雄,何不交还牧羊图带人北上,不再理这里的事。”
关中岳道:“话是如此说,但小兄已对督帅大人有过承诺,再说,这保镖一行,也不是我的终身事业,大丈夫生于天地之间,应该做一桩有益人间,轰轰烈烈的大事。”
方振远沉吟了一阵,道:“大哥,是否感觉到情势不对了?”
关中岳点点头,道:“情势有些不对,飞轮王已过了时间,但还未到镖局中来……”
长长吁一口气,道:“我一生做事,没有冒过今日之险,也无法预测到以后会有些什么变化,所以,我准备今晚把镖局中人,遣走一些,免得多增加无谓的死伤。”
方振远道:“大哥,你既然决心管了,干脆就明目张胆的干吧!告诉督帅,在他调集一队官兵来……”
关中岳摇摇头,接道:“去告诉大立,如是有人愿意离开时,尽管放他们走,并赠仪程百两,要他们尽早离开。”
方振远应了一声,转身而去。
|
C++
|
UTF-8
| 1,829 | 2.671875 | 3 |
[] |
no_license
|
#include <EEPROM.h>
#include "settings.h"
#include "supervisor.h"
void ParamSettings::writeEepromLong(unsigned int base, unsigned int slot, long value)
{
base = base + (slot * sizeof(long));
const byte *b = (const byte *) (const void *) &value;
for (unsigned int i = 0; i < sizeof(long); i++) {
EEPROM.write(base + i, b[i]);
}
}
long ParamSettings::readEepromLong(unsigned int base, unsigned int slot)
{
base = base + (slot * sizeof(long));
long x;
byte *b = (byte *) (void *) &x;
for (unsigned int i = 0; i < sizeof(long); i++) {
b[i] = EEPROM.read(base + i);
}
return x;
}
void ParamSettings::manualReadParam(const char *desc, long &pval)
{
long vnew;
Serial.print("# Enter ");
Serial.print(desc);
Serial.print("(");
Serial.print(pval);
Serial.print("): ");
if (Supervisor::blockingReadLong(&vnew) > 0) {
pval = vnew;
} else {
Serial.print(F("# (not updated)\r\n"));
}
}
void ParamSettings::manualReadParam(const char *desc, unsigned long &pval)
{
long vnew;
Serial.print("# Enter ");
Serial.print(desc);
Serial.print("(");
Serial.print(pval);
Serial.print("): ");
if ((Supervisor::blockingReadLong(&vnew) > 0) && (vnew >= 0)) {
pval = vnew;
} else {
Serial.print(F("# (not updated)\r\n"));
}
}
void ParamSettings::manualReadParam(const char *desc, unsigned int &pval)
{
long vnew;
Serial.print("# Enter ");
Serial.print(desc);
Serial.print("(");
Serial.print(pval);
Serial.print("): ");
if ((Supervisor::blockingReadLong(&vnew) > 0) && (vnew >= 0)) {
pval = vnew;
} else {
Serial.print(F("# (not updated)\r\n"));
}
}
void ParamSettings::serialWriteParams(void)
{
Serial.print(F("# Current settings:\r\n"));
formatParams(Supervisor::outbuf, Supervisor::outbufLen);
Serial.write(Supervisor::outbuf);
}
|
Markdown
|
UTF-8
| 3,420 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
---
title: Առաջնահերթություններ
date: 15/03/2023
---
Հիսուսի առակներն ու դասերը, աստվածաշնչյան հերոսների մասին պատմող պատմությունները, ինչպես նաև Էլեն Ուայթի խորհուրդները հստակորեն ցույց են տալիս, որ չկա Աստծուն կիսատ նվիրվելու ճանապարհ։ Մենք կա՛մ Տիրոջ կողմն ենք, կա՛մ Նրա դեմ։
Երբ դպիրը Հիսուսին հարցրեց, թե որ պատվիրանն է ամենամեծը, Հիսուսը պատասխանեց. «Եվ սիրի՛ր քո Տեր Աստծուն քո ամբողջ սրտով, ամբողջ հոգով, ամբողջ մտքով ու ամբողջ զորությամբ» (Մարկոս 12.30)։ Երբ մենք ամեն ինչ տալիս ենք Քրիստոսին, մեկ այլ տիրոջ համար ոչինչ չի մնում։ Ահա թե ինչպես պետք է ամեն ինչ լինի։
`Կարդացե՛ք Մատթեոս 6.24 համարը։ Սեփական փորձով զգացե՞լ եք արդյոք այս բառերի ճշմարտացիությունը։`
Ուշադրությո՛ւն դարձրեք, որ Հիսուսը չի ասում, թե Աստծուն ու փողին միաժամանակ ծառայելը բարդ է, կամ որ մենք այդ անելիս պետք է շատ զգույշ լինենք։ Նա ասում է՝ դա անելն անհնար է։ Վերջակետ։ Այս միտքը պետք է որ մեր սրտերն ահով ու դողով լցնի (Փիլիպպեցիներին 2.12)։
`Կարդացե՛ք Ա Հովհաննես 2.15–17 համարները։ Ինչպե՞ս են այս երեք բաները դրսևորվում մեր աշխարհում, և ինչո՞ւ է դրանց ներկայացրած վտանգը երբեմն ավելի աննկատ, քան մենք պատկերացնում ենք։`
Զարմանալի չէ, որ Պողոսը գրել է. «Վերևում եղած բաների մասի՛ն մտածեք և ոչ թե այն, ինչ երկրի վրա է» (Կողոսացիներին 3.2): Իհարկե, դա ավելի հեշտ է ասել, քան անել, որովհետև աշխարհի բաներն ամեն օր մեր աչքի առջև են: «Այն ամենի» հրապույրը, «ինչ աշխարհի մեջ է», շատ ուժեղ է, արագ հաճույքի ձգողականությունը միշտ շշնջում է մեր ականջներին կամ քաշում մեր ձեռքից, կամ՝ երկուսն էլ: Մի՞թե ամենահավատարիմ քրիստոնյան անգամ որոշակի սեր չի զգացել աշխարհի բաների հանդեպ։ Նույնիսկ ունենալով այն գիտակցումը, որ մի օր ամեն ինչ կավարտվի՝ մենք դեռ զգում ենք այդ փափագը, այնպես չէ՞: Սակայն բարի լուրն այն է, որ մենք չպետք է թույլ տանք, որ այն մեզ հեռացնի Տիրոջից:
`Կարդացե՛ք Բ Պետրոս 3.10–14 համարները։ Պետրոսի այս ասածներն ինչպե՞ս պետք է ազդեն մեր ապրած կյանքի վրա, ներառյալ այն, թե ինչպես ենք մենք վարվում մեր ռեսուրսների հետ։`
|
Java
|
UTF-8
| 483 | 2.484375 | 2 |
[] |
no_license
|
package com.readlearncode;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RUNTIME)
public @interface Colour {
Name name();
enum Name {RED, GREEN, BLUE}
}
|
C++
|
UTF-8
| 4,859 | 2.78125 | 3 |
[] |
no_license
|
/**
* Controlls the camera using a mass-spring system. The camera
* always follows the target (player).
*/
#include <NiApplication.h>
#include <NiPhysX.h>
#include <NiViewMath.h>
#include "CameraController.h"
#include "VelocityController.h"
#include "Bee.h"
#include "ConfigurationManager.h"
#include "GameManager.h"
#include <fstream>
#include <math.h>
//---------------------------------------------------------------------------
/**
* The constructor
*
* @param camera
*/
CameraController::CameraController(NiCameraPtr camera) :
m_spCamera(camera),
m_fLastUpdate(0.0f),
m_fDeltaTime(0.0f),
m_vVelocity(0.0f, 0.0f, 0.0f),
m_fcDistanceFromTarget(ConfigurationManager::Get()->cameraController_distanceFromTarget),
m_fcMaxVelocity(ConfigurationManager::Get()->cameraController_maxVelocity),
m_vPosition(0.0, 0.0, 0.0),
m_vTarget(0.0, 0.0, 0.0),
m_vTargetVel(0.0, 0.0, 0.0),
m_fRotateZ(0.0f),
m_fRotateY(0.0f),
m_bIsRotating(false),
m_spVelController(NiNew VelocityController(ConfigurationManager::Get()->cameraController_damping,
ConfigurationManager::Get()->cameraController_springConstant, m_fcMaxVelocity))
{
}
//---------------------------------------------------------------------------
/**
* The destructor
*
*/
CameraController::~CameraController()
{
m_spVelController = 0;
}
//---------------------------------------------------------------------------
/**
* Updates the camera's position
*
* @param fTime
*/
void CameraController::Update(float fTime)
{
m_fDeltaTime = (fTime - m_fLastUpdate) * 50.0f;
m_fLastUpdate = fTime;
UpdatePositionAndOrientation();
}
//---------------------------------------------------------------------------
/**
* Rotates the view by dx on the Y axis and dy on the Z axis
*
* @param dx
* @param dy
*/
void CameraController::RotateCamera(float dx, float dy)
{
if (!m_bIsRotating) m_bIsRotating = true;
// increase rotation angles
m_fRotateZ += dy*0.01;
m_fRotateY += dx*0.01;
// make sure that the Z rotation is
// -pi/2 < zRotation < pi/2
if (m_fRotateZ >= 1.56)
m_fRotateZ = 1.56f;
else if (m_fRotateZ <= -1.56)
m_fRotateZ = -1.56f;
// rotate camera on the y axis and the parent's (queen)
// local Z axis
NiMatrix3 rotation = m_spCamera->GetParent()->GetWorldRotate();
// get local Z
NiPoint3 localZ;
rotation.GetCol(2, localZ);
// create a quaternion to make a rotation matrix
// along the local Z axis
NiQuaternion zQuat;
zQuat.FromAngleAxis(-m_fRotateZ, localZ);
NiMatrix3 zRotation;
zQuat.ToRotation(zRotation);
// make Y rotation
NiMatrix3 yRotation;
yRotation.MakeYRotation(m_fRotateY);
// create new rotation matrix
m_mNewRotation = yRotation*zRotation*rotation;
}
//---------------------------------------------------------------------------
/**
* Stops the rotation of the camera
*
*/
void CameraController::StopRotateCamera()
{
m_bIsRotating = false;
m_fRotateZ = 0.0f;
m_fRotateY = 0.0f;
}
//---------------------------------------------------------------------------
/**
* Updates the position and orientation of the camera
*
*/
void CameraController::UpdatePositionAndOrientation()
{
// get the camera's parent node
NiNodePtr m_spTarget = m_spCamera->GetParent();
// get the parent's rotation matrix
NiMatrix3 rotation = m_spTarget->GetWorldRotate();
// find the local heading vector
NiPoint3 heading;
rotation.GetCol(0, heading);
// if the camera is not rotated by user input then update the
// current target
if (!m_bIsRotating)
{
// position the target behind the parent
m_vTarget = m_spTarget->GetWorldTranslate() - heading*m_fcDistanceFromTarget;
// find the distance between the target and the camera
NiPoint3 distance = (m_vTarget - m_vPosition);
// update the camera's velocity using a mass-spring controller
m_spVelController->Update(m_vVelocity, distance);
// integrate position
m_vPosition = m_vPosition + m_vVelocity * m_fDeltaTime;
// set orientation (look at parent)
m_mNewRotation = NiViewMath::LookAt(m_spTarget->GetWorldTranslate(), m_vPosition, NiPoint3(0.0, 1.0, 0.0));
}
// move the camera to the head of the queen
// and set its orientation to what the user desires
else
{
// position the target a little in front of the parent
m_vTarget = m_spTarget->GetWorldTranslate() + heading*20.0f;
// integrate position
m_vPosition = m_vTarget;
}
// set new position
m_spCamera->SetWorldTranslate(m_vPosition);
// set new orientation
//m_mNewRotation = GameManager::Get()->GetQueen()->GetNode()->GetWorldRotate();
m_spCamera->SetWorldRotate(m_mNewRotation);
}
//---------------------------------------------------------------------------
|
C++
|
UTF-8
| 869 | 3.5 | 4 |
[] |
no_license
|
#include <iostream>
#include <list>
using std::list;
bool Isbalance(const char* str, int len)
{
bool ret = false;
list<char> stack;
for (size_t i = 0; i < len; i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
stack.push_back(str[i]);
}
else if (str[i] == ')')
{
if (stack.back() == '(')
{
stack.pop_back();
}
else
break;
}
else if (str[i] == ']')
{
if (stack.back() == '[')
{
stack.pop_back();
}
else
break;
}
else if (str[i] == '}')
{
if (stack.back() == '{')
{
stack.pop_back();
}
else
break;
}
}
if (stack.empty())
{
ret = true;
}
return ret;
}
int main_isbalanced()
{
char str[] = "[P{qwe[wq]e}]";
if (Isbalance(str,strlen(str)))
{
std::cout << "balance \n" << std::endl;
}
else
{
std::cout << "not balance \n" << std::endl;
}
return 0;
}
|
Java
|
UTF-8
| 805 | 2.59375 | 3 |
[] |
no_license
|
package com.smartmarket.display;
import java.text.DecimalFormat;
import com.pi4j.component.lcd.LCDTextAlignment;
import com.pi4j.component.lcd.impl.I2CLcdDisplay;
import com.pi4j.io.i2c.I2CBus;
public class LCD extends I2CLcdDisplay {
public LCD(int i2cAdress) throws Exception {
super(2, 16, I2CBus.BUS_1, i2cAdress, 3, 0, 1, 2, 7, 6, 5, 4);
}
public void init() {
clear();
write(0, "Smartmarket", LCDTextAlignment.ALIGN_CENTER);
write(1, "Inicializando...", LCDTextAlignment.ALIGN_CENTER);
}
public void writeProduct(String product) {
write(0, product, LCDTextAlignment.ALIGN_CENTER);
}
public void writePrice(double price) {
DecimalFormat df = new DecimalFormat("0.00");
write(1, "R$ "+df.format(price), LCDTextAlignment.ALIGN_CENTER);
}
}
|
Java
|
UTF-8
| 7,006 | 1.96875 | 2 |
[] |
no_license
|
package com.bt.zhangzy.logisticstraffic.activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import com.bt.zhangzy.logisticstraffic.app.AppParams;
import com.bt.zhangzy.logisticstraffic.app.BaseActivity;
import com.bt.zhangzy.logisticstraffic.d.R;
import com.bt.zhangzy.logisticstraffic.data.Type;
import com.bt.zhangzy.logisticstraffic.data.User;
import com.bt.zhangzy.network.AppURL;
import com.bt.zhangzy.network.HttpHelper;
import com.bt.zhangzy.network.JsonCallback;
import com.bt.zhangzy.network.entity.JsonUser;
import com.bt.zhangzy.network.entity.ResponseLogin;
import com.bt.zhangzy.tools.Tools;
/**
* Created by ZhangZy on 2015/6/9.
*/
public class LoginActivity extends BaseActivity {
EditText username;
EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.login_username_ed);
// if (!TextUtils.isEmpty(User.getInstance().getUserName())) {
// username.setText(User.getInstance().getUserName());
// }
if (!TextUtils.isEmpty(User.getInstance().getPhoneNum())) {
username.setText(User.getInstance().getPhoneNum());
}
if (AppParams.DEBUG && User.getInstance().isSave()) {
setTextView(R.id.login_password_ed, User.getInstance().getPassword());
}
password = (EditText) findViewById(R.id.login_password_ed);
password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
//密码每次点击都重新输入
password.getText().clear();
}
}
});
password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (actionId) {
case EditorInfo.IME_ACTION_DONE:
case EditorInfo.IME_ACTION_GO:
onClick_Login(v);
break;
}
return false;
}
});
CheckBox checkBox = (CheckBox) findViewById(R.id.login_remember_ck);
checkBox.setChecked(User.getInstance().isSave());
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
User.getInstance().setIsSave(isChecked);
if (isChecked) {
if (!TextUtils.isEmpty(username.getText()))
User.getInstance().setPhoneNum(username.getText().toString());
}
}
});
}
//跳转到注册页面
public void onClick_Register(View view) {
startActivity(RegisterActivity.class);
finish();
}
public void onClick_Forget(View view) {
startActivity(ForgetActivity.class);
finish();
}
//进行登录操作
public void onClick_Login(View view) {
// loginSusses();
// EditText username = (EditText) findViewById(R.id.login_username_ed);
EditText password = (EditText) findViewById(R.id.login_password_ed);
String nameStr, passwordStr;
nameStr = username.getText().toString();
passwordStr = password.getText().toString();
if (nameStr.isEmpty() || passwordStr.isEmpty()) {
showToast("请填写用户名和密码");
return;
}
if (!Tools.IsPhoneNum(nameStr)) {
showToast("用户名格式错误");
return;
}
if (User.getInstance().isSave() && passwordStr.equals(User.getInstance().getPassword())) {
} else {
passwordStr = Tools.MD5(passwordStr);
}
request_Login(nameStr, passwordStr);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onClick_Back(null);
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onClick_Back(View view) {
// super.onClick_Back(view);
startActivity(HomeActivity.class);
finish();
}
private void loginSusses() {
// Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
// User.getInstance().setLogin(true);
// User.getInstance().setUserType(Type.EnterpriseType);
// startActivity(new Intent(LoginActivity.this,UserActivity.class));
//登录成功后保存一下信息;
getApp().saveUser();
getApp().setAliasAndTag();
Bundle bundle = getIntent().getExtras();
startActivity(HomeActivity.class, bundle);
finish();
}
// 发起登录请求
private void request_Login(String username, String password) {
JsonUser user = new JsonUser();
// user.setName(username);
user.setPhoneNumber(username);
user.setPassword(password);
if (User.getInstance().isSave()) {
User.getInstance().setPassword(password);
}
HttpHelper.getInstance().post(AppURL.Login, user, new JsonCallback() {
@Override
public void onFailed(String str) {
showToast("用户登录失败:" + str);
}
@Override
public void onSuccess(String msg, String jsonstr) {
if (TextUtils.isEmpty(jsonstr)) {
showToast("用户登录失败:" + msg);
return;
}
ResponseLogin json = ParseJson_Object(jsonstr, ResponseLogin.class);
User.getInstance().setLoginResponse(json);
// JsonUser jsonUser = ParseJson_Object(jsonstr, JsonUser.class);
if (AppParams.DRIVER_APP) {
if (User.getInstance().getUserType() != Type.DriverType) {
showToast("用户类型错误");
return;
}
} else {
if (User.getInstance().getUserType() == Type.DriverType) {
showToast("用户类型错误");
return;
}
}
showToast("用户登录成功");
loginSusses();
}
});
}
}
|
Java
|
UTF-8
| 577 | 2.296875 | 2 |
[] |
no_license
|
package manager;
import java.io.IOException;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public abstract class SQLmanager {
private SqlMapClient sc;
public SQLmanager(){
sc=null;
try{
sc=SqlMapClientBuilder.buildSqlMapClient(Resources.getResourceAsReader("sqlmap/SqlMapConfig.xml"));
System.out.println(sc.toString()+" , ");
}catch(IOException e){
e.printStackTrace();
}
}
public SqlMapClient getSqlMap(){
return sc;
}
}
|
JavaScript
|
UTF-8
| 1,568 | 3.046875 | 3 |
[] |
no_license
|
$(function(){
var step1Li = $('.step1 li');
var step2Li = $('.step2 li');
var id1 = "", id2 = "", id1Text = "", id2Text = "";
step1Li.on('click',function(){
step1Li.removeClass('active');
$(this).toggleClass('active');
console.log($('.step1 li.active'));
});
step2Li.on('click',function(){
step2Li.removeClass('active');
$(this).toggleClass('active');
console.log($('.step2 li.active'));
});
$('.resultBtn').on('click',function(e){
e.preventDefault();
if(step1Li.hasClass('active') && step2Li.hasClass('active')){
id1 = $('.step1 li.active').attr('id');
id2 = $('.step2 li.active').attr('id');
id1Text = $('.step1 li.active').text();
id2Text = $('.step2 li.active').text();
localStorage.id1 = id1;
localStorage.id2 = id2;
localStorage.id1Text = id1Text;
localStorage.id2Text = id2Text;
location.href = $(this).attr('href');
// $.ajax({
// url:'https://graphicnovel.github.io/coffeeforyou/data_story.json',
// type:'GET',
// success:function(data){
// console.log(id1, id2);
// stepText += id1 + "과 " + id2 + "를 즐기는";
// $('.stepResult').html(stepText);
// }
// });
}else{
alert('STEP01과 STEP02를 선택해주세요.');
}
});
});
|
Java
|
UTF-8
| 1,537 | 3.90625 | 4 |
[] |
no_license
|
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
public class ByteOrdering{
public static void main(String[] args){
ByteBuffer buffer = ByteBuffer.allocate(5);
buffer.put((byte)1).put((byte)2).put((byte)3).put((byte)4);
buffer.flip();
System.out.println("ByteBuffer reading with byte order: " + buffer.order());
while(buffer.hasRemaining()){
System.out.println("Element at position " + buffer.position() + " : " + buffer.get());
}
System.out.println();
buffer.flip();
CharBuffer charBuf = buffer.asCharBuffer();
System.out.println("charBuf byte order: " + charBuf.order());
while(charBuf.hasRemaining()){
System.out.println("charBuf element's int value at position " + charBuf.position() + " : " + (int)(charBuf.get()));
}
System.out.println();
// set the byte buffer order to be little endian.
buffer.order(ByteOrder.LITTLE_ENDIAN);
CharBuffer charBuf2 = buffer.asCharBuffer();
System.out.println("ByteBuffer reading with byte order: " + buffer.order());
while(buffer.hasRemaining()){
System.out.println("Element at position " + buffer.position() + " : " + buffer.get());
// single byte read, byte order does not matter here.
}
System.out.println();
System.out.println("charBuf2 byte order: " + charBuf2.order());
while(charBuf2.hasRemaining()){
System.out.println("charBuf2 element's int value at position " + charBuf2.position() + " : " + (int)(charBuf2.get()));
// multi-byte read, where the byte order does matter.
}
}
}
|
TypeScript
|
UTF-8
| 555 | 3.3125 | 3 |
[] |
no_license
|
interface ConvertDateReturnType {
year: string;
month: string;
day: string;
hour: string;
minute: string;
second: string;
}
const convertDate = (date: string): ConvertDateReturnType => {
// 2021-05-22T00:26:12.843439
const year = date.slice(0, 4);
const month = date.slice(5, 7);
const day = date.slice(8, 10);
const hour = date.slice(11, 13);
const minute = date.slice(14, 16);
const second = date.slice(17, 19);
return { year, month, day, hour, minute, second };
};
export default convertDate;
|
Java
|
UTF-8
| 700 | 1.757813 | 2 |
[] |
no_license
|
package cn.dingyuegroup.gray.server.mysql.dao;
import cn.dingyuegroup.gray.server.mysql.entity.GrayPolicyEntity;
import java.util.List;
public interface GrayPolicyMapper {
int deleteByPrimaryKey(Integer id);
int insert(GrayPolicyEntity record);
GrayPolicyEntity selectByPrimaryKey(Integer id);
List<GrayPolicyEntity> selectAll();
int updateByPrimaryKey(GrayPolicyEntity record);
List<GrayPolicyEntity> selectListByPolicyId(List<String> list);
GrayPolicyEntity selectByPolicyId(String policyId);
int updateByPolicyId(GrayPolicyEntity record);
int deleteByPolicyId(String policyId);
List<GrayPolicyEntity> selectByDepartmentId(String departmentId);
}
|
Java
|
UTF-8
| 780 | 2.796875 | 3 |
[] |
no_license
|
package com.dbobrov.jdk8demo;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class Unsigned {
@Test
public void unsignedToString() {
int a = 1 << 31;
assertThat(Integer.toString(a),
is("-2147483648"));
assertThat(Integer.toUnsignedString(a),
is("2147483648"));
}
@Test
public void unsignedArithmetics() {
int a = (1 << 31) + (1 << 20);
assertThat(Integer.toString(a), is("-2146435072"));
assertThat(Integer.toUnsignedString(a), is("2148532224"));
}
@Test
public void compare() {
assertThat(-1 < 1, is(true));
assertThat(Integer.compareUnsigned(-1, 1) > 0, is(true));
}
}
|
C++
|
UTF-8
| 1,957 | 3.65625 | 4 |
[] |
no_license
|
#pragma once
#include "List.h"
namespace Collections {
template<class T>
class ArrayList : public List<T>
{
private:
T* m_Arr;
int m_Count;
int m_Capacity;
int m_InitialCapacity;
public:
ArrayList(int capacity = 4)
: m_InitialCapacity(capacity), m_Capacity(capacity)
{
m_Arr = new T[capacity];
m_Count = 0;
}
~ArrayList()
{
delete[] m_Arr;
}
void Clear() override
{
delete[] m_Arr;
m_Arr = new T[m_InitialCapacity];
m_Count = 0;
}
T Insert(int index, T element) override
{
if (index < 0 || index > m_Count) throw IndexOutOfBoundsException(index);
if (m_Capacity < m_Count + 1)
{
reallocate();
}
for (int i = m_Count; i > index; i--)
{
m_Arr[i] = m_Arr[i - 1];
}
m_Arr[index] = element;
m_Count++;
return m_Arr[index];
}
T RemoveAt(int index) override
{
if (index < 0 || index >= m_Count) throw IndexOutOfBoundsException(index);
T removed = m_Arr[index];
for (int i = index + 1; i < m_Count; i++)
{
m_Arr[i - 1] = m_Arr[i];
}
m_Count--;
return removed;
}
T Get(int index) const override
{
if (index < 0 || index >= m_Count) throw IndexOutOfBoundsException(index);
return m_Arr[index];
}
void Set(int index, T value) override
{
if (index < 0 || index >= m_Count) throw IndexOutOfBoundsException(index);
m_Arr[index] = value;
}
T& operator[](int index) override
{
if (index < 0 || index >= m_Count) throw IndexOutOfBoundsException(index);
return m_Arr[index];
}
const T& operator[](int index) const override
{
if (index < 0 || index >= m_Count) throw IndexOutOfBoundsException(index);
return m_Arr[index];
}
inline int GetCount() const override { return m_Count; }
private:
void reallocate()
{
m_Capacity = (int)(m_Capacity * 3 / 2);
T* newArr = new T[m_Capacity];
std::copy(m_Arr, m_Arr + m_Count, newArr);
delete[] m_Arr;
m_Arr = newArr;
}
};
}
|
Python
|
UTF-8
| 214 | 3.203125 | 3 |
[] |
no_license
|
class emp():
a = 1
def dispnames(self,name):
print("this is ",name)
def company(self, name, cname):
print("{} belongs to {}".format(name,cname))
emp.
emp.company('superman', 'avengers')
|
Java
|
UTF-8
| 2,223 | 2.125 | 2 |
[] |
no_license
|
/*
* SSLR Squid Bridge
* Copyright (C) 2010-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.squidbridge.text;
import javax.annotation.Nullable;
public class SingleLineCommentHandler extends LineContextHandler {
private StringBuilder comment;
private final String commentStartTag;
private final String commentNotStartTag;
public SingleLineCommentHandler(String commentStartTag) {
this(commentStartTag, null);
}
public SingleLineCommentHandler(String commentStartTag, @Nullable String commentNotStartTag) {
this.commentStartTag = commentStartTag;
this.commentNotStartTag = commentNotStartTag;
}
@Override
boolean matchToEnd(Line line, StringBuilder pendingLine) {
if (comment == null) {
throw new IllegalStateException("Method doContextBegin(StringBuilder pendingLine) has not been called.");
}
comment.append(getLastCharacter(pendingLine));
return false;
}
@Override
boolean matchToBegin(Line line, StringBuilder pendingLine) {
boolean doContextBegin = matchEndOfString(pendingLine, commentStartTag)
&& (commentNotStartTag == null || !matchEndOfString(pendingLine, commentNotStartTag));
if (doContextBegin) {
comment = new StringBuilder(commentStartTag);
}
return doContextBegin;
}
@Override
boolean matchWithEndOfLine(Line line, StringBuilder pendingLine) {
line.setComment(comment.toString());
comment = null;
return true;
}
}
|
Markdown
|
UTF-8
| 629 | 2.671875 | 3 |
[] |
no_license
|
# C Examples
Some C exercises related to (but not only) my OSes exam.
These are essentially split in two subdirs:
- _my-own_: own stuff, like reimplementations of nice things
- _tlpi_: exercises taken from The Linux Programming Interface
## Special note
This is **not** to be intended as software to be run once more than the minimum checks needed for it to be ok-this-sorta-works. These are exercises that I did to study syscalls and their behaviour, none of these is to be intended as code of mine as a work of art or as standard quality of my job.
I can prove you that I am a much better Javascripter/Gopher/Pythonista.
|
Java
|
UTF-8
| 1,640 | 2.390625 | 2 |
[] |
no_license
|
package com.amarnehsoft.vaccinations.database.db2.schema;
/**
* Created by alaam on 2/11/2018.
*/
public class KindergartenTable {
public static final String TBL_NAME = "KINDER_TBL";
public static final String _CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ " ("
+ Cols.CODE + " VARCHAR ,"
+ Cols.NAME + " VARCHAR ,"
+ Cols.IMG + " VARCHAR ,"
+ Cols.ADDRESS + " VARCHAR ,"
+ Cols.DESC + " VARCHAR ,"
+ Cols.CONTACT + " VARCHAR ,"
+ Cols.EXTRA + " VARCHAR ,"
+ Cols.FROM_DAY + " INTEGER ,"
+ Cols.FROM_TIME + " VARCHAR ,"
+ Cols.FROM_YEAR + " INTEGER ,"
+ Cols.TO_DAY + " INTEGER ,"
+ Cols.TO_TIME + " VARCHAR ,"
+ Cols.TO_YEAR + " INTEGER "
+ ")";
public static final class Cols
{
public static final String CODE = "TXT_CODE";
public static final String NAME = "TXT_NAME";
public static final String IMG="TXT_IMG";
public static final String ADDRESS="TXT_ADDRESS";
public static final String DESC="TXT_DESC";
public static final String CONTACT = "TXT_CONTACT";
public static final String EXTRA = "EXTRA";
public static final String FROM_DAY = "FROM_DAY";
public static final String FROM_TIME = "FROM_TIME";
public static final String FROM_YEAR = "FROM_YEAR";
public static final String TO_DAY = "TO_DAY";
public static final String TO_TIME = "TO_TIME";
public static final String TO_YEAR = "TO_YEAR";
}
}
|
C#
|
UTF-8
| 588 | 3.171875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomanNumeralKata02
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int userNumber = Convert.ToInt32(Console.ReadLine());
RomanConverter converter = new RomanConverter();
string finalResult = converter.Convert(userNumber);
Console.WriteLine($"Your result is {finalResult}.");
Console.ReadLine();
}
}
}
|
Python
|
UTF-8
| 11,185 | 2.71875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
"""
GeneratorSheet: a sheet with a pattern generator.
"""
import param
from topo.base.sheet import Sheet
from topo.base.patterngenerator import PatternGenerator,Constant
from topo.base.simulation import FunctionEvent, PeriodicEventSequence
from holoviews.interface.collector import AttrDict
from holoviews import Image
import numpy as np
# JLALERT: This sheet should have override_plasticity_state/restore_plasticity_state
# functions that call override_plasticity_state/restore_plasticty_state on the
# sheet output_fn and input_generator output_fn.
class GeneratorSheet(Sheet):
"""
Sheet for generating a series of 2D patterns.
Typically generates the patterns by choosing parameters from a
random distribution, but can use any mechanism.
"""
src_ports=['Activity']
period = param.Number(default=1,bounds=(0,None),
inclusive_bounds=(False, True), constant=True, doc="""
Delay (in Simulation time) between generating new input patterns.""")
phase = param.Number(default=0.05,doc="""
Delay after the start of the Simulation (at time zero) before
generating an input pattern. For a clocked, feedforward
simulation, one would typically want to use a small nonzero
phase and use delays less than the user-visible step size
(typically 1.0), so that inputs are generated and processed
before this step is complete.
""")
input_generator = param.ClassSelector(PatternGenerator,default=Constant(),
doc="""Specifies a particular PatternGenerator type to use when creating patterns.""")
def __init__(self,**params):
super(GeneratorSheet,self).__init__(**params)
self.input_generator_stack = []
self.set_input_generator(self.input_generator)
def set_input_generator(self,new_ig,push_existing=False):
"""
Set the input_generator, overwriting the existing one by
default.
If push_existing is false, the existing input_generator is
discarded permanently. Otherwise, the existing one is put
onto a stack, and can later be restored by calling
pop_input_generator.
"""
if push_existing:
self.push_input_generator()
# CEBALERT: replaces any bounds specified for the
# PatternGenerator with this sheet's own bounds. When
# PatternGenerators can draw patterns into supplied
# boundingboxes, should remove this.
new_ig.set_matrix_dimensions(self.bounds, self.xdensity, self.ydensity)
self.input_generator = new_ig
def push_input_generator(self):
"""Push the current input_generator onto a stack for future retrieval."""
self.input_generator_stack.append(self.input_generator)
# CEBALERT: would be better to reorganize code so that
# push_input_generator must be supplied with a new generator.
# CEBALERT: presumably we can remove this import.
from topo.base.patterngenerator import Constant
self.set_input_generator(Constant())
def pop_input_generator(self):
"""
Discard the current input_generator, and retrieve the previous one from the stack.
Warns if no input_generator is available on the stack.
"""
if len(self.input_generator_stack) >= 1:
self.set_input_generator(self.input_generator_stack.pop())
else:
self.warning('There is no previous input generator to restore.')
def generate(self):
"""
Generate the output and send it out the Activity port.
"""
self.verbose("Generating a new pattern")
try:
ac = self.input_generator()
except StopIteration:
# Note that a generator may raise an exception
# StopIteration if it runs out of patterns. Example is if
# the patterns are files that are loaded sequentially and
# are not re-used (e.g. the constructors are discarded to
# save memory).
self.warning('Pattern generator {0} returned None. Unable to generate Activity pattern.'.format(self.input_generator.name))
else:
self.activity[:] = ac
if self.apply_output_fns:
for of in self.output_fns:
of(self.activity)
self.send_output(src_port='Activity',data=self.activity)
def start(self):
assert self.simulation
if self.period > 0:
# if it has a positive period, then schedule a repeating event to trigger it
e=FunctionEvent(0,self.generate)
now = self.simulation.time()
self.simulation.enqueue_event(PeriodicEventSequence(now+self.simulation.convert_to_time_type(self.phase),self.simulation.convert_to_time_type(self.period),[e]))
def input_event(self,conn,data):
raise NotImplementedError
class ChannelGeneratorSheet(GeneratorSheet):
"""
A GeneratorSheet that handles input patterns with multiple
simultaneous channels.
Accepts either a single-channel or an NChannel input_generator.
If the input_generator stores separate channel patterns, it is
used as-is; if other (single-channel) PatternGenerators are used,
the Class behaves like a normal GeneratorSheet.
When a pattern is generated, the average of the channels is sent
out on the Activity port as usual for a GeneratorSheet, and
channel activities are sent out on the Activity0, Activity1, ...,
ActivityN-1 ports. Thus this class can be used just like
GeneratorSheet, but with optional color channels available, too.
If the input_generator is NChannel, this GeneratorSheet will
handle the separate channels and create the specific output
ports. If the input_generator is single-channel (eg, a monochrome
image) then this GeneratorSheet will behave as a normal
non-NChannel GeneratorSheet.
"""
constant_mean_total_channels_output = param.Number(default=None,doc="""
If set, it enforces the average of the mean channel values to
be fixed. Eg, M = ( activity0+activity1+...+activity(N-1)
).mean() / N = constant_mean_total_channels_output""")
channel_output_fns = param.Dict(default={},doc="""
Dictionary with arrays of channel-specific output functions:
eg, {0:[fnc1, fnc2],3:[fnc3]}. The dictionary isn't required
to specify every channel, but rather only those required.""")
def __init__(self,**params):
# We need to setup our datastructures before calling
# super.init, as that will automatically call
# set_input_generator
self._channel_data = []
super(ChannelGeneratorSheet,self).__init__(**params)
def set_input_generator(self,new_ig,push_existing=False):
"""
If single-channel generators are used, the Class reverts to a
simple GeneratorSheet behavior. If NChannel inputs are used,
it will update the number of channels of the
ChannelGeneratorSheet to match those of the input. If the
number of channels doesn't change, there's no need to reset.
"""
num_channels = new_ig.num_channels()
if( num_channels>1 ):
if( num_channels != len(self._channel_data) ):
self.src_ports = ['Activity']
self._channel_data = []
for i in range(num_channels):
# TODO: in order to add support for generic naming
# of Activity ports, it's necessary to
# implement a .get_channel_names method.
# Calling .channels() and inspecting the
# returned dictionary in fact could change
# the state of the input generator.
self.src_ports.append( 'Activity'+str(i) )
self._channel_data.append(self.activity.copy())
else: # monochrome
# Reset channels to match single-channel inputs.
self.src_ports = ['Activity']
self._channel_data = []
super(ChannelGeneratorSheet,self).set_input_generator(new_ig,push_existing=push_existing)
def generate(self):
"""
Works as in the superclass, but also generates NChannel output and sends
it out on the Activity0, Activity1, ..., ActivityN ports.
"""
try:
channels_dict = self.input_generator.channels()
except StopIteration:
# Note that a generator may raise an exception
# StopIteration if it runs out of patterns. Example is if
# the patterns are files that are loaded sequentially and
# are not re-used (e.g. the constructors are discarded to
# save memory).
self.warning("Pattern generator {0} returned None."
"Unable to generate Activity pattern.".format(self.input_generator.name))
else:
self.activity[:] = channels_dict.items()[0][1]
if self.apply_output_fns:
for of in self.output_fns:
of(self.activity)
self.send_output(src_port='Activity',data=self.activity)
## These loops are safe: if the pattern doesn't provide
## further channels, self._channel_data = []
for i in range(len(self._channel_data)):
self._channel_data[i][:] = channels_dict.items()[i+1][1]
if self.apply_output_fns:
## Default output_fns are applied to all channels
for f in self.output_fns:
for i in range(len(self._channel_data)):
f( self._channel_data[i] )
# Channel specific output functions, defined as a
# dictionary {chn_number:[functions]}
for i in range(len(self._channel_data)):
if(i in self.channel_output_fns):
for f in self.channel_output_fns[i]:
f( self._channel_data[i] )
if self.constant_mean_total_channels_output is not None:
M = sum(act for act in self._channel_data).mean()/len(self._channel_data)
if M>0:
p = self.constant_mean_total_channels_output/M
for act in self._channel_data:
act *= p
np.minimum(act,1.0,act)
for i in range(len(self._channel_data)):
self.send_output(src_port=self.src_ports[i+1], data=self._channel_data[i])
def __getitem__(self, coords):
metadata = AttrDict(precedence=self.precedence,
row_precedence=self.row_precedence,
timestamp=self.simulation.time())
if self._channel_data:
arr = np.dstack(self._channel_data)
else:
arr = self.activity.copy()
im = Image(arr, self.bounds,
label=self.name+' Activity', group='Activity')[coords]
im.metadata=metadata
return im
|
Python
|
UTF-8
| 320 | 3.203125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = 'calpa'
__mtime__ = '3/11/2016'
"""
def power_of_four(number):
# Use the same idea in power of two, plus 32 bits logic
return number > 0 and (number & (number - 1)) == 0 and number & 0x55555555 != 0
print power_of_four(5)
print power_of_four(16)
|
JavaScript
|
UTF-8
| 882 | 3.140625 | 3 |
[] |
no_license
|
//解决js数字计算中的浮点数问题
function fixed(arg1, arg2, computeMethod){
switch (computeMethod) {
case 'add':
var r1, r2, m;
try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
m = Math.pow(10, Math.max(r1, r2))
return (arg1 * m + arg2 * m) / m
break;
case 'sub':
return (arg1 * 10 - arg2 * 10) / 10
break;
case 'mul':
var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
try { m += s1.split(".")[1].length } catch (e) { }
try { m += s2.split(".")[1].length } catch (e) { }
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
break;
case 'div':
return (arg1 * 1000) / (arg2 * 1000);
break;
}
}
module.exports = {
fixed: fixed,
}
|
Python
|
UTF-8
| 584 | 3.25 | 3 |
[] |
no_license
|
class a():
def __init__(self):
print("init from a")
def add(self,m1,m2):
m3=m1.self+m2.self
print(m3)
class b(a):
def __init__(self):
print("init from b")
b1=b()# object creation for the class b
#here python checks for the init in b
# if b exists
#======> print init in b
# else
#======> print init in a since inherited
|
Markdown
|
UTF-8
| 5,181 | 3.046875 | 3 |
[] |
no_license
|
# iForest
## Introduction
Isolation Forest, also known as iForest, is a data structure for anomaly detection. Traditional model-based methods need to construct a profile of normal instances and identify the instances that do not conform to the profile as anomalies. The traditional methods are optimized for normal instances, so they may cause false alarms. They may not be suitable for large data sets as well, due to high complexities. iForest, different from traditional methods, is more robust in these situations.
This project contains an encapsulation of iForest in `scikit-learn` together with some data prerocessing tools. It is specifically used for **categorical data**. The idea of iForest is from Liu, Ting and Zhou's research.[1]
## Setup
This section contains a short instruction about how to configure and run this program.
### Prequisites
1. `Python (>= 3.3)`
2. `NumPy (>= 1.8.2) and SciPy (>= 0.13.3)`
If you don't have `NumPy` or `SciPy` on your system, you can install them with the following command.[2]
~~~~
python3 -m pip install --user numpy scipy
~~~~
3. `Pandas`
`Pandas` is a data analysis library for Python. To install Pandas, you can use the following command.[4]
~~~~
pip3 install pandas
~~~~
4. `scikit-learn`
The library `scikit-learn` contains a set of simple tools for machine learning.[3]
~~~~
pip3 install scikit-learn
~~~~
5. Other missing packages
If you miss any other packages required by the listed prequisites, please follow the instructions to install them.
### How To Run
The `main` function is in `main.py`. You may run this script directly. You can also import iForest in your own projects.
## Technical Details
### Structure
This project contains a set of files. This section introduces the functions of these files and the core functions within the corresponding files.
#### 1. `main.py`
Script `main.py` contains the main function. It shows a sample procedure of using iForest. This script is also available for you to run the test in the paper [1].
##### i) `CatForest(filename,threshold)`
This function shows the procedure of using iForest to detect anomalies. It returns the `data frame` of anomalies and takes the following arguments as input:
`filename`: String type. The path of the data file. The file should be in **CSV** format.
`threshold`: The threshold of decision boundary in iForest. It ranges from **-1 to 0**. In my test this parameter is usually set to values in **-0.4 to -0.1**.
##### ii) `__main()`
This is the main function to call, but it is mainly used to measure the detection time and accuracy. It calls `CatForest` for all iForest related procedures.
#### 2. `iForest.py`
This script contains an encapsulation of the iForest function in `scikit-learn`.
##### `iforest(category,user,threshold)`
This function encapsulates the `IsolationForest` class in `scikit-learn`. It returns an `array` with the decision boundaries smaller than `threshold`.
#### 3. `Preprocessing.py`
This script preprocesses the data. It contains the following two functions.
##### i) `preprocessing(data,topnkey,num)`
This function mainly transfers categorical data to numerical data. The original iForest algorithm works for numerical only so categorical data has to be pre-processed.
Note that the columns are now hard-coded in this script, which is uneasy to fit different types of data. I will write a parser in the future to read the metadata from files.
##### ii) `add_flag(data_frame)`
This function adds flags to existing data. It introduces domain knowledge to the data and is only used for future testing purposes.
#### 4. `readindi.py`
This script is a file loader.
##### `readindividual(filename)`
This function reads the data from `CSV` files. It returns the file contents and top-n-keys. The input parameter `filename` should be the path to a valid **CSV** file.
### Build Your Own Tests
This sections introduces basic steps to apply iForest to your data.
#### 1. Read Data From CSV File
You can follow the following example to read the data.
~~~~python
data, topnkey = readindividual(filename)
~~~~
#### 2. Preprocess Data
The data is preprocessed for each value in the range of `topnkey`.
~~~~python
total_num_examples = 0
for num in range(1,len(topnkey)):
category, user, predict = preprocessing(data, topnkey, num)
total_num_examples += len(user)
~~~~
#### 3. Anomaly Detection
Tis process is also done for each value in the range of `topnkey`. It should be coded in the loop in `Step 2`.
~~~~python
u = iforest(category, user, threshold)
anomalies = predict.iloc[u,:]
~~~~
## Future Work
1. Implement a parser for reading the metadata of the data in the CSV file.
2. Use domain knowledge to verify the classification.
## References
[1] Isolation Forest [https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf](https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf)
[2] SciPy Official Site [https://www.scipy.org/about.html](https://www.scipy.org/about.html)
[3] Installing scikit-learn [http://scikit-learn.org/stable/install.html](http://scikit-learn.org/stable/install.html)
[4] Pandas [https://pandas.pydata.org](https://pandas.pydata.org)
|
Java
|
UTF-8
| 7,166 | 2.03125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nprot.vista;
import NProt.accesoDatos.ManejoBD;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.LinkedList;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListDataListener;
import nprot.modelo.Graficohistograma;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.ui.RefineryUtilities;
/**
*
* @author juan
*/
public class OrganismBars extends JInternalFrame{
ManejoBD manejador = new ManejoBD();
LinkedList <String[]> organisms;
String sbBarType = "";
/**
* Creates new form Graphs
*/
public OrganismBars(String sbBarType) {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
initComponents();
organisms = manejador.getTopOrganisms(100);
this.sbBarType = sbBarType;
this.organismCB.setModel(new ComboModel());
this.organismCB.addItemListener(new ComboEvents());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
organismCB = new javax.swing.JComboBox();
topOrgaMI = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
setClosable(true);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Organism"));
organismCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
topOrgaMI.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "25", "50", "75 ", "100", "200", " " }));
jLabel1.setText("Top");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(topOrgaMI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(organismCB, javax.swing.GroupLayout.PREFERRED_SIZE, 351, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(topOrgaMI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(organismCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public class ComboModel implements ComboBoxModel{
Object selected;
@Override
public void setSelectedItem(Object anItem) {
this.selected = anItem;
}
@Override
public Object getSelectedItem() {
return selected;
}
@Override
public int getSize() {
//System.out.println("organism count "+organisms.size());
return organisms.size();
}
@Override
public Object getElementAt(int index) {
return organisms.get(index)[0];
}
@Override
public void addListDataListener(ListDataListener l) {
}
@Override
public void removeListDataListener(ListDataListener l) {
}
}
public class ComboEvents implements ItemListener{
@Override
public void itemStateChanged(ItemEvent e) {
organismEDBar nuevo = new organismEDBar (
sbBarType,
( String ) organismCB.getSelectedItem(),
( String ) topOrgaMI.getSelectedItem()
);
nuevo.pack();
RefineryUtilities.centerFrameOnScreen(nuevo);
nuevo.setExtendedState(JFrame.MAXIMIZED_BOTH);
nuevo.setLocationRelativeTo(null);
nuevo.setVisible(true);
nuevo.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
}
}
public class ComboEventsTop implements ItemListener{
@Override
public void itemStateChanged(ItemEvent e) {
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JComboBox organismCB;
private javax.swing.JComboBox topOrgaMI;
// End of variables declaration//GEN-END:variables
}
|
Markdown
|
UTF-8
| 1,286 | 2.703125 | 3 |
[] |
no_license
|
# Realtime Transport Map
Show real time transport locations on a map.
## Map highlights
- Zoom (mouse scroll)
- Filter Routes
- Show/Hide Stops
- Vehicles are triangle and Stops are rectangular
- Vehicles color, Stops color (inherited from associated Route color)
- Vehicles heading (shown by rotating triangle)
## Demo:
http://realtime-transport-map.surge.sh
## Tools:
- Build tool: Angular CLI
- SPA Framework: Angular 5
- UI Framework: Angular Material
- Data Visulization Framework: D3.js
- Data Flow: @ngrx/store, @ngrx/effects, RxJs
## Performance consideration:
- Progressive Web App philosophy (Service Worker)
- Used associative array for faster and partial data update
- Requested data in chunks to ensure optimize the http traffic
## Development consideration:
- Modular, single source of truth, SRP, LIFT (Locate quickly, Identify at a glance, Flat structure, and Try to be DRY)
- Unit Tests (critical cases only)
## Development server
Run `ng serve`. Navigate to `http://localhost:4200/`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
|
Python
|
UTF-8
| 1,930 | 3.046875 | 3 |
[] |
no_license
|
import pyttsx3
import PyPDF2
import sys, getopt, os
def main(argv):
inputfile = ''
inputpage = 1
try:
opts, args = getopt.getopt(argv,"hi:p:",["ifile=","pnum="])
except getopt.GetoptError as e:
print("Something went wrong...")
print('ab.py -i <inputfile> -o <pagenumber>')
print(e)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('ab.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ('-i', '--ifile'):
inputfile = arg
elif opt in ('-p', '--pnum'):
inputpage = int(arg)
else:
print("Flag {o} not defined".format(o=opt))
sys.exit()
print("Input File: {i}, page {p}".format(i=inputfile, p=inputpage))
readings = os.listdir('readings')
if inputfile not in readings:
print('Please make sure {r} is in the `readings` folder'.format(r=inputfile))
sys.exit(2)
print("Starting audiobook reader...")
read_file_aloud(inputfile, inputpage)
print("Finished reading.")
def read_file_aloud(fn, pnum):
full_fn = "readings/" + fn
pdf = open(full_fn, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdf)
pages = pdfReader.numPages
if pnum >= pages:
print("Trying to read from a page that doesn't exist. There are only {m} pages found in the pdf `{fn}`".format(m=pages, fn=full_fn))
print(" Hint: Use a number less than {m}".format(m=pages))
else:
print("Starting to read {n} of {m}".format(n=pnum, m=pages))
print("initializing speaker...")
speaker = pyttsx3.init()
print("Getting page... {p}".format(p=pnum))
page = pdfReader.getPage(pnum)
print("Getting text:")
text = page.extractText()
print(text)
print("\n\nSpeaking...")
speaker.say(text)
speaker.runAndWait()
if __name__ == "__main__":
main(sys.argv[1:])
|
Markdown
|
UTF-8
| 2,216 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
+++
title = "WGD 2022-05-20"
categories = ["zet"]
tags = ["zet"]
slug = "WGD-2022-05-20"
date = "2022-05-20 00:00:00 +0000 UTC"
draft = "false"
ShowToc = "true"
+++
# WGD 2022-05-20
Still working on Mudmap's switch from single user accounts to multiple
accounts per organisation.
## Mudmap
I'm making a lot of progress on the transition from the one user one
account model. I've had to create extra tables, migrate users and devices
between them whilst ensuring backwards compatibility. I think the changes
to the database models are done for this section of changes - permissions
will come next.
I learned how to write Postgres subqueries this week and it's pretty
cool seeing a complex query execute repeatedly without issue.
User and organisation (what I'm calling *accounts*) data is stored in
the database but a couple of items are being used in `context.Values`.
Doing this prevents Mudmap from having to do queries for user or organisation
data when accessing other related data. I understand that it is a slight
anti-pattern but I feel it's actually a good use case for it.
Using `context` also allows for storing certain keys in the authentication
token. Again, it saves extra queries.
I've been using [go-resty](https://github.com/go-resty/resty) for making
and receiving HTTP requests inside Mudmap. In the past I've written HTTP
clients using just the standard lib but `resty` provides a few things I
need almost out of the box. Namely, retries and *interceptors*. When
a token expires, `resty` is configured to automatically re-authenticate
by sending a POST to the auth backend. I could write that myself but I'm
running a business and don't have time for that!
Also got to play with some Go Mutex's this week too. Have not really
had a need to implement any until now, and it's pretty easy. Three lines
of code will get you pretty far.
```go
// contrived example
var mu sync.Mutex
mu.Lock()
defer mu.Unlock
```
## Work
Had some huge wins at work this week. Our team got a lot of kudo's for
the work we've been putting it too. No rest though, straight from one
fire to the next. So far, I've worked on Django, Angular and Android
this week alone. Its enough to scatter a man's brain.
|
Python
|
UTF-8
| 59,771 | 2.796875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#####################################################################
##### IMPORT STANDARD MODULES
#####################################################################
#Python 3 support:
from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# import pydot
import os
from scipy.stats.mstats import chisquare, mode
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, GridSearchCV
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn import metrics, model_selection
from sklearn.feature_selection import RFE, RFECV
from abc import ABCMeta, abstractmethod
# from StringIO import StringIO
# import xgboost as xgb
# from xgboost.sklearn import XGBClassifier
from .genericmodelclass import GenericModelClass
from .data import DataBlock
#####################################################################
##### GENERIC MODEL CLASS
#####################################################################
class base_classification(GenericModelClass):
""" A base class which defines the generic classification functions
and variable definitions.
Parameters
----------
alg : object
An sklearn-style estimator
data_block : object
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
#Define as a meta class to disable direct instances
__metaclass__ = ABCMeta
# Map possible inputs to functions in sklean.metrics.
# Each value of the dictionary is a tuple of 3:
# (function, multi-class support, requires-probabilities)
# function: the sklearn metrics function
# multi-class support: if True, function allows multi-class support
# requires-probabilities: if True, the function requires
# probabilities to be passed as arguments
metrics_map = {
'accuracy':(metrics.accuracy_score,True,False),
'auc':(metrics.roc_auc_score,False,True),
'log_loss':(metrics.log_loss,True,True),
'f1':(metrics.f1_score,True,False),
'average_precision':(metrics.average_precision_score,False,True)
}
def __init__(
self, alg, data_block, predictors=[],cv_folds=5,
scoring_metric='accuracy',additional_display_metrics=[]
):
GenericModelClass.__init__(
self, alg=alg, data_block=data_block, predictors=predictors,
cv_folds=cv_folds,scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics)
#Run input datatype checks:
self.check_datatype(data_block,'data_block',DataBlock)
self.subset_check(predictors)
self.check_datatype(cv_folds,'cv_folds',int)
self.check_datatype(scoring_metric,'scoring_metric',basestring)
self.check_datatype(
additional_display_metrics,'additional_display_metrics',list)
#Store predicted probabilities in a dictionary with keys as the
# name of the dataset (train/test/predict) and values as the actual
# predictions.
self.predictions_probabilities = {}
#Boolean to store whether the estimator chosen allows probability
# predictions
self.probabilities_available = True
#Define number of classes in target.
self.num_target_class = len(
self.datablock.train[self.datablock.target].unique())
#A Series object to store generic classification model outcomes.
self.classification_output=pd.Series(
index = ['ModelID','CVScore_mean','CVScore_std','AUC',
'ActualScore (manual entry)','CVMethod','Predictors']
)
#Get the dictionary of available dataframes
self.dp = self.datablock.data_present()
#Check all the entered metrics. Note that this check has to be
#placed after declaration of num_target_class attribute
for metric in [scoring_metric]+additional_display_metrics:
self.check_metric(metric,self.num_target_class)
@classmethod
def check_metric(cls,metric,num_target_class):
if metric not in cls.metrics_map:
raise self.InvalidInput("The input '%s' is not a valid scoring metric for this module"%metric)
if num_target_class>2:
if not cls.metrics_map[metric][1]:
raise self.InvalidInput("The %s metric does not support multi-class classification case"%metric)
def fit_model(
self, performCV=True, printResults=True,
printTopN=None, printConfusionMatrix=True,
printModelParameters=True):
"""An advanced model fit function which fits the model on the
training data and performs cross-validation. It prints a model
report containing the following:
- The parameters being used to fit the model
- Confusion matrix for the train and test data
- Scoring metrics for the train and test data
- CV mean and std scores for scoring metric
- Additional scoring metrics on train and test data, if specified
Note that you can decide which details are to be printed using method
arguments.
Parameters
----------
performCV : bool, default True
if True, the model performs cross-validation using the number of
folds as the cv_folds parameter of the model
printResults : bool, default True
if True, prints the report of the model. This should be kept as
True unless the module being used in a background script
printTopN : int, default None
The number of top scored features to be displayed in the feature
importance or coefficient plot of the model. If None, all the
features will be displayed by default. Note:
- For algorithms supporting real coefficient, the features will
be sorted by their magnitudes (absolute values).
- For algorithms supporting positive feature importance scores,
features are sorted on the score itself.
This will be ignored is printResults is False.
printConfusionMatrix : bool, default True
if True, the confusion matrix for the train and test dataframes
are printed, otherwise they are ommitted.
This will be ignored is printResults is False.
print
printModelParameters : bool, default True
if True, the parameters being used to the run the model are
printed. It helps in validating the parameters and also makes
jupyter notebooks more informative if used
"""
self.check_datatype(performCV,'performCV',bool)
self.check_datatype(printResults,'printResults',bool)
self.check_datatype(printConfusionMatrix,'printConfusionMatrix',bool)
self.check_datatype(printModelParameters,'printModelParameters',bool)
if printTopN:
self.check_datatype(printTopN,'printTopN',int)
self.alg.fit(
self.datablock.train[self.predictors],
self.datablock.train[self.datablock.target])
#Get algo_specific_values
self.algo_specific_fit(printTopN)
#Get predictions:
for key,data in self.dp.items():
self.predictions_class[key] = self.alg.predict(
data[self.predictors])
if self.probabilities_available:
for key,data in self.dp.items():
self.predictions_probabilities[key] = self.alg.predict_proba(
data[self.predictors])
self.calc_model_characteristics(performCV)
if printResults:
self.printReport(printConfusionMatrix, printModelParameters)
def calc_model_characteristics(self, performCV=True):
# Determine key metrics to analyze the classification model. These
# are stored in the classification_output series object belonginf to
# this class.
for metric in [self.scoring_metric]+self.additional_display_metrics:
#Determine for both test and train, except predict:
for key,data in self.dp.items():
if key!='predict':
name = '%s_%s'%(metric,key)
#Case where probabilities to be passed as arguments
if base_classification.metrics_map[metric][2]:
self.classification_output[name] = \
base_classification.metrics_map[metric][0](
data[self.datablock.target],
self.predictions_probabilities[key])
#case where class predictions to be passed as arguments
else:
self.classification_output[name] = \
base_classification.metrics_map[metric][0](
data[self.datablock.target],
self.predictions_class[key])
#Determine confusion matrix:
name = 'ConfusionMatrix_%s'%key
self.classification_output[name] = pd.crosstab(
data[self.datablock.target],
self.predictions_class[key]
).to_string()
if performCV:
cv_score = self.KFold_CrossValidation(
scoring_metric=self.scoring_metric)
else:
cv_score = {
'mean_error': 0.0,
'std_error': 0.0
}
self.classification_output['CVMethod'] = \
'KFold - ' + str(self.cv_folds)
self.classification_output['CVScore_mean'] = cv_score['mean_error']
self.classification_output['CVScore_std'] = cv_score['std_error']
self.classification_output['Predictors'] = str(self.predictors)
def printReport(self, printConfusionMatrix, printModelParameters):
# Print the metric determined in the previous function.
print("\nModel Report")
#Outpute the parameters used for modeling
if printModelParameters:
print('\nModel being built with the following parameters:')
print(self.alg.get_params())
if printConfusionMatrix:
for key,data in self.dp.items():
if key!='predict':
print("\nConfusion Matrix for %s data:"%key)
print(pd.crosstab(
data[self.datablock.target],
self.predictions_class[key])
)
print('Note: rows - actual; col - predicted')
print("\nScoring Metric:")
for key,data in self.dp.items():
if key!='predict':
name = '%s_%s'%(self.scoring_metric,key)
print("\t%s (%s): %s" %
(
self.scoring_metric,
key,
"{0:.3%}".format(self.classification_output[name])
)
)
print("\nCV Score for Scoring Metric (%s):"%self.scoring_metric)
print("\tMean - %f | Std - %f" % (
self.classification_output['CVScore_mean'],
self.classification_output['CVScore_std'])
)
if self.additional_display_metrics:
print("\nAdditional Scoring Metrics:")
for metric in self.additional_display_metrics:
for key,data in self.dp.items():
if key!='predict':
name = '%s_%s'%(metric,key)
print("\t%s (%s): %s" % (
metric,
key,
"{0:.3%}".format(
self.classification_output[name])
)
)
def plot_feature_importance(self, printTopN):
num_print = len(self.feature_imp)
if printTopN is not None:
num_print = min(printTopN,len(self.feature_imp))
self.feature_imp.iloc[:num_print].plot(
kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
def plot_abs_coefficients(self,coeff,printTopN):
num_print = len(coeff)
if printTopN is not None:
num_print = min(printTopN,num_print)
coeff_abs_sorted = sorted(
abs(coeff).index,
key=lambda x: abs(coeff_abs[x]),
reverse=True
)
coeff[coeff_abs_sorted].iloc[:num_print,].plot(
kind='bar',
title='Feature Coefficients (Sorted by Magnitude)'
)
plt.ylabel('Magnitute of Coefficients')
plt.show(block=False)
def submission_proba(
self, IDcol, proba_colnames,filename="Submission.csv"):
"""
"""
submission = pd.DataFrame({
x: self.datablock.predict[x] for x in list(IDcol)
})
if len(list(proba_colnames))>1:
for i in range(len(proba_colnames)):
submission[proba_colnames[i]] = self.test_pred_prob[:,i]
else:
submission[list(proba_colnames)[0]] = self.test_pred_prob[:,1]
submission.to_csv(filename, index=False)
def set_parameters(self, param=None, cv_folds=None, set_default=False):
""" Set the parameters of the model. Only the parameters to be
updated are required to be passed.
Parameters
__________
param : dict, default None
A dictionary of key,value pairs where the keys are the parameters
to be updated and values as the new value of those parameters.
If None, no update performed
Ignored if set_default iss True.
cv_folds : int, default None
Pass the number of CV folds to be used in the model.
If None, no update performed.
set_default : bool, default True
if True, the model will be set to default parameters as defined
in model definition by scikit-learn. Note that this will not
affect the cv_folds parameter.
"""
#Check input
self.check_datatype(param,'param',dict)
self.check_datatype(set_default,'set_default',bool)
if param:
if set(param.keys()).issubset(
set(base_classification.default_parameters.keys())
):
raise self.InvalidInput("""The parameters passed should be a
subset of the model parameters""")
if set_default:
param = self.default_parameters
self.alg.set_params(**param)
self.model_output.update(pd.Series(param))
if cv_folds:
self.cv_folds = cv_folds
def export_model_base(self, IDcol, mstr):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/%s_models.csv'%mstr)
comb_series = self.classification_output.append(
self.model_output,
verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(
os.getcwd(),
'ensemble/%s_%s.csv'%(mstr,str(mID))
)
self.submission(IDcol, model_filename)
@abstractmethod
def algo_specific_fit(self,printTopN):
#Run algo-specific commands
pass
@abstractmethod
def export_model(self,IDcol):
#Export models
pass
#####################################################################
##### LOGISTIC REGRESSION
#####################################################################
class logistic_regression(base_classification):
""" Create a Logistic Regression model using implementation from
scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'C':1.0,
'tol':0.0001,
'solver':'liblinear',
'multi_class':'ovr',
'class_weight':'balanced'
}
def __init__(
self,data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=LogisticRegression(), data_block=data_block,
predictors=predictors,cv_folds=cv_folds,
scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics
)
self.model_output=pd.Series(self.default_parameters)
self.model_output['Coefficients'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
def algo_specific_fit(self, printTopN):
if self.num_target_class==2:
coeff = pd.Series(
np.concatenate(
(self.alg.intercept_,
self.alg.coef_[0])),
index=["Intercept"]+self.predictors
)
self.plot_abs_coefficients(coeff,printTopN)
else:
cols=['coef_class_%d'%i for i in range(0,self.num_target_class)]
coeff = pd.DataFrame(
self.alg.coef_.T,
columns=cols,
index=self.predictors
)
print('\nCoefficients:')
print(coeff)
self.model_output['Coefficients'] = coeff.to_string()
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'logistic_reg')
#####################################################################
##### DECISION TREE
#####################################################################
class decision_tree(base_classification):
""" Create a Decision Tree model using implementation from
scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'criterion':'gini',
'max_depth':None,
'min_samples_split':2,
'min_samples_leaf':1,
'max_features':None,
'random_state':None,
'max_leaf_nodes':None,
'class_weight':'balanced'
}
def __init__(
self,data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=DecisionTreeClassifier(), data_block=data_block,
predictors=predictors,cv_folds=cv_folds,
scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics
)
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
def algo_specific_fit(self, printTopN):
# print Feature Importance Scores table
self.feature_imp = pd.Series(
self.alg.feature_importances_,
index=self.predictors
).sort_values(ascending=False)
self.plot_feature_importance(printTopN)
self.model_output['Feature_Importance'] = \
self.feature_imp.to_string()
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'decision_tree')
## UNDER DEVELOPMENT CODE FOR PRINTING TREES
# def get_tree(self):
# return self.alg.tree_
# Print the tree in visual format
# Inputs:
# export_pdf - if True, a pdf will be exported with the
# filename as specified in pdf_name argument
# pdf_name - name of the pdf file if export_pdf is True
# def printTree(self, export_pdf=True, file_name="Decision_Tree.pdf"):
# dot_data = StringIO()
# export_graphviz(
# self.alg, out_file=dot_data, feature_names=self.predictors,
# filled=True, rounded=True, special_characters=True)
# export_graphviz(
# self.alg, out_file='data.dot', feature_names=self.predictors,
# filled=True, rounded=True, special_characters=True
# )
# graph = pydot.graph_from_dot_data(dot_data.getvalue())
# if export_pdf:
# graph.write_pdf(file_name)
# return graph
#####################################################################
##### RANDOM FOREST
#####################################################################
class random_forest(base_classification):
""" Create a Random Forest model using implementation from
scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'n_estimators':10,
'criterion':'gini',
'max_depth':None,
'min_samples_split':2,
'min_samples_leaf':1,
'max_features':'auto',
'max_leaf_nodes':None,
'oob_score':False,
'random_state':None,
'class_weight':'balanced',
'n_jobs':1
}
def __init__(
self,data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=RandomForestClassifier(), data_block=data_block,
predictors=predictors,cv_folds=cv_folds,
scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics
)
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
self.model_output['OOB_Score'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
def algo_specific_fit(self, printTopN):
# print Feature Importance Scores table
self.feature_imp = pd.Series(
self.alg.feature_importances_,
index=self.predictors
).sort_values(ascending=False)
self.plot_feature_importance(printTopN)
self.model_output['Feature_Importance'] = \
self.feature_imp.to_string()
if self.model_output['oob_score']:
print('OOB Score : %f' % self.alg.oob_score_)
self.model_output['OOB_Score'] = self.alg.oob_score_
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'random_forest')
#####################################################################
##### EXTRA TREES FOREST
#####################################################################
class extra_trees(base_classification):
""" Create an Extra Trees Forest model using implementation from
scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'n_estimators':10,
'criterion':'gini',
'max_depth':None,
'min_samples_split':2,
'min_samples_leaf':1,
'max_features':'auto',
'max_leaf_nodes':None,
'oob_score':False,
'random_state':None,
'class_weight':'balanced',
'n_jobs':1
}
def __init__(
self,data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=ExtraTreesClassifier(), data_block=data_block,
predictors=predictors,cv_folds=cv_folds,
scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics)
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
self.model_output['OOB_Score'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
def algo_specific_fit(self, printTopN):
# print Feature Importance Scores table
self.feature_imp = pd.Series(
self.alg.feature_importances_,
index=self.predictors
).sort_values(ascending=False)
self.plot_feature_importance(printTopN)
self.model_output['Feature_Importance'] = \
self.feature_imp.to_string()
if self.model_output['oob_score']:
print('OOB Score : %f' % self.alg.oob_score_)
self.model_output['OOB_Score'] = self.alg.oob_score_
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'extra_trees')
#####################################################################
##### ADABOOST CLASSIFICATION
#####################################################################
class adaboost(base_classification):
""" Create an AdaBoost model using implementation from
scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'n_estimators':50,
'learning_rate':1.0
}
def __init__(
self,data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=AdaBoostClassifier(), data_block=data_block,
predictors=predictors,cv_folds=cv_folds,
scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics
)
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
def algo_specific_fit(self, printTopN):
# print Feature Importance Scores table
self.feature_imp = pd.Series(
self.alg.feature_importances_,
index=self.predictors
).sort_values(ascending=False)
self.plot_feature_importance(printTopN)
self.model_output['Feature_Importance'] = \
self.feature_imp.to_string()
plt.xlabel("AdaBoost Estimator")
plt.ylabel("Estimator Error")
plt.plot(
range(1, int(self.model_output['n_estimators'])+1),
self.alg.estimator_errors_
)
plt.plot(
range(1, int(self.model_output['n_estimators'])+1),
self.alg.estimator_weights_
)
plt.legend(
['estimator_errors','estimator_weights'],
loc='upper left'
)
plt.show(block=False)
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'adaboost')
#####################################################################
##### GRADIENT BOOSTING MACHINE
#####################################################################
class gradient_boosting_machine(base_classification):
""" Create a GBM (Gradient Boosting Machine) model using implementation
from scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'loss':'deviance',
'learning_rate':0.1,
'n_estimators':100,
'subsample':1.0,
'min_samples_split':2,
'min_samples_leaf':1,
'max_depth':3, 'init':None,
'random_state':None,
'max_features':None,
'verbose':0,
'max_leaf_nodes':None,
'warm_start':False,
'presort':'auto'
}
def __init__(
self, data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=GradientBoostingClassifier(), data_block=data_block,
predictors=predictors,cv_folds=cv_folds,
scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics
)
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
def algo_specific_fit(self, printTopN):
# print Feature Importance Scores table
self.feature_imp = pd.Series(
self.alg.feature_importances_,
index=self.predictors
).sort_values(ascending=False)
self.plot_feature_importance(printTopN)
self.model_output['Feature_Importance'] = \
self.feature_imp.to_string()
#Plot OOB estimates if subsample <1:
if self.model_output['subsample']<1:
plt.xlabel("GBM Iteration")
plt.ylabel("Score")
plt.plot(
range(1, self.model_output['n_estimators']+1),
self.alg.oob_improvement_
)
plt.legend(['oob_improvement_','train_score_'], loc='upper left')
plt.show(block=False)
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'gbm')
#####################################################################
##### Support Vector Classifier
#####################################################################
class linear_svm(base_classification):
""" Create a Linear Support Vector Machine model using implementation
from scikit-learn.
Parameters
----------
data_block : object of type easyML.DataBlock
An object of easyML's DataBlock class. You should first create an
object of that class and then pass it as a parameter.
predictors : list of strings, default []
A list of columns which are to be used as predictors (also called
independent variables or features).
The default value is an empty list because these need not always be
defined at the time of class initialization. The set_predictors
method can be used later but before creating any predictive model.
cv_folds : int, default 5
The number of folds to be created while performing CV.
This parameter can be adjusted later by passing using the
set_parameters method
scoring_metric : str, default 'accuracy'
The scoring metric to be used for evaluating the model across the
different functions available. The available options are
- 'accuracy'
- 'auc'
- 'log_loss'
- 'f1'
- 'average_precision'
additional_display_metrics : list of string, default []
A list of additional display metrics to be shown for the test and
train dataframes in data_block. Note:
- These will be just shown for user reference and not actually used
for model evaluation
- The same available options as scoring_metric apply
"""
default_parameters = {
'C':1.0,
'kernel':'linear', #modified not default
'degree':3,
'gamma':'auto',
'coef0':0.0,
'shrinking':True,
'probability':False,
'tol':0.001,
'cache_size':200,
'class_weight':None,
'verbose':False,
'max_iter':-1,
'decision_function_shape':None,
'random_state':None
}
def __init__(
self,data_block, predictors=[],cv_folds=10,
scoring_metric='accuracy',additional_display_metrics=[]):
base_classification.__init__(
self, alg=SVC(), data_block=data_block, predictors=predictors,
cv_folds=cv_folds,scoring_metric=scoring_metric,
additional_display_metrics=additional_display_metrics
)
self.model_output=pd.Series(self.default_parameters)
self.model_output['Coefficients'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
#Check if probabilities enables:
if not self.alg.get_params()['probability']:
self.probabilities_available = False
def algo_specific_fit(self, printTopN):
if self.num_target_class==2:
coeff = pd.Series(
np.concatenate((self.alg.intercept_,self.alg.coef_[0])),
index=["Intercept"]+self.predictors
)
#print the chart of importances
self.plot_abs_coefficients(coeff, printTopN)
else:
cols=['coef_class_%d'%i for i in range(0,self.num_target_class)]
coeff = pd.DataFrame(
self.alg.coef_.T,
columns=cols,
index=self.predictors
)
print('\nCoefficients:')
print(coeff)
self.model_output['Coefficients'] = coeff.to_string()
def export_model(self, IDcol):
#Export the model into the model file as well as create a submission
#with model index. This will be used for creating an ensemble.
self.export_model_base(IDcol,'linear_svm')
#####################################################################
##### XGBOOST ALGORITHM (UNDER DEVELOPMENT)
#####################################################################
"""
#Define the class similar to the overall classification class
class XGBoost(base_classification):
def __init__(self,data_block, predictors, cv_folds=5,scoring_metric_skl='accuracy', scoring_metric_xgb='error'):
base_classification.__init__(self, alg=XGBClassifier(), data_block=data_block, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric_skl)
#Define default parameters on your own:
self.default_parameters = {
'max_depth':3, 'learning_rate':0.1,
'n_estimators':100, 'silent':True,
'objective':"binary:logistic",
'nthread':1, 'gamma':0, 'min_child_weight':1,
'max_delta_step':0, 'subsample':1, 'colsample_bytree':1, 'colsample_bylevel':1,
'reg_alpha':0, 'reg_lambda':1, 'scale_pos_weight':1,
'base_score':0.5, 'seed':0, 'missing':None
}
self.model_output = pd.Series(self.default_parameters)
#create DMatrix with nan as missing by default. If later this is changed then the matrix are re-calculated. If not set,will give error is nan present in data
self.xgtrain = xgb.DMatrix(self.datablock.train[self.predictors].values, label=self.datablock.train[self.datablock.target].values, missing=np.nan)
self.xgtest = xgb.DMatrix(self.datablock.predict[self.predictors].values, missing=np.nan)
self.num_class = 2
self.n_estimators = 10
self.eval_metric = 'error'
self.train_predictions = []
self.train_pred_prob = []
self.test_predictions = []
self.test_pred_prob = []
self.num_target_class = len(data_train[target].unique())
#define scoring metric:
self.scoring_metric_skl = scoring_metric_skl
# if scoring_metric_xgb=='f1':
# self.scoring_metric_xgb = self.xg_f1
# else:
self.scoring_metric_xgb = scoring_metric_xgb
#Define a Series object to store generic classification model outcomes;
self.classification_output=pd.Series(index=['ModelID','Accuracy','CVScore_mean','CVScore_std','SpecifiedMetric',
'ActualScore (manual entry)','CVMethod','ConfusionMatrix','Predictors'])
#feature importance (g_scores)
self.feature_imp = None
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
# self.set_parameters(set_default=True)
#Define custom f1 score metric:
def xg_f1(self,y,t):
t = t.get_label()
y_bin = [1. if y_cont > 0.5 else 0. for y_cont in y] # binaryzing your output
return 'f1',metrics.f1_score(t,y_bin)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
if set_default:
param = self.default_parameters
self.alg.set_params(**param)
self.model_output.update(pd.Series(param))
if 'missing' in param:
#update DMatrix with missing:
self.xgtrain = xgb.DMatrix(self.datablock.train[self.predictors].values, label=self.datablock.train[self.datablock.target].values, missing=param['missing'])
self.xgtest = xgb.DMatrix(self.datablock.predict[self.predictors].values, missing=param['missing'])
if 'num_class' in param:
self.num_class = param['num_class']
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
# def set_feature_importance(self):
# fs = self.alg.booster().get_fscore()
# ftimp = pd.DataFrame({
# 'feature': fs.keys(),
# 'importance_Score': fs.values()
# })
# ftimp['predictor'] = ftimp['feature'].apply(lambda x: self.predictors[int(x[1:])])
# self.feature_imp = pd.Series(ftimp['importance_Score'].values, index=ftimp['predictor'].values)
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True, useTrainCV=False, TrainCVFolds=5, early_stopping_rounds=20, show_progress=True, printTopN='all'):
if useTrainCV:
xgb_param = self.alg.get_xgb_params()
if self.num_class>2:
xgb_param['num_class']=self.num_class
if self.scoring_metric_xgb=='f1':
cvresult = xgb.cv(xgb_param,self.xgtrain, num_boost_round=self.alg.get_params()['n_estimators'], nfold=self.cv_folds,
metrics=['auc'],feval=self.xg_f1,early_stopping_rounds=early_stopping_rounds, show_progress=show_progress)
else:
cvresult = xgb.cv(xgb_param,self.xgtrain, num_boost_round=self.alg.get_params()['n_estimators'], nfold=self.cv_folds,
metrics=self.scoring_metric_xgb, early_stopping_rounds=early_stopping_rounds, show_progress=show_progress)
self.alg.set_params(n_estimators=cvresult.shape[0])
print(self.alg.get_params())
obj = self.alg.fit(self.datablock.train[self.predictors], self.datablock.train[self.datablock.target], eval_metric=self.eval_metric)
#Print feature importance
# self.set_feature_importance()
self.feature_imp = pd.Series(self.alg.booster().get_fscore()).sort_values(ascending=False)
num_print = len(self.feature_imp)
if printTopN is not None:
if printTopN != 'all':
num_print = min(printTopN,len(self.feature_imp))
self.feature_imp.iloc[:num_print].plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
self.model_output['Feature_Importance'] = self.feature_imp.to_string()
#Get train predictions:
self.train_predictions = self.alg.predict(self.datablock.train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.datablock.train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.datablock.predict[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.datablock.predict[self.predictors])
self.calc_model_characteristics(performCV)
self.printReport()
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/xgboost_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/xgboost_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
"""
#####################################################################
##### ENSEMBLE (UNDER DEVELOPMENT)
#####################################################################
"""
#Class for creating an ensemble model using the exported files from previous classes
class Ensemble_Classification(object):
#initialize the object with target variable
def __init__(self, target, IDcol):
self.datablock.target = target
self.data = None
self.relationMatrix_chi2 = None
self.relationMatrix_diff = None
self.IDcol = IDcol
#create the ensemble data
# Inputs:
# models - dictionary with key as the model name and values as list containing the model numbers to be ensebled
# Note: all the models in the list specified should be present in the ensemble folder. Please cross-check once
def create_ensemble_data(self, models):
self.data = None
for key, value in models.items():
# print key,value
for i in value:
fname = key + '_' + str(i)
fpath = os.path.join(os.getcwd(), 'ensemble', fname+'.csv')
tempdata = pd.read_csv(fpath)
tempdata = tempdata.rename(columns = {self.datablock.target: fname})
if self.data is None:
self.data = tempdata
else:
self.data = self.data.merge(tempdata,on=self.data.columns[0])
#get the data being used for ensemble
def get_ensemble_data(self):
return self.data
#Check chisq test between different model outputs to check which combination of ensemble will generate better results. Note: Models with high correlation should not be combined together.
def chisq_independence(self, col1, col2, verbose = False):
contingencyTable = pd.crosstab(col1,col2,margins=True)
if len(col1)/((contingencyTable.shape[0] - 1) * (contingencyTable.shape[1] - 1)) <= 5:
return "TMC"
expected = contingencyTable.copy()
total = contingencyTable.loc["All","All"]
# print contingencyTable.index
# print contingencyTable.columns
for m in contingencyTable.index:
for n in contingencyTable.columns:
expected.loc[m,n] = contingencyTable.loc[m,"All"]*contingencyTable.loc["All",n]/float(total)
if verbose:
print('\n\nAnalysis of models: %s and %s' % (col1.name, col2.name))
print('Contingency Table:')
print(contingencyTable)
# print '\nExpected Frequency Table:'
# print expected
observed_frq = contingencyTable.iloc[:-1,:-1].values.ravel()
expected_frq = expected.iloc[:-1,:-1].values.ravel()
numless1 = len(expected_frq[expected_frq<1])
perless5 = len(expected_frq[expected_frq<5])/len(expected_frq)
#Adjustment in DOF so use the 1D chisquare to matrix shaped data; -1 in row n col because of All row and column
matrixadj = (contingencyTable.shape[0] - 1) + (contingencyTable.shape[1] - 1) - 2
# print matrixadj
pval = np.round(chisquare(observed_frq, expected_frq,ddof=matrixadj)[1],3)
if numless1>0 or perless5>=0.2:
return str(pval)+"*"
else:
return pval
#Create the relational matrix between models
def check_ch2(self, verbose=False):
col = self.data.columns[1:]
self.relationMatrix_chi2 = pd.DataFrame(index=col,columns=col)
for i in range(len(col)):
for j in range(i, len(col)):
if i==j:
self.relationMatrix_chi2.loc[col[i],col[j]] = 1
else:
pval = self.chisq_independence(self.data.iloc[:,i+1],self.data.iloc[:,j+1], verbose=verbose)
self.relationMatrix_chi2.loc[col[j],col[i]] = pval
self.relationMatrix_chi2.loc[col[i],col[j]] = pval
print('\n\n Relational Matrix (based on Chi-square test):')
print(self.relationMatrix_chi2)
def check_diff(self):
col = self.data.columns[1:]
self.relationMatrix_diff = pd.DataFrame(index=col,columns=col)
nrow = self.data.shape[0]
for i in range(len(col)):
for j in range(i, len(col)):
if i==j:
self.relationMatrix_diff.loc[col[i],col[j]] = '-'
else:
# print col[i],col[j]
pval = "{0:.2%}".format(sum( np.abs(self.data.iloc[:,i+1]-self.data.iloc[:,j+1]) )/float(nrow))
self.relationMatrix_diff.loc[col[j],col[i]] = pval
self.relationMatrix_diff.loc[col[i],col[j]] = pval
print('\n\n Relational Matrix (based on perc difference):')
print(self.relationMatrix_diff)
#Generate submission for the ensembled model by combining the mentioned models.
# Inputs:
# models_to_use - list with model names to use; if None- all models will be used
# filename - the filename of the final submission
# Note: the models should be odd in nucmber to allow a clear winner in terms of mode otherwise the first element will be chosen
def submission(self, models_to_use=None, filename="Submission_ensemble.csv"):
#if models_to_use is None then use all, else filter:
if models_to_use is None:
data_ens = self.data
else:
data_ens = self.data[models_to_use]
def mode_ens(x):
return int(mode(x).mode[0])
ensemble_output = data_ens.apply(mode_ens,axis=1)
submission = pd.DataFrame({
self.IDcol: self.data.iloc[:,0],
self.datablock.target: ensemble_output
})
submission.to_csv(filename, index=False)
"""
|
Python
|
UTF-8
| 5,121 | 3.375 | 3 |
[] |
no_license
|
import ast
code = """\
a = 23
b = 42
c = a + 2*b - z
"""
top = ast.parse(code)
print(ast.dump(top))
print("first visit")
print("-"*10)
class NameVisitor(ast.NodeVisitor):
def visit_Name(self,node):
print((node.id,node.ctx))
NameVisitor().visit(top)
print("second visit")
print("-"*10)
class NameNumVisitor(ast.NodeVisitor):
def visit_Name(self, node):
print((node.id, node.ctx))
def visit_Num(self, node):
print(node.n)
NameNumVisitor().visit(top)
print("third visit")
print("-"*10)
class NameChecker(ast.NodeVisitor):
def __init__(self):
self.symbols = set()
def visit_Name(self, node):
if isinstance(node.ctx, ast.Store):
self.symbols.add(node.id)
elif isinstance(node.ctx, ast.Load):
if node.id not in self.symbols:
print("Error: Name %s not defined" % node.id)
NameChecker().visit(top)
print("type checking")
print("-"*10)
class TypeCheck(ast.NodeVisitor):
def visit_Num(self,node):
node.check_type = "num"
def visit_Str(self,node):
node.check_type = "str"
# Perform type checking
TypeCheck().visit(top)
top = ast.parse("2+3")
ast.dump(top)
TypeCheck().visit(top)
print(top.body[0].value.left.check_type)
print(top.body[0].value.right.check_type)
class TypeCheck(ast.NodeVisitor):
def visit_Num(self,node):
node.check_type = "num"
def visit_Str(self,node):
node.check_type = "str"
def visit_BinOp(self,node):
self.visit(node.left)
self.visit(node.right)
if hasattr(node.left, "check_type") and hasattr(node.right, "check_type"):
if node.left.check_type != node.right.check_type:
print("Type Error: %s %s %s" % (node.left.check_type,
node.op.__class__.__name__,
node.right.check_type))
else:
node.check_type = node.left.check_type
def visit_UnaryOp(self,node):
self.visit(node.operand)
if hasattr(node.operand, "check_type"):
node.check_type = node.operand.check_type
top = ast.parse("3 + 4 * (23 - 45) / 2")
TypeCheck().visit(top)
print(top.body[0].value.check_type)
top = ast.parse("2+ 'Hello'")
TypeCheck().visit(top)
class TypeDefinition(object):
def __init__(self,name,bin_ops, unary_ops):
self.name = name
self.bin_ops = bin_ops
self.unary_ops = unary_ops
num_type = TypeDefinition("num", {'Add','Sub','Mult','Div'}, {'UAdd','USub'})
str_type = TypeDefinition("str", {'Add'},set())
class TypeCheck(ast.NodeVisitor):
def __init__(self):
self.symtab = {}
def visit_Assign(self,node):
self.visit(node.value)
check_type = getattr(node.value,"check_type",None)
# Store known type information in the symbol table (if any)
for target in node.targets:
self.symtab[target.id] = check_type
def visit_Name(self,node):
if isinstance(node.ctx,ast.Load):
# Check if any type information is known. If so, attach it
if node.id in self.symtab:
check_type = self.symtab[node.id]
if check_type:
node.check_type = check_type
else:
print("Undefined identifier %s" % node.id)
def visit_Num(self,node):
node.check_type = num_type
def visit_Str(self,node):
node.check_type = str_type
def visit_BinOp(self,node):
self.visit(node.left)
self.visit(node.right)
opname = node.op.__class__.__name__
if hasattr(node.left,"check_type") and hasattr(node.right,"check_type"):
if node.left.check_type != node.right.check_type:
print("Type Error: %s %s %s" % (node.left.check_type.name,
opname,
node.right.check_type.name))
elif opname not in node.left.check_type.bin_ops:
print("Unsupported binary operation %s for type %s" % (opname, node.left.check_type.name))
else:
node.check_type = node.left.check_type
def visit_UnaryOp(self,node):
self.visit(node.operand)
opname = node.op.__class__.__name__
if hasattr(node.operand,"check_type"):
if opname not in node.operand.check_type.unary_ops:
print("Unsupported unary operation %s for type %s" % (opname, node.operand.check_type.name))
else:
node.check_type = node.operand.check_type
top = ast.parse("2 + 'hello'")
TypeCheck().visit(top)
top = ast.parse("'Hello' - 'World'")
TypeCheck().visit(top)
top = ast.parse("2 + 3 * (4 + 20) % 3")
TypeCheck().visit(top)
checker = TypeCheck()
code = """
a = 23
b = 45
c = "Hello"
d = a + 20 * b - 30
"""
checker.visit(ast.parse(code))
print(checker.symtab)
def check(expr):
checker.visit(ast.parse(expr))
check("99*d - a + b")
check("99*d - c + b")
check("c + 'World'")
check("c - 'World'")
check("10 + a + b * x")
|
C#
|
UTF-8
| 1,993 | 2.59375 | 3 |
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using HttpClientFactoryExample.Extensions;
using HttpClientFactoryExample.Model;
using Microsoft.Extensions.Logging;
namespace HttpClientFactoryExample.Services
{
public class HttpClientFactoryInstanceManagementService : IIntegrationService
{
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<HttpClientFactoryInstanceManagementService> _logger;
public HttpClientFactoryInstanceManagementService(
IHttpClientFactory httpClientFactory,
ILogger<HttpClientFactoryInstanceManagementService> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
public async Task Run()
{
await GetDrinksWithHttpClientFromFactory(_cancellationTokenSource.Token);
}
private async Task GetDrinksWithHttpClientFromFactory(CancellationToken cancellationToken)
{
var httpClient = _httpClientFactory.CreateClient("CocktailClient");
var request = new HttpRequestMessage(HttpMethod.Get, "api/json/v1/1/random.php");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var stream = await response.Content.ReadAsStreamAsync();
response.EnsureSuccessStatusCode();
var drinks = stream.ReadAndDeserializeFromJson<DrinkResult>();
_logger.LogInformation(drinks.Drinks.FirstOrDefault()?.StrAlcoholic);
}
}
}
|
Java
|
UTF-8
| 736 | 3.015625 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aula06_at03_01;
import java.util.Scanner;
/**
*
* @author clecioferreira
*/
public class Aula06_at03_01 {
/**
* @param args the command line arguments
* Nesse programa acontece um erro durante a execucao
* devido a selecao incorreta dos itens do vetor.
* acontece o erro "Index 10 out of bounds."
*/
public static void main(String[] args) {
int[] valores = new int[10];
Scanner leitor = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
valores[i] = leitor.nextInt();
}
}
}
|
PHP
|
UTF-8
| 3,368 | 2.578125 | 3 |
[] |
no_license
|
<?php
namespace PMW\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use PMW\Models\LogBook;
use Illuminate\Support\Facades\Auth;
/**
* Controller ini berfungsi untuk melakukan aksi yang berkaitan dengan
* logbook
*
* @author BagasMuharom <bagashidayat@mhs.unesa.ac.id|bagashidayat45@gmail.com>
* @package PMW\Http\Controllers
*/
class LogBookController extends Controller
{
private $validationArr = [
'catatan' => 'required',
'biaya' => 'required|numeric'
];
/**
* Menambah LogBook
*
* @param Request $request
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function tambah(Request $request)
{
$this->validate($request, $this->validationArr);
if ($this->bolehTambahLogBook()) {
// Menambah Logbook ke database
$tambah = LogBook::create([
'catatan' => $request->catatan,
'biaya' => $request->biaya,
'tanggal' => $request->tanggal,
'id_proposal' => Auth::user()->mahasiswa()->proposal()->id
]);
Session::flash('message', 'Berhasil menambah logbook !');
return redirect()->route('logbook');
}
Session::flash('message', 'Anda tidak bisa menambah logbook !');
return back()->withInput();
}
/**
* Mengedit logbook tertentu
*
* @param Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function edit(Request $request)
{
$this->validate($request, $this->validationArr);
// Menambah LogBook ke database
$edit = LogBook::find($request->id)->update([
'catatan' => $request->catatan,
'biaya' => $request->biaya,
'tanggal' => $request->tanggal
]);
Session::flash('message', 'Berhasil mengubah logbook !');
return redirect()->route('logbook');
}
/**
* Menghapus logbook tertentu
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function hapus(Request $request)
{
$logbook = LogBook::find($request->id);
if(is_null($logbook)){
return response()->json([
'message' => 'Anda tidak bisa menghapus logbook tersebut !',
'type' => 'error'
]);
}
if($logbook->id_proposal !== Auth::user()->mahasiswa()->proposal()->id){
return response()->json([
'message' => 'Anda tidak bisa menghapus logbook tersebut !',
'type' => 'error'
]);
}
try {
$logbook->delete();
} catch (\Exception $e) {
return response()->json([
'message' => 'Anda tidak bisa menghapus logbook tersebut !',
'type' => 'error'
]);
}
return response()->json([
'message' => 'Berhasil menghapus logbook !',
'type' => 'success'
]);
}
/**
* Mengecek apakah user terkait bisa menambah logbook
*
* @return boolean
*/
private function bolehTambahLogBook()
{
// Jika user adalah ketua tim dan
// proposal dinyatakan lolos
return (Auth::user()->isKetua() && Auth::user()->mahasiswa()->proposal()->lolos());
}
}
|
Java
|
UTF-8
| 2,810 | 2.5 | 2 |
[] |
no_license
|
package Admin;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Save_Client
*/
@WebServlet("/Save_Client")
public class Save_Client extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Save_Client() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter out=response.getWriter();
response.setContentType("text/html");
boolean b=true;
ArrayList<User> list=AdminDAO.GetAllUsers();
for(User uu:list)
{
if(uu.getEmail().equals(request.getParameter("email")) || uu.getPhone().equals(request.getParameter("contact"))) b=false;
}
if(b)
{
if(request.getParameter("psw1").toString().equals(request.getParameter("psw2").toString()))
{
User u=new User();
u.setFn(request.getParameter("fn"));
u.setLn(request.getParameter("ln"));
u.setEmail(request.getParameter("email"));
u.setGender(request.getParameter("gender"));
u.setPhone(request.getParameter("contact"));
u.setPassword(request.getParameter("psw1"));
if(AdminDAO.SaveUser(u)>0)
{
out.println("<script>alert('User Saved Successfully')</script>");
request.getRequestDispatcher("MainPage.jsp").include(request, response);
}
else
{
out.println("<script>alert('Error in Saving User')</script>");
request.getRequestDispatcher("Client_SignUp.jsp").include(request, response);
}
}
else
{
out.println("<script>alert('Please Re-Enter Password Correctly')</script>");
request.getRequestDispatcher("Client_SignUp.jsp").include(request, response);
}
}
else
{
out.println("<script>alert('Enter Unique Email and Contact')</script>");
request.getRequestDispatcher("Client_SignUp.jsp").include(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
Java
|
UTF-8
| 948 | 3.578125 | 4 |
[] |
no_license
|
package com.casino.carddealer.utility;
/**
* Cards with their symbols and names; they are used used to display with the rank after the
* evaluation.
*/
public enum Cards {
TWO("2", "Two"),
THREE("3", "Three"),
FOUR("4", "Four"),
FIVE("5", "Five"),
SIX("6", "Six"),
SEVEN("7", "Seven"),
EIGHT("8", "Eight"),
NINE("9", "Nine"),
TEN("T", "Ten"),
JACK("J", "Jack"),
QUEEN("Q", "Queen"),
KING("K", "King"),
ACE("A", "Ace"),
CLUBS("C", "Clubs"),
DIAMONDS("D", "Diamonds"),
HEARTS("H", "Hearts"),
SPADES("S", "Spades");
private final String symbol;
private final String name;
Cards(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}
public static String findBySymbol(String symbol) {
for (Cards c : values()) {
if (c.symbol.equals(symbol)) {
return c.name;
}
}
return "";
}
@Override
public String toString() {
return symbol;
}
}
|
C++
|
UTF-8
| 3,547 | 3.046875 | 3 |
[] |
no_license
|
#include "Shader.hpp"
#include <sstream>
#include <fstream>
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <math.h>
Shader::Shader(const std::string& vertexPath, const std::string& fragmentPath) {
std::ifstream vertexFile;
std::ifstream fragmentFile;
std::stringstream vertexStream;
std::stringstream fragmentStream;
std::string vertexCode;
std::string fragmentCode;
vertexFile.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
fragmentFile.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try{
vertexFile.open(vertexPath, std::ios::in);
fragmentFile.open(fragmentPath, std::ios::in);
vertexStream << vertexFile.rdbuf();
fragmentStream << fragmentFile.rdbuf();
vertexCode = vertexStream.str();
fragmentCode = fragmentStream.str();
vertexFile.close();
fragmentFile.close();
}
catch (std::ifstream::failure e){
std::cerr << e.what() << " - cannot open shader file.\n";
}
CreateAndCompileShader(vertexCode, fragmentCode);
}
void Shader::Use() {
glUseProgram(programID_);
}
void Shader::CreateAndCompileShader(const std::string& vertexCodeString, const std::string& fragmentCodeString) {
unsigned int vertexShader;
unsigned int fragmentShader;
int success;
char infoLog[512];
vertexShader = glCreateShader(GL_VERTEX_SHADER);
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
const char* vertexCode = vertexCodeString.c_str();
const char* fragmentCode = fragmentCodeString.c_str();
glShaderSource(vertexShader, 1, &vertexCode, nullptr);
glShaderSource(fragmentShader, 1, &fragmentCode, nullptr);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success){
glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog);
std::cerr << "Failed to compile vertex shader " << infoLog << "\n";
}
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success){
glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog);
std::cerr << "Failed to compile fragment shader: " << infoLog << "\n";
}
programID_ = glCreateProgram();
glAttachShader(programID_, vertexShader);
glAttachShader(programID_, fragmentShader);
glLinkProgram(programID_);
glGetProgramiv(programID_, GL_LINK_STATUS, &success);
if(!success){
glGetProgramInfoLog(programID_, 512, nullptr, infoLog);
std::cerr << "Failed to link program: " << infoLog << "\n";
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
Shader::~Shader() {
glDeleteProgram(programID_);
}
void Shader::setFloat(const std::string &name, float value) const {
glUniform1f(glGetUniformLocation(programID_, name.c_str()), value);
}
void Shader::setInt(const std::string &name, int value) const {
glUniform1i(glGetUniformLocation(programID_, name.c_str()), value);
}
void Shader::setMat4f(const std::string &name, const glm::mat4& matrix) {
glUniformMatrix4fv(glGetUniformLocation(programID_, name.c_str()), 1, GL_FALSE, &matrix[0][0]);
}
void Shader::setVec3f(const std::string &name, float v1, float v2, float v3) {
glUniform3f(glGetUniformLocation(programID_, name.c_str()), v1, v2, v3);
}
void Shader::setVec3f(const std::string& name, const glm::vec3& value) {
glUniform3fv((glGetUniformLocation(programID_, name.c_str())), 1, &value[0]);
}
|
PHP
|
UTF-8
| 594 | 3.015625 | 3 |
[] |
no_license
|
<?php
echo "<center> Array assignment</center>";
$a=array("php","java","embedded","android");
sort($a);
print_r($a);
echo "<br>";
$a=array("php","java","embedded","android");
array_unique($a);
print_r($a);
echo "<br>";
$a1=array("a","b","c","d");
$a2= array("php","java","embedded","android");
print_r(array_merge($a1,$a2));
echo "<br>";
print_r(array_combine($a1,$a2));
echo "<br>";
print_r(array_diff($a1,$a2));
echo "<br>";
$a=array("php","java","embedded","android");
array_push($a,".net");
print_r($a);
echo "<br>";
unset($a[3]);
print_r($a);
echo "<br>";
?>
|
Java
|
UTF-8
| 2,752 | 3.875 | 4 |
[] |
no_license
|
/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 Zarin Tasnim
*/
package ex32;
import java.util.Scanner;
import java.util.Random;
class numberGame {
//not allowing non numeric value
public static boolean inputValidation(String input) {
if (input.matches("[0-9]+")) {
return true;
} else {
System.out.print("Wrong input. Try again: ");
return false;
}
}
//getting the level
public static int chooseLevel(String level) {
int n=0;
if (level.matches("1")) {
n = 10;
} else if (level.matches("2")) {
n = 100;
} else if (level.matches("3")) {
n = 1000;
}
return n;
}
//comparing numbers
public static void compareNumbers(int computer)
{
int count = 0;
while (true) {
count++;
Scanner sc2 = new Scanner(System.in);
String numbString=sc2.nextLine();
if (inputValidation(numbString)) {
int user = Integer.parseInt(numbString);
if (user < computer) {
System.out.print("Too low. Guess again? ");
} else if (user > computer) {
System.out.print("Too high. Guess again? ");
} else {
System.out.print("You got it in " + count + " guesses\n\n");
break;
}
}
}
}
//getting random numbers
public static int getRandom(int high, int low) {
Random rand = new Random();
int random = rand.nextInt(high - low) + low;
return random;
}
public static void main(String[] args) {
int low = 1;
int high;
int computer;
int count;
System.out.print("Let's play guess the number!");
while (true) {
Scanner sc1 = new Scanner(System.in);
System.out.print("\nEnter the difficulty level (1, 2, or 3): ");
String level = sc1.nextLine();
if (inputValidation(level)) {
high = chooseLevel(level);
computer = getRandom(high, low);
System.out.print("I have my number. What's your guess? ");
compareNumbers(computer);
System.out.print("Do you wish to play again (Y/N)? ");
Scanner sc3 = new Scanner(System.in);
String answer = sc3.nextLine();
if (answer.equals("n")) {
break;
} else if (answer.equals("y")) {
continue;
}
} else {
continue;
}
}
}
}
|
JavaScript
|
UTF-8
| 234 | 3.03125 | 3 |
[] |
no_license
|
console.log('---GENERATORS---');
function* numbersGen() {
yield 1;
yield 2;
yield 3;
}
let getNum = numbersGen();
console.log(getNum.next());
console.log(getNum.next());
console.log(getNum.next());
console.log(getNum.next());
|
Rust
|
UTF-8
| 4,535 | 3.171875 | 3 |
[] |
no_license
|
use core::ops::RangeInclusive;
use std::cmp::{ min, max };
#[derive(PartialEq, Clone, Copy, Debug)]
pub struct Point { x: i32, y: i32 }
impl Point {
fn origin() -> Self { Point{x: 0, y: 0} }
fn manhattan_dist_to(&self, other: Point) -> u32 {
((self.x - other.x).abs() + (self.y - other.y).abs()) as u32
}
fn manhattan_dist_origin(&self) -> u32 {
self.manhattan_dist_to(Point::origin())
}
}
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Alignment { Ver, Hor, Other }
#[derive(Clone, Copy, Debug)]
pub struct Segment {
steps: u32,
p1: Point,
p2: Point,
}
impl Segment {
fn empty() -> Self {
Segment{ steps: 0, p1: Point::origin(), p2: Point::origin() }
}
fn alignment(&self) -> Alignment {
if self.p1 == self.p2 { Alignment::Other }
else if self.p1.x == self.p2.x { Alignment::Ver }
else if self.p1.y == self.p2.y { Alignment::Hor }
else { Alignment::Other }
}
fn x_range(&self) -> RangeInclusive<i32> {
min(self.p1.x, self.p2.x)..=max(self.p1.x, self.p2.x)
}
fn y_range(&self) -> RangeInclusive<i32> {
min(self.p1.y, self.p2.y)..=max(self.p1.y, self.p2.y)
}
fn intersects(&self, other: Segment) -> Option<Point> {
if (self.alignment() == Alignment::Other) ||
(other.alignment() == Alignment::Other) ||
(self.alignment() == other.alignment()) {
return None;
}
let (x, y, x_range, y_range) =
if self.alignment() == Alignment::Ver {
(self.p1.x, other.p1.y, other.x_range(), self.y_range())
} else {
(other.p1.x, self.p1.y, self.x_range(), other.y_range())
};
if x_range.contains(&x) && y_range.contains(&y) { Some(Point {x: x, y: y}) }
else { None }
}
}
fn parse_path(input: &str) -> Vec<Segment> {
let mut p1 = Point{x:0, y:0};
let mut steps = 0;
input
.trim()
.split(",")
.map(|s| {
let len = s[1..].parse::<i32>().unwrap();
let seg = match &s[..1] {
"U" => Segment{ steps: steps, p1: p1, p2: Point{ x: p1.x, y: p1.y + len } },
"D" => Segment{ steps: steps, p1: p1, p2: Point{ x: p1.x, y: p1.y - len } },
"L" => Segment{ steps: steps, p1: p1, p2: Point{ x: p1.x - len, y: p1.y } },
"R" => Segment{ steps: steps, p1: p1, p2: Point{ x: p1.x + len, y: p1.y } },
_ => Segment::empty()
};
steps += p1.manhattan_dist_to(seg.p2);
p1 = seg.p2;
seg
})
.collect()
}
#[aoc_generator(day3)]
pub fn parse(input: &str) -> [Vec<Segment>; 2] {
let paths: Vec< Vec<Segment> > = input
.lines()
.map(|line| parse_path(line))
.collect();
[paths[0].clone(), paths[1].clone()]
}
#[aoc(day3, part1)]
pub fn part1(paths: &[Vec<Segment>; 2]) -> u32 {
let path1 = paths[0].clone();
let path2 = paths[1].clone();
path1
.iter()
.map(|seg1| {
path2
.iter()
.map(|seg2| seg1.intersects(*seg2))
.filter_map(|pt| pt)
.min_by_key(|pt| pt.manhattan_dist_origin())
})
.filter_map(|pt| pt)
.min_by_key(|pt| pt.manhattan_dist_origin())
.unwrap()
.manhattan_dist_origin()
}
#[aoc(day3, part2)]
pub fn part2(paths: &[Vec<Segment>; 2]) -> u32 {
let path1 = paths[0].clone();
let path2 = paths[1].clone();
path1
.iter()
.map(|seg1| {
path2
.iter()
.map(|seg2| {
match seg1.intersects(*seg2) {
None => std::u32::MAX,
Some(pt) => {
let seg1_steps = seg1.steps + seg1.p1.manhattan_dist_to(pt);
let seg2_steps = seg2.steps + seg2.p1.manhattan_dist_to(pt);
let steps = seg1_steps + seg2_steps;
steps
}
}
})
.min()
})
.filter_map(|steps| steps) // steps to intersection point
.min()
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hor_segment() {
let s1 = Segment{ p1: Point{x:0, y:0}, p2: Point{x:10, y:0} };
assert_eq!(s1.x_range(), 0..=10);
assert_eq!(s1.y_range(), 0..=0);
assert_eq!(s1.alignment(), Alignment::Hor);
}
#[test]
fn test_ver_segment() {
let s1 = Segment{ p1: Point{x:0, y:-5}, p2: Point{x:0, y:5} };
assert_eq!(s1.x_range(), 0..=0);
assert_eq!(s1.y_range(), -5..=5);
assert_eq!(s1.alignment(), Alignment::Ver);
}
#[test]
fn test_segment_intersects() {
let s1 = Segment{ p1: Point{x:-2, y:0}, p2: Point{x:10, y:0} };
let s2 = Segment{ p1: Point{x:1, y:-5}, p2: Point{x:1, y:5} };
assert_eq!(s1.intersects(s2), Some(Point{x:1, y:0}));
}
}
|
JavaScript
|
UTF-8
| 3,113 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
/*
bbmaker.js 1.0
BBMaker is a script that converts a QuickUp Object Model to BBCode.
BBMaker complies with QUOMs made in http://www.crazymatt.net/quickup/scripts/compiler.2.1.js , and is built around QuickUp
Specification 1.2 revision 1, which can be found at http://www.crazymatt.net/quickup/QuickUp1.2r1.pdf .
Copyright (c) 2016 Crazymatt.net
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of this Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function quomToBBCode(pageObject){
var order = pageObject.order;
var contents = pageObject.contents;
var finalAssembly = "";
for(var i = 0; i < order.length; i++){
var cobj = contents[order[i]];
switch(cobj.type){
case "title":
finalAssembly += '[size=200]' + cobj.contents.text + '[/size]\n';
break;
case "heading":
finalAssembly += '[size=150]' + cobj.contents.text + '[/size]\n';
break;
case "text":
finalAssembly += cobj.contents.text;
break;
case "quote":
finalAssembly += '[quote]' + cobj.contents.text + '[/quote]';
break;
case "hyperlink":
finalAssembly += '[url=' + cobj.contents.url + ']' + cobj.contents.text + '[/url]';
break;
case "image":
finalAssembly += '[img]' + cobj.contents.url + '[/img]';
break;
case "break":
switch(cobj.contents.mode){
case "break":
finalAssembly += '\n';
break;
case "space":
finalAssembly += ' ';
break;
case "tab":
finalAssembly += ' ';
break;
case "line":
finalAssembly += '--------\n';
break;
case "nbsp":
console.log("bbMaker.js does not currently support non-breaking spaces. A regular space was inserted instead.");
finalAssembly += ' ';
break;
}
break;
case "html":
console.log("bbMaker.js does not allow HTML or JavaScript to convert to bbCode as it is not widely supported or allowed.");
break;
case "javascript":
console.log("bbMaker.js does not allow HTML or JavaScript to convert to bbCode as it is not widely supported or allowed.");
break;
}
}
return finalAssembly;
}
|
Markdown
|
UTF-8
| 1,479 | 2.890625 | 3 |
[] |
no_license
|
### what do I want to learn or understand better?
As of now with one week in of the course:
- The fundamentals of agile strategy and how to apply effectively it to our team.
### how can I help someone else, or the entire team, to learn something new?
As we sat and discussed our social contract, we came to a conclusion that we would post the problem/question in our Discord channel for each and everyone to be able to contribute, as long as the person reading the post are able to solve/help. As a learning curve in coding, we applied a code review system. Each member is going to read another member's code and give feedback for quality control and potential improvement. All code is going to be documented thoroughly for all the members to take a look and learn as we progress with the project. As it goes for helping someone/everyone and learning, I will have to be all ears about the team's struggle and help within my capability.
### what is my contribution towards the team’s use of Scrum?
We have not really started to setup the scrum framework yet and I have not been giving input about Scrum other than we will need a Scrum master, some program alternatives for our scrum board and the scrum board itself.
### what is my contribution towards the team’s deliveries?
First and foremost participating the first meeting. During the meeting I contributed with some propositions about our workflow and future meetings that is included in the social contract.
|
C++
|
UTF-8
| 1,274 | 2.640625 | 3 |
[] |
no_license
|
#ifndef _Point_h_
#define _Point_h_
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Point holds two integer coordinates
*/
class Point
{
public:
int x;
int y;
Point();
Point(int x, int y);
Point(Point *src);
/**
* Set the point's x and y coordinates
*/
void set(int x, int y);
/**
* Negate the point's coordinates
*/
void negate();
/**
* Offset the point's coordinates by dx, dy
*/
void offset(int dx, int dy);
/**
* Returns true if the point's coordinates equal (x,y)
*/
bool equals(int x, int y);
//bool equals(Object o);
int hashCode();
std::string toString();
};
#endif
|
JavaScript
|
UTF-8
| 2,606 | 3.03125 | 3 |
[] |
no_license
|
// ===============================================================================
// LOAD DATA
// We are linking our routes to a series of "data" sources.
// These data sources hold arrays of information on table-data, waitinglist, etc.
// ===============================================================================
const friends = require("../data/friends");
// ===============================================================================
// ROUTING
// ===============================================================================
module.exports = function (app) {
// API GET Requests
// Below code handles when users "visit" a page.
// In each of the below cases when a user visits a link
// (ex: localhost:PORT/api/admin... they are shown a JSON of the data in the table)
// ---------------------------------------------------------------------------
app.get("/api/friends", function (req, res) {
res.json(friends);
});
// API POST Requests
// Below code handles when a user submits a form and thus submits data to the server.
// In each of the below cases, when a user submits form data (a JSON object)
// ...the JSON is pushed to the appropriate JavaScript array
// (ex. User fills out a reservation request... this data is then sent to the server...
// Then the server saves the data to the tableData array)
// ---------------------------------------------------------------------------
// POST route to /api/friends
app.post("/api/friends", function (req, res) {
let userScore = req.body.scores;
const scoresArr = [];
let bestMatch = 0;
for (var i = 0; i < friends.length; i++) {
var scoreDiff = 0;
for (var j = 0; j < userScore.length; j++) {
scoreDiff += (Math.abs(parseInt(friends[i].scores[j]) - parseInt(userScore[j])))
}
scoresArr.push(scoreDiff);
}
// loop through scoresArr
for (var i = 0; i < scoresArr.length; i++) {
if (scoresArr[i] <= scoresArr[bestMatch]) {
bestMatch = i;
}
}
// return the best match
let soulMate = friends[bestMatch];
res.json(soulMate);
friends.push(req.body)
});
app.post("/api/clear", function (req, res) {
// Empty out the arrays of data
friends.length = [];
res.json({
ok: true
});
});
};
|
JavaScript
|
UTF-8
| 386 | 3.46875 | 3 |
[] |
no_license
|
console.log("linha 1");
console.log("linha 2");
//throw new Error("Novo erro!");
console.log("linha 3");
try {
console.log(soma(10, new Array(10)));
} catch (error) {
console.log(error.name);
console.log(error.message);
console.log(error.stack);
} finally {
console.log("Sempre sera executado!");
}
function soma(a,b) {
//a + b;
//a / b;
return a.exec(20);
}
|
Python
|
UTF-8
| 7,299 | 2.984375 | 3 |
[] |
no_license
|
from abc import abstractmethod
from contracts import ContractsMeta, contract
from decent_logs import WithInternalLog
from reprep import Report
from reprep.interface import ReportInterface
__all__ = ['AgentInterface', 'UnsupportedSpec', 'ServoAgentInterface',
'PredictorAgentInterface', 'PassiveAgentInterface']
class UnsupportedSpec(Exception):
''' Thrown by agents if they do not support the spec. '''
class PassiveAgentInterface(WithInternalLog):
__metaclass__ = ContractsMeta
class LearningConverged(Exception):
"""
Thrown by process_observations() in learning agents
to signal that they do not need more data to converge.
"""
pass
@abstractmethod
def process_observations(self, bd):
'''
Process new observations.
:param bd: a numpy array with field ['observations']
For learning agents, it might raise LearningConverged to signal that
the learning has converged and no more data is necessary.
'''
@abstractmethod
def init(self, boot_spec):
'''
Called when the observations and commands shape are available,
so that the agent can initialize its data structures.
The agent might throw the exception UnsupportedSpec if the
spec is not supported.
:param boot_spec: An instance of the class BootSpec, which
describes the specifications of the sensorimotor cascades.
'''
def publish(self, pub):
return self.display(pub)
@contract(report=ReportInterface)
def display(self, report):
report.text('warn', 'display not implemented for %r' % type(self).__name__)
class ActiveAgentInterface(PassiveAgentInterface):
@abstractmethod
@contract(returns='array,finite')
def choose_commands(self):
'''
Chooses commands to be generated; must return an
array that conforms to the specs.
'''
class ServoAgentInterface(ActiveAgentInterface):
@abstractmethod
@contract(goal='array')
def set_goal_observations(self, goal):
pass
@contract(report=Report, observations='array', goal='array')
def display_query(self, report, observations, goal): # @UnusedVariable
""" Displays information regarding this particular query. """
# report.text('warn', 'display_query not implemented for %r' % type(self).__name__)
f = report.figure(cols=4)
y0 = observations
y_goal = goal
e = y0 - y_goal
# from yc1304.s10_servo_field.plots import plot_style_sensels # XXX
with f.plot('y0_vs_y_goal') as pylab:
pylab.plot(y0, '.', label='y0')
pylab.plot(y_goal, '.', label='ygoal')
# plot_style_sensels(pylab)
pylab.legend()
with f.plot('error') as pylab:
pylab.plot(e, label='error')
def get_distance(self, y1, y2):
import numpy as np
return np.linalg.norm(y1 - y2)
class PredictorAgentInterface(PassiveAgentInterface):
@abstractmethod
@contract(returns='array')
def predict_y(self, dt):
pass
@abstractmethod
@contract(returns='array')
def estimate_u(self):
""" Estimate current u """
class AgentInterface(PassiveAgentInterface):
'''
This is the interface that the agents must implement.
The following is a list of conventions that we use.
Initialization
--------------
init(boot_spec) is called first.
process_observations() is guaranteed to be called at least once
before choose_commands().
Processing the observations
---------------------------
The function ``process_observations()`` is given an instance
of the class Observations, which contains many info other than
the raw sensel values.
Logging stuff
-------------
Use the function ``self.info(msg)`` to log stuff.
Do not use ``rospy.loginfo`` or ``print``: the agents implementation s
hould be independent of ROS.
Saving the state
----------------
Implement the functions ``set_state()`` and ``get_state()``.
``get_state()`` can return anything that is Pickable.
``set_state()`` will be given whatever ``get_state()`` returned.
Publishing information
----------------------
Implement the function ``publish()`` to output information, such
as graphs, statistics, etc. The function is given an instance of the
class Publisher, whose implementation is hidden.
During a ROS simulation, Publisher will be a ROSPublisher that
will publish the data as ROS topics which can be subscribed by RViz.
During offline learning, the data will be written to HTML files.
'''
@contract(returns=PredictorAgentInterface)
def get_predictor(self):
raise NotImplementedError()
@contract(returns=ServoAgentInterface)
def get_servo(self):
raise NotImplementedError()
@contract(i='int,>=0,i', n='int,>=1,>=i')
def parallel_process_hint(self, i, n):
"""
Hint for parallel processing. It tells this instance that
it is instance "i" of "n" that sees the same data.
Learning modality:
1) N copies of the same thing that looks at the same data
Then parallel_process_hint(i, N) is called for each one.
2) Different learners look at the same thing.
Then parallel_process_hint(0, 1) is called for all learners.
"""
raise NotImplementedError()
def merge(self, other):
raise NotImplementedError()
# Serialization stuff
def state_vars(self):
# print('default state vars for %s' % type(self))
return self.__dict__.keys()
def get_state(self):
''' Return the state for the agent so that it can be saved. '''
return self.get_state_vars(self.state_vars())
def set_state(self, state):
''' Load the given state (obtained by 'get_state'). '''
return self.set_state_vars(state, self.state_vars())
def __str__(self):
return 'Agent(%s)' % self.__class__.__name__
def get_state_vars(self, state_vars):
return dict((x, self.__dict__[x]) for x in state_vars)
def set_state_vars(self, state, state_vars):
# print('Setting state vars: %s' % state_vars)
for v in state_vars:
if v not in state:
self.info('Warning, no variable %r found in state vars,'
' setting none.' % v)
self.__dict__[v] = None
else:
if ((state[v] is None) and (v in self.__dict__) and
(self.__dict__[v] is not None)):
print('Warning, null state %s but has value in instance' % v)
else:
self.__dict__[v] = state[v]
# self.info('State loaded: %s' % state_vars)
|
Ruby
|
UTF-8
| 240 | 2.984375 | 3 |
[] |
no_license
|
class Categories
attr_accessor :name, :index
@@all = []
def initialize(name, index)
@name = name
@index = index
@@all << self
end
def self.all
@@all
end
end
|
Python
|
UTF-8
| 3,551 | 2.953125 | 3 |
[] |
no_license
|
import math
from bisect import bisect_right
from functools import partial
import torch.optim as optim
from torch.optim.optimizer import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
class CosineAnnealingLR_withwarmup(_LRScheduler):
r"""Set the learning rate of each parameter group using a cosine annealing
schedule, where :math:`\eta_{max}` is set to the initial lr and
:math:`T_{cur}` is the number of epochs since the last restart in SGDR:
.. math::
\eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})(1 +
\cos(\frac{T_{cur}}{T_{max}}\pi))
When last_epoch=-1, sets initial lr as lr.
It has been proposed in
`SGDR: Stochastic Gradient Descent with Warm Restarts`_. Note that this only
implements the cosine annealing part of SGDR, and not the restarts.
Args:
optimizer (Optimizer): Wrapped optimizer.
T_max (int): Maximum number of iterations.
eta_min (float): Minimum learning rate. Default: 0.
last_epoch (int): The index of last epoch. Default: -1.
.. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
https://arxiv.org/abs/1608.03983
"""
def __init__(self, optimizer, total_steps, warmup_lr=0.0, warmup_steps=0, hold_base_rate_steps=0, eta_min=0, last_epoch=-1):
self.total_steps = total_steps
self.eta_min = eta_min
self.warmup_lr = warmup_lr
self.warmup_steps = warmup_steps
self.hold_base_rate_steps = hold_base_rate_steps
super(CosineAnnealingLR_withwarmup, self).__init__(optimizer, last_epoch)
def get_lr(self):
# return [self.eta_min + (base_lr - self.eta_min) *
# (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / 2
# for base_lr in self.base_lrs]
learning_rate = [self.eta_min + 0.5 *
base_lr *
(1 + math.cos(2 * math.pi * (self.last_epoch - self.warmup_steps - self.hold_base_rate_steps)
/ (self.total_steps - self.warmup_steps - self.hold_base_rate_steps)))
for base_lr in self.base_lrs]
if self.warmup_steps > 0:
if self.last_epoch < self.warmup_steps:
slope = [(base_lr - self.warmup_lr)/self.warmup_steps for base_lr in self.base_lrs]
learning_rate = [s * self.last_epoch + self.warmup_lr for s in slope]
return learning_rate
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# if __name__ == '__main__':
# net = mobilenetv1(pretrained=False)
# parameter_dict = dict(net.named_parameters())
# params = []
# for name, param in parameter_dict.items():
# params += [{'params': [param], 'lr': 0.1, 'weight_decay': 0.0004}]
#
# optimizer = optim.SGD(params, lr=0.1, momentum=0.9, weight_decay=0.0004)
# scheduler = CosineAnnealingLR_withwarmup(optimizer, total_steps=1000, warmup_lr=0.02, warmup_steps=100, hold_base_rate_steps=0, eta_min=0)
#
# lr_to_follow = []
# for i in range(1000):
# scheduler.step()
#
# lr = scheduler.get_lr()
# lr_to_follow.append(lr[0])
#
# plt.plot(lr_to_follow)
# plt.show()
|
C#
|
UTF-8
| 7,949 | 2.765625 | 3 |
[] |
no_license
|
using System.Collections.Generic;
using System;
namespace XYZware_SLS.model.geom
{
public class TopoTriangleStorage
{
public HashSet<TopoTriangle> triangles = new HashSet<TopoTriangle>();
public List<List<TopoTriangle>> tempTriangles = new List<List<TopoTriangle>>(4);
public TopoTriangleStorage()
{
for (int i = 0; i < 4; i++)
tempTriangles.Add(new List<TopoTriangle>());
}
public void Add(TopoTriangle triangle) {
triangles.Add(triangle);
//if (tree != null)
//tree.AddTriangle(triangle);
}
public void Add(TopoTriangle triangle, int index)
{
if(tempTriangles.Count == 0)
{
for (int i = 0; i < 4; i++)
tempTriangles.Add(new List<TopoTriangle>());
}
tempTriangles[index].Add(triangle);
}
public void convertTempToHashSet()//Mark Add
{
for(int i = 0;i<4;i++)
{
if(tempTriangles[i] != null)
{
HashSet<TopoTriangle> t = new HashSet<TopoTriangle>(tempTriangles[i]);
triangles.UnionWith(t);
}
}
tempTriangles.Clear();
}
public bool Remove(TopoTriangle triangle)
{
//if (tree != null)
//tree.RemoveTriangle(triangle);
return triangles.Remove(triangle);
}
public System.Collections.IEnumerator GetEnumerator()
{
foreach (TopoTriangle t in triangles)
yield return t;
}
public void Clear()
{
//tree = null;
triangles.Clear();
}
public bool Contains(TopoTriangle test)
{
return triangles.Contains(test);
}
public int Count
{
get { return triangles.Count; }
}
/*public void PrepareFastSearch()
{
//tree = new TopoTriangleNode(null);
foreach (TopoTriangle triangle in triangles)
{
tree.AddTriangle(triangle);
}
}
public HashSet<TopoTriangle> FindIntersectionCandidates(TopoTriangle triangle)
{
if (tree == null) PrepareFastSearch();
HashSet<TopoTriangle> result = new HashSet<TopoTriangle>();
tree.FindIntersectionCandidates(triangle, result);
return result;
}*/
}
public class TopoTriangleNode
{
//int dimension = -1;
//double middlePosition;
//int nextTrySplit = 50;
TopoTriangleNode parent = null;
TopoTriangleNode left = null;
//TopoTriangleNode middle = null;
//TopoTriangleNode right = null;
RHBoundingBox box = new RHBoundingBox();
private HashSet<TopoTriangle> triangles = null;
public TopoTriangleNode(TopoTriangleNode _parent)
{
parent = _parent;
}
public void AddTriangle(TopoTriangle triangle) {
if(left == null && triangles == null) {
triangles = new HashSet<TopoTriangle>();
}
if (triangles != null)
{
triangles.Add(triangle);
//box.Add(triangle.boundingBox);
//if (triangles.Count > nextTrySplit) TrySplit();
}
/*else
{
if (triangle.boundingBox.maxPoint[dimension] < middlePosition)
left.AddTriangle(triangle);
else if (triangle.boundingBox.minPoint[dimension] > middlePosition)
right.AddTriangle(triangle);
else
middle.AddTriangle(triangle);
}*/
}
/*public bool RemoveTriangle(TopoTriangle triangle)
{
TopoTriangleNode node = FindNodeForTriangle(triangle);
if (node != null)
return node.triangles.Remove(triangle);
return false;
}
public TopoTriangleNode FindNodeForTriangle(TopoTriangle triangle)
{
if (triangles != null) return this;
if (triangle.boundingBox.maxPoint[dimension] < middlePosition)
return left.FindNodeForTriangle(triangle);
else if (triangle.boundingBox.minPoint[dimension] > middlePosition)
return right.FindNodeForTriangle(triangle);
else
return middle.FindNodeForTriangle(triangle);
}
public void FindIntersectionCandidates(TopoTriangle triangle,HashSet<TopoTriangle> resultList)
{
if (triangles != null) // end leaf, test all boxes for intersection
{
foreach (TopoTriangle test in triangles)
{
if(test!=triangle && test.boundingBox.IntersectsBox(triangle.boundingBox))
resultList.Add(test);
}
return;
}
if (left == null) return;
if(triangle.boundingBox.minPoint[dimension]<middlePosition)
left.FindIntersectionCandidates(triangle,resultList);
if(triangle.boundingBox.maxPoint[dimension]>middlePosition)
right.FindIntersectionCandidates(triangle,resultList);
if(triangle.boundingBox.minPoint[dimension]<middlePosition && triangle.boundingBox.maxPoint[dimension]>middlePosition)
middle.FindIntersectionCandidates(triangle,resultList);
}
private void TrySplit()
{
int newDim = 0;
int parentDimension = -1;
if (parent != null)
parentDimension = parent.dimension;
RHVector3 size = box.Size;
if (parentDimension != 0) newDim = 0;
if (parentDimension != 1 && size.x < size.y) newDim = 1;
if (parentDimension != 2 && size.z > size[newDim]) newDim = 2;
int loop = 0;
int maxLoop = 4;
double bestCenter = 0;
double bestPercentage = 3000;
int bestDim = 0;
for (int dim = 0; dim < 3; dim++)
{
if (dim == parentDimension) continue;
for (loop = 0; loop < maxLoop; loop++)
{
int count = 0;
double testDist = box.minPoint[newDim] + size[newDim] * (1 + loop) / (maxLoop + 1);
foreach (TopoTriangle tri in triangles)
{
if (tri.boundingBox.maxPoint[newDim] < testDist)
count++;
}
double percent = 100.0 * (double)count / triangles.Count;
if (Math.Abs(50 - percent) < bestPercentage)
{
bestPercentage = percent;
bestCenter = testDist;
bestDim = dim;
}
}
}
if (bestPercentage < 5)
{
nextTrySplit = (nextTrySplit * 3) / 2;
return; // not effective enough
}
left = new TopoTriangleNode(this);
right = new TopoTriangleNode(this);
middle = new TopoTriangleNode(this);
dimension = newDim;
middlePosition = bestCenter;
foreach (TopoTriangle tri in triangles)
{
if (tri.boundingBox.maxPoint[dimension] < middlePosition)
left.AddTriangle(tri);
else if (tri.boundingBox.minPoint[dimension] > middlePosition)
right.AddTriangle(tri);
else
middle.AddTriangle(tri);
}
triangles = null;
}*/
}
}
|
C++
|
UTF-8
| 320 | 2.546875 | 3 |
[] |
no_license
|
#include "TableRow.h"
std::ostream& operator<<(std::ostream& stream, const TableRow& tableRow) {
stream << "TableRow { "
<< "keyStr: \"" << tableRow.getTableKeyStr()
<< "\"; keyNum: " << tableRow.getTableKeyNum()
<< "; field: " << tableRow.getField()
<< "; }";
return stream;
}
|
Python
|
UTF-8
| 6,528 | 2.96875 | 3 |
[] |
no_license
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import shutil
import urllib
import re
import sys
url_feed = "http://www.radio-t.com/atom.xml"
podcast_path = "/home/mak/Музыка/podcasts/"
player_path = "/media/disk/music/podcast/"
def get_list_urls(url):
""" возвращает список доступных подкастов
Arguments:
- `url`: урл rss - ленты
"""
rss_page = urllib.urlopen(url).read()
podcast_list_url = re.compile(r'http:\/\/[a-z\-\.]+\.radio-t\.com\/rt_podcast[0-9]+\.mp3').findall(rss_page)
return podcast_list_url
def download_podcast(url, download_file):
""" загружается подкаст
Arguments:
- `url`: ссылка для скачивания
"""
def progress_show(count, block_size, size):
""" показывает прогресс скачивания файа """
percent = int(count*block_size*100/size)
sys.stdout.write("\r" + "Идет скачивание скачивание " + download_file + "......%d%%" % percent)
sys.stdout.flush()
urllib.urlretrieve(url, download_file, progress_show)
print '\n'
def download_on_pc(url_feed, podcast_path):
""" по желанию пользователя загружает нужные подкасты
"""
print "Доступные для скачивания подкасты: "
list_urls = list(set(get_list_urls(url_feed)))
list_urls = sorted(list_urls)
for i in list_urls:
print i.split("/")[-1]
try:
for_download_string = raw_input("Введите номера подкастов, через запятую: ")
if for_download_string == '':
print "Вы не указали подкастов для скачивания!"
else:
for_download = for_download_string.split("/")
for i in list_urls:
for p in for_download:
if (p in i) and os.path.exists(podcast_path):
download_podcast(i, podcast_path + i.split("/")[-1])
print "Файл сохранен как %s" % podcast_path + i.split("/")[-1]
except:
print "Что-то пошло не так"
def delete_podcast_on_player(player_path):
""" с помощью этой функции можно удалить ненужные подкасты на плеере
Arguments:
- `player_path`: путь до каталога плеера
"""
if os.path.exists(player_path):
print "На плеере имеются следующие подкасты: "
list_podcast = os.listdir(player_path)
for i in list_podcast: print i
delete_string = raw_input("Введите через запятую подкасты, что надо удалить: ")
if delete_string == '':
print "Вы не указали подкастов для удаления!"
else:
delete_list = delete_string.split(",")
for i in delete_list:
for p in list_podcast:
if i in p:
os.remove(player_path + p)
list_podcast = os.listdir(player_path)
print "Оставшиеся подкасты: "
for i in list_podcast: print i
else:
print "Плеер же не подключен, не буду ничего удалять!"
def upload_podcast_on_player(podcast_path, player_path):
""" копируется выбранные пользователем подкасты на плеер
podcast_path: - путь до каталога с подкастами на компе
player_path: - путь до плеера
"""
if os.path.exists(player_path):
os.system("df -h")
list_podcast = os.listdir(podcast_path)
print "Список подкастов, доступных для копирования: "
for i in list_podcast: print i
copy_string = raw_input("Введите через запятую подкасты, что надо скопировать: ")
if copy_string == '':
print "Вы не указали подкастов для копирования!"
else:
copy_list = copy_string.split(",")
for i in copy_list:
for p in list_podcast:
if i in p:
shutil.copy(podcast_path + p, player_path + p)
print "Подкасть %s скопирован на плеер." % p
print "Список подкастов на плеере сейчас: "
for i in os.listdir(player_path): print i
else:
print "Плеер же не подключен, не буду ничего удалять!"
def user_request():
""" возвращает выбранный пункт пользователем
"""
message = """ Приветствую тебя, мой белый господин.
Пожалуйста, скажите мне, что именно Вы желаете сделать сейчас:
[1] Скачать подкасты
[2] Очистить место на плеере
[3] Загрузить подкасты на плеер
[0] Выход
============================================================="""
print message
try:
answer = int(raw_input("Введите нужный Вам вариант: "))
return answer
except:
print "Что-то я не раслышал, скажите еще раз!"
print message
def user_dialog(url_feed, player_path, podcast_path):
""" интерактивная часть программы
"""
answer = user_request()
n = True
while n:
if answer == 0:
print "До свидания, мой Повелитель!"
n = False
elif answer == 1:
download_on_pc(url_feed, podcast_path)
answer = user_request()
elif answer == 2:
delete_podcast_on_player(player_path)
answer = user_request()
elif answer == 3:
upload_podcast_on_player(podcast_path, player_path)
answer = user_request()
else:
print "Что-то я не раслышал, скажите еще раз!"
answer = user_request()
user_dialog(url_feed, player_path, podcast_path)
|
Java
|
UTF-8
| 1,426 | 2.375 | 2 |
[] |
no_license
|
package com.teacore.teascript.team.adapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.teacore.teascript.R;
import com.teacore.teascript.base.BaseListAdapter;
import com.teacore.teascript.team.bean.TeamMember;
import com.teacore.teascript.widget.AvatarView;
/**
* 团队项目成员适配器
* @author 陈晓帆
* @version 1.0
* Created 2017-5-22
*/
public class TeamProjectMemberAdapter extends BaseListAdapter<TeamMember>{
@Override
protected View getRealView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null || convertView.getTag() == null) {
convertView = View.inflate(parent.getContext(),
R.layout.list_cell_team_project_member, null);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
TeamMember item = mDatas.get(position);
vh.userAV.setAvatarUrl(item.getPortrait());
vh.nameTV.setText(item.getName());
return convertView;
}
public static class ViewHolder {
AvatarView userAV;
TextView nameTV;
public ViewHolder(View view) {
userAV=(AvatarView) view.findViewById(R.id.user_av);
nameTV=(TextView) view.findViewById(R.id.name_tv);
}
}
}
|
Java
|
UTF-8
| 691 | 2.140625 | 2 |
[] |
no_license
|
package com.rahul.program.employee.service;
import java.util.List;
import javax.validation.ConstraintViolationException;
import com.rahul.program.employee.exception.EmployeeException;
import com.rahul.program.employee.model.Employee;
public interface EmployeeService {
public Employee createEmployee(Employee employee) throws ConstraintViolationException, EmployeeException;
public List<Employee> getAllEmployee();
public Employee getSingleEmployee(Long id) throws EmployeeException;
public Employee updateEmployee(Long id, Employee employee) throws EmployeeException;
public String deleteEmployeeById(Long id) throws EmployeeException;
}
|
JavaScript
|
UTF-8
| 771 | 2.59375 | 3 |
[] |
no_license
|
const db = require("quick.db")
module.exports.run = async(client, message, args) => {
const permission = "ADMINISTRATOR"
if (!message.member.hasPermission(permission)) return message.reply(`You need the **${permission}** permission to do this.`)
if (!message.guild.me.hasPermission(permission)) return message.reply(`I need the **${permission}** permission to do this.`)
let channel = message.mentions.channels.first();
if (!channel) {
return message.reply('Specify a channel..')
}
db.set(`lgch_${message.guild.id}`, channel.id)
message.channel.send(`Set the channel to ${channel}.`)
}
module.exports.help = {
name: "setlog",
description: "set's a log channel",
aliases: ["sl"],
category: "🛠 Moderation"
}
|
Java
|
UTF-8
| 983 | 2.453125 | 2 |
[
"MIT"
] |
permissive
|
package net.glowstone.net.codec.play.game;
import com.flowpowered.network.Codec;
import com.flowpowered.network.util.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import net.glowstone.net.GlowBufUtils;
import net.glowstone.net.message.play.game.EditBookMessage;
import org.bukkit.inventory.ItemStack;
import java.io.IOException;
public final class EditBookCodec implements Codec<EditBookMessage> {
@Override
public EditBookMessage decode(ByteBuf buf) throws IOException {
ItemStack item = GlowBufUtils.readSlot(buf);
boolean signing = buf.readBoolean();
int hand = ByteBufUtils.readVarInt(buf);
return new EditBookMessage(item, signing, hand);
}
@Override
public ByteBuf encode(ByteBuf buf, EditBookMessage message) throws IOException {
GlowBufUtils.writeSlot(buf, message.getBook());
buf.writeBoolean(message.isSigning());
ByteBufUtils.writeVarInt(buf, message.getHand());
return buf;
}
}
|
PHP
|
UTF-8
| 4,419 | 3.0625 | 3 |
[] |
no_license
|
<?php
namespace tool;
/**
* 请求类
*
* @author EricGU178
*/
class Request extends Base
{
/**
* 发起post请求
*
* @param string $url
* @param array $data
* @return void
* @author EricGU178
*/
static public function requestPost(string $url, array $data , $headers = [])
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
if (isset($_SERVER['HTTP_USER_AGENT'])) {
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
}
$postMultipart = false;
$postBodyString = '';
if(is_array($data) == true) {
// Check each post field
foreach($data as $key => &$value) {
// Convert values for keys starting with '@' prefix
if ("@" != substr($value, 0, 1)) { //判断是不是文件上传
$postBodyString .= "$key=" . urlencode($value) . "&";
// $postBodyString .= "$key=" . $value . "&";
}
if(strpos($value, '@') === 0) {
$postMultipart = true;
$filename = ltrim($value, '@');
$data[$key] = new \CURLFile($filename);
}
}
}
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
// Post提交的数据包
if ($postMultipart) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
} else {
curl_setopt($curl, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
}
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// 看不懂 总之解决了 编码错误的问题
if (!$postMultipart) {
array_push($headers,'content-type: application/x-www-form-urlencoded;charset=utf-8'); // 一个用来设置HTTP头字段的数组
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // 一个用来设置HTTP头字段的数组
}
$response = curl_exec($curl); // 执行操作
curl_close($curl); // 关闭CURL会话
return $response; // 返回数据
}
/**
* 发起get请求
*
* @param string $url
* @param array $headers
* @param bool $isProxy 是否代理
* @param string $proxy 代理
* @return void
* @author EricGU178
*/
static public function requestGet(string $url, $headers = [],$isProxy = false , $proxy = '')
{
$curl = curl_init();
//设置选项,包括URL
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);//绕过ssl验证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
if ($isProxy == true) {
curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($curl, CURLOPT_PROXY, $proxy);
}
//执行并获取HTML文档内容
$response = curl_exec($curl);
//释放curl句柄
curl_close($curl);
return $response;
}
/**
* 正常的post请求 不会上传文件的那种
* xml 请求需要传入headers "Content-type: text/xml"
*
* @return void
* @author EricGU178
*/
static public function requestNormalPost(string $url, $data, array $headers = [])
{
if (is_array($data)) {
$data = json_encode($data,256);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_POST, 1); // post数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // post的变量
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
}
|
Java
|
UTF-8
| 718 | 3.578125 | 4 |
[] |
no_license
|
package java0719_api;
import java.util.StringTokenizer;
public class Java129_StringTokenizer {
public static void main(String[] args) {
// 연속된 구분자는 두번째 구분자부터는 무시한다.
StringTokenizer st = new StringTokenizer("java,,jsp/spring", ",/");
System.out.println("counttoken : " + st.countTokens()); // 3
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
System.out.println("///////////");
// 구분자 갯수만큼 무조건 나누어준다.
String[] data = "java,,jsp/spring".split("[,/]");
System.out.println("length:" + data.length); // 4
for (String string : data) {
System.out.println(string);
}
}// end main()
}// end class
|
Java
|
UTF-8
| 1,533 | 2.28125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
*
*/
package kbox.extractor.framework.persistence;
/**
* @author Ciro Baron Neto
*
* Nov 4, 2016
*/
public class KnsTable {
String name;
String target;
String description;
String publisher;
long size;
public KnsTable(String name, String target, String description, String publisher,long size) {
super();
this.name = name;
this.target = target;
this.description = description;
this.publisher = publisher;
this.size= size;
}
/**
* @param name
* Set the name value.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param target
* Set the target value.
*/
public void setTarget(String target) {
this.target = target;
}
/**
* @return the target
*/
public String getTarget() {
return target;
}
/**
* @param description
* Set the description value.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param publisher
* Set the publisher value.
*/
public void setPublisher(String publisher) {
this.publisher = publisher;
}
/**
* @return the publisher
*/
public String getPublisher() {
return publisher;
}
/**
* @return the size
*/
public long getSize() {
return size;
}
/**
* @param size
* Set the size value.
*/
public void setSize(long size) {
this.size = size;
}
}
|
Python
|
UTF-8
| 6,809 | 2.671875 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
r"""
This is a port of zend-config to Python
Some idioms of PHP are still employed, but where possible I have Pythonized it
IGNORE:
Author: Asher Wolfstein Copyright 2017
Blog: http://wunk.me/
E-Mail: asherwunk@gmail.com
Twitter: https://twitter.com/asherwolfstein Send Me Some Love!
Package Homepage: http://wunk.me/programming-projects/objconfig-python/
GitHub: http://github.com/asherwunk/objconfig for the source repository
DevPost: https://devpost.com/software/objconfig
Buy Me A Coffee: https://ko-fi.com/A18224XC
Support Me On Patreon: https://www.patreon.com/asherwolfstein
IGNORE
Following is the header as given in zend-config::
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the
* canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc.
* (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
"""
from objconfig.writer import AbstractWriter
from objconfig.exception import RuntimeException
import inspect
class Ini(AbstractWriter):
r"""
Following is the class documentation as given in zend-config:
There is no documentation
"""
def __init__(self, nestSeparator='.', renderWithoutSections=False):
"""Initializes nestSeparator and renderWithoutSections."""
r"""
Following is the header as given in zend-config::
/**
* Separator for nesting levels of configuration data identifiers.
*
* @var string
*/
"""
self.nestSeparator = nestSeparator
r"""
Following is the header as given in zend-config::
/**
* If true the INI string is rendered in the global namespace without
* sections.
*
* @var bool
*/
"""
self.renderWithoutSections = renderWithoutSections
def setNestSeparator(self, separator):
r"""
Following is the header as given in zend-config::
/**
* Set nest separator.
*
* @param string $separator
* @return self
*/
"""
self.nestSeparator = separator
return self
def getNestSeparator(self):
r"""
Following is the header as given in zend-config::
/**
* Get nest separator.
*
* @return string
*/
"""
return self.nestSeparator
def setRenderWithoutSectionsFlags(self, withoutSections):
r"""
Following is the header as given in zend-config::
/**
* Set if rendering should occur without sections or not.
*
* If set to true, the INI file is rendered without sections completely
* into the global namespace of the INI file.
*
* @param bool $withoutSections
* @return Ini
*/
"""
self.renderWithoutSections = withoutSections
return self
def shouldRenderWithoutSections(self):
r"""
Following is the header as given in zend-config::
/**
* Return whether the writer should render without sections.
*
* @return bool
*/
"""
return self.renderWithoutSections
def processConfig(self, config):
r"""
Following is the header as given in zend-config::
/**
* processConfig(): defined by AbstractWriter.
*
* @param array $config
* @return string
*/
"""
config = config.toArray() if 'toArray' in dir(config) and inspect.ismethod(config.toArray) else config
iniContents = ''
if self.shouldRenderWithoutSections():
iniContents = "[DEFAULT]\n" + self.addBranch(config)
else:
config = self.sortRootElements(config)
if not config["DEFAULT"]:
del config["DEFAULT"]
for sectionName, data in config.items():
if not isinstance(data, dict):
iniContents += sectionName + " = " + self.prepareValue(data) + "\n"
else:
iniContents += "[" + sectionName + "]\n" + self.addBranch(data) + "\n"
return iniContents
def addBranch(self, config, parents=None):
r"""
Following is the header as given in zend-config::
/**
* Add a branch to an INI string recursively.
*
* @param array $config
* @param array $parents
* @return string
*/
"""
if parents is None:
parents = []
iniContents = ''
for key, value in config.items():
group = parents + [key]
if isinstance(value, dict):
iniContents += self.addBranch(value, group)
else:
iniContents += self.nestSeparator.join(group) + " = " + self.prepareValue(value) + "\n"
return iniContents
def prepareValue(self, value):
r"""
NOTE:
Just converts to string (minus double-quotes)
Following is the header as given in zend-config::
/**
* Prepare a value for INI.
*
* @param mixed $value
* @return string
* @throws Exception\RuntimeException
*/
"""
if '"' in str(value):
raise RuntimeException("Ini: Value Cannot Contain Double Quotes")
else:
return str(value)
def sortRootElements(self, config):
r"""
NOTE:
Default section replaces empty section, as Ini reader won't read without sections
Following is the header as given in zend-config::
/**
* Root elements that are not assigned to any section needs to be on the
* top of config.
*
* @param array $config
* @return array
*/
"""
ret = {"DEFAULT": {}}
for key, value in config.items():
if not isinstance(value, dict):
# v1.1.1 fixed error of two arguments into one dict
ret["DEFAULT"].update({key: value})
else:
ret[key] = value
return ret
|
SQL
|
UTF-8
| 830 | 3.0625 | 3 |
[] |
no_license
|
-- alter session set "_ORACLE_SCRIPT"=true; THIS IS NOT REQUIRED
CREATE TABLESPACE tbs_perm_01 DATAFILE 'tbs_perm_01.dbf' SIZE 256M;
CREATE TEMPORARY TABLESPACE tbs_temp_02 TEMPFILE 'tbs_temp_02.dbf' SIZE 64M;
CREATE USER spring_user
IDENTIFIED BY spring_password
DEFAULT TABLESPACE tbs_perm_01
-- QUOTA 128M on tbs_perm_01
TEMPORARY TABLESPACE tbs_temp_02;
-- QUOTA 32M on tbs_temp_02;
GRANT create session TO spring_user;
GRANT create table TO spring_user;
GRANT create view TO spring_user;
GRANT create any trigger TO spring_user;
GRANT create any procedure TO spring_user;
GRANT create sequence TO spring_user;
GRANT create synonym TO spring_user;
ALTER USER spring_user quota 256M on tbs_perm_01; -- ORA-01950
COMMIT;
select username,account_status from dba_users;
alter user spring_user account unlock;
COMMIT;
|
PHP
|
UTF-8
| 143 | 3.09375 | 3 |
[] |
no_license
|
<?php
$time= date("his");
$date= date("Ymd");
$print= ' Time= '.$time."\n";
$print.= ' Date= '.$date."\n";
echo $print;
exit(2);
?>
|
PHP
|
UTF-8
| 618 | 2.734375 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace Meeting\Controller;
use Meeting\Repository\MeetingsRepository;
final class MeetingsController
{
/**
* @var MeetingsRepository
*/
private $meetingsRepository;
public function __construct(MeetingsRepository $meetingsRepository)
{
$this->meetingsRepository = $meetingsRepository;
}
public function indexAction() : string
{
$meeting = $this->meetingsRepository->fetchAll();
ob_start();
include __DIR__.'/../../../views/meetings.phtml';
return ob_get_clean();
}
}
|
Python
|
UTF-8
| 114 | 2.796875 | 3 |
[] |
no_license
|
nama = [
'Ihsan', 'Sheila', 'HackMe', 'WizKhalifa', 'Tegar'
]
for nama_list in nama:
print(nama_list)
|
Markdown
|
UTF-8
| 1,158 | 2.546875 | 3 |
[] |
no_license
|
# animeapp
Anime Flutter application.
it's just another app that i made for fun. it's connected to KITSU API: https://kitsu.docs.apiary.io/
I'm still learning about flutter.
<div style="display: inline">
<img src="https://github.com/yomergonzalez/anime_app/blob/master/screenshots/img1.png?raw=true" width="200">
<img src="https://github.com/yomergonzalez/anime_app/blob/master/screenshots/img2.png?raw=true" width="200">
<img src="https://github.com/yomergonzalez/anime_app/blob/master/screenshots/img3.png?raw=true" width="200">
<img src="https://github.com/yomergonzalez/anime_app/blob/master/screenshots/img4.png?raw=true" width="200">
</div>
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
|
Java
|
UTF-8
| 1,061 | 2.5625 | 3 |
[] |
no_license
|
package beanutil;
public class RecordBean {
private int R_id;
private int R_sumtime;
private int U_id;
private String R_date;
@Override
public String toString() {
return "RecordBean [R_id=" + R_id + ", R_sumtime=" + R_sumtime
+ ", U_id=" + U_id + ", R_date=" + R_date + "]";
}
public RecordBean(int r_id, int r_sumtime, int u_id, String r_date) {
super();
R_id = r_id;
R_sumtime = r_sumtime;
U_id = u_id;
R_date = r_date;
}
public RecordBean(int r_sumtime, int u_id, String r_date) {
super();
R_sumtime = r_sumtime;
U_id = u_id;
R_date = r_date;
}
public int getR_id() {
return R_id;
}
public void setR_id(int r_id) {
R_id = r_id;
}
public int getR_sumtime() {
return R_sumtime;
}
public void setR_sumtime(int r_sumtime) {
R_sumtime = r_sumtime;
}
public int getU_id() {
return U_id;
}
public void setU_id(int u_id) {
U_id = u_id;
}
public String getR_date() {
return R_date;
}
public void setR_date(String r_date) {
R_date = r_date;
}
}
|
C++
|
GB18030
| 1,126 | 2.53125 | 3 |
[] |
no_license
|
#pragma once
#ifndef _TASKDEFINE_H_
#define _TASKDEFINE_H_
#include <vector>
using std::vector;
enum enJOINT
{
JOINT_NONE,//ڵ
JOINT_J1,//J1ڵ
JOINT_J2,
JOINT_J3,
JOINT_J4,
JOINT_J5,
JOINT_J6,
JOINT_J7,
JOINT_J8,
JOINT_J9,
JOINT_J10
};
enum enJOINTTASK
{
JOINTTASK_NONE,//
JOINTTASK_PARK,//ͣ
JOINTTASK_LOADING,//װ
JOINTTASK_UNLOAD,//ж
JOINTTASK_CHARGE//
};
enum enFORWARD
{
FORWARD_NONE,//н
FORWARD_FRONT,//ǰ
FORWARD_BACK,//
FORWARD_LEFT,//
FORWARD_RIGHT//
};
enum enROTATE
{
ROTATE_NONE,//ת
ROTATE_LEFT90,
ROTATE_LEFT180,
ROTATE_LEFT270,
ROTATE_LEFT360,
ROTATE_RIGHT90,
ROTATE_RIGHT180,
ROTATE_RIGHT270,
ROTATE_RIGHT360
};
class CTaskDefine
{
friend class CTaskDealing;
public:
CTaskDefine();
CTaskDefine(int nJointNum);
~CTaskDefine();
int m_nrow;
int** m_ppnTaskTable;//5壺[T1:ǰڵ㣬T2һڵ㣬T3ǰT4ǰT5תǶ]
int** m_ppnTaskEspecial;//Щ(ȷ)
private:
};
#endif // !_TASKDEFINE_H_
|
C#
|
UTF-8
| 6,422 | 3.796875 | 4 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace ALGON.DataStructures.LinkedLists
{
/// <summary>
/// Реализация кольцевого односвязного списка
/// </summary>
/// <typeparam name="T"></typeparam>
public class SinglyCircularALinkedList<T> : ICollection<T>
{
/// <summary>
/// Ссылка на первый элемент (начало отсчета)
/// </summary>
ALinkedListNode<T> _Head;
/// <summary>
/// Ссылка на последний элемент
/// </summary>
ALinkedListNode<T> _Tail;
/// <summary>
/// Количество элементов в списке
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Данная коллекция не может использоваться только для чтения
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Добавление элемента в конец списка
/// Сложность: O(1), если есть ссылка на последний узел
/// Сложность: O(n), если требуется выполнять последовательный доступ к последнему элементу
/// </summary>
/// <param name="item"></param>
public void Add(T item)
{
var node = new ALinkedListNode<T>(item);
if (Count == 0)
{
_Head = node;
_Tail = node;
_Tail.Next = _Head;
}
else
{
_Tail.Next = node;
node.Next = _Head;
_Tail = node;
}
Count++;
}
/// <summary>
/// Удаление элемента
/// Сложность: O(n)
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Remove(T item)
{
ALinkedListNode<T> previous = null;
ALinkedListNode<T> current = _Head;
if (Count == 0)
return false;
do
{
if (current.Value.Equals(item))
{
if (previous != null)
{
previous.Next = current.Next;
if (current == _Tail)
_Tail = previous;
}
else
{
if (Count == 1)
{
_Head = null;
_Tail = null;
}
else
{
_Head = current.Next;
_Tail.Next = _Head;
}
}
Count--;
return true;
}
previous = current;
current = current.Next;
}
while (current != _Head);
return false;
}
/// <summary>
/// Очистка коллекции
/// Сложность: O(1)
/// </summary>
public void Clear()
{
_Head = null;
_Tail = null;
Count = 0;
}
/// <summary>
/// Наличие элемента в коллекции
/// Сложность: O(n)
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(T item)
{
ALinkedListNode<T> current = _Head;
if (Count == 0)
return false;
do
{
if (current.Value.Equals(item))
return true;
else
current = current.Next;
}
while (current != _Head);
return false;
}
/// <summary>
/// Копирует данные из коллекции в массив начиная с определенного индекса
/// Сложность: O(n)
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array is null");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex is less than 0");
if (Count > array.Length - arrayIndex)
throw new ArgumentException("The number of elements in the source System.Collections.Generic.ICollection`1 is greater " +
"than the available space from arrayIndex to the end of the destination array.");
var current = _Head;
do
{
if (current != null)
{
array[arrayIndex++] = current.Value;
current = current.Next;
}
}
while (current != _Head);
}
/// <summary>
/// Обход по всем элементам
/// Сложность получения итератора: O(1)
/// Сложность обхода коллекции (очевидно): O(n)
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
ALinkedListNode<T> current = _Head;
do
{
if (current != null)
{
yield return current.Value;
current = current.Next;
}
}
while (current != _Head);
}
/// <summary>
/// Явная реализация интерфейса для получения итератора
/// Сложность получения итератора: O(1)
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)this).GetEnumerator();
}
}
}
|
C++
|
UTF-8
| 5,473 | 2.765625 | 3 |
[] |
no_license
|
#include "deadlock_detector.h"
#include <vector>
#include <map>
#include <stack>
using namespace std;
#define maxT 50 //maxNumOfCurrentTransaction
bool abortT[maxT];
//POSSIBLE DATA STRUCTURE FOR WAIT-FOR GRAPH
bool waitFor[maxT][maxT];
vector<vector<Node *>*> *cycles; // a list whose elements are lists of strongly connected components in the graph
map<int,Node*> *nodeTable; // a map of transaction ids to transaction nodes
stack<Node *> *nodeStack; // used for Tarjan's algorithm
int index = 0; // used for Tarjan's algorithm to group strongly connected components
void DeadlockDetector::BuildWaitForGraph()
{
vector<int> *haveLock = new vector<int>(); // a list of all transactions that have a lock on an object
for each(KeyValuePair<int, ReadWriteFIFOLock^> kvp in LockManager::lockTable)
{
int oid = kvp.Key;
ReadWriteFIFOLock^ lock = kvp.Value;
// Make sure Monitor::Exit(lock->_m) is called for every Monitor::Enter
// (so watch out if you use "continue" or "break")
Monitor::Enter(lock->_m);
//TRAVERSAL lockingList
for each (int pid in lock->lockingList)
{
if (nodeTable->count(pid) == 0) { // new transaction node encountered
Node *v = new Node(pid,-1,-1,1,false); // create node
nodeTable->insert(pair<int,Node *>(pid,v)); // add to table
} else { // existing transation, update lock count
map<int,Node*>::iterator it;
it = nodeTable->find(pid);
Node *v = it->second;
v->numLocks = v->numLocks + 1;
}
haveLock->push_back(pid); // add it to the set of transactions that "have lock"
}
//TRAVERSAL waitQ
for each (Request^ req in lock->waitQ)
{
int pid = req->pid;
if (nodeTable->count(pid) == 0) { // new transaction node encountered
Node *v = new Node(pid,-1,-1,0,false);
nodeTable->insert(pair<int,Node *>(pid,v)); // add to table
}
// build waitFor
for (int i=0;i<haveLock->size();i++) {
int tid = haveLock->at(i);
if (pid != tid) {
waitFor[pid][tid] = 1; // pid is waiting for tid
}
}
}
haveLock->clear();
Monitor::Exit(lock->_m);
}
delete haveLock;
}
void DeadlockDetector::AnalyzeWaitForGraph()
{
// Awesome algorithm starts here
DetectCycle();
// Determine abort
int numLocks = 0; Node *abortTarget; bool found = false;
for (int i=0;i<cycles->size();i++) {
vector<Node *> *list = cycles->at(i);
if (list->size()>1) { // if there is a cycle
for (int j=0;j<list->size();j++) {
Node *v = list->at(j);
if (v->numLocks > numLocks) { // the find transaction that holds the most locks
numLocks = v->numLocks;
abortTarget = v;
found = true;
}
}
}
}
if (found) abortT[abortTarget->tid] = true;
// Reset graph and such
for (int i=0;i<maxT;i++){
for (int j=0;j<maxT;j++){
waitFor[i][j] = 0;
}
}
index = 0;
for (int i=0;i<cycles->size();i++) {
delete cycles->at(i);
}
cycles->clear();
while (!nodeStack->empty()) {
nodeStack->pop();
}
nodeTable->clear();
}
void DeadlockDetector::DetectCycle() {
// Tarjan's algorithm
map<int, Node *>::iterator it;
for(it = nodeTable->begin(); it != nodeTable->end(); it++) {
Node *v = it->second;
if (v->index < 0){
StrongConnect(v);
}
}
}
void DeadlockDetector::StrongConnect(Node *v){
// Tarjan's algorithm
v->index = index;
v->lowLink = index;
index++;
nodeStack->push(v);
v->inStack = true;
for (int i=0;i<maxT;i++) {
if (waitFor[v->tid][i] == 1){ // v is waiting for transaction i
map<int,Node*>::iterator it;
it = nodeTable->find(i);
Node *w = it->second; // find w
if (w->index < 0){
StrongConnect(w);
v->lowLink = min(v->lowLink, w->lowLink);
} else if (w->inStack){
v->lowLink = min(v->lowLink, w->index);
}
}
}
if (v->lowLink == v->index){ // v is the root of a cycle
vector<Node *> *list = new vector<Node *>();
Node *w;
do {
w = nodeStack->top();
nodeStack->pop();
list->push_back(w);
} while (v != w);
cycles->push_back(list);
}
}
void DeadlockDetector::AbortTransactions()
{
//DO NOT CHANGE ANY CODE HERE
bool deadlock = false;
for (int i = 0; i < maxT; ++i)
if (abortT[i])
{
deadlock = true;
break;
}
if (!deadlock) {
Console::WriteLine("no deadlock found");
}
else {
for (int i = 0; i < maxT; ++i)
if (abortT[i])
{
Console::WriteLine("DD: Abort Transaction: " + i);
}
for each(KeyValuePair<int, ReadWriteFIFOLock^> kvp in LockManager::lockTable)
{
int oid = kvp.Key;
ReadWriteFIFOLock^ lock = kvp.Value;
Monitor::Enter(lock->_m);
bool pall = false;
for each(Request^ req in lock->waitQ)
if (abortT[req->pid])
{
lock->abortList->Add(req->pid);
lock->wakeUpList->Add(req->pid);
Console::WriteLine("DD: Transaction " + req->pid + " cancel object " + oid);
pall = true;
}
if (pall)
{
Monitor::PulseAll(lock->_m);
}
Monitor::Exit(lock->_m);
}
}
}
void DeadlockDetector::run()
{
while (true)
{
Thread::Sleep(timeInterval);
memset(waitFor, 0 ,sizeof(waitFor));
//INITIALIZE ANY OTHER DATA STRUCTURES YOU DECLARE.
cycles = new vector<vector<Node *>*>();
nodeTable = new map<int,Node *>();
nodeStack = new stack<Node *>();
memset(abortT, 0 ,sizeof(abortT));
Monitor::Enter(LockManager::lockTable);
BuildWaitForGraph();
AnalyzeWaitForGraph();
AbortTransactions();
delete nodeTable;
delete cycles;
delete nodeStack;
Monitor::Exit(LockManager::lockTable);
}
}
|
C#
|
UTF-8
| 2,451 | 3.203125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace DnsShell
{
// DnsShell.IO.EndianBinaryReader - A modified version of System.IO.BinaryReader
// allowing for control over Endian order for certain methods.
//
// Constructors:
// Public: EndianBinaryReader(Stream BaseStream)
//
// Methods:
// Public Override: UInt16()
// Public Override: UInt32()
internal class EndianBinaryReader : BinaryReader
{
internal EndianBinaryReader(Stream BaseStream) : base(BaseStream) { }
internal UInt16 ReadUInt16(Boolean IsBigEndian)
{
return (UInt16)((base.ReadByte() << 8) | base.ReadByte());
}
internal UInt32 ReadUInt32(Boolean IsBigEndian)
{
return (UInt32)(
(base.ReadByte() << 24) |
(base.ReadByte() << 16) |
(base.ReadByte() << 8) |
base.ReadByte());
}
internal UInt64 ReadUInt64(Boolean IsBigEndian)
{
return (UInt64)(
(base.ReadByte() << 56) |
(base.ReadByte() << 48) |
(base.ReadByte() << 40) |
(base.ReadByte() << 32) |
(base.ReadByte() << 24) |
(base.ReadByte() << 16) |
(base.ReadByte() << 8) |
base.ReadByte());
}
internal Byte PeekByte()
{
Byte Value = base.ReadByte();
base.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);
return Value;
}
internal IPAddress ReadIPAddress()
{
return IPAddress.Parse(
String.Format("{0}.{1}.{2}.{3}",
base.ReadByte(),
base.ReadByte(),
base.ReadByte(),
base.ReadByte()));
}
internal IPAddress ReadIPv6Address()
{
return IPAddress.Parse(
String.Format("{0:X}:{1:X}:{2:X}:{3:X}:{4:X}:{5:X}:{6:X}:{7:X}",
this.ReadUInt16(true),
this.ReadUInt16(true),
this.ReadUInt16(true),
this.ReadUInt16(true),
this.ReadUInt16(true),
this.ReadUInt16(true),
this.ReadUInt16(true),
this.ReadUInt16(true)));
}
}
}
|
Ruby
|
UTF-8
| 671 | 4.03125 | 4 |
[] |
no_license
|
def volume
volume=(1...20)
Puts "What is the volume of your amplifier?"
Puts "Do you want to throw it off the cliff?" (y/n)
if user_input <=11 && y
Puts "Crank it to eleven"
elsif volume <=11 && n
Puts "That's not very rock, man"
elsif volume >=11
Puts "Crank it up (+1)"
end
end
#Matt's solution
puts "what's your volume?"
volume = gets.chomp.to_i
puts "do you want to take it over the cliff?(y/n)"
cliff = gets.chomp.downcase[0]
# so that Yes yes YES will be acceptable
if volume < 11 && cliff == "y"
puts "Crank it to 11"
elsif volume < 11 && cliff == "n"
puts "You are a feeble rocker."
else volume >= 11
puts "turn it up to #{volume+1}"
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.