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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 1,711 | 2.0625 | 2 | [] | no_license | package co.com.myproject.delivereatspersistence.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import co.com.myproject.delivereatspersistence.entity.Mailestadotipo;
import co.com.myproject.delivereatspersistence.entity.MailestadotipoPK;
import co.com.myproject.delivereatspersistence.repository.IMailEstadoTipoRepo;
@Service
public class MailEstadoTipoServImpl implements IMailEstadoTipoServ{
@Autowired
private IMailEstadoTipoRepo repo;
public List<Mailestadotipo> findAll() {
return repo.findAll();
}
public Optional<Mailestadotipo> findById(MailestadotipoPK id) {
return repo.findById(id);
}
public Mailestadotipo getOne(MailestadotipoPK id) {
return repo.getOne(id);
}
public boolean existsById(MailestadotipoPK id) {
return repo.existsById(id);
}
public Mailestadotipo save(Mailestadotipo entity) {
return repo.save(entity);
}
public List<Mailestadotipo> saveAll(List<Mailestadotipo> entities) {
return repo.saveAll(entities);
}
public Mailestadotipo update(Mailestadotipo entity) {
return repo.save(entity);
}
public List<Mailestadotipo> updateAll(List<Mailestadotipo> entities) {
return repo.saveAll(entities);
}
public void delete(Mailestadotipo entity) {
repo.delete(entity);
}
public void deleteAll(List<Mailestadotipo> entities) {
repo.deleteAll(entities);
}
@Override
public Mailestadotipo getOne(Integer id) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean existsById(Integer id) throws Exception {
// TODO Auto-generated method stub
return false;
}
}
|
C | UTF-8 | 1,579 | 3.859375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_list(char ** data);
int main(int argc, char* argv[]) {
/*CS306 Assignment 2.1:
*Program accepts string(s) from command line and converts letters to
*uppercase or lowercase based on the case of the first letter*/
int inc=1;
char ** ret2=(char**)malloc(argv*sizeof(char*));
while(inc<argc) {
//input validation: make sure string has been input
if(argc=1) {
printf("Did not enter string or strings.");
return -1;
}
int i=0,gt=0,lt=0,mod,len;
for(len=0;argv[inc][len]!='\0';len++);
char *ret=(char*)malloc(len*sizeof(char)); //create array of proper length
if(ret==NULL) {
printf("Memory not allocated.");
exit(0);
}
//convert to uppercase or lowercase
while((i!=-1) && (i<len)) {
if(argv[inc][i]>64 && argv[inc][i]<93) {
gt=64;
lt=93;
mod=32;
i=-1;
}
else if(argv[inc][i]>96 && argv[inc][i]<125) {
gt=96;
lt=125;
mod=-32;
i=-1;
}
i++;
}
i=0; //reset incrementer
if(gt=0) {
//string has no characters, don't modify
}
else {
while(i<len) {
if(argv[inc][i]>gt && argv[inc][i]<lt) { //char is gt/lt, change case
ret[i]=argv[inc][i]+mod;
}
else { //not a character, don't modify
ret[i]=argv[inc][i];
}
i++;
}
}
ret2[inc]=ret;
inc++;
}
print_list(ret2);
//free sub-arrays
for(i=0;i<argc;i++) {
free(ret2[i]);
}
//free 2d array
free(ret2);
return 0;
}
void print_list(char **data) {
int j,k;
for(j=0;j<argc;j++) {
k=0;
while(argc[j][k]!='\0') {
printf("%c",argc[j][k]);
k++;
}
printf(" ");
} |
C++ | UTF-8 | 1,773 | 3.03125 | 3 | [] | no_license | //Functions that use the servo to look in different directions and compare/save readings.
void LookAhead() //Unused at d mo...
{
servo1.write(90);// angle to look forward
delay(175); // wait 0.175 seconds
ping();
centerDist = cm; //get the center distance
}
bool checkRoute()
{
servo1.write(135); // angle (right)
delay(160); // wait 0.16 seconds
ping();
rightDist = cm; //get the right distance
servo1.write(45); // look to the other side
delay(320); // wait 0.62 seconds
ping();
leftDist = cm; // get the left distance
servo1.write(90); // 90° angle
delay(160); // wait 0.275 seconds
centerDist = cm; // get the c distance
if (leftDist < minSafeDist || rightDist < minSafeDist || centerDist < minSafeDist)
return false;//obstacle
else
return true;//obstacle free
//Ccm = (leftDist + rightDist + centerDist)/3;
//Prints following serial monitor
Serial.print("RightDist: ");
Serial.println(rightDist);
Serial.print("LeftDist: ");
Serial.println(leftDist);
Serial.print("CenterDist: ");
Serial.println(centerDist);
}
void FarLeftRight()
{ //check 90 degrees left and right
servo1.write(180); // 180° angle (right)
delay(320); // wait 0.32 seconds
ping();
FarRightDist = cm; //get the right distance
servo1.write(0); // look to the other side
delay(640); // wait 0.62 seconds
ping();
FarLeftDist = cm; // get the left distance
servo1.write(90); // 90° angle
delay(320); // wait 0.275 seconds
// Prints following serial monitor
Serial.print("FarRightDist: ");
Serial.println(FarRightDist);
Serial.print("FarLeftDist: ");
Serial.println(FarLeftDist);
}
|
JavaScript | UTF-8 | 3,095 | 3.046875 | 3 | [] | no_license | /**
* 回复组件
* @class Component:Reply
*
*/
function Reply(db, totalChar) {
this.db = db; // 数据库连接
this.user = this.db.getLoginUser(); // 当前登录用户
this.util = new Util(); // 工具类示例
this.left = totalChar; // 剩余输入字数
this.totalChar = totalChar; // 总共可输入字数
/**
* 处理回复提交
* @private
* @method Component:Reply#handleSubmit
* @param {Object} event 点击事件
* @returns {void}
*/
var handleSubmit = function (event) {
event.preventDefault();
var text = leftChar();
if (text) {
this.db.addComment({ id: "" + Date.now(), content: text }).then(function (data) {
console.log("add comment", data);
});
document.querySelector("form.reply").content.value = ""; // 清空输入框
}
}.bind(this);
/**
* 回复器剩余输入字数
* @private
* @method Component:Reply#leftChar
* @returns {Boolean} 回复内容
*/
var leftChar = function () {
var text = document.querySelector("form.reply").content.value;
var commentChar = this.util.getLength(text);
var leftChar = totalChar - commentChar;
var countNode = document.querySelector("form.reply .submit span.count");
countNode.querySelector(".message").textContent = leftChar >= 0 ? "" : "已超出" + (commentChar - 140) + "字!";
if (leftChar < 0) {
return false;
}
countNode.querySelector("span").textContent = 140 - commentChar;
return text;
}.bind(this);
/**
* 获取回复渲染后的DOM字符串
* @public
* @method Component:Reply#render
* @returns {void}
*/
this.render = function () {
return "<div class=\"c-reply f-clear\">"+
"<a class=\"w-avatar\" href=\"#\">"+
"<img src=\"./style/" + this.user.avatarURL + "\" alt=\"\" />"+
"</a>"+
"<form class=\"reply\" method=\"post\">"+
"<div class=\"txt\">"+
"<textarea name=\"content\" required placeholder=\"评论\"></textarea>"+
"</div>"+
"<div class=\"submit f-clear\">"+
"<span class=\"count\">"+
"<span>" + this.left + "</span>/140"+
"<span class=\"message\"></span>"+
"</span>"+
"<button type=\"submit\">评论</button>"+
"</div>"+
"</form>"+
"</div>";
};
/**
* 绑定回复组件事件
* @public
* @method Component:Reply#bind
* @returns {void}
*/
this.bind = function () {
var form = document.querySelector(".c-reply form.reply");
form.addEventListener("submit", handleSubmit);
form.content.addEventListener("input", leftChar);
form.content.addEventListener("focus", leftChar);
form.content.addEventListener("blur", leftChar);
};
} |
C++ | UTF-8 | 4,219 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<cstdlib>
int BOARD_SIZE = 6;
class Point{
public:
int x;
int y;
int step;
Point(int x = 0, int y = 0, int step = 0){
this->x = x;
this->y = y;
this->step = step;
}
/*Point operator+(Point& a){
Point result;
result.x = a.x + this->x;
result.y = a.y + this->y;
return result;
}*/
friend std::ostream& operator<< (std::ostream& out, Point &cPoint);
friend Point operator+ (const Point& a, const Point& b);
};
Point operator+ (const Point& a, const Point& b)
{
Point result;
result.x = a.x + b.x;
result.y = a.y + b.y;
return result;
}
std::ostream& operator<< (std::ostream& out, Point &cPoint)
{
out<<cPoint.x<<","<<cPoint.y;
}
//The First result.size() - 1 elements must be valid
bool check_valid(std::vector<Point> result)
{
if(result.back().x < 0 || result.back().x > BOARD_SIZE || result.back().y < 0 || result.back().y > BOARD_SIZE )
{
return false;
}
for(std::vector<Point>::iterator iter=result.begin(); iter == --result.end(); ++iter)
{
if((*iter).x == result.back().x && (*iter).y == result.back().y)
return false;
}
return true;
}
bool check_valid(std::vector<Point> result, Point step)
{
Point last = result.back() + step;
if(last.x < 0 || last.x > BOARD_SIZE || last.y < 0 || last.y > BOARD_SIZE )
{
return false;
}
for(std::vector<Point>::iterator iter=result.begin(); iter != result.end(); ++iter)
{
if((*iter).x == last.x && (*iter).y == last.y)
return false;
}
return true;
}
void print_result(std::vector<Point> result)
{
for(std::vector<Point>::iterator iter = result.begin(); iter != result.end(); ++iter)
{
std::cout<<*iter<<" ";
}
std::cout<<std::endl;
}
int main(int argc, char* argv[])
{
if(argc >= 2)
BOARD_SIZE = atoi(argv[1]);
std::vector<Point> steps;
steps.push_back(Point(1, 2));
steps.push_back(Point(2, 1));
steps.push_back(Point(2, -1));
steps.push_back(Point(1, -2));
steps.push_back(Point(-1, -2));
steps.push_back(Point(-2, -1));
steps.push_back(Point(-2, 1));
steps.push_back(Point(-1, 2));
//std::vector<Point> test[1] = {Point(1, 2),};
std::vector<Point> result;
result.push_back(Point(0, 0));
Point test = steps[0] + steps[1];
std::cout<<test<<std::endl;
//std::cout<<(steps[0] + steps[1])<<std::endl;
/*while(!result.empty())
{
if(result.at(result.size() - 2).step >= BOARD_SIZE)
{
result.pop_back();
++result.back().step;
continue;
}
else if(check_valid(result))
{
if(BOARD_SIZE * BOARD_SIZE == result.size())
{
break;
}
else{
//New iteration from step 0
result.back().step = 0;
result.push_back(result.back() + steps[result.back().step]);
continue;
}
}
else{
result.pop_back();
++result.back().step;
result.push_back(result.back() + steps[result.back().step]);
}
}*/
while(!result.empty())
{
//print_result(result);
//std::cout<<"back().step: "<<result.back().step<<std::endl;
if( BOARD_SIZE * BOARD_SIZE == result.size())
{
break;
}
else if(result.back().step >= BOARD_SIZE)
{
result.pop_back();
if (result.empty()) {
break;
}
++result.back().step;
continue;
}
else if(check_valid(result, steps[result.back().step]))
{
result.push_back(result.back()+ steps[result.back().step]);
result.back().step = 0;
}
else
{
++result.back().step;
continue;
}
}
if(result.empty())
std::cout<<"No result!"<<std::endl;
else{
print_result(result);
}
return 0;
}
|
Java | UTF-8 | 2,231 | 2.234375 | 2 | [] | no_license | /**
* FailProcessor.java
* com.uxuexi.web.common.chain
* Copyright (c) 2012, 北京聚智未来科技有限公司版权所有.
*/
package com.uxuexi.core.web.chain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.impl.processor.ViewProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.uxuexi.core.common.exception.IBusinessException;
import com.uxuexi.core.common.exception.ITimeoutException;
import com.uxuexi.core.common.util.Util;
/**
* web项目统一的异常处理
*
* @author 庄君祥
* @Date 2012-4-25
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class FailProcessor extends ViewProcessor {
/**
* Logger for this class
*/
private static final Logger logger = LoggerFactory.getLogger(FailProcessor.class);
/**
* request存放错误信息的key
*/
public static final String REQ_ERROR_KEY = "REQ_ERROR_KEY";
@Override
public void init(final NutConfig config, final ActionInfo ai) throws Throwable {
view = evalView(config, ai, ai.getFailView());
}
/**
* 处理错误信息
* <p>
* 首先根据错误类别对错误进行日志记录
* 根据错误view的方式,返回错误信息
* @see org.nutz.mvc.impl.processor.ViewProcessor#process(org.nutz.mvc.ActionContext)
*/
@Override
public void process(final ActionContext ac) throws Throwable {
Throwable th = ac.getError();
handleError(ac, th);
}
/**
* 错误处理逻辑
*
* @param ac 请求的上下文
* @param th 异常信息
*/
protected void handleError(final ActionContext ac, final Throwable th) {
ac.getRequest().setAttribute("javax.servlet.error.status_code", 500);//防止jsp解析错误的时候报错。
if (th instanceof IBusinessException || th instanceof ITimeoutException) {
return;
}
String url = "unknown";
if (ac.getRequest() != null && !Util.isEmpty(ac.getRequest().getRequestURL())) {
url = ac.getRequest().getRequestURL().toString();
}
logger.error("exception happen,please handle it!the url is " + url, th); //$NON-NLS-1$
}
}
|
TypeScript | UTF-8 | 3,183 | 2.609375 | 3 | [
"MIT"
] | permissive | import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectModel } from "@nestjs/mongoose";
import { SupportersService } from "../supporters/supporters.service";
import {
FeedSchedule,
FeedScheduleModel,
} from "./entities/feed-schedule.entity";
interface FeedDetails {
_id: string;
url: string;
guild: string;
}
@Injectable()
export class FeedSchedulingService {
defaultRefreshRateSeconds: number;
constructor(
private readonly supportersService: SupportersService,
private readonly configService: ConfigService,
@InjectModel(FeedSchedule.name)
private readonly feedScheduleModel: FeedScheduleModel
) {
this.defaultRefreshRateSeconds =
(this.configService.get(
"BACKEND_API_DEFAULT_REFRESH_RATE_MINUTES"
) as number) * 60;
}
async getAllSchedules(): Promise<FeedSchedule[]> {
return this.feedScheduleModel.find({}).lean();
}
async findSchedulesOfRefreshRate(
refreshRateSeconds: number
): Promise<FeedSchedule[]> {
return this.feedScheduleModel
.find({
refreshRateMinutes: Math.round(refreshRateSeconds / 60),
})
.lean();
}
async findSchedulesNotMatchingRefreshRate(
refreshRateSeconds: number
): Promise<FeedSchedule[]> {
return this.feedScheduleModel.find({
refreshRateMinutes: {
$ne: Math.round(refreshRateSeconds / 60),
},
});
}
/**
* Determine the refresh rate of the given feeds.
*
* @returns The refresh rate in seconds
*/
async getRefreshRatesOfFeeds(feeds: FeedDetails[]) {
const serverIds = Array.from(new Set(feeds.map((feed) => feed.guild)));
const [schedules, serverBenefits] = await Promise.all([
this.feedScheduleModel
.find({
name: {
$ne: "default",
},
})
.lean(),
this.supportersService.getBenefitsOfServers(serverIds),
]);
return feeds.map((feed) => {
const feedServerBenefits = serverBenefits.find(
(serverBenefit) => serverBenefit.serverId === feed.guild
);
if (!feedServerBenefits) {
console.error(
`Missing calculated server benefits for ${feed.guild} when determing feed refresh rates`
);
return this.defaultRefreshRateSeconds;
}
// Maintaining some legacy logic for now
if (
feedServerBenefits.hasSupporter &&
feedServerBenefits.refreshRateSeconds !== undefined &&
!feed.url.includes("feed43")
) {
return feedServerBenefits.refreshRateSeconds;
}
return this.getRefreshRateOfFeedFromSchedules(feed, schedules);
});
}
private getRefreshRateOfFeedFromSchedules(
feed: FeedDetails,
schedules: FeedSchedule[]
) {
for (const schedule of schedules) {
if (schedule?.feeds?.includes(feed._id)) {
return schedule.refreshRateMinutes * 60;
}
const someKeywordMatch = schedule?.keywords?.some((word) =>
feed.url.includes(word)
);
if (someKeywordMatch) {
return schedule.refreshRateMinutes * 60;
}
}
return this.defaultRefreshRateSeconds;
}
}
|
Python | UTF-8 | 3,111 | 3.375 | 3 | [] | no_license | import csv
import sys
from collections import defaultdict,Counter
def read_file(input_file):
"""
Function to read the input file
:param input_file: input filename
:return: results : list of list containing complaints
"""
result=[]
with open(input_file) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
i=100
for row in readCSV:
result.append(row)
i-=1
if i<0:
break
result.pop(0)
return result
def write_to_file(filename,hashmap):
"""
Function to process the input and write the output to the file
:param filename: Output file name
:param hashmap: A map of product to its complaints
:return:
"""
import csv
writer=csv.writer(open(filename, 'w'), delimiter=',',quotechar='"')
for product in sorted(hashmap.keys()):
years_list=list(val[0] for val in hashmap[product])
years=list(set(years_list))
years.sort()
for year in years:
unique_data = [list(x) for x in set(tuple(x) for x in hashmap[product] if x[0]==year )]
list_yearwise=[ x for x in hashmap[product] if x[0]==year ]
#print(list_yearwise)
max_count=max(list_yearwise)
#print(max_count)
percent=(list_yearwise.count(max_count)*100)/len(list_yearwise)
#print(len(unique_data)," ______________",len(hashmap[product]))
#print(product)
if "," in product:
writer.writerow([""+product+"",year,years_list.count(year),len(unique_data),round(percent)])
else:
writer.writerow([product,year,years_list.count(year),len(unique_data),round(percent)])
def get_sorted_hashmap(hashmap):
"""
Function to sort complaints for each product according to year
:param hashmap: A map of product to its complaints
:return: sorted hashmap
"""
# For each product
for product in hashmap.keys():
#print(product,hashmap[product])
# Sort the complaints according to year
hashmap[product]=[ complaint for complaint in sorted(hashmap[product], key=lambda x: x[0])]
return hashmap
def get_hashmap(records):
"""
:param records: List of list containing complaints
:return: hashmap: A map of product to its complaints
"""
hashmap=defaultdict(list)
for record in records:
key =record[1].lower()
hashmap[key].append([record[0][0:4],record[7].lower()])
return hashmap
def main():
# Read command line arguments
input_file = str(sys.argv[1])
output_file = sys.argv[2]
#output_file="report.csv"
# Read data from file
result = read_file(input_file)
#print('\n')
# Get a hashmap containing products as keys and their complaints as values
hashmap = get_hashmap(result)
#print("PART 1\n")
hashmap = get_sorted_hashmap(hashmap)
#print("PART 2\n")
#print(hashmap)
write_to_file(output_file,hashmap)
#print("PART 3\n")
if __name__ == '__main__' :
main()
|
C# | UTF-8 | 415 | 2.671875 | 3 | [] | no_license | using System;
namespace Last_K_Numbers_Sums_Sequence
{
class Program
{
static void Main(string[] args)
{
long n = long.Parse(Console.ReadLine());
int k = int.Parse(Console.ReadLine());
long[] seq = new long[k];
seq[0] = 1;
for (int i = 0; i <+ n; i++)
{
}
}
}
}
|
Java | UTF-8 | 607 | 2.328125 | 2 | [] | no_license | package com.zhujie.study.mybatis._02_Configuration;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import java.util.Properties;
/**
* Created by zhujie on 15/9/25.
*/
public class ExamplePlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
}
|
JavaScript | UTF-8 | 3,379 | 2.71875 | 3 | [] | no_license | var idSeleccionarConstanciaRecuperar=0;
function actionRead(){
$.ajax({
url: "php/validar-constancias.php",
method: "GET",
data: {
accion: "Read"
},
success: function(resultado) {
alert(resultado);
var objetoJSON=JSON.parse(resultado);
if (objetoJSON.estado==1){
var tabla = $('#example1').DataTable();
for(constancia of objetoJSON.constancias){
var botones =' <a class="btn btn-block btn-warning btn-flat" data-toggle="modal" data-target="#modal-Actualizar" href="#" onclick="accionRecuperarUnaConstancia('+constancia.id+')">';
botones= botones +'<i class="fas fa-tasks">';
botones= botones +'</i>';
botones= botones +'</a>';
tabla.row.add([
constancia.programa,
constancia.nombre,
constancia.actividad,
constancia.horas,
botones
]).node().id = 'row_'+constancia.id;
tabla.draw(false);
}
}
}
});
}
function accionRecuperarUnaConstancia(id){
idSeleccionarConstanciaRecuperar=id;
$.ajax({
url: "php/validar-constancias.php",
method: "GET",
data: {
id:idSeleccionarConstanciaRecuperar,
accion: "Read"
},
success: function(resultado) {
//alert(resultado);
var objetoJSON=JSON.parse(resultado);
if(objetoJSON.estado==1){
document.getElementById("nombre_validar").innerHTML=objetoJSON.nombre
document.getElementById("actividad_validar").value=objetoJSON.actividad;
document.getElementById("fecha_inicio_validar").value=objetoJSON.fecha_inicio;
document.getElementById("fecha_fin_validar").value=objetoJSON.fecha_fin;
document.getElementById("horas_validar").value=objetoJSON.horas;
document.getElementById("observaciones_encargado").value=objetoJSON.observaciones;//
}else{
alert(objetoJSON.mensaje);
}
}
});
}
function accionValidarConstancia(){
var constancia_valida=document.getElementById("constancia_valida").value;
var observaciones_encargado_validar=document.getElementById("observaciones_encargado").value;
$.ajax({
url: "php/validar-constancias.php",
method: "POST",
data: {
id:idSeleccionarConstanciaRecuperar,
valida:constancia_valida,
observaciones_encargado:observaciones_encargado_validar,
accion:"Update"
},
success: function(resultado) {
alert(resultado);
var objetoJSON=JSON.parse(resultado);
if(objetoJSON.estado==1){
alert(objetoJSON.mensaje);
$('#modal-Actualizar').modal('hide');
var tabla = $('#example1').DataTable();
tabla.row("#row_"+idSeleccionarConstanciaRecuperar).remove().draw();
}else{
alert(objetoJSON.mensaje);
}
}
});
}
|
Java | GB18030 | 141 | 1.828125 | 2 | [] | no_license | package adapter1;
public interface Target {
public void socket2();//йײ
public int volt220();//й220V
}
|
Java | UTF-8 | 1,773 | 2.515625 | 3 | [] | no_license | package entities;
import java.io.Serializable;
import javax.persistence.*;
/**
*
* @author Igor Sarcevic(igisar@gmail.com)
* Entity implementation class for Entity: Kupljeno
*
* za detalje pogledati diagram u fajlu diagram.png
*/
@Entity
@NamedQueries ({
@NamedQuery( name="Kupljeno.findByKorisnik",
query = "SELECT k FROM Kupljeno k WHERE k.korisnik = :korisnik" ),
@NamedQuery( name="Kupljeno.findByArtikal",
query = "SELECT k FROM Kupljeno k WHERE k.artikal = :artikal" ),
@NamedQuery( name="Kupljeno.findBySessionID",
query = "SELECT k FROM Kupljeno k, Korisnik k2 WHERE k2.sessionID = :sessionID AND k.korisnik = k2" )
})
public class Kupljeno implements Serializable {
@Id
@GeneratedValue
private int id;
@ManyToOne
private Korisnik korisnik;
@ManyToOne
private Artikal artikal;
private int kolicina;
private int ocena;
private String komentar;
//
//
// generisani getteri i setteri, konstruktori i ostalo ^_^
//
//
private static final long serialVersionUID = 1L;
public Kupljeno() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Korisnik getKorisnik() {
return korisnik;
}
public void setKorisnik(Korisnik korisnik) {
this.korisnik = korisnik;
}
public Artikal getArtikal() {
return artikal;
}
public void setArtikal(Artikal artikal) {
this.artikal = artikal;
}
public int getKolicina() {
return kolicina;
}
public void setKolicina(int kolicina) {
this.kolicina = kolicina;
}
public int getOcena() {
return ocena;
}
public void setOcena(int ocena) {
this.ocena = ocena;
}
public String getKomentar() {
return komentar;
}
public void setKomentar(String komentar) {
this.komentar = komentar;
}
}
|
Markdown | UTF-8 | 16,660 | 3.484375 | 3 | [
"Apache-2.0"
] | permissive | # Lesson 4 - RecyclerView

## Index
- [RecyclerView](#recyclerview)
- [ViewHolder](#viewholder)
- [Adapter](#adapter)
- [LayoutManager](#layoutmanager)
- [Handling click events](#handling-click-events)
- [Hooking everything up in the Activity](#hooking-everything-up-in-the-activity)
## RecyclerView
The `RecyclerView` widget is a *more advanced and flexible* version of `ListView` with improved performance and customizability. It was included in API level 22 (Lollipop) in the support-v7 library. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.

The `RecyclerView` class simplifies the display and handling of large data sets by providing:
- Layout managers for positioning items.
- Default animations for common item operations, such as removal or addition of items.
<img src="https://github.com/fjoglar/android-dev-challenge/blob/master/assets/images/recyclerview-vs-listview.png" width="400" align="right" hspace="10">
Under the `RecyclerView` model, several different components work together to display our data. The overall container for our dynamic user interface is a `RecyclerView` object. We add this object to our activity's or fragment's layout; the `RecyclerView`, fills itself with smaller views representing the individual items. The `RecyclerView` uses the *layout manager* we provide to arrange the items. We can use one of the standard layout managers (such as `LinearLayoutManager` or `GridLayoutManager`), or implement our own.
The individual items are represented by view holder objects. These objects are instances of the class we define by extending `RecyclerView.ViewHolder`. Each view holder is in charge of displaying a single item, and has its own view. The `RecyclerView` creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the `RecyclerView` takes the off-screen views and rebinds them to the data which is scrolling onto the screen.
The view holder objects are managed by an *adapter*, which we create by extending the `RecyclerView.Adapter` abstract class. The adapter creates view holders as needed and binds the view holders to their data. It does this by assigning the view holder to a position, and calling the adapter's `onBindViewHolder()` method. This method uses the view holder's position to determine what the contents should be.
- ### ViewHolder
A ViewHolder describes an item view and metadata about its place within the RecyclerView.
`RecyclerView.Adapter` implementations should subclass ViewHolder and add fields for caching potentially expensive `findViewById(int)` results. ViewHolders belong to the adapter. Adapters should feel free to use their own custom ViewHolder implementations to store data that makes binding view contents easier. Implementations should assume that individual item views will hold strong references to ViewHolder objects and that RecyclerView instances may hold strong references to extra off-screen item views for caching purposes.
When the view is first populated, it *creates and binds* some view holders on either side of the list. That way, if the user scrolls the list, the next element is ready to display. As the user scrolls the list, the `RecyclerView` creates new view holders as necessary. It also saves the view holders which have scrolled off-screen, so they can be reused. If the user switches the direction they were scrolling, the view holders which were scrolled off the screen can be brought right back. On the other hand, if the user keeps scrolling in the same direction, the view holders which have been off-screen the longest can be rebound to new data. The view holder does not need to be created or have its view inflated; instead, the app just updates the view's contents to match the new item it was bound to.
An example ViewHolder within an Adapter could look like this:
``` java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// we provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.tv_item_id);
}
}
// Rest of the Adapter
// ...
}
```
- ### Adapter
The adapter is the piece that will *connect* our data to our `RecyclerView` and determine the ViewHolder which will need to be used to display that data. It is a good practice to make the adapter as "dumb" as possible. No work performed on the data should live in the adapter. Instead, we must handle all data manipulation outside of our adapter, for example in our data model.
Our Adapter must override 3 methods for it to work:
- `onCreateViewHolder(ViewGroup parent, int viewType)`, called when `RecyclerView` needs a new `RecyclerView.ViewHolder` of the given type to represent an item.
This new ViewHolder should be constructed with a new View that can represent the items of the given type. We can either create a new View manually or inflate it from an XML layout file.
The new ViewHolder will be used to display items of the adapter using `onBindViewHolder(ViewHolder, int, List)`. Since it will be re-used to display different items in the data set, it is a good idea to cache references to sub views of the View to avoid unnecessary `findViewById(int)` calls.
``` java
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = inflater.LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_item_view, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
```
- `onBindViewHolder(VH holder, int position)`, called by `RecyclerView` to display the data at the specified position.
This method should update the contents of the itemView to reflect the item at the given position.
Note that `RecyclerView` will not call this method again if the position of the item changes in the data set unless the item itself is invalidated or the new position cannot be determined. For this reason, we should only use the position parameter while acquiring the related data item inside this method and should not keep a copy of it. If we need the position of an item later on (e.g. in a click listener), use `getAdapterPosition()` which will have the updated adapter position.
``` java
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position]);
}
```
- `getItemCount()`, that returns the total number of items in the data set held by the adapter.
``` java
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
if (null == mDataset) return 0;
return mDataset.length;
}
```
We now have a fully functioning RecyclerView Adapter ready to do its thing.
- ### LayoutManager
A `LayoutManager` is responsible for measuring and positioning item views within a `RecyclerView` as well as determining the policy for when to recycle item views that are no longer visible to the user. By changing the `LayoutManager` a `RecyclerView` can be used to implement a standard vertically scrolling list, a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock layout managers are provided for general use.
- [`LinearLayoutManager`](https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html) arranges the items in a one-dimensional list. Using a `RecyclerView` with `LinearLayoutManager` provides functionality like the older `ListView` layout.
- [`GridLayoutManager`](https://developer.android.com/reference/android/support/v7/widget/GridLayoutManager.html) arranges the items in a two-dimensional grid. Using a `RecyclerView` with `GridLayoutManager` provides functionality like the older `GridView` layout.
- [`StaggeredGridLayoutManager`](https://developer.android.com/reference/android/support/v7/widget/StaggeredGridLayoutManager.html) arranges the items in a two-dimensional grid, with each column slightly offset from the one before.
If none of these layout managers suits our needs, we can create our own by extending the `RecyclerView.LayoutManager` abstract class.
- ### Handling click events
Handling click events on the items of a `RecyclerView` is something we have to do by our own. But it is not difficult and by following a set of steps it can be done easily.
In our Adapter:
``` java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
// Create a final private AdapterOnClickHandler called mClickHandler
private final AdapterOnClickHandler mClickHandler;
// Add an interface called AdapterOnClickHandler
// Within that interface, define a void method that handles the onClick event
public interface AdapterOnClickHandler {
void onClick(String data);
}
// Add a AdapterOnClickHandler as a parameter to the constructor and store it in mClickHandler
public MyAdapter(AdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
// Implement View.OnClickListener in the ViewHolder class
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
// each data item is just a string in this case
TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.tv_item_id);
// Call setOnClickListener on the view passed into the constructor
view.setOnClickListener(this);
}
// Override onClick, passing the clicked item's data to mClickHandler via its onClick method
@Override
public void onClick(View view) {
mClickHandler.onClick(mDataset[getAdapterPosition()]);
}
}
// Rest of the Adapter
// ...
}
```
Then in our `Activity` we have to implement the `AdapterOnClickHandler.onClick` callback:
``` java
// Implement AdapterOnClickHandler from the MainActivity
public class MainActivity extends AppCompatActivity
implements MyAdapter.AdapterOnClickHandler{
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter passing the Context of the Activity
mAdapter = new MyAdapter(this);
// Rest of onCreate()
// ...
}
// Override AdapterOnClickHandler's onClick method
// Show a Toast when an item is clicked, displaying that item's data
@Override
public void onClick(String data) {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
// Rest of Activity
// ...
}
```
- ### Hooking everything up in the Activity
The `Activity` will be the screen that will display our `RecyclerView` and all of its containing data to our users. We need to add one method override for all of this to work, the override `onCreate(Bundle savedInstanceState)`. In the `onCreate` method, we need to add a call to the super method and also add the `setContentView(int layoutResID)` method passing in our Activity’s layout resource id.
Then we will initialize the `MyAdapter` and `RecyclerView` in our `onCreate()` method. After that, we will need to instantiate our `RecyclerView` using the id resource that we created in our Activity’s XML layout file.
Now that we have a `RecyclerView`, there are a few more things we will need to do to make it work. One of the most important being the `LayoutManager`. The next step, setting whether or not the `RecyclerView` has a fixed size, isn’t required but it helps the Android framework optimize the `RecyclerView` by letting it know in advance the the `RecyclerView` size will not be affected by the Adapter contents.
Finally, we will need to attach our `MyAdapter` to the `RecyclerView`.
But first of all we have to add the dependencies for `RecyclerView` to our app's module Gradle file, where `$support_lib_version` is the appropiate version of the [Support Library](https://developer.android.com/topic/libraries/support-library/revisions.html):
``` groovy
dependencies {
...
compile 'com.android.support:recyclerview-v7:$support_lib_version'
}
```
Now our complete `Activity` class should look something like this:
``` java
public class MainActivity extends AppCompatActivity
implements MyAdapter.AdapterOnClickHandler{
private MyAdapter mAdapter;
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter passing the Context of the Activity
mAdapter = new MyAdapter(this);
// Instantiate our RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_id);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
}
// Override AdapterOnClickHandler's onClick method
// Show a Toast when an item is clicked, displaying that item's data
@Override
public void onClick(String data) {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
// Rest of Activity
// ...
}
```
And our XML files should be like these:
``` xml
<!--
activity_main.xml
-->
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
<!--
my_item_view.xml
-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_item_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"/>
</LinearLayout>
```
- ### References
[Recycler View API Guide](https://developer.android.com/guide/topics/ui/layout/recyclerview.html)<br>
[`RecyclerView` reference](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html)<br>
[`RecyclerView.ViewHolder` reference](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html)<br>
[`RecyclerView.Adapter` reference](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html)<br>
[`RecyclerView.LayoutManager` reference](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.LayoutManager.html)<br>
[Creating Lists and Cards](https://developer.android.com/training/material/lists-cards.html#RecyclerView)<br>
[Android Fundamentals: Working with the RecyclerView, Adapter, and ViewHolder Pattern](https://willowtreeapps.com/ideas/android-fundamentals-working-with-the-recyclerview-adapter-and-viewholder-pattern/) by WillowTreeApps
###### Note: the images of the headers used in this serie of articles are from Udacity's [Developing Android Apps Course](https://www.udacity.com/course/new-android-fundamentals--ud851)
|
Java | UTF-8 | 682 | 2.234375 | 2 | [] | no_license | package com.example.androidswipetoshowbutton.adapter;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.androidswipetoshowbutton.R;
class MyRecyclerViewHolder extends RecyclerView.ViewHolder {
TextView cardName, cardPrice;
ImageView cardImg;
public MyRecyclerViewHolder(@NonNull View itemView) {
super(itemView);
cardName = itemView.findViewById(R.id.card_item_name);
cardPrice = itemView.findViewById(R.id.card_item_price);
cardImg = itemView.findViewById(R.id.card_image);
}
}
|
Java | UTF-8 | 3,229 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | package jp.s64.android.viewability.viewarea;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import jp.s64.android.viewability.ViewUtils;
import jp.s64.android.viewability.core.gaps.ContentGaps;
import jp.s64.android.viewability.core.gaps.SystemGaps;
import jp.s64.android.viewability.core.rect.WidgetRectInContent;
import jp.s64.android.viewability.core.rect.WidgetRectInDisplay;
import jp.s64.android.viewability.core.rect.WidgetRectInWindow;
import jp.s64.android.viewability.apparea.AppAreaCalculator;
public class ViewAreaCalculator {
@NonNull
private final AppAreaCalculator area;
@NonNull
private final View view;
public ViewAreaCalculator(
@NonNull View view,
@NonNull AppAreaCalculator areaCalc
) {
this.view = view;
this.area = areaCalc;
}
public ViewAreaCalculator(@NonNull View view) {
this.view = view;
this.area = new AppAreaCalculator(view);
}
@Nullable
public WidgetRectInContent getViewRectInContent() {
ContentGaps content = area.getContentGaps();
WidgetRectInWindow widgetRect = getViewRectInWindow();
return widgetRect != null ? getViewRectInContent(
content,
widgetRect
) : null;
}
@NonNull
public WidgetRectInContent getViewRectInContent(
@NonNull ContentGaps contentGaps,
@NonNull WidgetRectInWindow widgetRectInWindow
) {
int left = widgetRectInWindow.left - contentGaps.getLeftInPixels();
int top = widgetRectInWindow.top - contentGaps.getTopInPixels();
return new WidgetRectInContent(
left,
top,
left + widgetRectInWindow.getWidthInPixels(),
top + widgetRectInWindow.getHeightInPixels()
);
}
@Nullable
public WidgetRectInWindow getViewRectInWindow() {
SystemGaps systemGaps = area.getSystemGaps();
WidgetRectInDisplay widgetRectInDisplay = getViewRectInDisplay();
return systemGaps != null ? getViewRectInWindow(systemGaps, widgetRectInDisplay) : null;
}
@NonNull
public WidgetRectInWindow getViewRectInWindow(
@NonNull SystemGaps systemGaps,
@NonNull WidgetRectInDisplay widgetRectInDisplay
) {
int left = widgetRectInDisplay.left - systemGaps.getLeftInPixels();
int top = widgetRectInDisplay.top - systemGaps.getTopInPixels();
return new WidgetRectInWindow(
left,
top,
left + widgetRectInDisplay.getWidthInPixels(),
top + widgetRectInDisplay.getHeightInPixels()
);
}
@NonNull
public WidgetRectInDisplay getViewRectInDisplay() {
int[] loc = new int[2];
view.getLocationOnScreen(loc);
return new WidgetRectInDisplay(
loc[0],
loc[1],
loc[0] + view.getMeasuredWidth(),
loc[1] + view.getMeasuredHeight()
);
}
@NonNull
Activity requireActivity() {
return ViewUtils.requireActivity(view);
}
}
|
Markdown | UTF-8 | 413 | 2.578125 | 3 | [] | no_license | # PW-2019-01
## Programação Web 2019
## Demonstrações da disciplina de Programação para Web.
## Para fazer clone do repositório:
git clone + Link de seu repositório.
# Links
* [Curso de Git](https://www.youtube.com/playlist?list=PLQCmSnNFVYnRdgxOC_ufH58NxlmM6VYd1) - Do professor do Rodrigo Branas.
* [Guia Markdown](https://www.markdownguide.org/) - Um guia para você aprender a usar a linguagem Markdown.
|
Java | UTF-8 | 195 | 1.570313 | 2 | [] | no_license | package me.loki2302.expectations.element.typereference;
import me.loki2302.dom.DOMTypeReference;
public interface TypeReferenceExpectation {
void check(DOMTypeReference domTypeReference);
} |
Java | UTF-8 | 1,231 | 2.453125 | 2 | [] | no_license | package io.rolgalan.musicsearch.view;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import io.rolgalan.musicsearch.util.CompatUtils;
/**
* Created by Roldán Galán on 14/11/2016.
*/
public class PlayPauseTransition extends TransitionDrawable {
private final static int CROSSFADE_ANIM_DURATION = 600;
private boolean animated = false;
public PlayPauseTransition(Context context) {
super(getLayers(context));
setCrossFadeEnabled(true);
}
private static Drawable[] getLayers(Context context) {
Drawable[] layers = {CompatUtils.getDrawable(context, android.R.drawable.ic_media_play), CompatUtils.getDrawable(context, android.R.drawable.ic_media_pause)};
return layers;
}
public void animate() {
if (animated) {
pauseToPlayTransition();
} else {
playToPauseTransition();
}
}
public void playToPauseTransition() {
super.startTransition(CROSSFADE_ANIM_DURATION);
animated = true;
}
public void pauseToPlayTransition() {
super.reverseTransition(CROSSFADE_ANIM_DURATION);
animated = false;
}
}
|
Python | UTF-8 | 1,400 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env python3
import sys
def calculate(**kw):
for id1,salary in kw.items():
insurance = salary * (0.08 + 0.02 + 0.005 + 0.06)
TaxAmount = salary - insurance - 3500
if TaxAmount < 0:
TaxRate = 0
deduction = 0
elif TaxAmount <= 1500:
TaxRate = 0.03
deduction = 0
elif TaxAmount <= 4500:
TaxRate = 0.1
deduction = 105
elif TaxAmount <=9000:
TaxRate = 0.2
deduction = 555
elif TaxAmount <= 35000:
TaxRate = 0.25
deduction = 1005
elif TaxAmount <= 55000:
TaxRate = 0.3
deduction = 2755
elif TaxAmount <= 80000:
TaxRate = 0.35
deduction = 5505
else:
TaxRate = 0.45
deduction = 13505
tax = TaxAmount*TaxRate - deduction
after_tax = salary - insurance - tax
print('{}:{:.2f}'.format(id1,after_tax))
if __name__ == '__main__':
dict1 = {}
list1 = sys.argv[1:]
for i in list1:
i.strip()
list2 = i.split(':')
str1 = list2[0]
try:
str2 = int(list2[1])
if str2 < 0:
raise ValueError()
except ValueError:
print("Parameter Error")
break
dict1[str1]=str2
calculate(**dict1)
|
Markdown | UTF-8 | 1,426 | 3.453125 | 3 | [] | no_license | Pretty-prints a binary tree with child fields `left` and `right`. Each node contains a `data` field, which is printed.
Run `python tree.py` and check out the results.
The tree may be of any depth, but usually after 6 levels it's too wide for most screens.
Looks best when the nodes' printed values are under 3 characters long (especially on leaf nodes).
```python
# prep the tree...
#
# layer 1
root = Node('A')
# layer 2
root.left = Node('B')
root.right = Node('C')
# layer 3
root.left.left = Node('D')
root.left.right = Node('E')
# add a sub-tree ('X' nodes) using the createTree method
root.left.right.right = Node.createTree(2)
root.right.left = Node('F')
root.right.right = Node('G')
# layer 3
root.left.left.left = Node('H')
root.left.left.right = Node('I')
root.left.right.left = Node('J')
root.right.right.left = Node('N')
root.right.right.right = Node('O')
root.prettyPrint()
```
______________A______________
/ \
______B______ ______C______
/ \ / \
__D__ __E__ F __G__
/ \ / \ / \
H I J X N O
/ \
X XX
|
PHP | UTF-8 | 1,781 | 2.640625 | 3 | [] | no_license | <?php
class ValidationFactory
{
public function __construct(PDO $db)
{
$this->db = $db;
}
public function checkRoundIdAndUser($HorseRaceLinkId, $UserId)
{
$q = $this->db->prepare("
SELECT
Race.RoundId
FROM Race
JOIN HorseRaceLink as HR
ON Race.RaceId = HR.RaceId
JOIN Horse
ON HR.HorseId = Horse.HorseId
WHERE
HR.HorseRaceLinkId = :horseracelinkid;
");
$q->execute([
'horseracelinkid' => $HorseRaceLinkId
]);
$roundId = $q->fetchAll();
$q2 = $this->db->prepare("
SELECT rac.RoundId FROM MakeItRein.Prediction prd
JOIN horseracelink hrl
ON hrl.HorseRaceLinkId = prd.HorseRaceLinkId
JOIN Race rac
ON rac.RaceId = hrl.RaceId
where userid = :userId
group by prd.UserId, rac.RoundId
order by rac.RoundId desc
LIMIT 1");
$q2->execute([
':userId' => $UserId
]);
$returnedRow = $q2->fetchAll();
if (!$q2) {
return false;
}
if (empty($returnedRow)) {
//echo "You have never bet";
return true;
} else {
if ($returnedRow[0][0] == $roundId[0][0]) {
//echo "you have already bet on this round";
return false;
} else {
//echo "you have not bet on this round yet" ;
return true;
}
}
}
}
|
Python | UTF-8 | 1,045 | 3.875 | 4 | [] | no_license | # coding=utf-8
"""
@project: Everyday_LeetCode
@Author:Charles
@file: 01.字符串消消乐游戏.py
@date:2022/12/15 11:12
"""
# 题目描述 https://blog.csdn.net/forest_long/article/details/125803208
# 输入一个只包含英文字母的字符串,字符串中的两个字母如果相邻且相同,就可以消除。
# 在字符串上反复执行消除的动作,直到无法继续消除为止,此时游戏结束。
# 输出最终消除完后留下的字符串。
while True:
try:
a = input()
stack = []
for i in a:
# 如果列表为空则加入新的字符串
if not stack:
stack.append(i)
else:
# 如果新加入的字符与最后一个相等,则剔除最后一个字符
if i == stack[-1]:
stack.pop()
# 如果新的字符,则加入列表
else:
stack.append(i)
print("".join(stack))
except:
break
|
Shell | UTF-8 | 511 | 2.625 | 3 | [] | no_license |
#alias inkscape='C:/Users/40027000/PortableApps/InkscapePortable/App/Inkscape/inkscape.exe'
if [ $# -eq 0 ]
then
# Convert everything
for f in *.svg; do
inkscape $f --export-pdf `basename $f svg`pdf;
# inkscape $f --export-pdf `basename $f svg`pdf;
done
else
# Convert specified files
for f in $@; do
inkscape $f --export-pdf `basename $f svg`pdf;
# inkscape $f --export-png `basename $f svg`png;
done
fi
# for f in *.svg; do
# IMC
# done
|
C# | UTF-8 | 1,271 | 2.765625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment_17
{
public partial class UpdateStudent : Form
{
public UpdateStudent()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnBack_Click(object sender, EventArgs e)
{
MainForm obj = new MainForm();
obj.Show();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
StudentDataHandler obj = new StudentDataHandler();
if(obj.UpdateStudent(
Int32.Parse(txtEnroll.Text),
Int32.Parse(cmbClass.SelectedItem.ToString()),
cmbStream.SelectedItem.ToString(),
cmbState.SelectedItem.ToString()
))
lblMessage.Text = "Value Updated successfully !!!";
else
lblMessage.Text = "Unsuccessful";
}
}
}
|
Java | UTF-8 | 3,925 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | /*
* JPPF.
* Copyright (C) 2005-2019 JPPF Team.
* http://www.jppf.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jppf.admin.web.health.threaddump;
import java.util.*;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.wicket.*;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.jppf.admin.web.JPPFWebSession;
import org.jppf.admin.web.health.HealthConstants;
import org.jppf.admin.web.tabletree.*;
import org.jppf.admin.web.utils.AbstractActionLink;
import org.jppf.client.monitoring.topology.AbstractTopologyComponent;
import org.jppf.management.diagnostics.*;
import org.jppf.ui.utils.HealthUtils;
import org.jppf.utils.*;
import org.slf4j.*;
/**
*
* @author Laurent Cohen
*/
public class ThreadDumpLink extends AbstractActionLink {
/**
* Logger for this class.
*/
static Logger log = LoggerFactory.getLogger(ThreadDumpLink.class);
/**
* Determines whether debug log statements are enabled.
*/
static boolean debugEnabled = log.isDebugEnabled();
/**
*
*/
private transient ModalWindow modal;
/**
* @param form .
*/
public ThreadDumpLink(final Form<String> form) {
super(HealthConstants.THREAD_DUMP_ACTION, Model.of("Thread dump"));
imageName = "thread_dump.gif";
setEnabled(false);
modal = new ModalWindow("health.threaddump.dialog");
form.add(modal);
}
@Override
public void onClick(final AjaxRequestTarget target) {
if (debugEnabled) log.debug("clicked on thread dump");
final JPPFWebSession session = JPPFWebSession.get();
final TableTreeData data = session.getHealthData();
final List<DefaultMutableTreeNode> selectedNodes = data.getSelectedTreeNodes();
if (!selectedNodes.isEmpty()) {
final DefaultMutableTreeNode treeNode = selectedNodes.get(0);
final AbstractTopologyComponent comp = (AbstractTopologyComponent) treeNode.getUserObject();
final Locale locale = Session.get().getLocale();
final String title = HealthUtils.getThreadDumpTitle(comp, locale);
final StringBuilder html = new StringBuilder();
try {
final ThreadDump info = HealthUtils.retrieveThreadDump(comp);
if (info == null) html.append(HealthUtils.localizeThreadDumpInfo("threaddump.info_not_found", locale));
else html.append(HTMLThreadDumpWriter.printToString(info, title, false, 10));
} catch(final Exception e) {
html.append(ExceptionUtils.getStackTrace(e).replace("\n", "<br>"));
}
//if (debugEnabled) log.debug("html = {}", html);
modal.setPageCreator(new PageCreator(html.toString()));
stopRefreshTimer(target);
addTableTreeToTarget(target);
modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
@Override
public void onClose(final AjaxRequestTarget target) {
restartRefreshTimer(target);
}
});
modal.show(target);
}
}
/** */
private static class PageCreator implements ModalWindow.PageCreator {
/** */
private transient final String html;
/**
* @param html .
*/
public PageCreator(final String html) {
this.html = html;
}
@Override
public Page createPage() {
return new ThreadDumpPage(html);
}
}
}
|
Python | UTF-8 | 3,604 | 2.984375 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
""" Sentiment Analysis using PTT movie articles """
import logging
import numpy as np
from random import shuffle
import sys
from time import time
import matplotlib.pyplot as plt
from glob import glob
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn import metrics
jieba.load_userdict("/Users/mac/projects/ptt-sentiment-analysis/emotion_classifier/data/dict.txt.big")
def preprocess_textfiles(src_txt):
with open(src_txt, 'r') as reader:
text_lines = reader.readlines()
all_words = ""
for text in text_lines:
word_list = jieba.cut(text, cut_all=False)
words = " ".join(word_list)
all_words = all_words + words
return all_words
def make_data_and_label(pos_data, neg_data):
data = []
label = []
for textfile in pos_data:
data.append(preprocess_textfiles(textfile))
label.append('pos')
for textfile in neg_data:
data.append(preprocess_textfiles(textfile))
label.append('neg')
return data, label
def sentiment_analyse(sklearn_pipeline, text, ispath=False):
if ispath:
words = preprocess_textfiles(text)
else:
word_list = jieba.cut(text, cut_all=False)
words = " ".join(word_list)
pred = sklearn_pipeline.predict([words])
return pred[0]
model_path = "./model/tfidf_svm-mk1.joblib"
pos_files = glob("/Users/mac/projects/ptt-comment-spider/egs/movie_posneg/data/positives/*.txt")
neg_files = glob("/Users/mac/projects/ptt-comment-spider/egs/movie_posneg/data/negatives/*.txt")
if __name__ == "__main__":
print()
print("Preprocessing raw data ...")
print("---"*10)
shuffle(pos_files)
shuffle(neg_files)
print("Splitting data to train/validate/test sets ...")
pos_train = pos_files[0:int(0.8*len(pos_files))]
pos_validate = pos_files[int(0.8*len(pos_files)):int(0.9*len(pos_files))]
pos_test = pos_files[int(0.9*len(pos_files)):]
neg_train = neg_files[0:int(0.8*len(neg_files))]
neg_validate = neg_files[int(0.8*len(neg_files)):int(0.9*len(neg_files))]
neg_test = neg_files[int(0.9*len(neg_files)):]
print("Number of positive data (train/validate/test):", len(pos_train), len(pos_validate), len(pos_test))
print("Number of negative data (train/validate/test):", len(neg_train), len(neg_validate), len(neg_test))
data_train, y_train = make_data_and_label(pos_train, neg_train)
data_validate, y_validate = make_data_and_label(pos_validate, neg_validate)
data_test, y_test = make_data_and_label(pos_test, neg_test)
print()
print("Training Model ...")
print("---"*10)
sentiment_pipe = Pipeline([
('tfidf', TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words=None)),
('svm', LinearSVC(penalty="l1", dual=False, tol=1e-3))])
sentiment_pipe.fit(data_train, y_train)
pred_validate = sentiment_pipe.predict(data_validate)
score = metrics.accuracy_score(y_validate, pred_validate)
print("validation accuracy: %0.4f" % score)
print(metrics.confusion_matrix(y_validate, pred_validate))
print()
print("Saving model ...")
from joblib import dump, load
dump(sentiment_pipe, model_path)
print()
print("Testing ...")
print("---"*10)
new_pipe = load(model_path)
pred_test = new_pipe.predict(data_test)
score = metrics.accuracy_score(y_test, pred_test)
print("testing accuracy: %0.3f" % score)
print(metrics.confusion_matrix(y_test, pred_test))
|
C++ | UTF-8 | 1,361 | 2.875 | 3 | [] | no_license | //Codeforces - Nephren gives a riddle - 897C
#include <bits/stdc++.h>
using namespace std;
const int N = 100'010;
const string BASE = "What are you doing at the end of the world? Are you busy? Will you save us?";
const string s1 = "What are you doing while sending \"";
const string s2 = "\"? Are you busy? Will you send \"";
const string s3 = "\"?";
uint64_t len[N];
char query(int n, uint64_t k) {
if (n == 0) {
if (k <= BASE.size())
return BASE[k-1];
else
return '.';
}
if (k <= s1.size())
return s1[k-1];
else if (k <= s1.size() + len[n-1])
return query(n-1, k - s1.size());
else if (k <= s1.size() + len[n-1] + s2.size())
return s2[k - s1.size() - len[n-1] - 1];
else if (k <= s1.size() + len[n-1] + s2.size() + len[n-1])
return query(n-1, k - s1.size() - len[n-1] - s2.size());
else if (k <= s1.size() + len[n-1] + s2.size() + len[n-1] + s3.size())
return s3[k - s1.size() - len[n-1] - s2.size() - len[n-1] - 1];
else
return '.';
}
int main() {
ios::sync_with_stdio(false);
int q, n;
uint64_t k;
len[0] = 75;
for (int i = 1; i < N; i++)
len[i] = 1'000'000'000'000'000'001;
for (int i = 1; i < N; i++) {
len[i] = 34 + len[i-1] + 32 + len[i-1] + 2;
if (len[i] >= 1'000'000'000'000'000'001)
break;
}
cin >> q;
while (q--) {
cin >> n >> k;
cout << query(n, k);
}
cout << endl;
return 0;
}
|
C++ | UTF-8 | 4,875 | 3.015625 | 3 | [] | no_license | #include "procfs.h"
#include <dirent.h>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <cstdlib>
const static char* const PROCFS_PATH_SEPARATOR = "/";
Direntry::Direntry (struct dirent* de, Direntry* parent) :
m_parent (parent) {
m_pathName = 0;
m_de = new struct dirent;
memcpy (m_de, de, sizeof (*de));
if (parent) {
m_path = parent->path ();
if (m_path != PROCFS_PATH_SEPARATOR) {
m_path.append (PROCFS_PATH_SEPARATOR);
}
m_path.append (parent->name ());
} else {
m_path = PROCFS_PATH_SEPARATOR;
}
}
Direntry::~Direntry () {
delete m_de;
for (std::vector<Direntry*>::iterator it = m_column.begin () ; it != m_column.end (); ++it) {
delete *it;
}
if (m_pathName) {
delete [] m_pathName;
}
}
Direntry* Direntry::copy (Direntry* parent) {
struct dirent de;
memcpy (&de, m_de, sizeof (*m_de));
Direntry* cpy = new Direntry (&de, parent);
for (std::vector<Direntry*>::iterator it = m_column.begin (); it < m_column.end (); ++it) {
cpy->push_back ((*it)->copy (cpy));
}
return cpy;
}
bool Direntry::isDir () {
return DT_DIR == m_de->d_type;
}
int Direntry::type () {
return m_de->d_type;
}
char* Direntry::name () {
return m_de->d_name;
}
const char* Direntry::path () {
return m_path.c_str ();
}
const char* Direntry::pathName () {
static const char* sep = "/";
if (m_pathName == 0) {
int plen = strlen (path ());
int nlen = strlen (m_de->d_name);
m_pathName = new char [plen + nlen + 2];
char* ppn = m_pathName;
memcpy (ppn, path (), plen);
ppn += plen;
if (plen != 1) {
memcpy (ppn, sep, 1);
++ppn;
}
memcpy (ppn, m_de->d_name, nlen);
ppn += nlen;
*ppn = '\0';
}
return m_pathName;
}
Direntry* Direntry::parent () {
return m_parent;
}
Direntry* Direntry::at (int pos) {
if (pos >= m_column.size ()) {
return 0;
}
return m_column[pos];
}
int Direntry::row () {
int pos = 0;
if (m_parent) {
for (std::vector<Direntry*>::iterator it = m_parent->begin (); it != m_parent->end (); ++it) {
if ((*it) == this) {
break;
}
++pos;
}
}
return pos;
}
int Direntry::count () {
return m_column.size ();
}
bool Direntry::compare_dirent (Direntry* lhd, Direntry* rhd) {
if (lhd->isDir () && !rhd->isDir ()) {
return true;
}
if (rhd->isDir () && !lhd->isDir ()) {
return false;
}
if (isdigit (lhd->name ()[0])) {
if (!isdigit (rhd->name ()[0])) {
return true;
}
int l = strtol (lhd->name (), 0, 10);
int r = strtol (rhd->name (), 0, 10);
return l < r;
}
return strcmp (lhd->name (), rhd->name ()) < 0;
}
void Direntry::sort () {
std::sort (m_column.begin (), m_column.end (), compare_dirent);
}
std::vector<Direntry*>::iterator Direntry::insert (Direntry* entry, std::vector<Direntry*>::iterator iter) {
return m_column.insert (iter, entry);
}
std::vector<Direntry*>::iterator Direntry::erase (std::vector<Direntry*>::iterator iter) {
return m_column.erase (iter);
}
ProcFs::ProcFs ()
: m_de (0), m_last_err (0), m_last_error_level (PFE_NONE) {
m_dirp = opendir ("/proc");
if (m_dirp == 0) {
error (strerror (errno), PFE_FATAL);
} else {
struct dirent de;
strcpy (de.d_name, "proc");
de.d_type = DT_DIR;
m_de = new Direntry (&de);
readDir (m_dirp, m_de, true);
m_de->sort ();
}
}
ProcFs::~ProcFs () {
if (m_de) {
delete m_de;
}
if (m_dirp) {
closedir (m_dirp);
}
}
void ProcFs::error (char* err, ProcFsError level) {
if (m_last_err) {
delete m_last_err;
}
m_last_err = new char[strlen (err) + 1];
strcpy (m_last_err, err);
m_last_error_level = level;
}
void ProcFs::readDir (DIR* dir, Direntry* parent, bool close) {
struct dirent* nxt;
while ((nxt = readdir (dir))) {
if ((strcmp (nxt->d_name, ".") == 0) || (strcmp (nxt->d_name, "..") == 0)) continue;
Direntry* de = new Direntry (nxt, parent);
de->sort ();
parent->push_back (de);
if (de->isDir ()) {
std::string dp = parent->pathName ();
if (dp != PROCFS_PATH_SEPARATOR) {
dp.append (PROCFS_PATH_SEPARATOR);
}
dp.append (de->name ());
DIR* d = opendir (dp.c_str ());
if (d) {
readDir (d, de, true);
if (close) {
closedir (d);
}
}
}
}
}
|
Markdown | UTF-8 | 1,583 | 3.265625 | 3 | [] | no_license | # Getting-and-Cleaning-data-Project
This repository contains the final week project of Getting and Cleaning Data.
### DESCRIBING THE DATA
The data-set is basically consisting of an experiment that has been carried out with a group of 30 volunteers within an age bracket of 19-48 years.
Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING)
wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope,
3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz were observed. The experiments have been
video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets,
where 70% of the volunteers was selected for generating the training data and 30% the test data.
### CLEANING DATA
The script for cleaning and obtaining tidy data has been developed according to the instructions provided in the problem statement of the project.
### TIDY DATA-SET
A clean and tidy data-set has been generated based on the instructions of the problem statement of the project.
* Merge the training and the test sets to create one data set.
* Extract only the measurements on the mean and standard deviation for each measurement.
* Use descriptive activity names to name the activities in the data set
* Appropriately label the data set with descriptive variable names.
* From the data set in step 4, create a second, independent tidy data set with the average of each variable for each activity and each subject.
|
Python | UTF-8 | 932 | 3.03125 | 3 | [] | no_license | from auth import authenticate
from datetime import datetime
album = None # You can also enter an album ID here
image_path = 'static/images/daisy.jpg'
def upload_image(client):
"""
Uploads an image to imgur.
"""
# Here's the metadata for the upload. All of these are optional, including
# this config dict itself.
config = {
'album': album,
'name': 'A lonely pink daisy',
'title': 'A pink daisy',
'description': 'When this flower sprouted: {0}'.format(datetime.now())
}
print("Uploading image...")
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
return image
# To run this as a standalone script
if __name__ == "__main__":
# Authenticate
client = authenticate()
image = upload_image(client)
print("Image was posted!")
print("You can find the image here: {0}".format(image['link']))
|
Markdown | UTF-8 | 297 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | ## Size Enum
### Import
```
from ArchicadDG.Font import Size
```
## Example
```
from ArchicadDG import *
ft1=Font.Large
ft2=Font.Size.ExtraSmall
```
### Values
* **Large**:Large font size.
* **Small**:Small font size.
* **ExtraSmall**:Extrasmall font size.
* **DefaultSize**:Default font size. |
PHP | UTF-8 | 65 | 2.765625 | 3 | [] | no_license | <?php
$arr = [1,2,3,4,5,6,7,8,9,10];
echo(array_product($arr)); |
Python | UTF-8 | 4,403 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env python
import twitter
# import apiKey
from resources import apiKey
from _datetime import datetime, timedelta
from newsapi import NewsApiClient
import pyEX
import json
import requests
import csv
import ml.classifier
########
# init API key Settings
########
# init Twitter API keys
api = twitter.Api(consumer_key=apiKey.twitter_consumerKey,
consumer_secret=apiKey.twitter_consumerSecret,
access_token_key=apiKey.twitter_accessToken,
access_token_secret=apiKey.twitter_accessSecret
)
# init NewsAPI API keys
newsapi = NewsApiClient(api_key=apiKey.newsAPI_Key)
# Basic search for Twitter tweets, returns 10 tweets
def twitterBasicSearch(query):
queryString = "q={}&result_type=recent&count=10".format(query)
# queryString = f"q={query}&result_type=recent&count=10&lang=en"
results = api.GetSearch(raw_query=queryString)
return results
# print([r for r in twitterBasicSearch(query="Microsoft")])
# Advanced search, allowing for query, result_type and count modifications
def twitterAdvancedSearch(query, resultType, count):
queryString = "q={}&result_type={}&count={}&lang=en".format(query, resultType, count)
results = api.GetSearch(raw_query=queryString)
# print([t.text for t in results])
tweets_from_API = [t.text for t in results]
print(tweets_from_API)
classification = [];
if tweets_from_API:
classification = ml.classifier.classifier(tweets_from_API)
for i in range(0, len(classification)):
results[i].classification = classification[i][0]
return results
# print(twitterAdvancedSearch(query="AAPL", resultType="popular", count=10))
# print([r for r in twitterAdvancedSearch(query="Microsoft",
# resultType="recent",
# count="5")])
def twitterEmbed(status_id, url):
result = api.GetStatusOembed(status_id=status_id, url=url, hide_media=True)
return result
# print(twitterEmbed(status_id=1037962403370225664, url="https://t.co/qvUU30HkJM"))
# print(twitterEmbed(status_id=1041699384151498754, url="https://t.co/bwQz4nOJHd"))
# Everything search, gets the last 2 weeks of most recent news
def newsApiEverythingSearch(query):
date_fortnightAgo = datetime.now() - timedelta(days=14)
date_fortnightAgo = date_fortnightAgo.strftime("%Y-%m-%d")
date_now = datetime.now().strftime("%Y-%m-%d")
results = newsapi.get_everything(q=query,
language="en",
sort_by="relevancy",
from_param=date_fortnightAgo,
to=date_now)
# print(results.get('articles'))
# print(newsApiEverythingSearch(query="Apple"))
def pyEXTest(query):
result = pyEX.ohlc(query);
return result
# print(pyEXTest("AAPL"))
def pyEXStockInfo(query):
queryResult = pyEX.ohlc(query)
currentPrice = pyEX.price(query)
company = pyEX.company(query)
if (queryResult.get('open').get('time') >= queryResult.get('close').get('time')):
queryResult.update({'live': True})
if (queryResult.get('open').get('time') < queryResult.get('close').get('time')):
queryResult.update({'live': False})
queryResult.update({'currentPrice': currentPrice})
queryResult.update({'companyDetails': company})
return queryResult
# print(pyEXStockInfo("AAPL"))
def pyEXNews(query):
newsResult = pyEX.news(query, count=10)
return newsResult
# print(pyEXNews("AAPL"))
def pyEXLivePrice(query):
livePrice = pyEX.price(query)
return livePrice
def pyEXChart(query):
# chartData = pyEX.chart(symbol=query, timeframe='6m')
chartData = pyEX.chart(symbol=query)
price = []
date = []
for x in chartData:
price.append(x['close'])
date.append(x['date'])
return price, date
# pyEXChart("AAPL")
def iEXManualRequest(query):
print("accessing endpoint")
payload = {'symbols': query, 'types': 'ohlc,price,news,company,chart'}
r = requests.get("https://api.iextrading.com/1.0/stock/market/batch", params=payload)
print(r.url)
price = r.json()[query]["price"]
close = []
date = []
for x in r.json()[query]["chart"]:
close.append(x['close'])
date.append(x['date'])
ohlc = r.json()[query]["ohlc"]
if (ohlc["open"]["time"] >= ohlc["close"]["time"]):
ohlc.update({'live': True})
if (ohlc["open"]["time"] < ohlc["close"]["time"]):
ohlc.update({'live': False})
company = r.json()[query]["company"]
news = r.json()[query]["news"]
print(datetime.now())
return price, close, date, ohlc, company, news
# iEXManualRequest("AAPL");
|
JavaScript | UTF-8 | 3,970 | 2.515625 | 3 | [
"MIT"
] | permissive |
$(document).ready(function () {
//on navigation between upper links
$('.mainNavLink').click(function (e) {
e.preventDefault();
$('.main-navigationContainer .main-navigation li').removeClass('active');
$(this).parent().addClass("active");
var id = $(this).attr('href');
$('html,body').animate({
scrollTop: $(id).offset().top
}, 800);
});
//on navigation between works
$('.worksControl').on("click", function (e) {
var x = $(this);
e.preventDefault();
if (x.hasClass("controlActive")) {
return false;
}
$('.worksControl').removeClass('controlActive');
$(this).addClass("controlActive");
idName = $(this).attr("href");
$(".worksItems").fadeOut();
$(".worksTabs").find('#' + idName).fadeIn();
});
//slick slider on features
$('.featuresContent').slick({
dots: true,
infinite: true,
rtl: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
arrows: false,
draggable: false,
autoplaySpeed: 5000,
responsive: [
{
breakpoint: 1200,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 991,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
//my team slider
$('.myTeamContent').slick({
dots: true,
infinite: true,
rtl: true,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
autoplay: false,
arrows: false,
draggable: false,
autoplaySpeed: 5000,
responsive: [
{
breakpoint: 1200,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 991,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 767,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
//hover on my team images
$(".memberImg").hover(function () {
$(this).children('.memberOnHover').fadeIn();
$(this).siblings('.memberName').css("color", "#1EA78D");
}, function () {
$(this).children('.memberOnHover').fadeOut();
$(this).siblings('.memberName').css("color", "#062033");
});
google.maps.event.addDomListener(window, 'load', initialize);
});
//to adjust nav on scroll
$(window).scroll(function () {
if ($(window).scrollTop() > 200) {
$('.main-navigationContainer').addClass("removeTransparency");
}
else {
$('.main-navigationContainer').removeClass("removeTransparency");
}
}
);
//google map
function initialize() {
var myLatlng = new google.maps.LatLng(31.1980450, 29.9191707);
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var iconBase = '../assets/images/';
// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Hello World!",
icon: iconBase + 'map-cursor.png'
});
} |
Markdown | UTF-8 | 2,431 | 3.234375 | 3 | [] | no_license | # RockScissorsPaper
Добавте код в редактор и запустите. Игра Камень-Ножницы-Бумага
import random
hum_ch = True
random_choice = ['r', 's', 'p']
while hum_ch:
print('Камень - Ножныци - Бумага')
print('Камень - Rock - R \nНожницы - Scissors - S \nБумага - Paper - P')
computer_random = random.choice(random_choice)
#print(computer_random)
human_random = input('R или S или P - ').lower()
if human_random not in ['r', 's', 'p']:
print('------------')
print('Неверный ввод. Попробуйте следовать инструкции.')
print('------------')
continue
if computer_random == human_random:
print('Вы равны по силе!')
if computer_random == 'r' and human_random == 's': #камень-ножницы
print('Камень бьёт ножницы - Вы проиграли')
elif computer_random == 's' and human_random == 'r':
print('Камень бьёт ножницы - Вы выиграли')
if computer_random == 's' and human_random == 'p': #ножницы-бумага
print('Ножницы режут бумагу - Вы проиграли')
elif computer_random == 'p' and human_random == 's':
print('Ножницы режут бумагу - Вы выиграли')
if computer_random == 'p' and human_random == 'r': #бумага-камень
print('Бумага оборачивает камень - Вы проиграли')
elif computer_random == 'r' and human_random == 'p':
print('Бумага оборачивает камень - выиграли')
print('Хотите ещё?')
human_answer = True
while human_answer:
human_choice = input('Да(Y) или Нет(N)').lower()
if human_choice not in ['y', 'n']:
print('------------')
print('Неверный ввод. Попробуйте следовать инструкции')
print('------------')
continue
else:
break
if human_choice == 'y':
print('----------\n----------')
continue
if human_choice == 'n':
break
print('Спасибо за игру!')
|
Java | UTF-8 | 5,951 | 2.484375 | 2 | [] | no_license | package com.example.logincadastro;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.logincadastro.model.MyCountDownTimer;
// nessa interface será apresentado 2 lógica:
// contagem de tempo até a chegada do veículo e conexão bluetooth bem sucedida
// a outra será a computação do preço do veículo/Hora
public class MenuLocacao extends AppCompatActivity {
public static int RETORNO_APLICACAO = 1;// Constante de request Code
private boolean flag = false;// Será responsável por indicar o retorno
// E indicar que essa não é a primeira vez em que o usuário está entrando nessa Atividade
private MyCountDownTimer timerChegarAoVeiculo;
private TextView txvCronometro, txvNomeVeiculo, txvSaldoTotal, txv2, txv1;
private Button btnConectar, btnDevolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_locacao);
// Escreve o nome do veículo escolhido
txv1 = (TextView) findViewById(R.id.txv1);
txv2 = (TextView) findViewById(R.id.txv2);
txvSaldoTotal = (TextView) findViewById(R.id.txvSaldoTotal);
btnConectar = (Button)findViewById(R.id.btnConectar);
btnDevolver = (Button)findViewById(R.id.btnDevolver);
// Componentes dde crompra ainda invisíveis
txv2.setVisibility(View.GONE);
txvSaldoTotal.setVisibility(View.GONE);
btnDevolver.setVisibility(View.GONE);
Intent recebeString = getIntent();
txvNomeVeiculo = (TextView) findViewById(R.id.txvNomeVeiculo);
txvNomeVeiculo.setText(recebeString.getStringExtra("nomeVeiculo"));
}
// O método onResume é o instante em que uma atividade se torna visível na IU
@Override
public void onResume(){
super.onResume();
// Primeira entrada do usuário
if(!flag ) {
txvCronometro = (TextView) findViewById(R.id.txvCronometro);
//String cronometro = txvCronometro.getText().toString();
//long l = Long.parseLong(cronometro);
timerChegarAoVeiculo = new MyCountDownTimer(this, txvCronometro, 30 * 1000, 1000);
// Para teste do sistema, a chegada ao
// Veículo deve ser realizada em até 30 seg.
timerChegarAoVeiculo.start();
/*if(l == 0){
Toast.makeText(getApplicationContext(), "Tempo Encerrado",Toast.LENGTH_SHORT).show();
finish();
}*/
}
else{
// Representa o retorno para pagamento
Intent recebeInteiro = getIntent();
// Calculo baseado nas horas definidas
int recebido = 0;
recebido = recebeInteiro.getIntExtra("horasSelecionadas",recebido);
int calculoTotal = recebido*30;
Log.i("script",""+recebido);
txvSaldoTotal.setText((calculoTotal)+",00R$");
}
}
@Override
public void onDestroy() {
super.onDestroy();
//Ou seja, caso a activity se encerre por algum motivo, o contador para
if(timerChegarAoVeiculo != null){
timerChegarAoVeiculo.cancel();
}
}
// evento de botão
public void conectarVeiculo(View view){
try {
// interrompe a contagem para chegar ao veículo, significando que o usuário está proximo ao carro
if (timerChegarAoVeiculo != null) {
timerChegarAoVeiculo.cancel();
Toast.makeText(this, "tentatíva de conexão iniciáda", Toast.LENGTH_SHORT).show();
Log.i("Timer", "A contagem timerChegarAoVeiculo foi encerrada com sucessor");
}
Intent intentConectorBluetooth = new Intent(this, InterfaceConexao.class);
startActivityForResult(intentConectorBluetooth, RETORNO_APLICACAO);
}catch (Exception e){
e.printStackTrace();
}
}
public void devolverVeiculo(View view){
Toast.makeText(this, "Veículo devolvido com sucesso", Toast.LENGTH_SHORT).show();
finish();
}
// Resultado de uma conexão bem sucedida
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent dado){
if(requestCode == RETORNO_APLICACAO){
if (resultCode == RESULT_OK){
// Quando a conectividade for estabelecida a flag é setada para o retorno
Toast.makeText(getApplicationContext(), "Obrigado Por Utilizar Nossos Serviços",Toast.LENGTH_SHORT).show();
// Antigo componente de contador Some
txv1.setVisibility(View.GONE);
txvCronometro.setVisibility(View.GONE);
btnConectar.setVisibility(View.GONE);
// Àrea de cobrança aparece
txvSaldoTotal.setVisibility(View.VISIBLE);
txv2.setVisibility(View.VISIBLE);
btnDevolver.setVisibility(View.VISIBLE);
flag = true;
}
else{
// Situação onde o usuário não chegou no veículo ou não estabeleceu conexão
//Senão ela permanece em false, e o usuário será forçado a retornar a tela de aplicação
Toast.makeText(getApplicationContext(), "Conexão Com o Veículo não Estabelecida",Toast.LENGTH_SHORT).show();
flag = false;
Intent retornaTelaAplicacao = new Intent(this, SelecaoVeiculo.class);
retornaTelaAplicacao.addFlags(retornaTelaAplicacao.FLAG_ACTIVITY_CLEAR_TOP);// Atividade no topo da pilha
startActivity(retornaTelaAplicacao);
}
}
}
}
|
Java | UTF-8 | 535 | 2.4375 | 2 | [] | no_license | package Fenetres;
import javax.swing.JFrame;
import LDVH.Livre;
public class Menu extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public PanelMenu p;
public Livre l;
public Menu() {
this.setTitle("LDVH");
this.setSize(1024,768 );
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
p = new PanelMenu(this);
this.setContentPane(p);
this.setVisible(true);
}
public void AjouterLivre(String s){
l = new Livre(s);
}
}
|
C++ | UTF-8 | 14,701 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | // -*- C++ -*-
// A basic LSTM implementation in C++. All you should need is clstm.cc and
// clstm.h. Library dependencies are limited to a small subset of STL and
// Eigen/Dense
#ifndef ocropus_lstm_
#define ocropus_lstm_
#include <vector>
#include <string>
#include <iostream>
#include <typeinfo>
#include <memory>
#include <map>
#include <Eigen/Dense>
#include <random>
namespace ocropus {
using std::string;
using std::vector;
using std::map;
using std::shared_ptr;
using std::unique_ptr;
using std::function;
void throwf(const char *format, ...);
extern char exception_message[256];
#ifdef LSTM_DOUBLE
typedef double Float;
typedef Eigen::VectorXi iVec;
typedef Eigen::VectorXd Vec;
typedef Eigen::MatrixXd Mat;
#else
typedef float Float;
typedef Eigen::VectorXi iVec;
typedef Eigen::VectorXf Vec;
typedef Eigen::MatrixXf Mat;
#endif
// These macros define the major matrix operations used
// in CLSTM. They are here for eventually converting the
// inner loops of CLSTM from Eigen::Matrix to Eigen::Tensor
// (which uses different and incompatible notation)
#define DOT(M, V) ((M) *(V))
#define MATMUL(A, B) ((A) *(B))
#define MATMUL_TR(A, B) ((A).transpose() * (B))
#define MATMUL_RT(A, B) ((A) *(B).transpose())
#define EMUL(U, V) ((U).array() * (V).array()).matrix()
#define EMULV(U, V) ((U).array() * (V).array()).matrix()
#define TRANPOSE(U) ((U).transpose())
#define ROWS(A) (A).rows()
#define COLS(A) (A).cols()
#define COL(A, b) (A).col(b)
#define MAPFUN(M, F) ((M).unaryExpr(ptr_fun(F)))
#define MAPFUNC(M, F) ((M).unaryExpr(F))
#define SUMREDUCE(M) float(M.sum())
#define BLOCK(A, i, j, n, m) (A).block(i, j, n, m)
inline void ADDCOLS(Mat &m, Vec &v) {
for (int i = 0; i < COLS(m); i++)
for (int j = 0; j < ROWS(m); j++)
m(i, j) += v(j);
}
inline void randgauss(Mat &m) {
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<double> randn;
for (int i = 0; i < ROWS(m); i++)
for (int j = 0; j < COLS(m); j++)
m(i, j) = randn(gen);
}
inline void randgauss(Vec &v) {
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<double> randn;
for (int i = 0; i < ROWS(v); i++)
v(i) = randn(gen);
}
inline void randinit(Mat &m, float s, const string mode="unif") {
if (mode == "unif") {
m.setRandom();
m = (2*s*m).array()-s;
} else if (mode == "pos") {
m.setRandom();
m = m*s;
} else if (mode == "normal") {
randgauss(m);
m = m*s;
}
}
inline void randinit(Vec &m, float s, const string mode="unif") {
if (mode == "unif") {
m.setRandom();
m = (2*s*m).array()-s;
} else if (mode == "pos") {
m.setRandom();
m = m*s;
} else if (mode == "normal") {
randgauss(m);
m = m*s;
}
}
inline void randinit(Mat &m, int no, int ni, float s, const string mode="unif") {
m.resize(no, ni);
randinit(m, s, mode);
}
inline void randinit(Vec &m, int no, float s, const string mode="unif") {
m.resize(no);
randinit(m, s, mode);
}
inline void zeroinit(Mat &m, int no, int ni) {
m.resize(no, ni);
m.setZero();
}
inline void zeroinit(Vec &m, int no) {
m.resize(no);
m.setZero();
}
typedef vector<Mat> Sequence;
inline void resize(Sequence &seq, int nsteps, int dims, int bs) {
seq.resize(nsteps);
for (int i=0; i<nsteps; i++) seq[i].resize(dims,bs);
}
inline int size(Sequence &seq, int dim) {
if (dim==0) return seq.size();
if (dim==1) return seq[0].rows();
if (dim==2) return seq[0].cols();
THROW("bad dim ins size");
}
typedef vector<int> Classes;
typedef vector<Classes> BatchClasses;
inline Vec timeslice(const Sequence &s, int i, int b=0) {
Vec result(s.size());
for (int t = 0; t < s.size(); t++)
result[t] = s[t](i, b);
return result;
}
struct VecMat {
Vec *vec = 0;
Mat *mat = 0;
VecMat() {
}
VecMat(Vec *vec) {
this->vec = vec;
}
VecMat(Mat *mat) {
this->mat = mat;
}
};
struct ITrainable {
virtual ~ITrainable() {
}
string name = "";
virtual const char *kind() = 0;
// Learning rate and momentum used for training.
Float learning_rate = 1e-4;
Float momentum = 0.9;
enum Normalization : int {
NORM_NONE, NORM_LEN, NORM_BATCH, NORM_DFLT = NORM_NONE,
} normalization = NORM_DFLT;
// The attributes array contains parameters for constructing the
// network, as well as information necessary for loading and saving
// networks.
map<string, string> attributes;
string attr(string key, string dflt="") {
auto it = attributes.find(key);
if (it == attributes.end()) return dflt;
return it->second;
}
int iattr(string key, int dflt=-1) {
auto it = attributes.find(key);
if (it == attributes.end()) return dflt;
return std::stoi(it->second);
}
double dattr(string key, double dflt=0.0) {
auto it = attributes.find(key);
if (it == attributes.end()) return dflt;
return std::stof(it->second);
}
int irequire(string key) {
auto it = attributes.find(key);
if (it == attributes.end()) {
sprintf(exception_message, "missing parameter: %s", key.c_str());
THROW(exception_message);
}
return std::stoi(it->second);
}
void set(string key, string value) {
attributes[key] = value;
}
void set(string key, int value) {
attributes[key] = std::to_string(value);
}
void set(string key, double value) {
attributes[key] = std::to_string(value);
}
// Learning rates
virtual void setLearningRate(Float lr, Float momentum) = 0;
// Main methods for forward and backward propagation
// of activations.
virtual void forward() = 0;
virtual void backward() = 0;
virtual void update() = 0;
virtual int idepth() {
return -9999;
}
virtual int odepth() {
return -9999;
}
virtual void initialize() {
// this gets initialization parameters
// out of the attributes array
}
// These are convenience functions for initialization
virtual void init(int no, int ni) final {
set("ninput", ni);
set("noutput", no);
initialize();
}
virtual void init(int no, int nh, int ni) final {
set("ninput", ni);
set("nhidden", nh);
set("noutput", no);
initialize();
}
virtual void init(int no, int nh2, int nh, int ni) final {
set("ninput", ni);
set("nhidden", nh);
set("nhidden2", nh2);
set("noutput", no);
initialize();
}
};
struct INetwork;
typedef shared_ptr<INetwork> Network;
struct INetwork : virtual ITrainable {
// Networks have input and output "ports" for sequences
// and derivatives. These are propagated in forward()
// and backward() methods.
Sequence inputs, d_inputs;
Sequence outputs, d_outputs;
// Some networks have subnetworks. They should be
// stored in the `sub` vector. That way, functions
// like `save` can automatically traverse the tree
// of networks. Together with the `name` field,
// this forms a hierarchical namespace of networks.
vector<Network > sub;
// Data for encoding/decoding input/output strings.
vector<int> codec;
vector<int> icodec;
unique_ptr<map<int, int> > encoder; // cached
unique_ptr<map<int, int> > iencoder; // cached
void makeEncoders();
std::wstring decode(Classes &cs);
std::wstring idecode(Classes &cs);
void encode(Classes &cs, const std::wstring &s);
void iencode(Classes &cs, const std::wstring &s);
// Parameters specific to softmax.
Float softmax_floor = 1e-5;
bool softmax_accel = false;
virtual ~INetwork() {
}
std::function<void(INetwork*)> initializer = [] (INetwork*){};
virtual void initialize() {
// this gets initialization parameters
// out of the attributes array
initializer(this);
}
// Expected number of input/output features.
virtual int ninput() {
return -999999;
}
virtual int noutput() {
return -999999;
}
// Add a network as a subnetwork.
virtual void add(Network net) {
sub.push_back(net);
}
// Hooks to iterate over the weights and states of this network.
typedef function<void (const string &, VecMat, VecMat)> WeightFun;
typedef function<void (const string &, Sequence *)> StateFun;
virtual void myweights(const string &prefix, WeightFun f) {
}
virtual void mystates(const string &prefix, StateFun f) {
}
// Hooks executed prior to saving and after loading.
// Loading iterates over the weights with the `weights`
// methods and restores only the weights. `postLoad`
// allows classes to update other internal state that
// depends on matrix size.
virtual void preSave() {
}
virtual void postLoad() {
}
// Set the learning rate for this network and all subnetworks.
virtual void setLearningRate(Float lr, Float momentum) {
this->learning_rate = lr;
this->momentum = momentum;
for (int i = 0; i < sub.size(); i++)
sub[i]->setLearningRate(lr, momentum);
}
void info(string prefix);
void weights(const string &prefix, WeightFun f);
void states(const string &prefix, StateFun f);
void networks(const string &prefix, function<void (string, INetwork*)>);
Sequence *getState(string name);
// special method for LSTM and similar networks, returning the
// primary internal state sequence
Sequence *getState() {
THROW("unimplemented");
};
void save(const char *fname);
void load(const char *fname);
};
// standard layer types
INetwork *make_SigmoidLayer();
INetwork *make_SoftmaxLayer();
INetwork *make_ReluLayer();
INetwork *make_Stacked();
INetwork *make_Reversed();
INetwork *make_Parallel();
INetwork *make_LSTM();
INetwork *make_NPLSTM();
INetwork *make_BidiLayer();
// setting inputs and outputs
void set_inputs(INetwork *net, Sequence &inputs);
void set_targets(INetwork *net, Sequence &targets);
void set_targets_accelerated(INetwork *net, Sequence &targets);
void set_classes(INetwork *net, Classes &classes);
void set_classes(INetwork *net, BatchClasses &classes);
// single sequence training functions
void train(INetwork *net, Sequence &xs, Sequence &targets);
void ctrain(INetwork *net, Sequence &xs, Classes &cs);
void ctrain_accelerated(INetwork *net, Sequence &xs, Classes &cs, Float lo=1e-5);
void cpred(INetwork *net, Classes &preds, Sequence &xs);
void mktargets(Sequence &seq, Classes &targets, int ndim);
// batch training functions
void ctrain(INetwork *net, Sequence &xs, BatchClasses &cs);
void ctrain_accelerated(INetwork *net, Sequence &xs, BatchClasses &cs, Float lo=1e-5);
void cpred(INetwork *net, BatchClasses &preds, Sequence &xs);
void mktargets(Sequence &seq, BatchClasses &targets, int ndim);
// instantiating layers and networks
typedef std::function<INetwork*(void)> ILayerFactory;
extern map<string, ILayerFactory> layer_factories;
Network make_layer(const string &kind);
struct String : public std::string {
String() {
}
String(const char *s) : std::string(s) {
}
String(const std::string &s) : std::string(s) {
}
String(int x) : std::string(std::to_string(x)) {
}
String(double x) : std::string(std::to_string(x)) {
}
double operator+() { return atof(this->c_str()); }
operator int() {
return atoi(this->c_str());
}
operator double() {
return atof(this->c_str());
}
};
struct Assoc : std::map<std::string, String> {
using std::map<std::string, String>::map;
Assoc(const string &s);
String at(const std::string &key) const {
auto it = this->find(key);
if (it == this->end()) throwf("%s: key not found", key.c_str());
return it->second;
}
};
typedef std::vector<Network> Networks;
Network layer(
const string &kind,
int ninput, int noutput,
const Assoc &args,
const Networks &subs
);
typedef std::function<Network(const Assoc &)> INetworkFactory;
extern map<string, INetworkFactory> network_factories;
Network make_net(const string &kind, const Assoc ¶ms);
Network make_net_init(const string &kind, const std::string ¶ms);
// new, proto-based I/O
Network proto_clone_net(INetwork *net);
void debug_as_proto(INetwork *net, bool do_weights=false);
void write_as_proto(std::ostream &output, INetwork *net);
void save_as_proto(const string &fname, INetwork *net);
Network load_as_proto(const string &fname);
inline void save_net(const string &file, Network net) {
save_as_proto(file, net.get());
}
inline Network load_net(const string &file) {
return load_as_proto(file);
}
// training with CTC
void forward_algorithm(Mat &lr, Mat &lmatch, double skip=-5.0);
void forwardbackward(Mat &both, Mat &lmatch);
void ctc_align_targets(Sequence &posteriors, Sequence &outputs, Sequence &targets);
void ctc_align_targets(Sequence &posteriors, Sequence &outputs, Classes &targets);
void trivial_decode(Classes &cs, Sequence &outputs, int batch=0);
void ctc_train(INetwork *net, Sequence &xs, Sequence &targets);
void ctc_train(INetwork *net, Sequence &xs, Classes &targets);
void ctc_train(INetwork *net, Sequence &xs, BatchClasses &targets);
// DEPRECATED
extern Mat debugmat;
// loading and saving networks (using HDF5)
void load_attributes(map<string, string> &attrs, const string &file);
}
namespace {
inline bool anynan(ocropus::Sequence &a) {
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < ROWS(a[i]); j++) {
for (int k = 0; k < COLS(a[i]); k++) {
if (isnan(a[i](j, k))) return true;
}
}
}
return false;
}
template <class A, class B>
double levenshtein(A &a, B &b) {
using std::vector;
int n = a.size();
int m = b.size();
if (n > m) return levenshtein(b, a);
vector<double> current(n+1);
vector<double> previous(n+1);
for (int k = 0; k < current.size(); k++) current[k] = k;
for (int i = 1; i <= m; i++) {
previous = current;
for (int k = 0; k < current.size(); k++) current[k] = 0;
current[0] = i;
for (int j = 1; j <= n; j++) {
double add = previous[j]+1;
double del = current[j-1]+1;
double change = previous[j-1];
if (a[j-1] != b[i-1]) change = change+1;
current[j] = fmin(fmin(add, del), change);
}
}
return current[n];
}
}
#endif
|
Python | UTF-8 | 604 | 2.90625 | 3 | [] | no_license | import tcod as libtcod
def render_all(con, entities, screen_width, screen_height):
for entity in entities:
draw_entity(con, entity)
libtcod.console_blit(con, 0, 0, screen_width, screen_height, 0, 0, 0)
def clear_all(con, entities):
for entity in entities:
clear_entity(con, entity)
def draw_entity(con, entity):
libtcod.console_set_default_foreground(con, entity.color)
libtcod.console_put_char(con, entity.x, entity.y, entity.char, libtcod.BKGND_NONE)
def clear_entity(con, entity):
libtcod.console_put_char(con, entity.x, entity.y, ' ', libtcod.BKGND_NONE)
|
Java | UTF-8 | 762 | 3.125 | 3 | [] | no_license | package example1;
import java.util.List;
import example1.Book.Chapter;
public class Mainclass {
public static void main(String[] args) {
Chapter introChapter = new Book().new Chapter(1, "Alice");
Book book = new Book("Alice is in Wonderland", 2007, introChapter);
book.setIntroPage();
FirstPage fp = new FirstPage();
book.addPage(fp);
book.addPage(new Page() {
private String color = "Black";
@Override
public void getContent() {
System.out.println("Color is " + color);
System.out.println("Second page");
}
});
book.setAuthor(new Author() {
@Override
public void getInfo() {
System.out.println("Primary author: Some author");
}
});
book.getInfo();
}
} |
C | UTF-8 | 2,779 | 2.578125 | 3 | [
"Apache-2.0",
"SHL-0.51",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (C) 2018 ETH Zurich and University of Bologna
*
* 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.
*/
/*
* Authors: Germain Haugou, ETH (germain.haugou@iis.ee.ethz.ch)
*/
#include "tinyprintf.h"
#include <stdarg.h>
#include "hal/pulp.h"
#include <stdint.h>
static int errno;
int *__errno() { return &errno; }
int strcmp(const char *s1, const char *s2)
{
while (*s1 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
return (*(unsigned char *) s1) - (*(unsigned char *) s2);
}
int strncmp(const char *s1, const char *s2, size_t n)
{
if (n == 0)
return 0;
while (n-- != 0 && *s1 == *s2)
{
if (n == 0 || *s1 == '\0')
break;
s1++;
s2++;
}
return (*(unsigned char *) s1) - (*(unsigned char *) s2);
}
size_t strlen(const char *str)
{
const char *start = str;
while (*str)
str++;
return str - start;
}
int memcmp(const void *m1, const void *m2, size_t n)
{
unsigned char *s1 = (unsigned char *) m1;
unsigned char *s2 = (unsigned char *) m2;
while (n--)
{
if (*s1 != *s2)
{
return *s1 - *s2;
}
s1++;
s2++;
}
return 0;
}
void *memset(void *m, int c, size_t n)
{
char *s = (char *)m;
while (n--)
*s++ = (char) c;
return m;
}
void *memcpy(void *dst0, const void *src0, size_t len0)
{
char *dst = (char *) dst0;
char *src = (char *) src0;
void *save = dst0;
while (len0--)
{
*dst++ = *src++;
}
return save;
}
static void __rt_putc_stdout(char c)
{
//*(uint32_t*)(long)(0x1A104000 + (hal_core_id() << 3) + (hal_cluster_id() << 7)) = c;
*(uint32_t*)(long)(0x1A104000) = c;
// Poll while microblaze debug module's FIFo is full
//while (pulp_read8(ARCHI_STDOUT_ADDR + 0x8) & 0x8);
//*(uint32_t *)(long)(ARCHI_STDOUT_ADDR + STDOUT_PUTC_OFFSET + 0x4) = c;
}
static void tfp_putc(void *data, char c) {
__rt_putc_stdout(c);
}
int printf(const char *fmt, ...) {
va_list va;
va_start(va, fmt);
tfp_format(NULL, tfp_putc, fmt, va);
va_end(va);
return 0;
}
int puts(const char *s) {
char c;
do {
c = *s;
if (c == 0) {
tfp_putc(NULL, '\n');
break;
}
tfp_putc(NULL, c);
s++;
} while(1);
return 0;
}
int putchar(int c) {
tfp_putc(NULL, c);
return c;
}
|
Python | UTF-8 | 11,111 | 2.59375 | 3 | [
"MIT"
] | permissive | import uuid
from pprint import pformat
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
import pandas as pd
from .utils import add_default_to_data
from .utils import create_db_folders
from .utils import dump_cached_schema
from .utils import dump_db
from .utils import generate_hash_id
from .utils import get_db_path
from .utils import load_cached_schema
from .utils import load_db
from .utils import validate_data_with_schema
from .utils import validate_query_data
from .utils import validate_schema
from .utils import validate_update_data
from onstrodb.errors.common_errors import DataDuplicateError
from onstrodb.errors.common_errors import DataError
from onstrodb.errors.schema_errors import SchemaError
# types
DBDataType = Dict[str, object]
SchemaDictType = Dict[str, Dict[str, object]]
GetType = Union[Dict[str, Union[Dict[str, object], str]], None]
class OnstroDb:
"""The main API for the DB"""
def __init__(self, db_name: str, schema: Optional[SchemaDictType] = None,
db_path: Optional[str] = None, allow_data_duplication: bool = False,
in_memory: bool = False) -> None:
self._db_name = db_name
self._schema = schema
self._data_dupe = allow_data_duplication
self._in_memory = in_memory
# db variables
self._db: pd.DataFrame = None
self._db_path: str = get_db_path(db_name)
if db_path:
self._db_path = f"{db_path}/{self._db_name}"
# validate the user defined schema
self._validate_schema()
# meta data about the db
if self._schema:
self._columns = list(self._schema.keys())
# start the loading sequence
self._load_initial_schema()
self._reload_db()
def __repr__(self) -> str:
return pformat(self._to_dict(self._db), indent=4, width=80, sort_dicts=False)
def __len__(self) -> int:
return len(self._db.index)
def add(self, values: List[Dict[str, object]], get_hash_id: bool = False) -> Union[None, List[str]]:
"""Adds a list of values to the DB"""
new_data: List[Dict[str, object]] = []
new_hashes: List[str] = []
for data in values:
if self._schema:
if validate_data_with_schema(data, self._schema):
data = add_default_to_data(data, self._schema)
hash_id = self._get_hash(
[str(i) for i in data.values()], list(self._db.index) + new_hashes)
new_data.append(data)
new_hashes.append(hash_id)
else:
raise DataError(
f"The data {data!r} does not comply with the schema")
new_df = pd.DataFrame(new_data, new_hashes)
try:
self._db = pd.concat([self._db, new_df],
verify_integrity=not self._data_dupe)
except ValueError:
raise DataDuplicateError(
"The data provided, contains duplicate values") from None
if get_hash_id:
return new_hashes
return None
def get_by_query(self, query: Dict[str, object]) -> GetType:
"""Get values from the DB. queries must comply with the schema and must be of length 1"""
if self._schema:
if validate_query_data(query, self._schema):
key = list(query)[0]
filt = self._db[key] == query[key]
return self._to_dict(self._db.loc[filt])
return None
def get_by_hash_id(self, hash_id: str) -> GetType:
"""Get values from the DB based on their hash ID"""
if hash_id in self._db.index:
return self._to_dict(self._db.loc[hash_id])
return {}
def get_hash_id(self, condition: Dict[str, object]) -> List[str]:
"""Returns a hash id or a list of ids that matches all the conditions"""
# the validate_update_method can be used as the same verification style is required here.
if self._schema:
if validate_update_data(condition, self._schema):
return list(self._db.loc[(self._db[list(condition)]
== pd.Series(condition)).all(axis=1)].index)
return []
def get_all(self) -> GetType:
"""Return the entire DB in a dict representation"""
return self._to_dict(self._db)
def update_by_query(self, query: Dict[str, object], update_data: DBDataType) -> Dict[str, str]:
"""Update the records in the DB with a query"""
u_db = self._db.copy(deep=True)
if self._schema:
if validate_query_data(query, self._schema) and validate_update_data(update_data, self._schema):
q_key = list(query)[0]
q_val = query[q_key]
filt = u_db[q_key] == q_val
for key, val in update_data.items():
u_db.loc[filt, key] = val
# update the indexes
new_vals = u_db.loc[filt].to_dict("index")
new_idx = self._verify_and_get_new_idx(
new_vals, list(u_db.index))
if new_idx:
new_df = self._update_hash_id(new_idx, u_db)
self._db = new_df.copy(deep=True)
del [u_db, new_df]
return new_idx
return {}
def update_by_hash_id(self, hash_id: str, update_data: DBDataType) -> Dict[str, str]:
"""Update the records in the DB using their hash id"""
u_db = self._db.copy(deep=True)
if hash_id in u_db.index:
if self._schema:
if validate_update_data(update_data, self._schema):
for key, val in update_data.items():
u_db.loc[hash_id, key] = val
# update the indexes
new_vals = pd.DataFrame(
u_db.loc[hash_id].to_dict(), index=[hash_id]).to_dict("index")
new_idx = self._verify_and_get_new_idx(
new_vals, list(u_db.index))
if new_idx:
new_df = self._update_hash_id(new_idx, u_db)
self._db = new_df.copy(deep=True)
del [u_db, new_df]
return new_idx
return {}
def delete_by_query(self, query: Dict[str, object]) -> None:
"""Delete the records from the db that complies to the query"""
if self._schema:
if validate_query_data(query, self._schema):
key = list(query)[0]
filt = self._db[key] != query[key]
self._db = self._db.loc[filt]
def delete_by_hash_id(self, hash_id: str) -> None:
"""Delete the a records from thr DB based on their hash_id"""
ids = list(self._db.index)
if hash_id in ids:
self._db = self._db.drop(hash_id)
def raw_db(self) -> pd.DataFrame:
"""Returns the in in memory representation of the DB"""
return self._db.copy(deep=True)
def purge(self) -> None:
"""Removes all the data from the runtime instance of the db"""
self._db = self._db.iloc[0:0]
def commit(self) -> None:
"""Store the current db in a file"""
if isinstance(self._db, pd.DataFrame):
if not self._in_memory:
dump_db(self._db, self._db_path, self._db_name)
def _get_hash(self, values: List[str], hash_list: List[str]) -> str:
"""returns the hash id based on the dupe value"""
def gen_dupe_hash(extra: int = 0) -> str:
if extra:
hash_ = generate_hash_id(values + [str(extra)])
else:
hash_ = generate_hash_id(values)
if hash_ in hash_list:
return gen_dupe_hash(uuid.uuid4().int)
else:
hash_list.append(hash_)
return hash_
if not self._data_dupe:
return generate_hash_id(values)
else:
return gen_dupe_hash()
def _update_hash_id(self, new_hashes: Dict[str, str], _df: pd.DataFrame) -> pd.DataFrame:
"""Updates the hash to the new hashes """
for idx, hash_ in new_hashes.items():
_df.rename(index={idx: hash_}, inplace=True)
return _df
def _verify_and_get_new_idx(self, new_vals: Dict[str, Dict[str, object]], hash_list: List[str]) -> Dict[str, str]:
"""verify whether the updated is not a duplicate of an existing data"""
new_hashes: Dict[str, str] = {}
idxs = list(new_vals)
for k, v in new_vals.items():
hash_ = self._get_hash(
list(map(str, v.values())), hash_list)
if hash_ in self._db.index or (hash_ in idxs and k != hash_) or hash_ in new_hashes.values():
if not self._data_dupe:
new_hashes.clear()
raise DataDuplicateError(
"The updated data is a duplicate of an existing data in the DB")
else:
new_hashes[k] = hash_
else:
new_hashes[k] = hash_
return new_hashes
def _to_dict(self, _df: Union[pd.DataFrame, pd.Series]) -> Dict[str, Union[Dict[str, object], str]]:
"""Returns the dict representation of the DB based on
the allow_data_duplication value
"""
if isinstance(_df, pd.DataFrame):
return _df.to_dict("index")
else:
return _df.to_dict()
def _validate_schema(self) -> None:
if self._schema:
validate_schema(self._schema)
def _reload_db(self) -> None:
"""Reload the the pandas DF"""
if not self._in_memory:
data = load_db(self._db_path, self._db_name)
if isinstance(data, pd.DataFrame):
self._db = data
else:
self._db = pd.DataFrame(columns=self._columns)
else:
self._db = pd.DataFrame(columns=self._columns)
def _load_initial_schema(self) -> None:
"""Loads the schema that was provided when the DB was created for the first time"""
if not self._in_memory:
create_db_folders(self._db_path)
if not self._in_memory:
schema = load_cached_schema(self._db_path)
else:
schema = None
if schema:
if self._schema:
if not schema == self._schema:
raise SchemaError(
"The schema provided does not match with the initial schema")
else:
self._schema = schema.copy()
self._columns = list(self._schema.keys())
else:
if not self._schema:
raise SchemaError("The schema is not provided")
else:
if not self._in_memory:
dump_cached_schema(self._db_path, self._schema)
|
Python | UTF-8 | 1,408 | 3.078125 | 3 | [] | no_license | # """
# PyAudio Example: Make a wire between input and output (i.e., record a
# few samples and play them back immediately).
#
# This is the callback (non-blocking) version.
# """
#
# import pyaudio
# import time
#
# WIDTH = 2
# CHANNELS = 2
# RATE = 44100
#
# p = pyaudio.PyAudio()
#
# def callback(in_data, frame_count, time_info, status):
# return (in_data, pyaudio.paContinue)
#
# stream = p.open(format=p.get_format_from_width(WIDTH),
# channels=CHANNELS,
# rate=RATE,
# input=True,
# output=True,
# stream_callback=callback)
#
# stream.start_stream()
#
# while stream.is_active():
# time.sleep(0.1)
#
# stream.stop_stream()
# stream.close()
#
# p.terminate()
"""
PyAudio Example: Make a wire between input and output (i.e., record a
few samples and play them back immediately).
"""
import pyaudio
CHUNK = 1024
WIDTH = 2
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(WIDTH),
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
print("* recording")
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
stream.write(data, CHUNK)
print("* done")
stream.stop_stream()
stream.close()
p.terminate() |
Markdown | UTF-8 | 4,630 | 2.90625 | 3 | [
"MIT"
] | permissive | ---
layout: post
cover: 'assets/images/covers/internet-archive.png'
title: The Internet Archive
date: 2018-08-26
tags: [internet,npo]
author: jaken
description: >
The Internet Archive là một kho lưu trữ khổng lồ phi lợi nhuận được tạo ra để lưu trữ dữ liệu trên internet: văn bản, hình ảnh, âm thanh, phần mềm. Họ tự đặt ra cho mình sứ mệnh càn quét intenet định kỳ và lưu lại tất cả những dữ liệu thu được. Có lẽ bạn sẽ thấy họ kỳ quặc vì internet không chỉ có vàng, mà còn đầy rác. Nhưng nếu bạn ở tình huống của tôi hôm nay, bạn sẽ thấy nó tuyệt vời và những con người đã tạo ra The Internet Archive mới đáng yêu làm sao.
---
[The Internet Archive](https://archive.org/) là một kho lưu trữ khổng lồ phi lợi nhuận được tạo ra để lưu trữ dữ liệu trên internet: văn bản, hình ảnh, âm thanh, phần mềm. Họ tự đặt ra cho mình sứ mệnh càn quét intenet định kỳ và lưu lại tất cả những dữ liệu thu được. Có lẽ bạn sẽ thấy họ kỳ quặc vì internet không chỉ có vàng, mà còn đầy rác. Nhưng nếu bạn ở tình huống của tôi hôm nay, bạn sẽ thấy đó là một ý tưởng tuyệt vời và những con người đã tạo ra nó mới đáng yêu làm sao.
Cuối năm 2016, lão [thien](/author/nguquen/) thử nghiệm chuyển blog sang opensource blog dùng github, sau khi mirgate thử vài bài từ botbie.io sang blog.botbie.io thì lão ngưng, và đề nghị các thành viên khác move và viết bài tiếp.
Sau hai năm, web botbie.io chết do không ai quan tâm bảo trì, thank github mà blog.botbie.io vẫn còn đó, nhưng cảm giác công sức dịch và viết bài trên blog cũ đã mất thật tệ. Với một người vừa dở Anh vừa dở Văn như tôi thì mỗi bài dịch là nhiều giờ ngồi tra từ điển và gõ phím, nên tôi rất rất muốn có lại những bài viêt đó. Sau khi thử tìm kiếm các bản backup trong máy tính, các văn bản đã từng lưu trữ trong google drive, dropbox và evernote, và không tìm thấy gì cả.
Đó là lúc mà vị cứu tinh Internet Archive bỗng nhiên xuất hiện trong đầu tôi. Thư viện số này thành lập cách đây 22 năm, khi một gã cuồng internet là [Brewster Kahle](https://en.wikipedia.org/wiki/Brewster_Kahle) bắt đầu lo lắng về việc các trang web không ai chăm sóc có thể chết đi, và lượng thông tin (rác) mà người dùng đã cất công tạo ra sẽ biến mất mãi mãi. Gã quyết định lập một công ty phi lợi nhuận để cứu vớt những dữ liệu này.
Ban đầu trung tâm dữ liệu của tổ chức được đặt ở ba thành phố San Francisco, Redwood City, và Richmond của bang California. Sau đó để đảm bảo an toàn cho hệ thống khi có thiên tai xảy ra, Kahle bắt đầu mở rộng hệ thống ra nhiều vị trí địa lý khác nhau, hệ thống kho hiện tại có ở cả Ai Cập và Anh Quốc. hệ thống này chỉ scan internet và lưu trữ cho đến 2001, Kahle mở dịch vụ [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine) cho phép người dùng truy cập vào cơ sở dữ liệu khổng lồ của công ty.
Cho tới nay, Internet Archive đã lưu trữ 279 tỉ trang web, 11 triệu sách và văn bản, 4 triệu bản ghi âm, 3 triệu video, 1 triệu hình ảnh và hơn 100 ngàn phần mềm. Và không chỉ internet, Kahle bắt đầu lưu trữ sách in bằng cách số hoá sách (hiện công ty scan 1000 đầu sách mới mỗi ngày), lưu trữ lại các kênh truyền hình đang phát. Có thể một ngày nào đó khi trái đất gặp phải thảm hoạ hạt nhân hoặc mạt thế, kho này là sẽ là nguồn tư liệu quý giá cho những ai muốn tái tạo văn minh loài người.
Quay trở lại với botbie blog, tôi đã tìm lại được một số bài viết cũ từ bản lưu trên webarchive của [botbie.io](https://web.archive.org/web/sitemap/botbie.io) lẫn [blog.botbie.com](https://web.archive.org/web/sitemap/blog.botbie.com) và sẽ cập nhật lên blog.botbie.io sớm, mọi người nếu muốn ủng hộ thì hãy fork [source github](https://github.com/botbie/blog) và tham gia viết bài cho botbie nhé. Trong mã nguồn đã có hướng dẫn sử dụng đi kèm. |
PHP | UTF-8 | 3,275 | 2.828125 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<style type="text/css">
body {
font-family: 'Open Sans', sans-serif;
background-color: darkgrey;
}
div.container {
border-radius: 0.5em;
background-color: white;
padding-top: 0.25em;
padding-left: 2.25em;
padding-right: 2.25em;
padding-bottom: 0.25em;
width: 50%;
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 5em;
margin-bottom: 1em;
}
</style>
</head>
<body>
<div class="container">
<ol>
<li>
<p>Даны два числа. Найти их сумму и произведение.</p>
<p>
<?php
$a = 7;
$b = 9;
echo "a = {$a} , b = {$b}";
echo '<br>';
echo 'a + b = ' . ($a + $b);
echo '<br>';
echo 'a * b = ' . ($a * $b);
?>
</p>
</li>
<li>
<p>Даны два числа. Найдите сумму их квадратов.</p>
<p>
<?php
$a = 7;
$b = 9;
echo "a = {$a} , b = {$b}";
echo '<br>';
echo 'a<sup>2</sup> + b<sup>2</sup> = ' . ($a * $a + $b * $b);
?></p>
</li>
<li>
<p>Даны три числа. Найдите их среднее арифметическое.</p>
<p>
<?php
$a = 7;
$b = 9;
$c = 8;
echo "a = {$a} , b = {$b}, c = {$c}";
echo '<br>';
echo '(a + b + c)/3 = ' . ($a + $b + $c) / 3;
?></p>
</li>
<li>
<p>Дано натуральное число. Найдите остатки от деления его на 3 и на 5.</p>
<p>
<?php
$a = 7;
echo "a = {$a}";
echo '<br>';
echo 'a % 3 = ' . ($a % 3);
echo '<br>';
echo 'a % 5 = ' . ($a % 5);
?></p>
</li>
<li>
<p>Дано число. Увеличьте его на 30%, на 120%.</p>
<p>
<?php
$a = 7;
echo "a = {$a}";
echo '<br>';
echo 'a + 30% = ' . ($a * 1.3);
echo '<br>';
echo 'a + 120% = ' . ($a * 2.2);
?>
</p>
</li>
<li>
<p>Дано два числа. Найдите сумму 40% от первого числа и 84% от второго числа.</p>
<p>
<?php
$a = 7;
$b = 9;
echo "a = {$a} , b = {$b}";
echo '<br>';
echo "a*0.4 + b*0.84 = " . ($a * 0.4 + $b * 0.84);
?>
</p>
</li>
</ol>
</div>
</body>
</html> |
Markdown | UTF-8 | 1,040 | 3.390625 | 3 | [] | no_license | # 概念
移动设备上的viewport就是设备的屏幕上能用来显示我们的网页的那一块区域,在具体一点,就是浏览器上(也可能是一个app中的webview)用来显示网页的那部分区域,但viewport又不局限于浏览器可视区域的大小,它可能比浏览器的可视区域要大,也可能比浏览器的可视区域要小。
# layout viewport
移动端浏览器的默认宽度,通过document.documentElement.clientWidth可获得
# visual viewport
可视视口,可通过window.innerWidth获取
# ideal viewport
先不需要用户缩放和横向滚动条就能正常的查看网站的所有内容;第二,显示的文字的大小是合适,比如一段14px大小的文字,不会因为在一个高密度像素的屏幕里显示得太小而无法看清,理想的情况是这段14px的文字无论是在何种密度屏幕,何种分辨率下,显示出来的大小都是差不多的
# 参考
[移动前端开发之viewport的深入理解](https://www.cnblogs.com/2050/p/3877280.html) |
Java | UTF-8 | 6,119 | 2.140625 | 2 | [] | no_license | package com.jointeach.iauditor.common;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.jointeach.iauditor.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import org.mylibrary.utils.LogTools;
import org.mylibrary.utils.Tools;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* 作者: ws
* 日期: 2016/4/7.
* 介绍:
*/
public class ImgLoadUtils {
private static final String TAG="ImgLoadUtils";
private ImageLoader imageLoader;
private static ImgLoadUtils ourInstance;
public static ImgLoadUtils getInstance() {
if(ourInstance==null){
ourInstance = new ImgLoadUtils();
}
return ourInstance;
}
private ImgLoadUtils() {
imageLoader = ImageLoader.getInstance();
}
/**
* 加载图片
* @param url String imageUri = "http://site.com/image.png"; // 网络图片
* String imageUri = "file:///mnt/sdcard/image.png"; //SD卡图片
* String imageUri = "content://media/external/audio/albumart/13"; // 媒体文件夹
* String imageUri = "assets://image.png"; // assets
* String imageUri = "drawable://" + R.drawable.image;
* @param imageView 图片控件
*/
public static void loadImageRes(String url, ImageView imageView,int round) {
loadImageRes(url, imageView, getDisplayOptions(round), null);
}
/**
* 加载图片
*
* @param url String imageUri = "http://site.com/image.png"; // 网络图片
* String imageUri = "file:///mnt/sdcard/image.png"; //SD卡图片
* String imageUri = "content://media/external/audio/albumart/13"; // 媒体文件夹
* String imageUri = "assets://image.png"; // assets
* String imageUri = "drawable://" + R.drawable.image;
* @param imageView 图片控件
*/
public static void loadImageRes(String url, ImageView imageView) {
loadImageRes(url, imageView, null, null);
}
/**
* 加载图片
*
* @param url String imageUri = "http://site.com/image.png"; // 网络图片
* String imageUri = "file:///mnt/sdcard/image.png"; //SD卡图片
* String imageUri = "content://media/external/audio/albumart/13"; // 媒体文件夹
* String imageUri = "assets://image.png"; // assets
* String imageUri = "drawable://" + R.drawable.image;
* @param imageView 图片控件
*/
public static void loadImageRes(String url, CircleImageView imageView) {
DisplayImageOptions options= new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.NONE)
.showStubImage(R.drawable.page5) // 设置图片下载期间显示的图片
.showImageForEmptyUri(R.drawable.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.drawable.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
.cacheInMemory(true) // 设置下载的图片是否缓存在内存中
.cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
loadImageRes(url, imageView, options, null);
}
/**
* 加载图片
*
* @param url String imageUri = "http://site.com/image.png"; // 网络图片
* String imageUri = "file:///mnt/sdcard/image.png"; //SD卡图片
* String imageUri = "content://media/external/audio/albumart/13"; // 媒体文件夹
* String imageUri = "assets://image.png"; // assets
* String imageUri = "drawable://" + R.drawable.image;
* @param imageView 图片控件
* @param options 显示设置
* @param listener 加载监听
*/
public static void loadImageRes(String url, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) {
LogTools.i(TAG, "loadImageRes:" + url);
if(Tools.isEmpty(url)){
url="drawable://"+ R.drawable.ic_launcher;
}
if(url.startsWith("www")){
url="http://"+url;
}
if(!url.startsWith("file://") && !url.startsWith("drawable://") && !url.startsWith("http://")){
url="file://"+url;
}
getInstance().imageLoader.displayImage(url, imageView, options, listener);
}
public static ImageLoader getImageLoader(){
return getInstance().imageLoader;
}
/**
* 获取显示设置类
* @param round 圆角
* */
public static DisplayImageOptions getDisplayOptions(int round){
DisplayImageOptions options= new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.NONE)
.showStubImage(R.drawable.page5) // 设置图片下载期间显示的图片
.showImageForEmptyUri(R.drawable.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.drawable.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
.cacheInMemory(true) // 设置下载的图片是否缓存在内存中
.cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
.displayer(new RoundedBitmapDisplayer(round)) // 设置成圆角图片
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
return options;
}
}
|
JavaScript | UTF-8 | 410 | 3.03125 | 3 | [] | no_license | var lis=document.querySelectorAll('ul:first-child>li')
var imgs=document.querySelectorAll('ul:last-child>li')
lis.forEach(function (value,index) {
value.onclick=function () {
for(i=0;i<lis.length;i++){
lis[i].classList.remove('active')
imgs[i].classList.remove('active')
}
this .classList.add('active')
imgs[index].classList.add('active')
}
})
|
Markdown | UTF-8 | 435 | 2.71875 | 3 | [] | no_license | TLDR - strace
==========
Overview
--------
[strace] is a command that traces system calls and signals
Examples
--------
- **Trace** the execution of the ls command:
$ strace ls
- **Trace** a specific system call in an executable:
$ strace -e open ls
- **Save** the trace execution into a file:
$ strace -o output.txt ls
Resources
---------
- [Linux Manual](http://man7.org/linux/man-pages/man1/strace.1.html)
|
TypeScript | UTF-8 | 1,089 | 2.53125 | 3 | [] | no_license | import { NextFunction, Request, Response } from "express";
import { IRequest } from "../Request&Response/IRequest";
import { IResponse } from "../Request&Response/IResponse";
import jwt from "jsonwebtoken";
import { HTTP_STATUS_CODES } from "../utils/HttpResponses";
import { getRawTokenFromAuthHeader } from "./utils/getTokenFromAuthHeader";
import { UserRole } from "../entities/User";
export interface IAuthToken {
id: number;
role: UserRole;
iat: number;
}
export async function auth(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader)
return res.status(HTTP_STATUS_CODES.UNAUTHORIZED).json({msg: "not allowed"});
const token = getRawTokenFromAuthHeader(authHeader);
try {
await jwt.verify(token, process.env.JWT_KEY!);
const decodedToken = jwt.decode(token);
(req as any).decodedToken = decodedToken;
return next();
} catch (err) {
console.log(err);
return res.status(401).json({msg: "not allowed: invalid token"});
}
} |
C# | UTF-8 | 537 | 2.96875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace SolidPrinciplesExample
{
class TemporaryEmployee : Employee,IEmployee
{
public TemporaryEmployee()
{
}
public TemporaryEmployee(int Id,string Name):base(Id,Name)
{
}
public override decimal CalculateBonus(decimal salary)
{
return salary * .05M;
}
public override decimal getMinimumsalary()
{
return 10000;
}
}
}
|
Java | UTF-8 | 610 | 3.0625 | 3 | [] | no_license | package ooProgramming_Class_Hierachies.PersonManagement;
public abstract class Employee extends Person {
protected int test;
private String jobTitle;
public Employee(String jobTitle, String name, String socialsecurity, int age, GenderType gender) {
super(name, socialsecurity, age, gender);
this.jobTitle = jobTitle;
}
public String getJobTitle() {
return jobTitle;
}
@Override
public String toString() {
return "Employee [jobTitle=" + jobTitle + ", toString()=" + super.toString() + "]";
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
}
|
Python | UTF-8 | 322 | 3.0625 | 3 | [] | no_license | class Solution:
#动态规划
def maxSubArray1(self, nums):
if nums == []:
return 0
else:
for i in range(1, len(nums)):
nums[i] = max(nums[i] + nums[i - 1], nums[i])
return max(nums)
sol = Solution()
a = [1,-1,-2,3]
print(sol.maxSubArray(a))
|
Python | UTF-8 | 1,915 | 2.515625 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from dateutil.parser import parse
# Load timestamp and position strings
filename = '/home/kampff/Dropbox/LC_THESIS/ARK/shader_vs_crop/BallTracking.csv'
split_data = np.genfromtxt(filename, delimiter=[33,100], dtype='unicode')
timestamp_strings = split_data[:,0]
positions_strings = split_data[:,1]
# Find positions
for index, s in enumerate(positions_strings):
tmp = s.replace('(', '')
tmp = tmp.replace(')', '')
tmp = tmp.replace('\n', '')
tmp = tmp.replace(' ', '')
positions_strings[index] = tmp
positions = np.genfromtxt(positions_strings, delimiter=',', dtype=float)
dx = np.diff(positions[:,0], prepend=[0])
dy = np.diff(positions[:,1], prepend=[0])
speed = np.sqrt(dx*dx + dy*dy)
moving = np.int32(speed > 0)
starts = np.where(np.diff(moving) == 1)[0]
# Convert to elapsed seconds
elapsed = []
start_time = parse(timestamp_strings[0])
for ts in timestamp_strings:
current_time = parse(ts)
delta_time = current_time - start_time
elapsed.append(delta_time.total_seconds())
elapsed = np.array(elapsed)
# Find timestamp jumps (i.e. start indices)
deltas = np.diff(elapsed, prepend=[0])
deltas[0] = 11 # Added so the first index is considered a "start"
#plt.plot(deltas, '.')
#plt.show()
start_indices = np.where(deltas > 1)[0]
start_timestamp_strings = timestamp_strings[start_indices]
# Find contact indices
dx = np.diff(positions[:,0], prepend=[0])
dy = np.diff(positions[:,1], prepend=[0])
contact_indices = []
for i in start_indices:
dx_trial = dx[(i+1):]
dy_trial = dy[(i+1):]
trial_end = len(dx_trial)
j = 0
while j < trial_end:
if((dx_trial[j] > 0) or (dy_trial[j] > 0)):
contact_indices.append(i + j)
j = trial_end
else:
j = j + 1
contact_indices = np.array(contact_indices)
contact_timestamp_strings = timestamp_strings[contact_indices]
#FIN |
Python | UTF-8 | 2,267 | 2.609375 | 3 | [
"MIT"
] | permissive | import xml.etree.ElementTree as ET
from os import getcwd
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
def convert_annotation(fo, image_id, list_file):
xmlpath = rootpath + fo +'/Annotations/'
in_file = open(xmlpath+'%s.xml'% image_id)
tree=ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult)==1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))
'''
foldername = ('MOT17-02', 'MOT17-04', 'MOT17-05',
'MOT17-09', 'MOT17-10', 'MOT17-11',
'MOT17-13')
length = (600, 1050, 837, 525, 654, 900, 750)
sunny(5,13)
night(4,10)
indoor(9,11)
cloudy(2)
'''
#%%
# 5 train 2 val
#%%
rootpath = '/home/qi/benchmark/QiMOT17det/'
trainvaltype = 'train5val2/'
# Here we use 5 train sequences and 2 val sequences
train = True
if train:
trainval = 'train'
foldername = ('MOT17-02', 'MOT17-04',
'MOT17-10', 'MOT17-11',
'MOT17-13')
length = (600, 1050, 837, 525, 654, 900, 750)
else:
trainval = 'val'
foldername = ('MOT17-05',
'MOT17-09')
length = (600, 1050, 837, 525, 654, 900, 750)
traintxt = rootpath + trainvaltype + '%s.txt'%(trainval)
list_file = open(traintxt, 'w')
for folder, l in zip(foldername, length):
image_ids = open(rootpath +'%s/ImageSets/Main/%s.txt' % (folder, trainval)).read().strip().split()
# traintxt = rootpath + trainvaltype + '%s.txt'%(trainval)
# list_file = open(traintxt, 'w')
for image_id in image_ids:
outputpath = rootpath + folder + '/JPEGImages/%s.jpg'
list_file.write( outputpath % image_id)
convert_annotation(folder, image_id, list_file)
list_file.write('\n')
list_file.close()
|
Java | UTF-8 | 2,316 | 2.25 | 2 | [] | no_license | /*
* Copyright (C) 2013 Code-House, Lukasz Dywicki.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.code_house.exchange.api;
/**
* Enumeration representing possible ways of communication.
*
* TODO Verify if it's properly ported, ie IN/OUT/FAULT are mapped properly.
*/
public enum ExchangePattern {
InOnly (true, false, false, "http://www.w3.org/ns/wsdl/in-only"),
InOptionalOut ("http://www.w3.org/ns/wsdl/in-optional-out"),
InOut ("http://www.w3.org/ns/wsdl/in-out"),
OutIn ("http://www.w3.org/ns/wsdl/out-in"),
OutOnly (false, true, false, "http://www.w3.org/ns/wsdl/out-only"),
OutOptionalIn ("http://www.w3.org/ns/wsdl/out-optional_in"),
RobustInOnly (true, false, "http://www.w3.org/ns/wsdl/robust-in-only"),
RobustOutOnly (false, "http://www.w3.org/ns/wsdl/robust-out-only");
private final boolean hasIn;
private final boolean hasOut;
private final boolean hasFault;
private final String wsdlSpecUri;
private ExchangePattern(String wsdlSpecUri) {
this(true, wsdlSpecUri);
}
private ExchangePattern(boolean hasIn, String wsdlSpecUri) {
this(hasIn, true, wsdlSpecUri);
}
private ExchangePattern(boolean hasIn, boolean hasOut, String wsdlSpecUri) {
this(hasIn, hasOut, true, wsdlSpecUri);
}
private ExchangePattern(boolean hasIn, boolean hasOut, boolean hasFault, String wsdlSpecUri) {
this.hasIn = hasIn;
this.hasOut = hasOut;
this.hasFault = hasFault;
this.wsdlSpecUri = wsdlSpecUri;
}
public boolean hasIn() {
return hasIn;
}
public boolean hasOut() {
return hasOut;
}
public boolean hasFault() {
return hasFault;
}
public String getWsdlSpecUri() {
return wsdlSpecUri;
}
}
|
C# | UTF-8 | 2,334 | 3.1875 | 3 | [
"MIT"
] | permissive | namespace Chris03.CodeSnippets.LinqFilterExpressions
{
using System;
using System.Linq;
using System.Linq.Expressions;
/// <summary>
/// Search a date
/// </summary>
public class DateAdvancedSearch : DateSearch
{
/// <summary>
/// Gets the supported comparators.
/// </summary>
public override Comparators[] SupportedComparators
{
get
{
return base.SupportedComparators.Concat(new[]
{
Comparators.DateToday,
Comparators.DateThisWeek,
Comparators.DateThisMonth,
Comparators.DateThisYear
}).ToArray();
}
}
/// <summary>
/// Builds the expression.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="comparator"></param>
/// <param name="searchTerms"></param>
/// <returns>The expression</returns>
protected override Expression BuildSearchExpression(Expression property, Comparators comparator, params string[] searchTerms)
{
/* Expression valueProperty = null;
if (this.PropertyIsNullable)
{
valueProperty = Expression.Property(property, "Value");
}
// DbFunctions.TruncateTime();
var methodInfo = typeof(DbFunctions).GetMethod("TruncateTime", new[] { typeof(DateTime?) });
var truncatedDate = Expression.Call(methodInfo, property);
var constSearchValue = Expression.Constant(this.SearchTerm, typeof(DateTime?));
var constNullValue = Expression.Constant(null);
*/
switch (comparator)
{
// Dates
case Comparators.DateToday:
// return Expression.Equal(truncatedDate, Expression.Constant(DateTime.Today, typeof(DateTime?)));
case Comparators.DateThisWeek:
case Comparators.DateThisMonth:
case Comparators.DateThisYear:
// TODO:
return null;
default:
throw new InvalidOperationException("Comparator not supported.");
}
}
}
}
|
JavaScript | UTF-8 | 12,836 | 2.59375 | 3 | [
"MIT"
] | permissive | import React, { useState, useEffect } from 'react';
import './QuizCreationView.css';
import QuestionEdit from './QuestionEdit';
import Axios from 'axios';
import PageTypeEdit from './PageTypeEdit';
const API_HOST = process.env.REACT_APP_API_URL;
const API_PORT = process.env.REACT_APP_API_PORT;
const API_URL = `${API_HOST}:${API_PORT}`;
function QuizCreationView() {
const [availableStories, setAvailableStories] = useState([]);
const [selectedStoryId, setSelectedStoryId] = useState(-1);
const [storyPreviewExpanded, setStoryPreviewExpanded] = useState(false);
const [loadingQuestions, setLoadingQuestions] = useState(false);
const [pageTypes, setPageTypes] = useState([]);
const [selectedPageTypeId, setSelectedPageTypeId] = useState(-1);
function changeSelectedStoryId(event) {
const storyId = event.target.value;
setSelectedStoryId(storyId);
setSelectedPageTypeId(-1);
setStoryPreviewExpanded(false);
loadQuestions(storyId)
}
function toggleStoryPreview() {
setStoryPreviewExpanded(!storyPreviewExpanded);
}
function changeSelectedPageType(id) {
setSelectedPageTypeId(id);
}
/******************
* QUESTIONS CODE *
******************/
function loadQuestions(storyId) {
setLoadingQuestions(true);
Axios.get(`${API_URL}/api/admin/stories/${storyId}/games`)
.then(response => {
console.log(response.data);
setPageTypes(response.data);
})
.catch(err => {
console.log('Error while fetching story questions', err);
})
.finally(() => {
setLoadingQuestions(false);
})
}
function updateQuestion(updatedQuestion) {
const newQuestions = questions.map((question) => {
if (question.id === updatedQuestion.id) return updatedQuestion;
else return question;
});
setQuestions(newQuestions);
}
function deleteQuestion(deletedQuestion) {
const newQuestions = questions.filter((question) => question.id !== deletedQuestion.id);
setQuestions(newQuestions);
}
function newQuestion() {
const question = {
id: Math.ceil(Math.random() * 100000000),
question: "",
answers: [
"",
"",
"",
"",
],
correctAnswer: -1,
difficulty: 1,
openEdit: true,
};
const newQuestions = [question, ...questions];
setQuestions(newQuestions);
}
function setQuestions(questions) {
const newPageType = {
...selectedPageType,
quizData: { questions: questions },
};
updatePageType(newPageType);
}
/******************
* PAGETYPES CODE *
******************/
function updatePageType(updatedPageType) {
const { strippedPt, imagesToUpload } = pageTypeStripImages(updatedPageType);
apiUpdatePageType(strippedPt)
.then(response => {
// Process updated images
const promises = [];
for (const { questionId, image } of imagesToUpload) {
updatedPageType.quizData.questions.find(q => q.id === questionId).image.updated = false;
promises.push(() => apiUploadQuestionImage(updatedPageType._id, questionId, image));
}
// Resolve promises for uploading the images sequentially
return promises.reduce((prevPromise, current) => {
return prevPromise.then(() => {
return current();
});
}, Promise.resolve());
}).then(() => {
const newPTs = pageTypes.map((pageType) => {
if (pageType._id === updatedPageType._id) return updatedPageType;
else return pageType;
});
console.log('updated pt', newPTs);
setPageTypes(newPTs);
})
.catch(err => {
console.log('Error while updating page type', err, updatedPageType)
});
}
function deletePageType(deletedPageType) {
apiDeletePageType(deletedPageType)
.then(response => {
const newPTs = pageTypes.filter((pageType) => pageType._id !== deletedPageType._id);
console.log('deleted pt', newPTs);
if (selectedPageTypeId === deletedPageType._id) {
setSelectedPageTypeId(-1);
}
setPageTypes(newPTs);
})
.catch(err => {
console.log('Error while deleting page type', err, deletedPageType)
});
}
function newPageType() {
const newType = {
story: selectedStoryId,
page: 0,
types: [],
quizData: { questions: [] },
};
apiPostPageType(newType)
.then(response => {
const rspNewType = response.data;
const newPTs = [rspNewType, ...pageTypes];
setPageTypes(newPTs);
})
.catch(err => {
console.log('Error while creating new page type', err, newType)
});
}
function apiPostPageType(pageType) {
return Axios.post(`${API_URL}/api/admin/stories/${selectedStoryId}/games`, { game: pageType });
}
function apiUpdatePageType(pageType) {
return Axios.put(`${API_URL}/api/admin/games/${pageType._id}`, { game: pageType });
}
function apiDeletePageType(pageType) {
return Axios.delete(`${API_URL}/api/admin/games/${pageType._id}`);
}
function apiUploadQuestionImage(pageTypeId, questionId, image) {
return Axios.put(`${API_URL}/api/admin/games/${pageTypeId}/questions/${questionId}/image`, { image });
}
/**
* Strip the questions (and puzzleData) in pagetype of images, because otherwise we can receive a
* 413 (Payload Too Large) error when making an API PUT / POST call.
* We upload updated images via a seperate call.
*/
function pageTypeStripImages(pageType) {
const imagesToUpload = [];
let strippedPt = pageType;
if (pageType.quizData) {
const questions = pageType.quizData.questions.map(question => {
if (!question.image) return question;
if (question.image.updated) {
imagesToUpload.push({ questionId: question.id, image: question.image });
}
return { ...question, image: null }
});
strippedPt = { ...pageType, quizData: { questions } }
}
if (strippedPt.puzzleData && strippedPt.puzzleData.image) {
strippedPt = { ...strippedPt, puzzleData: { image: undefined } }
}
return {
strippedPt,
imagesToUpload,
}
}
/******************
* PUZZLE *
******************/
function changeUploadedPuzzleImage(event) {
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
const input = event.target;
if (input.files && input.files.length) {
const kb = input.files[0].size / 1024;
if (kb > 512) {
alert(`Image is ${Math.round(kb)}kB big, which is bigger than the limit 512kB!`);
return;
}
toBase64(input.files[0]).then(result => {
const image = {
name: input.files[0].name,
data: result,
}
apiUploadPuzzleImage(selectedPageTypeId, image)
.then(respose => {
const localImage = {
image: {
name: image.name,
dataStr: image.data,
}
}
const pt = { ...selectedPageType, puzzleData: localImage };
updatePageType(pt);
})
.catch(err => {
console.log('Error while uploading puzzle image', err, image);
})
});
}
}
function removePuzzleImage(event) {
apiUploadPuzzleImage(selectedPageTypeId, null)
.then(respose => {
const pt = { ...selectedPageType, puzzleData: { image: null }};
updatePageType(pt);
})
.catch(err => {
console.log('Error while removing puzzle image', err, selectedPageType);
})
event.preventDefault();
}
function apiUploadPuzzleImage(pageTypeId, image) {
return Axios.put(`${API_URL}/api/admin/games/${pageTypeId}/puzzleData`, { image });
}
/******************
* LIFECYCLE *
******************/
useEffect(() => {
Axios.get(`${API_URL}/api/stories`)
.then(response => {
setAvailableStories(response.data);
})
.catch(function (error) {
console.log(error.message)
})
}, [])
/******************
* HTML *
******************/
const storyOptions = availableStories.map(({ _id, title }) => {
return (<option key={_id} value={_id}>{ title }</option>);
});
const storySelect = (
<select className="custom-select story-select" value={selectedStoryId} onChange={changeSelectedStoryId}>
<option key={-1} value={-1}>Select a story</option>
{ storyOptions }
</select>
);
const isStorySelected = selectedStoryId.toString() !== '-1';
const selectedStory = availableStories.find(story => story._id === selectedStoryId);
const storyPreview = isStorySelected ? (
<div className="card story-preview" onClick={toggleStoryPreview}>
<div className="card-body">
<h5 className="card-title">{ selectedStory.title }</h5>
<div className={"card-text story-content " + (storyPreviewExpanded ? "" : "closed")}>
{ selectedStory.shortDescription }
</div>
</div>
</div>
) : null;
/******************
* PAGETYPES HTML *
******************/
const storedPageTypes = pageTypes.map((pageType) => {
return (
<PageTypeEdit
key={pageType._id}
pageType={pageType}
isSelected={selectedPageTypeId === pageType._id}
openDefault={pageType.isDraft === true}
updateCallback={updatePageType}
deleteCallback={deletePageType}
selectCallback={() => changeSelectedPageType(pageType._id)}
></PageTypeEdit>
);
});
const pageTypeArea = isStorySelected && (
<div className="page-type-area">
<h4>Pages and types:</h4>
<button className="btn new-page-type" onClick={newPageType}>Create new page with types</button>
{ storedPageTypes }
</div>
);
const isPageTypeSelected = isStorySelected && selectedPageTypeId !== -1;
const selectedPageType = pageTypes.find(pt => pt._id === selectedPageTypeId);
/******************
* PUZZLE HTML *
******************/
const showPuzzleArea = isPageTypeSelected && selectedPageType.types.includes('puzzle');
const puzzleImage = showPuzzleArea && selectedPageType.puzzleData && selectedPageType.puzzleData.image;
let puzzleImageSrc = "";
if(puzzleImage){
if(puzzleImage.dataStr){
puzzleImageSrc = puzzleImage.dataStr;
} else if(puzzleImage.data){
for (var i=0; i<puzzleImage.data.data.length; i++) {
puzzleImageSrc += String.fromCharCode(puzzleImage.data.data[i])
}
}
}
//const puzzleImageSrc = puzzleImage &&
//(puzzleImage.dataStr ? puzzleImage.dataStr : String.fromCharCode.apply(null, puzzleImage.data.data));
const puzzleArea = showPuzzleArea && (
<div className="puzzle-area">
<h4>Puzzle Image</h4>
<form>
<div className="form-group">
<label htmlFor="file-upload">Add picture for the puzzle:</label>
<input
type="file"
className="form-control-file"
id="file-upload"
onChange={changeUploadedPuzzleImage}
/>
</div>
{ puzzleImage && (
<div className="form-group">
<img src={puzzleImageSrc} alt='Uploaded'/>
<br/>
<button className="btn btn-secondary" onClick={removePuzzleImage}>
Remove image
</button>
</div>
)}
</form>
</div>
);
/******************
* QUESTIONS HTML *
******************/
const questions = isPageTypeSelected ? selectedPageType.quizData.questions : []
const newQuestionButton = (
<button className="btn new-question" onClick={newQuestion}>Create new question</button>
);
const storedQuestions = questions.map((question) => (
<QuestionEdit
key={question.id}
question={question}
openDefault={question.openEdit === true}
updateCallback={updateQuestion}
deleteCallback={deleteQuestion}
></QuestionEdit>
))
const questionsArea = isPageTypeSelected && (
<div className="questions-area">
<h4>Questions:</h4>
{ newQuestionButton }
{ loadingQuestions ? (<p>Loading...</p>) : storedQuestions }
</div>
);
/******************
* FINAL HTML *
******************/
return (
<div className="container quiz-creation-view">
<h2>Create Questions for the Games</h2>
{ storySelect }
{ storyPreview }
{ pageTypeArea }
{ puzzleArea }
{ questionsArea }
</div>
);
}
export default QuizCreationView;
|
JavaScript | UTF-8 | 1,312 | 2.734375 | 3 | [] | no_license | const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
// 设定读取的文件的路径
const study = '/public/students.json';
// 获取数据接口
router.get('/readitem',function(req,res){
// 读取study文件,给用户返回
fs.readFile(path.join(__dirname + study),'utf8',function(err,data){
// 判断是否出现错误,如果有错误,那么需要给用户
if(err){
return res.send(err);
}
res.status(200).send(data);
})
});
router.post('/create',function(req,res){
// 设置model层
let newStudent = {
id:Date.now(),
name:req.body.name,
age:req.body.age,
class:req.body.class,
creatTime:new Date().toLocaleString(),
updateTime:new Date().toLocaleString()
}
// 要把newStudent写入文件,但是在写的时候,需要注意,不要直接覆盖,先读取之前的内容,然后拼接之后,写入新的json
fs.readFile((__dirname + study),'utf8',function(err,data){
if(err) throw err
try {
data = JSON.parse(data)
} catch(error){
return res.status(200).send(error)
}
data.push(newStudent);
fs.writeFile(path.join(__dirname + study),JSON.stringify(data),function(err){
res.status(200).send(err);
})
})
})
module.exports = router; |
JavaScript | UTF-8 | 1,810 | 3.375 | 3 | [
"MIT"
] | permissive | function validateForm(){
var name = document.forms["form1"]["name"].value;
if (name == ""){
alert("Please enter your name");
return false;
}
var year = document.forms["form1"]["age"].value;
var day = new Date();
var currentYear = day.getFullYear();
var bornYear = parseInt(year);
var age = currentYear - bornYear;
if (age < 18) {
alert("You are not eligible to give a feedback");
return false;
}
var email = document.forms["form1"]["email"].value;
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (email == ""){
alert("Please enter your email");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length){
alert("Not a valid email-address");
return false;
}
var phone = document.forms["form1"]["phone"].value;
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (phone.match(phoneno))
{
return true;
}
else
{
alert("not a valid phone number");
return false;
}
var service = document.forms["form1"]["service"].value;
if (service == ""){
alert("Please enter your service");
return false;
}
var message = document.forms["form1"]["message"].value;
if (message == ""){
alert("Please give us your feedback");
return false;
}
var score = document.forms["form1"]["score"].value;
if (score == ""){
alert("Please grade us");
return false;
}
}
|
Java | UTF-8 | 154 | 1.625 | 2 | [] | no_license | package com.bird.demo.infrastructure.drl;
/**
* @author youly
* 2019/8/2 11:05
*/
public interface IConverter {
String process(Object object);
}
|
Markdown | UTF-8 | 15,301 | 3.484375 | 3 | [
"Apache-2.0"
] | permissive | # 2022.05.30-2022.06.05
## Algorithm
### 1. 题目
```
448. 找到所有数组中消失的数字
```
### 2. 题目描述
```
给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
示例 1:
输入:nums = [4,3,2,7,8,2,3,1]
输出:[5,6]
示例 2:
输入:nums = [1,1]
输出:[2]
```
### 3. 解答:
```golang
func findDisappearedNumbers(nums []int) []int {
arrs := make([]int, len(nums)+1)
arrs[0] = 1
for _, v := range nums {
arrs[v] = 1
}
var rets []int
for i, v := range arrs {
if v == 0 {
rets = append(rets, i)
}
}
return rets
}
```
### 4. 说明
将nums的数字遍历存入到arrs中,其中arrs的索引值就是nums的元素值。最后遍历arrs,找出v为0的就是元素索引组合起来就是结果。
## Review
### 1. 原文链接
[http://blog.cleancoder.com/uncle-bob/2015/10/16/Agile-And-Waterfall.html](http://blog.cleancoder.com/uncle-bob/2015/10/16/Agile-And-Waterfall.html)
### 2. 翻译
Agile is not now, nor was it ever, Waterfall.
敏捷现在不是,过去也不是,瀑布。
I read Agile is the new Waterfall at first with disgust, then with horror, and then finally with a meager amount of very qualified approval.
当我读到《敏捷是新的瀑布》时,我先是感到厌恶,然后是恐惧,最后是少量非常有资格的认可。
The author makes a reasonable point towards the end;
but in getting to that point he states a number of falsehoods and eventually discredits a philosophy and discipline that does not deserve it.
He is close to throwing everything out with the bathwater.
最后作者提了一个合理的观点;
但为了达到这一点,他提出了许多错误,并最终诋毁了一种不值得的哲学和纪律。
他几乎要把所有东西连同洗澡水一起倒掉。
He begins by claiming that no sane person advocates waterfall.
I don’t know what universe the author lives in; but in this universe there are quite a few people who advocate waterfall.
Are they sane? By any legal standard they are. Anyone who thinks that the battle against waterfall is over simply hasn’t been fighting in the right trenches.
他一开始就声称没有一个理智的人会提倡瀑布。
我不知道作者生活在哪个世界;但在这个世界上,有相当多的人提倡瀑布。
他们是理智的吗?以任何法律标准来看,它们都是。任何认为与瀑布的战斗已经结束的人都没有站在正确的战壕里。
If you want to get a feel for just how wrong the author is about this,
just google “Waterfall Software Teams” and count the number of articles that talk about striking a balance, or mixing the two processes, etc.
People are not anxious to give up on the past.
如果你想感受一下作者的观点有多错误,
只需要谷歌一下“瀑布软件团队”,并计算讨论如何平衡或混合两个过程的文章的数量,等等,
人们并不急于放弃过去。
Next he quotes MacBeth’s lament over the futility of life, and equates it with the “the promise of Agile”
接下来,他引用了麦克白对生命的徒劳的哀叹,并将其等同于“敏捷的承诺”。
“…full of sound and fury, signifying nothing.”
“……充满了声音和愤怒,却毫无意义。”
I take rather profound exception to the idea that the events leading up to the Agile Manifesto, and the Manifesto itself are an example of futility and meaningless noise.
The author wasn’t there. The author doesn’t know. While I agree that in certain circles there is more heat than light;
to claim that the entire movement is insignificant is to ignore a vast swath of software history.
我对“敏捷宣言”的产生有着深刻的异议,而“宣言”本身就是一个无用和无意义的例子。
作者不在那里。作者不知道。虽然我同意在某些圈子里热比光多;
声称整个运动微不足道就是忽视了软件历史的一大片。
I’m not going to critique the author point by point.
Suffice it to say that he knows very little of the history, and what little he does know he’s gotten wrong.
In so doing he has cast a pall of disrespect over a large number of people who have made huge contributions to our field.
A pall that discredits an ideology that has had a profoundly positive effect.
我不打算逐点批判作者。
我只想说,他对历史知之甚少,而他所知道的那一点点都是错的。
他这样做是对许多为我们这个领域做出巨大贡献的人的不尊重。
一种曾产生深远积极影响的意识形态的抹黑。
He rails against the Agile consultancies who try to help organizations make the shift to Agile.
Some of his complaints are justified; but most are not. Changing an organization is hard!
Those companies that try to change, and hire help to make that change, are courageous.
他斥责那些试图帮助组织转向敏捷的敏捷顾问。
他的一些抱怨是有道理的;但大多数都不是。改变一个组织是困难的!
那些试图改变的公司,并聘请帮助来实现这种改变的公司,是有勇气的。
Are there Agile consultancies that are better than others?
Yes. Certainly. Caveat Emptor! But denigrating the entire effort is simply ignorant.
有比其他公司更好的敏捷咨询公司吗?
是的。当然有。购者自慎!但诋毁整个努力是无知的。
The One Point.
有一点。
The author is wrong about Agile in virtually every regard.
But he does make one good point. Unfortunately the context in which he makes that point is so wrong that the point is almost lost in the cacophony of blather that surrounds it.
That point is:
作者对敏捷的看法几乎在所有方面都是错误的。
但他说的有一点很好。不幸的是,他提出这一观点的背景是如此错误,以至于这一观点几乎湮没在围绕它的嘈杂的废话中。
这一点是:
“Bring in the bare minimum amount of process.”
“引入最简单的流程。”
Yes! Of course!
对!当然!
Does every software team need the entire suite of agile practices? Of course not. But let’s look at them:
每个软件团队都需要一整套敏捷实践吗?当然不是。但让我们来看看它们:
The Planning Game.
Over the years it has become very clear that there are many ways to shave this Yak.
Some teams need more process around this than others.
For some, a simple list of features will do.
For others, a Kanban board will be sufficient.
Still others will need the full suite of stories, and tasks, and releases, and story points, and… Well, you know.
Choose wisely!
计划游戏
这些年来,人们已经清楚地知道,有很多方法可以给牦牛剃毛。
有些团队需要比其他团队更多的流程。
对于一些人来说,一个简单的功能列表就可以了。
对于其他人来说,看板就足够了。
Customer Tests. Lots of customers don’t want to be bothered with these tests.
That’s a shame, since they are demonstrably the best way to specify requirements.
For those teams that have customers engaged enough to specify the requirements in terms of Cucumber tests, or FitNesse tests there is no better alternative.
Teams that are not so fortunate are not likely to benefit from this practice.
My personal rule is: If the customers neither read nor write the tests, then high level unit tests written in code suffice.
客户测试
许多客户不想为这些测试而烦恼。
这是一种遗憾,因为它们显然是指定需求的最佳方式。
对于那些有足够客户参与的团队来说,就黄瓜测试或FitNesse测试而言,没有更好的替代方案。
不那么幸运的团队不太可能从这种实践中获益。
我个人的原则是:如果客户既不读也不写测试,那么用代码编写的高级单元测试就足够了。
Small Releases. It’s hard to imagine a team that would not benefit from this practice. Keep the releases small.
The more time you wait between exposing the customers to the system, the more can go wrong.
小版本
很难想象一个团队不会从这种实践中受益。版本要小。
在将客户暴露给系统之间等待的时间越长,出错的可能性就越大。
Whole Team.
Again, it’s hard to imagine a team that would not benefit from a close relationships between the business people, and the developers.
Not all teams are so fortunate, of course.
完整的团队
同样,很难想象一个团队不会从业务人员和开发人员之间的密切关系中受益。
当然,并非所有团队都如此幸运。
Collective Ownership.
As far as I’m concerned any team that has individual code ownership is deeply dysfunctional.
If the owner of some part of the code decides to leave, the whole team is left in crisis mode.
There are many ways to achieve collective ownership, but the bottom line is very simple.
No single individual should be able to hold the team hostage.
Every part of the code should be known by more than one person – the more the better.
集体所有制
就我所知,任何拥有独立代码所有权的团队都是非常不正常的。
如果某部分代码的所有者决定离开,那么整个团队就会陷入危机模式。
实现集体所有制的方法有很多,但最根本的是非常简单的。
任何一个人都不能挟持整个团队。
代码的每一部分都应该被不止一个人知道——越多越好。
Coding Standard.
This simply goes along with Collective Ownership.
The code should look like the team wrote it, not like one of the individuals wrote it.
The members of the team should agree on the way that their code will appear.
This isn’t rocket science.
代码规范
这与集体所有制是一致的。
代码应该看起来像团队编写的,而不是某个个人编写的。
团队成员应该就代码出现的方式达成一致。
这不是火箭科学。
Sustainable Pace.
This is a real simple idea. Software projects are marathons, not sprints.
You dare not run at a rate that you cannot sustain for the long term.
Murphy tells us that any team that violates this practice is doomed to flame out at the worst possible moment.
可持续的速度
这是一个非常简单的想法。软件项目是马拉松,而不是短跑。
你不敢以你不能长期维持的速度跑步。
Murphy告诉我们,任何违反这种做法的团队注定会在最糟糕的时刻熄火。
Continuous Integration.
Certainly there are teams who’s projects are so small that setting up a CI server is redundant.
However, for most teams this is such a positive win that neglecting it would be immoral, if not insane.
持续集成
当然,有些团队的项目非常小,设置CI服务器是多余的。
然而,对于大多数球队来说,这是一场积极的胜利,忽视它将是不道德的,如果不是疯狂的。
Pair Programming.
Some teams benefit greatly by using this practice. Others do not.
For the latter, some form of code review is likely necessary.
In any case, it is a very good idea for every line of code to have been seen by more than one pair of eyes.
结对编程
一些团队通过使用这个实践大大受益。别人不。
对于后者,可能需要进行某种形式的代码检查。
无论如何,让每一行代码都被不止一双眼睛看到是一个非常好的想法。
Simple Design.
If we learned anything in the ’90s it is that over-design is suicide.
The level of design is team dependent, of course; but the simpler the better is simply a good rule of thumb.
简单设计
如果说我们在90年代学到了什么,那就是过度设计就是自杀。
当然,设计水平取决于团队;但是越简单越好是一个很好的经验法则。
Refactoring.
Does anybody really want to argue that programmers should not keep their code as clean as possible?
Does anyone want to argue that code should not be improved with time?
Teams may choose different degrees of refactoring; but zero is probably not acceptable.
重构
真的有人认为程序员不应该尽可能保持代码干净吗?
有没有人认为代码不应该随着时间的推移而改进?
团队可以选择不同程度的重构;但零可能是不可接受的。
Test Driven Development.
This is certainly the most controversial of all the Agile practices.
But the controversy is not about the word Test.
Virtually everyone agrees that writing unit tests is important.
Some of us think that the order in which they are written is important too.
Different teams will choose different strategies. But teams that ignore testing are not destined for rapid success.
测试驱动开发
这无疑是所有敏捷实践中最具争议的。
但争议并不在于Test这个词。
几乎每个人都同意编写单元测试很重要。
我们中的一些人认为书写的顺序也很重要。
不同的团队会选择不同的策略。但是忽视测试的团队注定不会很快成功。
Conclusion
Does every team need every one of these practices? Certainly not.
Do most teams need at least some of them? Of course they do! Again, choose wisely!
总结
每个团队都需要这些实践吗?当然不是。
大多数团队至少需要其中一些吗?当然了!再次,做出明智的选择!
I believe that the author of the original article was exposed to teams who were doing Flaccid Scrum and made the mistake that that’s all there was to Agile.
He is correct that there have been some uninformed consultancies who have taught this poor variant of the Agile practices. In that sense his diatribe is understandable.
Still, ignorance is no excuse. If you are going to impugn the character of good people and good ideas, you’d better do your damned homework.
我相信,原文章的作者接触过一些团队,他们在做Flaccid Scrum时犯了一个错误,认为敏捷就是这样。
他说的没错,有一些不知情的顾问教授了敏捷实践的这种糟糕变体。从这个意义上说,他的谩骂是可以理解的。
不过,无知并不是借口。如果你要质疑好人和好主意的品格,你最好做好你那该死的功课。
### 3. 点评
Bob达叔反驳了《敏捷是新的瀑布》的作者。他介绍了敏捷实战的一些关键点。
## Tip
### Nginx负载均衡策略和配置
1. 轮询:默认策略
2. 权重策略,配置如下:
```
upstream project {
server 127.0.0.1:8001 weight=2;
server 127.0.0.1:8002 weight=1;
}
```
ps:weight值越大,被发送请求的频率就越高
3. 备用策略,配置如下:
```
server localhost:8082 backup;
```
ps:标记该服务器为备用服务器。当主服务器停止时,请求会被发送到这里
4. 较少链接策略,配置如下:
```
upstream project {
least_conn; #把请求转发给连接数较少的后端服务器
server 127.0.0.1:8001 weight=2;
server 127.0.0.1:8002 weight=1;
}
```
ps:此负载均衡策略适合请求处理时间长短不一造成服务器过载的情况。
## Share
### CNCF x Alibaba 云原生技术公开课
[https://edu.aliyun.com/roadmap/cloudnative](https://edu.aliyun.com/roadmap/cloudnative) |
C# | UTF-8 | 4,262 | 3.109375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace ACO_TSP
{
public class OptimizationTSP
{
int[,] dist;
public OptimizationTSP(int[,] dist)
{
this.dist = dist;
}
public void opt2(int[] tour)
{
int i, j, k;
int a1, a2, a3, b1, b2, b3, swap;
for (i = 1; i < tour.Length - 2; i++)
{
a1 = dist[tour[i - 1], tour[i]];
a2 = dist[tour[i], tour[i + 1]];
a3 = dist[tour[i + 1], tour[i + 2]];
b1 = dist[tour[i - 1], tour[i + 1]];
b2 = dist[tour[i + 1], tour[i]];
b3 = dist[tour[i], tour[i + 2]];
if (a1 + a2 + a3 > b1 + b2 + b3)
{
//Console.WriteLine("opt2: optimization done!");
swap = tour[i];
tour[i] = tour[i + 1];
tour[i + 1] = swap;
}
}
}
public void opt3(int[] tour)
{
int i, j, k;
int[] distances = { 0, 0, 0, 0, 0, 0 };
for (i = 1; i < tour.Length - 3; i++)
{
// ABC
distances[0] = dist[tour[i - 1], tour[i]] + dist[tour[i], tour[i + 1]] + dist[tour[i + 1], tour[i + 2]] + dist[tour[i + 2], tour[i + 3]];
// ACB
distances[1] = dist[tour[i - 1], tour[i]] + dist[tour[i], tour[i + 2]] + dist[tour[i + 2], tour[i + 1]] + dist[tour[i + 1], tour[i + 3]];
// BAC
distances[2] = dist[tour[i - 1], tour[i + 1]] + dist[tour[i + 1], tour[i]] + dist[tour[i], tour[i + 2]] + dist[tour[i + 2], tour[i + 3]];
// BCA
distances[3] = dist[tour[i - 1], tour[i + 1]] + dist[tour[i + 1], tour[i + 2]] + dist[tour[i + 2], tour[i]] + dist[tour[i], tour[i + 3]];
// CAB
distances[4] = dist[tour[i - 1], tour[i + 2]] + dist[tour[i + 2], tour[i]] + dist[tour[i], tour[i + 1]] + dist[tour[i + 1], tour[i + 3]];
// CBA
distances[5] = dist[tour[i - 1], tour[i + 2]] + dist[tour[i + 2], tour[i + 1]] + dist[tour[i + 1], tour[i]] + dist[tour[i], tour[i + 3]];
// caut min
int min = Int32.MaxValue;
int minIdx = -1;
for (j = 0; j < 6; j++)
{
if (min > distances[j])
{
min = distances[j];
minIdx = j;
}
}
int swap;
switch (minIdx)
{
case 0: // ABC
break;
case 1: // ACB
//Console.WriteLine("opt3: optimization done!");
this.swap(tour, i + 1, i + 2);
break;
case 2: // BAC
//Console.WriteLine("opt3: optimization done!");
this.swap(tour, i, i + 1);
break;
case 3: // BCA
//Console.WriteLine("opt3: optimization done!");
// ABC -> BAC
this.swap(tour, i, i + 1);
// BAC -> BCA
this.swap(tour, i + 1, i + 2);
break;
case 4: // CAB
//Console.WriteLine("opt3: optimization done!");
// ABC -> CBA
this.swap(tour, i, i + 2);
// CBA -> CAB
this.swap(tour, i + 1, i + 2);
break;
case 5: // CBA
//Console.WriteLine("opt3: optimization done!");
this.swap(tour, i, i + 2);
break;
}
}
}
public void swap(int[] tour, int i, int j)
{
int swap = tour[i];
tour[i] = tour[j];
tour[j] = swap;
}
}
}
|
PHP | UTF-8 | 1,315 | 2.515625 | 3 | [] | no_license | <?php
/**
* Copyright 2010 - 2013, Cake Development Corporation (http://cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2013, Cake Development Corporation (http://cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* Static 0: Hide, 1:Active, 2:Expired, 3:Reserved
*/
class Staticpage extends AppModel
{
var $name = 'Staticpage';
public $validate = array(
'title' => array(
'rule1' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => "Title is not empty"
),
),
'slug' => array(
'rule1' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => "Slug is not empty"
),
'rule2' => array(
'rule' => 'isUnique',
'required' => true,
'message' => "Slug is Unique and not duplicate"
),
),
'content' => array(
'rule1' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => "Content is not empty"
),
),
);
} |
Java | ISO-8859-9 | 5,376 | 2.59375 | 3 | [] | no_license | // J5i_13.java: MultiListener (okluDinleyici) rnei.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
public class J5i_13 extends JPanel implements ActionListener {
JTextArea stMetinAlan;
JTextArea altMetinAlan;
JButton dme1, dme2;
final static String yeniSatr = "\n";
public J5i_13() {// Kurucu...
super (new GridBagLayout());
GridBagLayout zgaraantaSerilim = (GridBagLayout)getLayout();
GridBagConstraints snrlayclar = new GridBagConstraints();
JLabel etiket = null;
snrlayclar.fill = GridBagConstraints.BOTH;
snrlayclar.gridwidth = GridBagConstraints.REMAINDER;
etiket = new JLabel ("Senin duyduklarn:");
zgaraantaSerilim.setConstraints (etiket, snrlayclar);
add (etiket);
snrlayclar.weighty = 1.0;
stMetinAlan = new JTextArea();
stMetinAlan.setBackground (Color.getHSBColor ((float)Math.random(), (float)Math.random(), 0.65f) );
stMetinAlan.setForeground (Color.YELLOW);
stMetinAlan.setEditable (false); // Mdahalesiz...
JScrollPane stKaydra = new JScrollPane (stMetinAlan);
Dimension tercihiEbat = new Dimension (200, 75);
stKaydra.setPreferredSize (tercihiEbat);
zgaraantaSerilim.setConstraints (stKaydra, snrlayclar);
add (stKaydra);
snrlayclar.weightx = 0.0;
snrlayclar.weighty = 0.0;
etiket = new JLabel ("Dam stndeki saksaann duyduklar:");
zgaraantaSerilim.setConstraints (etiket, snrlayclar);
add (etiket);
snrlayclar.weighty = 1.0;
altMetinAlan = new JTextArea();
altMetinAlan.setBackground (Color.getHSBColor ((float)Math.random(), (float)Math.random(), 0.45f) );
altMetinAlan.setForeground (Color.CYAN);
altMetinAlan.setEditable (false); // Mdahalesiz...
JScrollPane altKaydra = new JScrollPane (altMetinAlan);
altKaydra.setPreferredSize (tercihiEbat);
zgaraantaSerilim.setConstraints (altKaydra, snrlayclar);
add (altKaydra);
snrlayclar.weightx = 1.0;
snrlayclar.weighty = 0.0;
snrlayclar.gridwidth = 1;
snrlayclar.insets = new Insets (1,1, 0,1);
dme1 = new JButton ("Lak lak lak");
zgaraantaSerilim.setConstraints (dme1, snrlayclar);
add (dme1);
snrlayclar.gridwidth = GridBagConstraints.REMAINDER;
dme2 = new JButton ("Deme yahu!");
zgaraantaSerilim.setConstraints (dme2, snrlayclar);
add (dme2);
dme1.addActionListener (this); // Her iki dme de dinleyiciye duyarl...
dme2.addActionListener (this);
// dme2, ayrca alt metin alan iin zel dinleyiciye de duyarl...
dme2.addActionListener (new DamstSaksaan (altMetinAlan));
setPreferredSize (new Dimension (250, 300));
setBorder (BorderFactory.createCompoundBorder (
BorderFactory.createMatteBorder (2,2,5,5,Color.ORANGE),
BorderFactory.createEmptyBorder (5,5,5,5)));
} // J5i_13() kurucusu sonu...
public void actionPerformed (ActionEvent olay) {
stMetinAlan.append (olay.getActionCommand() + yeniSatr);
stMetinAlan.setCaretPosition (stMetinAlan.getDocument().getLength());
} // actionPerformed(..) hazr metodu sonu...
private static void yaratVeGsterGUI() {
JFrame ereve = new JFrame ("oklu Dinleyici");
ereve.setDefaultCloseOperation (3); // 3=JFrame.EXIT_ON_CLOSE
JComponent yenierikPanosu = new J5i_13(); // Kurucuyu arr...
yenierikPanosu.setOpaque (true);
ereve.setContentPane (yenierikPanosu);
ereve.setLocation (500,50);
ereve.pack();
ereve.setVisible (true);
} // yaratVeGsterGUI() metodu sonu...
public static void main (String[] args) {
SwingUtilities.invokeLater (new Runnable() {public void run() {yaratVeGsterGUI();}});
} // main(..) metodu sonu...
} // J5i_13 snf sonu...
class DamstSaksaan implements ActionListener {
JTextArea metinAlanm;
public DamstSaksaan (JTextArea ma) {metinAlanm = ma;} // Kurucu...
public void actionPerformed (ActionEvent olay) {
metinAlanm.append (olay.getActionCommand() + J5i_13.yeniSatr);
metinAlanm.setCaretPosition (metinAlanm.getDocument().getLength());
} // actionPerformed(..) hazr metodu sonu...
} // DamstSaksaan snf sonu... |
C++ | UTF-8 | 569 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int T[2];
srand(time(NULL));
for (int i = 0; i < 20; i++) {
T[0] = (rand() % 900) + 100; //(zakres 100 - 1000)
T[1] = (rand() % 900) + 100;
cout << T[0] << " " << T[1] << endl;
if (T[0] % T[1] == 0) cout << "Liczba " << T[0] << " jest podzielna przez liczbe " << T[1] << endl;
else if (T[1] % T[0] == 0) cout << "Liczba " << T[1] << " jest podzielna przez liczbe " << T[2] << endl;
else cout << "Liczby nie sa przez siebie podzielne\n";
}
return 0;
} |
C++ | WINDOWS-1250 | 1,353 | 2.75 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tank
//
// Germn Martnez
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef ___Tank_h___
#define ___Tank_h___
#include <src/entities/Entity.h>
#include <src/base/Direction.h>
#include <mach/Point.h>
class Sprite;
class Tank : public Entity
{
public:
//
// Modelos de tanque
//
enum
{
TANK_MODEL_HERO_1 = 0,
TANK_MODEL_HERO_2 = 1,
TANK_MODEL_HERO_3 = 2,
TANK_MODEL_HERO_4 = 3,
TANK_MODEL_ENEMY_1 = 4,
TANK_MODEL_ENEMY_2 = 5,
TANK_MODEL_ENEMY_3 = 6,
TANK_MODEL_ENEMY_4 = 7,
MAX_TANK_MODELS = 8,
};
//
// Colores de tanque
//
enum
{
TANK_COLOR_RED = 0,
TANK_COLOR_GRAY = 1,
TANK_COLOR_BROWN = 2,
TANK_COLOR_GREEN = 3,
MAX_TANK_COLORS = 4,
};
protected:
Direction dir;
int tankModel;
int tankColor;
Sprite* sprite;
int animIndex;
public:
Tank(Map* m, Scene* s, int x, int y, int model, int color);
~Tank();
public:
void render(Graphics* gr);
private:
void updateSprite();
int getSpriteIndex() const;
bool moveVert(int dx, int dy);
bool moveHorz(int dx, int dy);
protected:
Point getShootPosition(Direction dir) const;
bool move(int dx, int dy);
void selectTankModel(int model);
void selectTankColor(int color);
};
#endif
|
Java | UTF-8 | 1,633 | 2.078125 | 2 | [] | no_license | package com.lavector.collector.crawler.project.article.tianya;
import com.lavector.collector.crawler.base.BaseCrawler;
import com.lavector.collector.crawler.base.CrawlerInfo;
import com.lavector.collector.crawler.base.CrawlerType;
import com.lavector.collector.crawler.base.MySpider;
import com.lavector.collector.crawler.project.article.Brand;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Request;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created on 2017/12/26.
*
* @author zeng.zhao
*/
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Service(CrawlerType.TIANYA_ARTICLE)
public class TianYaCrawler extends BaseCrawler {
@Override
protected MySpider createSpider(CrawlerInfo crawlerInfo) {
MySpider spider = MySpider.create(new TianYaPageProcessor(crawlerInfo));
spider.thread(10);
spider.startRequest(getStartRequest());
return spider;
}
private List<Request> getStartRequest() {
String baseUrl = "http://search.tianya.cn/bbs?q=";
return Brand.brands.keySet().stream().map(brand -> {
Request request = new Request(baseUrl + brand + "&pn=1&s=4");
request.putExtra("brand", brand);
return request;
}).collect(Collectors.toList());
}
public static void main(String[] args) {
TianYaCrawler crawler = new TianYaCrawler();
MySpider spider = crawler.createSpider(new CrawlerInfo());
spider.start();
}
}
|
C++ | UTF-8 | 2,153 | 2.65625 | 3 | [] | no_license | //Segment tree - lazy propagation
#include<cstdio>
#include<algorithm>
#include<cstring>
#define TREESIZE 400000
#define SIZE 100005
using namespace std;
int t, choice;
long long segtree[TREESIZE], lazy[TREESIZE], dif;
long n, c, i;
long st, nd; //for range sum and range update query
// -- RANGE SUM --
long long rangeSum(long l, long r, long idx) {
if (lazy[idx] != 0) { //if lazy node
segtree[idx] += (r-l+1)*lazy[idx];
if (l != r) { //not a leaf node
lazy[(idx<<1) + 1] += lazy[idx]; //mark its children as lazy
lazy[(idx<<1) + 2] += lazy[idx];
}
lazy[idx] = 0; //reset it
}
if (l>nd || r<st) return 0; //fully outside
if (l >= st && r <= nd) return segtree[idx]; //fully inside
long mid = (l+r)/2; //partial
return rangeSum(l, mid, ((idx<<1) + 1)) +
rangeSum(mid+1, r, ((idx<<1) + 2));
}
// -- RANGE UPDATE --
void update_rsq(long l, long r, long idx) {
if (lazy[idx] != 0) { //if lazy node
segtree[idx] += (r-l+1)*lazy[idx];
if (l != r) { //not a leaf node
lazy[(idx<<1) + 1] += lazy[idx]; //mark its children as lazy
lazy[(idx<<1) + 2] += lazy[idx];
}
lazy[idx] = 0; //reset it
}
if (l>nd || r<st) return; //fully outside
if (l >= st && r <= nd) { //fully inside
segtree[idx] += (r-l+1)*dif;
if (l != r) { //not a leaf node
lazy[(idx<<1) + 1] += dif; //mark its children as lazy
lazy[(idx<<1) + 2] += dif;
}
return;
}
long mid = (l+r)/2;
update_rsq(l, mid, ((idx<<1) + 1));
update_rsq((mid + 1), r, ((idx<<1) + 2));
segtree[idx] = segtree[(idx<<1) + 1] + segtree[(idx<<1) + 2];
}
int main() {
scanf("%d",&t);
while (t--) {
memset(segtree,0,sizeof(segtree));
memset(lazy,0,sizeof(lazy));
scanf("%ld %ld", &n, &c);
while (c--) {
scanf("%d",&choice);
if (choice == 0) { //range update query
scanf("%ld %ld %lld",&st, &nd, &dif);
st--; nd--;
update_rsq(0,n-1,0);
}
else { //range sum query
scanf("%ld %ld",&st, &nd);
st--; nd--;
printf("%lld\n",rangeSum(0,n-1,0));
}
}
}
return 0;
}
|
Python | UTF-8 | 3,936 | 3.65625 | 4 | [] | no_license | #Import the two sets of revenue data (`budget_data_1.csv` and `budget_data_2.csv`).
import os
import csv
data_1_path = os.path.join(".", "budget_data_1.csv")
combined_data = {}
#function to re-format dates
def format_date(full_date):
split = full_date.rpartition("-")
month = split[0]
year = split[2]
if month == "Jan":
month = "01"
elif month == "Feb":
month = "02"
elif month == "Mar":
month = "03"
elif month == "Apr":
month = "04"
elif month == "May":
month = "05"
elif month == "Jun":
month = "06"
elif month == "Jul":
month = "07"
elif month == "Aug":
month ="08"
elif month == "Sep":
month = "09"
elif month == "Oct":
month = "10"
elif month == "Nov":
month = "11"
elif month == "Dec":
month = "12"
if len(year) > 2:
year = year[2:]
return(str(year) + "-" + str(month))
def month_year(formatted_date):
split = formatted_date.rpartition("-")
year = split[0]
month = split[2]
return(str(month) + "-" + str(year))
#open first CSV
with open(data_1_path, newline="") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
date = format_date(row["Date"])
revenue = row["Revenue"]
combined_data[date] = revenue
#open second CSV
data_2_path = os.path.join(".", "budget_data_2.csv")
with open(data_2_path, newline="") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
date = format_date(row["Date"])
revenue = row["Revenue"]
if date not in combined_data:
combined_data[date] = revenue
#put the date/revenue in the dictionary
else:
combined_data[date] = int(combined_data[date]) + int(revenue)
#add the revenue to the matching date
#The total number of months included in the dataset
print("Total months: " + str(len(combined_data)))
#The total amount of revenue gained over the entire period
revenue_sum = 0
for data in combined_data:
#print(data)
revenue_sum = revenue_sum + int(combined_data[data])
print("Total revenue: $" + str(revenue_sum))
revenue_change = 0
previous = None
greatest_inc = 0
greatest_dec = 0
for key in sorted(combined_data.keys()):
if previous is None:
previous = combined_data[key]
else:
#Gathering total revenue change
revenue_change = revenue_change + int(combined_data[key]) - int(previous)
#The greatest increase in revenue (date and amount) over the entire period
if int(combined_data[key]) - int(previous) > greatest_inc:
greatest_inc = int(combined_data[key]) - int(previous)
inc_date = str(key)
#The greatest decrease in revenue (date and amount) over the entire period
if int(combined_data[key]) - int(previous) < greatest_dec:
greatest_dec = int(combined_data[key]) - int(previous)
dec_date = str(key)
previous = combined_data[key]
print("Average change over time: $" + str(revenue_change/len(combined_data)))
print("Greatest increase: $" + str(greatest_inc) + ", occurred " + month_year(inc_date))
print("Greatest decrease: $" + str(greatest_dec) + ", occurred " + month_year(dec_date))
file = open("mainpy.txt","w")
file.write("Total months: " + str(len(combined_data)) + "\n")
file.write("Total revenue: $" + str(revenue_sum) + "\n")
file.write("Average change over time: $" + str(revenue_change/len(combined_data)) + "\n")
file.write("Greatest increase: $" + str(greatest_inc) + ", occurred " + month_year(inc_date) + "\n")
file.write("Greatest decrease: $" + str(greatest_dec) + ", occurred " + month_year(dec_date) + "\n")
file.close()
#Your final script should both print the analysis to the terminal and export a text file with the results.
|
Markdown | UTF-8 | 1,245 | 2.59375 | 3 | [
"MIT"
] | permissive | ---
title: "PowerShell 实现 curl 的用户名和密码逻辑"
author: lindexi
date: 2021-1-16 8:42:55 +0800
CreateTime: 2021/1/16 8:39:45
categories:
---
在使用 curl 时,可以采用 -u 加上用户名和密码,这个对应在 PowerShell 也就是不到 10 句话的事情
<!--more-->
<!-- CreateTime:2021/1/16 8:39:45 -->
<!-- 发布 -->
假定使用 curl 输入的是如下代码
```
curl -ulindexi:AP7doYUzM7WApXobRb7X9qgURCF -T "E:\lindexi\doubi.exe" "https://blog.lindexi.com/artifactory/doubi.exe"
```
通过上面代码可以给我的存储服务上传文件
此时的 `-ulindexi:AP7doYUzM7WApXobRb7X9qgURCF` 的含义就是 `-u <用户名:密码>` 在对应的 Http 里面就是在 Head 的 Authorization 加入信息
在 PowerShell 中,按照规范需要传入一段 base64 的字符,于是代码如下
```
$encodedAuthString = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("lindexi:AP7doYUzM7WApXobRb7X9qgURCF"))
$Headers =
@{
Authorization = "Basic $encodedAuthString"
}
Invoke-WebRequest -Method Put -Uri "https://blog.lindexi.com/artifactory/doubi.exe" -Headers $Headers -InFile "E:\lindexi\doubi.exe"
```
感谢工具人 [lsj](https://blog.sdlsj.net/ ) 提供的方法
|
Markdown | UTF-8 | 3,400 | 2.859375 | 3 | [] | no_license | # Main Viewer

When openend, AMP will display its main image viewer. This window will contain figures generated
by plugins as well as direct images loaded in via the 'Open Cohort' menu option.
### Cohort Loading
To load a cohort of images into the viewer, find the `Open Cohort...` option under the `File`
section of the upper taskbar.

This will open a file explorer. Selecting and opening a folder in this explorer will have `AMP`
walk through the subdirectories within said folder until it finds the most shallow depth containing
`.tif(f)` files. It will then load the directory structure from the selected folder, through said
depth, into the `Files` section of the main viewer.
For example, for selecting the folder `slide01` with structure:
```
slide01
|
|------- fov1
| |-------- TIFs
| |-------- Au.tif
| |-------- betacat.tif
| ...
|
|------- fov2
| |-------- TIFs
| |-------- Au.tif
| ...
...
```
will find all of the FOV's channels. As a counter-example, selecting the folder `bad_slide01`:
```
bad_slide01
|
|------- fov1
| |-------- TIFs
| |-------- Au.tif
| |-------- betacat.tif
| ...
|
|------- fov2
| |-------- TIFs
| |-------- Au.tif
| ...
|
|------- bad.tif
...
```
will only load in tifs at the same file depth as `bad.tif`.
<div
style="
border: 0px solid #35f;
border-left-width: 6px;
padding: 8px;
margin-bottom: 8px;
background-color: #acf;
color: #000"
>
<b><i>Note</i></b>: The file explorer can only search for tifs at file depths less than 6,
relative to the selected folder.
</div>
![]()
If the cohort was successfully loaded, you should now see a file tree within the `Files` section
(1) of the main viewer.
Clicking on displayed checkboxes will add a figure displaying that image to the `Figures` section
(2) of the viewer.

Figures within this section can be freely renamed, reordered, deleted, and unchecked.

### View Features
#### Contrast Adjustment
For dim images, contrast can be enhanced via the `Brightness and Contrast` adjustment tool within
the `Image` section of the upper taskbar.

To brighten the image, simply drag the `Max` slider towards the left. It's recommended to enable
the `Locked` checkbox to preserve separate contrast settings for each figure.
<div
style="
border: 0px solid #35f;
border-left-width: 6px;
padding: 8px;
margin-bottom: 8px;
background-color: #acf;
color: #000"
>
<b><i>Note</i></b>: Again, this tool is under active development, so exact details on
functionality are subject to change.
</div>

#### Breakout Windows
To move a figure to a separate window, press the `Breakout` button.

Deleting this window will move the figure back into the `Figures` list within the main viewer,
where it can be deleted via the `Delete` button.
***
▶️ *NEXT*: [Plugin Loading](./plugin_loading.md)
◀️ *PREVIOUS*: [Installation](./installation.md) |
PHP | UTF-8 | 2,690 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EditUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => ['required','alpha','max:110','min:2'],
'lastname' => ['required','alpha','max:110','min:2'],
'nick' => ['required','regex:(^[a-zA-Z0-9.]+$)','max:80','min:2'],
'email' => ['required','email','max:100'],
'role' => ['required','numeric','exists:roles,id'],
'city' => ['required','numeric','exists:cities,id'],
'password' => ['confirmed']
];
}
public function messages()
{
return [
'name.required' => 'Campo Nombre es obligatorio',
'name:alpha' => 'Solo se permite el uso de letras',
'name.max' => 'Nombre no puede superar los 110 caracteres',
'name.min' => 'Nombre debe ser superior a 2 letras',
'lastname.required' => 'Campo Apellido es obligatorio',
'lastname:alpha' => 'Solo se permite el uso de letras',
'lastname.max' => 'Apellido no puede superar los 110 caracteres',
'lastname.min' => 'Apellido debe ser superior a 2 letras',
'nick.required' => 'Campo NIck/Nombre de usuario es obligatorio',
'nick.regex' => 'Solo se permite el uso de letras, numeros, y punto (.)',
'nick.max' => 'Nick no puede superar los 80 caracteres',
'nick.min' => 'Nick debe ser superior a 2 caracteres',
'nick.unique' => 'El Nombre de usuario o nick ya existe',
'email.required' => 'Campo Correo Electronico es obligatorio',
'email.email' => 'No es un formato de corre electronico',
'email.max' => 'tu correo no debe superar los 100 caracteres',
'email.unique' => 'Correo Electronico ya existe',
'role.required' => 'Debes Seleccionar un Rol',
'role.numeric' => 'Algo malo ha ocurrido, refresca tu navegador',
'city.required' => 'Debes Seleccionar un Rol',
'city.numeric' => 'Algo malo ha ocurrido, refresca tu navegador',
'password.confirmed' => 'Las contraseñas no coinciden',
'password.min' => 'La contraseña debe ser minimo de 6 caracteres',
'password.max' => 'La contrasela no debe superar los 12 caracteres'
];
}
}
|
C# | UTF-8 | 5,625 | 3.1875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Sixeyed.Mapping.MappingStrategies;
using Sixeyed.Mapping.MatchingStrategies;
using Sixeyed.Mapping.Spec;
namespace Sixeyed.Mapping
{
/// <summary>
/// Automap for populating an object from another object
/// </summary>
/// <remarks>
/// By default, uses <see cref="SimpleNameMatchingStrategy"/>, matching target properties which have
/// similar names to source properties. Ignores case and non-aplhanumeric characters
/// </remarks>
/// <typeparam name="TSource">Type of source object</typeparam>
/// <typeparam name="TTarget">Type of target object</typeparam>
public class AutoMap<TSource, TTarget> : ClassMap<TSource, TTarget>
where TTarget : class, new()
where TSource : class
{
/// <summary>
/// Whether to automatically matach & map unspecified target properties
/// </summary>
/// <remarks>
/// Required by map base, in AutoMap always returns true
/// </remarks>
public override bool AutoMapUnspecifiedTargets
{
get { return true; }
set { } //do nothing
}
/// <summary>
/// Specify the caching strategy for the map, used to cache the property match between source and target
/// </summary>
/// <typeparam name="TCachingStrategy"></typeparam>
/// <returns></returns>
public new AutoMap<TSource, TTarget> Cache<TCachingStrategy>()
where TCachingStrategy : ICachingStrategy, new()
{
return (AutoMap<TSource, TTarget>)base.Cache<TCachingStrategy>();
}
/// <summary>
/// Specify the matching strategy for the map, used to match source and target properties
/// </summary>
/// <typeparam name="TMatchingStrategy"></typeparam>
/// <returns></returns>
public new AutoMap<TSource, TTarget> Matching<TMatchingStrategy>()
where TMatchingStrategy : IMatchingStrategy<string>, new()
{
return (AutoMap<TSource, TTarget>)base.Matching<TMatchingStrategy>();
}
/// <summary>
/// Specify an explicit property mapping
/// </summary>
/// <typeparam name="TInput">Source property type</typeparam>
/// <typeparam name="TOutput">Target property type</typeparam>
/// <param name="sourcePropertyExpression">Accessor for the source property to get</param>
/// <param name="targetPropertyExpression">Accessor for the target property to set</param>
/// <returns></returns>
public new AutoMap<TSource, TTarget> Specify<TInput, TOutput>(Func<TSource, TInput> sourcePropertyExpression, Expression<Func<TTarget, TOutput>> targetPropertyExpression)
{
return (AutoMap<TSource, TTarget>)base.Specify<TInput, TOutput>(sourcePropertyExpression, targetPropertyExpression);
}
/// <summary>
/// Specify an explicit property mapping with a value conversion
/// </summary>
/// <typeparam name="TInput">Source property type</typeparam>
/// <typeparam name="TOutput">Target property type</typeparam>
/// <param name="sourcePropertyExpression">Accessor for the source property to get</param>
/// <param name="targetPropertyExpression">Accessor for the target property to set</param>
/// <param name="conversion">Conversion function to apply to the source value</param>
/// <returns></returns>
public new AutoMap<TSource, TTarget> Specify<TInput, TOutput>(Func<TSource, TInput> sourcePropertyExpression, Expression<Func<TTarget, TOutput>> targetPropertyExpression, Func<TInput, TOutput> conversion)
{
return (AutoMap<TSource, TTarget>)base.Specify<TInput, TOutput>(sourcePropertyExpression, targetPropertyExpression, conversion);
}
/// <summary>
/// Specify an explicit property mapping
/// </summary>
/// <param name="mappingAction">Action to populate target property value</param>
/// <returns></returns>
public new AutoMap<TSource, TTarget> Specify(Action<TSource, TTarget> mappingAction)
{
return (AutoMap<TSource, TTarget>)base.Specify(mappingAction);
}
/// <summary>
/// Populate an existing target object from a source object
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
public static void PopulateTarget(TSource source, TTarget target)
{
var map = new AutoMap<TSource, TTarget>();
map.Populate(source, target);
}
/// <summary>
/// Create a target object populated from a source object
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static TTarget CreateTarget(TSource source)
{
var map = new AutoMap<TSource, TTarget>();
return map.Create(source);
}
/// <summary>
/// Create a collection of target objects from a collection of source objects
/// </summary>
/// <param name="sourceList"></param>
/// <returns></returns>
public static List<TTarget> CreateTargetList(IList<TSource> sourceList)
{
var map = new AutoMap<TSource, TTarget>();
return map.CreateList(sourceList);
}
}
}
|
C++ | GB18030 | 30,425 | 2.65625 | 3 | [] | no_license | // FtpFile.cpp : ʵļ
//
#include "stdafx.h"
#include "FtpFile.h"
//#include ".\ftpfile.h"
// CFtpFile
CFtpFile::CFtpFile()
{
}
CFtpFile::~CFtpFile()
{
}
// ϴļ
BOOL CFtpFile::UploadFiletoFile(CString strLocalFilePath, CString strServerFilePath, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strLocalFilePath!="")&&(strServerFilePath!=""))
{
//жϱļǷ
CFileFind ff;
BOOL a=ff.FindFile(strLocalFilePath);
if(!a)
{
//AfxMessageBox("Ҫļڻ·ȷ");
}
else
{
//ʼFTP
CInternetSession* pSession;
CFtpConnection* pConnection;
pConnection=NULL;
//
pSession=new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
//
if(pConnection!=NULL)
{
BOOL b=pConnection->PutFile(strLocalFilePath,strServerFilePath);
if(b)
{
//AfxMessageBox("ļɹ");
returnvalue=1;
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
//AfxMessageBox("ӷʧܣ");
}
}
}
else
{
//AfxMessageBox("벻Ϊգ");
}
return returnvalue;
}
// ϴļָĿ¼
BOOL CFtpFile::UploadFiletoDirectory(CString strLocalFilePath, CString strServerDirectoryPath,FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strServerDirectoryPath!="")&&(strLocalFilePath!=""))
{
//жϱļǷ
CFileFind ff;
BOOL a=ff.FindFile(strLocalFilePath);
if(!a)
{
//AfxMessageBox("Ҫļڻ·ȷ");
}
else
{
//ʼFTP
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//
pSession=new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
//
if(pConnection!=NULL)
{
pFileFind=new CFtpFileFind(pConnection);
BOOL b=pFileFind->FindFile(strServerDirectoryPath);
//ָĿ¼Ƿ
if(!b)
{
//AfxMessageBox("ļĿ¼ڣ");
pFileFind->Close();
pFileFind=NULL;
}
else
{
//ͬļ
CString strName;
int numStart=strLocalFilePath.ReverseFind('\\');
if(numStart!=-1)
strName=strLocalFilePath.Right(strLocalFilePath.GetLength()-numStart-1).GetString();
CString strServerFilePath;
if(strServerDirectoryPath.Right(1)!="/")
strServerFilePath=strServerDirectoryPath+"/"+strName;
else
strServerFilePath=strServerDirectoryPath+strName;
//AfxMessageBox(strServerFilePath);
//AfxMessageBox(strName);
BOOL c=pConnection->PutFile(strLocalFilePath,strServerFilePath);
if(c)
{
//AfxMessageBox("ļɹ");
returnvalue=1;
}
}
//ϿFTP
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
//AfxMessageBox("ӷʧܣ");
}
}
}
else
{
//AfxMessageBox("벻Ϊգ");
}
return returnvalue;
}
// ϴĿ¼ļָĿ¼
BOOL CFtpFile::UploadDirectorytoDirectory(CString strLocalDirectoryPath, CString strServerDirectoryPath, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strLocalDirectoryPath!="")&&(strServerDirectoryPath!=""))
{
//ұĿ¼
CFileFind ff;
BOOL a=ff.FindFile(strLocalDirectoryPath);
if(!a)
{
AfxMessageBox("ҪĿ¼ڻ·ȷ");
}
//ҷĿ¼
else
{
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//ʼ
pFileFind= new CFtpFileFind(pConnection);
//ҷĿ¼
pConnection->SetCurrentDirectory("\\");
BOOL b=pFileFind->FindFile(strServerDirectoryPath);
if(!b)
{
AfxMessageBox("Ŀ¼ڻ·");
}
else
{
//Ŀ¼
CString szDir=strLocalDirectoryPath;
if(szDir.Right(1)!="/")
szDir+="/";
szDir+="*.*";
b=ff.FindFile(szDir);
while(b)
{
//ϴļ
b=ff.FindNextFile();
CString strPath=ff.GetFilePath();
CString strName=ff.GetFileName();
if(!ff.IsDirectory()&&!ff.IsDots())
{
CString strSaveName;
if(strServerDirectoryPath.Right(1)!="/")
strSaveName=strServerDirectoryPath+"/"+strName;
else
strSaveName=strServerDirectoryPath+strName;
pConnection->PutFile(strPath,strSaveName,FALSE);
}
else if(ff.IsDirectory()&&!ff.IsDots())
{
CString strSaveName;
if(strServerDirectoryPath.Right(1)!="/")
strSaveName=strServerDirectoryPath+"/"+strName;
else
strSaveName=strServerDirectoryPath+strName;
pConnection->CreateDirectory(strSaveName);
CString strLocalName;
if(strLocalDirectoryPath.Right(1)!="\\")
strLocalDirectoryPath+="\\";
strLocalName=strLocalDirectoryPath+strName;
//AfxMessageBox(strLocalName);
//AfxMessageBox(strSaveName);
UploadDirectorytoDirectory(strLocalName,strSaveName,info);
}
returnvalue=1;
}
}
//ر
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
AfxMessageBox("ӷʧܣ");
}
}
}
else
{
AfxMessageBox("벻Ϊգ");
}
return returnvalue;
}
// ϴĿ¼ļָĿ¼
BOOL CFtpFile::UploadDirectorytoDirectory2(CString strLocalDirectoryPath, CString strServerDirectoryPath, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strServerDirectoryPath!="")&&(strLocalDirectoryPath!=""))
{
CFileFind ff;
BOOL a=ff.FindFile(strLocalDirectoryPath);
if(a)
{
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//ҷĿ¼Ƿ
pFileFind=new CFtpFileFind(pConnection);
pConnection->SetCurrentDirectory("/");
BOOL b=pFileFind->FindFile(strServerDirectoryPath);
if(b)
{
CString theName;
if(strLocalDirectoryPath.Right(1)!="\\")
{
int num=strLocalDirectoryPath.ReverseFind('\\');
theName=strLocalDirectoryPath.Right(strLocalDirectoryPath.GetLength()-num-1);
}
else
{
CString temp=strLocalDirectoryPath.Left(strLocalDirectoryPath.GetLength()-1);
int num=temp.ReverseFind('\\');
theName=temp.Right(temp.GetLength()-num-1);
}
if(strServerDirectoryPath.Right(1)!="/")
{
strServerDirectoryPath+="/"+theName;
}
else
{
strServerDirectoryPath+=theName;
}
pConnection->CreateDirectory(strServerDirectoryPath);
returnvalue=1;
}
}
if(pFileFind!=NULL)
{
pFileFind->Close();
delete pFileFind;
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
}
if(returnvalue==1)
{
returnvalue=UploadDirectorytoDirectory(strLocalDirectoryPath,strServerDirectoryPath,info);
}
return returnvalue;
}
// ļ
BOOL CFtpFile::DownloadFiletoFile(CString strServerFilePath, CString strLocalFilePath, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strLocalFilePath!="")&&(strServerFilePath!=""))
{
//ʼFTP
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//
pSession=new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
//
if(pConnection!=NULL)
{
pFileFind=new CFtpFileFind(pConnection);
BOOL b=pFileFind->FindFile(strServerFilePath);
//ָĿ¼Ƿ
if(!b)
{
//AfxMessageBox("Ҫصļڣ");
pFileFind->Close();
pFileFind=NULL;
}
else
{
BOOL b=pConnection->GetFile(strServerFilePath,strLocalFilePath,FALSE);
if(b)
{
//AfxMessageBox("ļسɹ");
returnvalue=1;
}
}
//ϿFTP
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
//AfxMessageBox("ӷʧܣ");
}
}
else
{
//AfxMessageBox("벻Ϊգ");
}
return returnvalue;
}
// ļָĿ¼ͬļ
BOOL CFtpFile::DownloadFiletoDirectory(CString strServerFilePath, CString strLocalDirectoryPath, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strServerFilePath!="")&&(strLocalDirectoryPath!=""))
{
//жϱĿ¼Ƿ
CFileFind ff;
BOOL a=ff.FindFile(strLocalDirectoryPath);
if(!a)
{
//AfxMessageBox("ҪļĿ¼ڻ·");
}
//ʼFTP
else
{
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//
pSession=new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
//
if((pConnection!=NULL)&&(strServerFilePath!=""))
{
pFileFind=new CFtpFileFind(pConnection);
BOOL b=pFileFind->FindFile(strServerFilePath);
//ָļǷ
if(!b)
{
//AfxMessageBox("ļڣ");
pFileFind->Close();
pFileFind=NULL;
}
else
{
//ͬļ
CString strName;
int numStart=strServerFilePath.ReverseFind('/');
if(numStart!=-1)
strName=strServerFilePath.Right(strServerFilePath.GetLength()-numStart-1).GetString();
CString strSaveName;
if(strLocalDirectoryPath.Right(1)!="\\")
strSaveName=strLocalDirectoryPath+"\\"+strName;
else
strSaveName=strLocalDirectoryPath+strName;
//AfxMessageBox(strServerFilePath);
//AfxMessageBox(strName);
BOOL c=pConnection->GetFile(strServerFilePath,strSaveName);
if(c)
{
//AfxMessageBox("ļɹ");
returnvalue=1;
}
}
//ϿFTP
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
//AfxMessageBox("ӷʧܣ");
}
}
}
else
{
//AfxMessageBox("벻Ϊգ");
}
return returnvalue;
}
//һļĿ¼
BOOL CFtpFile::DownloadFilestoDirectory(CStringArray * strServerFilePath, CString strLocalDirectoryPath, FtpConnectInfo info,CString & strError)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
TCHAR * lpError="";
if((!strServerFilePath->IsEmpty())&&(strLocalDirectoryPath!=""))
{
//жϱĿ¼Ƿ
CFileFind ff;
BOOL a=ff.FindFile(strLocalDirectoryPath);
if(!a)
{
strError.Format("Ŀ¼%s,صĿ¼",strLocalDirectoryPath.GetBuffer());
return FALSE;
//AfxMessageBox("ҪļĿ¼ڻ·");
}
//ʼFTP
else
{
CInternetSession* pSession=NULL;
CFtpConnection* pConnection=NULL;
CFtpFileFind* pFileFind=NULL;
pConnection=NULL;
pFileFind=NULL;
//
pSession=new CInternetSession();
ASSERT(pSession!=NULL);
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException e)
{
e.GetErrorMessage(lpError,100,NULL);
strError=CString(lpError);
/*e->Delete();*/
delete pSession;
pConnection=NULL;
return FALSE;
}
//
if((pConnection!=NULL)&&(strServerFilePath->GetCount()>0))
{
pFileFind=new CFtpFileFind(pConnection);
//ȲһļǷ
for (int i=0;i<strServerFilePath->GetCount();i++)
{
BOOL b=pFileFind->FindFile(strServerFilePath->GetAt(i));
if (!b)
{
strError.Format("%sڷҵļ%s\n",strError,strServerFilePath->GetAt(i));
}
}
if (!strError.IsEmpty())
{
pFileFind->Close();
pFileFind=NULL;
delete pFileFind;
pConnection->Close();
delete pConnection;
delete pSession;
return FALSE;
}
for (int i=0;i<strServerFilePath->GetCount();i++)
{
BOOL b=pFileFind->FindFile(strServerFilePath->GetAt(i));
if (b)
{
CString strName;
int numStart=strServerFilePath->GetAt(i).ReverseFind('/');
if(numStart!=-1)
strName=strServerFilePath->GetAt(i).Right(strServerFilePath->GetAt(i).GetLength()-numStart-1).GetString();
CString strSaveName;
if(strLocalDirectoryPath.Right(1)!="\\")
strSaveName=strLocalDirectoryPath+"\\"+strName;
else
strSaveName=strLocalDirectoryPath+strName;
BOOL c=pConnection->GetFile(strServerFilePath->GetAt(i),strSaveName);
}
}
//Ͽ
pFileFind->Close();
pFileFind=NULL;
delete pFileFind;
pConnection->Close();
delete pConnection;
delete pSession;
}
}
}
return TRUE;
}
// طָĿ¼ļָĿ¼
BOOL CFtpFile::DownloadDirectorytoDirectory(CString strServerDirectoryPath, CString strLocalDirectoryPath, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strServerDirectoryPath!="")&&(strLocalDirectoryPath!=""))
{
//ұĿ¼
CFileFind ff;
BOOL a=ff.FindFile(strLocalDirectoryPath);
if(!a)
{
//AfxMessageBox("ָĿ¼ڣ");
}
else
{
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if((pConnection!=NULL)&&(strServerDirectoryPath!=""))
{
pFileFind= new CFtpFileFind(pConnection);
//Ŀ¼
pConnection->SetCurrentDirectory("\\");
BOOL b=pFileFind->FindFile(strServerDirectoryPath);
if(!b)
{
//AfxMessageBox("ָĿ¼ڣ");
}
//Ŀ¼
else
{
CString szDir=strServerDirectoryPath;
if(szDir.Right(1)!="/")
szDir+="/";
szDir+="*.*";
b=pFileFind->FindFile(szDir);
}
while(b)
{
b=pFileFind->FindNextFile();
CString strPath=pFileFind->GetFilePath();
CString strName=pFileFind->GetFileName();
if(!pFileFind->IsDirectory()&&!pFileFind->IsDots())
{
CString strSaveName;
if(strLocalDirectoryPath.Right(1)!="\\")
strLocalDirectoryPath+="\\";
strSaveName=strLocalDirectoryPath+strName;
pConnection->GetFile(strPath,strSaveName,FALSE);
}
else if(pFileFind->IsDirectory()&&!pFileFind->IsDots())
{
CString strSaveName;
if(strLocalDirectoryPath.Right(1)!="\\")
strLocalDirectoryPath+="\\";
strSaveName=strLocalDirectoryPath+strName;
::CreateDirectory(strSaveName,NULL);
CString strFromName;
if(strServerDirectoryPath.Right(1)!="/")
strServerDirectoryPath+="/";
strFromName=strServerDirectoryPath+strName;
//AfxMessageBox(strFromName);
DownloadDirectorytoDirectory(strFromName,strSaveName,info);
}
returnvalue=1;
}
//ر
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
//AfxMessageBox("ӷʧܣ");
}
}
}
else
{
//AfxMessageBox("벻Ϊգ");
}
return returnvalue;
}
// طָĿ¼ļָĿ¼
BOOL CFtpFile::DownloadDirectorytoDirectory2(CString strServerDirectoryPath, CString strLocalDirectoryPath,FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if((strServerDirectoryPath!="")&&(strLocalDirectoryPath!=""))
{
CFileFind ff;
BOOL a=ff.FindFile(strLocalDirectoryPath);
if(a)
{
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
pFileFind=new CFtpFileFind(pConnection);
pConnection->SetCurrentDirectory("/");
BOOL b=pFileFind->FindFile(strServerDirectoryPath);
if(b)
{
CString theName;
if(strServerDirectoryPath.Right(1)!="/")
{
int num=strServerDirectoryPath.ReverseFind('/');
theName=strServerDirectoryPath.Right(strServerDirectoryPath.GetLength()-num-1);
}
else
{
CString temp=strServerDirectoryPath.Left(strServerDirectoryPath.GetLength()-1);
int num=temp.ReverseFind('/');
theName=temp.Right(temp.GetLength()-num-1);
}
if(strLocalDirectoryPath.Right(1)!="\\")
{
strLocalDirectoryPath+="\\"+theName;
}
else
{
strLocalDirectoryPath+=theName;
}
::CreateDirectory(strLocalDirectoryPath,NULL);
returnvalue=1;
}
}
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
}
if(returnvalue==1)
{
returnvalue=DownloadDirectorytoDirectory(strServerDirectoryPath,strLocalDirectoryPath,info);
}
return returnvalue;
}
BOOL CFtpFile::CreateDirectory(FtpConnectInfo info, CString strDirName)
{
CString strFtp=info.strFtp;
CString strFtpUser=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpUser,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//AfxMessageBox("ӳɹ");
BOOL b=pConnection->CreateDirectory(strDirName);
if(b)
returnvalue=1;
}
else
{
AfxMessageBox("ݿʧܣ");
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
return returnvalue;
}
/************************************************************************/
/* Ŀ¼ */
/************************************************************************/
BOOL CFtpFile::CreateDirectorys(FtpConnectInfo info,CStringArray & strDirAry)
{
CString strFtp=info.strFtp;
CString strFtpUser=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpUser,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//AfxMessageBox("ӳɹ");
for (int i=0;i<strDirAry.GetCount();i++)
{
BOOL b=pConnection->CreateDirectory(strDirAry[i]);
if(b)
{
returnvalue=1;
break;
}
}
}
else
{
AfxMessageBox("ݿʧܣ");
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
return returnvalue;
}
BOOL CFtpFile::RemoveDirectory(FtpConnectInfo info, CString strDirName)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//AfxMessageBox("ӳɹ");
BOOL b=pConnection->RemoveDirectory(strDirName);
if(b)
returnvalue=1;
}
else
{
AfxMessageBox("ݿʧܣ");
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
return returnvalue;
}
BOOL CFtpFile::RemoveFile(FtpConnectInfo info, CString strDirName)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//AfxMessageBox("ӳɹ");
BOOL b=pConnection->Remove(strDirName);
if(b)
returnvalue=1;
}
else
{
AfxMessageBox("ݿʧܣ");
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
return returnvalue;
}
BOOL CFtpFile::GetCurrentDirectory(FtpConnectInfo info, CString * currentdirectory)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if(pConnection!=NULL)
{
//AfxMessageBox("ӳɹ");
BOOL b=pConnection->GetCurrentDirectory((*currentdirectory));
if(b)
returnvalue=1;
}
else
{
AfxMessageBox("ݿʧܣ");
}
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
return returnvalue;
}
/************************************************************************/
/* ɾָĿ¼µ */
/************************************************************************/
BOOL CFtpFile::DeleteDirAndFile(CString strServerDirectoryPath,/*, CString strLocalDirectoryPath,*/ FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
BOOL returnvalue=0;
if(strServerDirectoryPath!="")
{
//ҷĿ¼
CInternetSession* pSession;
CFtpConnection* pConnection;
CFtpFileFind* pFileFind;
pConnection=NULL;
pFileFind=NULL;
//ʼ
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
}
if((pConnection!=NULL)&&(strServerDirectoryPath!=""))
{
pFileFind= new CFtpFileFind(pConnection);
//Ŀ¼
pConnection->SetCurrentDirectory("\\");
BOOL b=pFileFind->FindFile(strServerDirectoryPath);
if(!b)
{
//AfxMessageBox("ָĿ¼ڣ");
returnvalue=1;
}
//Ŀ¼
else
{
CString szDir=strServerDirectoryPath;
if(szDir.Right(1)!="/")
szDir+="/";
szDir+="*.*";
b=pFileFind->FindFile(szDir);
while(b)
{
b=pFileFind->FindNextFile();
CString strPath=pFileFind->GetFilePath();
CString strName=pFileFind->GetFileName();
if(!pFileFind->IsDirectory()&&!pFileFind->IsDots())
{
pConnection->Remove(strPath);
}
else if(pFileFind->IsDirectory()&&!pFileFind->IsDots())
{
CString strFromName;
if(strServerDirectoryPath.Right(1)!="/")
strServerDirectoryPath+="/";
strFromName=strServerDirectoryPath+strName;
DeleteDirAndFile(strFromName,info);
}
returnvalue=1;
}
pConnection->RemoveDirectory(strServerDirectoryPath);
}
//ر
if(pFileFind!=NULL)
{
pFileFind->Close();
pFileFind=NULL;
}
delete pFileFind;
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
}
delete pSession;
}
else
{
AfxMessageBox("ӷʧܣ");
returnvalue=0;
}
}
return returnvalue;
}
/************************************************************************/
/* Ե */
/************************************************************************/
bool CFtpFile::TestConnect(FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
CInternetSession* pSession;
CFtpConnection* pConnection;
pConnection=NULL;
pSession= new CInternetSession();
ASSERT(pSession!=NULL);
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
delete pSession;
return false;
}
//ӳɹ
if(pConnection!=NULL)
{
pConnection->Close();
delete pConnection;
delete pSession;
return true;
}
return false;
}
BOOL CFtpFile::DownloadPartFileToDirectory(CString serverFileName, CString serverDirectory, CString LocalDirectory, FtpConnectInfo info)
{
return 0;
}
BOOL CFtpFile::Rename(CString serverDirectory,CString newName, FtpConnectInfo info)
{
CString strFtp=info.strFtp;
CString strFtpName=info.strFtpUser;
CString strFtpPwd=info.strFtpPwd;
int iFtpPort=info.iFtpPort;
CInternetSession* pSession;
CFtpConnection* pConnection;
pConnection=NULL;
pSession= new CInternetSession();
try
{
pConnection=pSession->GetFtpConnection(strFtp,strFtpName,strFtpPwd,iFtpPort);
}
catch(CInternetException* e)
{
ShowErrorMessage(e);
e->Delete();
pConnection=NULL;
delete pSession;
return false;
}
//ӳɹ
if(pConnection!=NULL)
{
if(!pConnection->Rename(serverDirectory,newName))
{
pConnection->Close();
return false;
}
pConnection->Close();
delete pConnection;
delete pSession;
return true;
}
return false;
}
void CFtpFile::ShowErrorMessage(CInternetException* e=NULL)
{
ASSERT(e!=NULL);
LPSTR strError="";
e->GetErrorMessage(strError,100);
if (strError!="")
{
AfxMessageBox(strError);
}
}
|
Java | UTF-8 | 2,225 | 1.851563 | 2 | [] | no_license | package cn.com.isurpass.securityplatform.service;
import cn.com.isurpass.securityplatform.dao.ZwaveSubDeviceDAO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AlarmServiceTest {
@Autowired
private AlarmService alarmservice;
@Autowired
private ZwaveSubDeviceDAO zwaveSubDeviceDAO;
@Test
public void DSCAlarmTest() {
JSONObject json = JSON.parseObject("{ " +
" \"newid\": 17951, " +
" \"zwavedeviceid\": 11545, " +
" \"newtime\": \"2018-05-25 15:05:25\", " +
" \"lastid\": 17950, " +
" \"type\": \"dscalarm\", " +
" \"deviceid\": \"iRemote8005000000001\", " +
" \"intparam\": 0, " +
" \"warningstatus\": 9, " +
" \"warningstatuses\": \"[9]\", " +
" \"id\": 17951 " +
"} ");
alarmservice.sendAlarmMessage(json);
}
@Test
public void deletewhennull() {
String s = "[]";
Integer[] integers = JSON.parseArray(s).toArray(new Integer[0]);
int[] ints = new int[integers.length];
System.out.println(ints.length);
// deviceInfoChangedDAO.delete(null);
// ZwaveSubDevicePO byZwavesubdeviceid = deviceInfoChangedDAO.findByZwavesubdeviceid(1231);
// System.out.println(byZwavesubdeviceid);
// deviceInfoChangedDAO.delete(byZwavesubdeviceid);
}
@Test
public void test1ndCache() {
System.out.println("11");
zwaveSubDeviceDAO.findByZwavedeviceid(101);
System.out.println("11");
zwaveSubDeviceDAO.findByZwavedeviceid(101);
}
}
|
Rust | UTF-8 | 4,139 | 3.078125 | 3 | [
"MIT"
] | permissive | use crate::char::CharExt;
pub trait StrExt {
fn column_count(&self, tab_column_count: usize) -> usize;
fn indentation(&self) -> Option<&str>;
fn longest_common_prefix(&self, other: &str) -> &str;
fn graphemes(&self) -> Graphemes<'_>;
fn grapheme_indices(&self) -> GraphemeIndices<'_>;
fn split_whitespace_boundaries(&self) -> SplitWhitespaceBoundaries<'_>;
}
impl StrExt for str {
fn column_count(&self, tab_column_count: usize) -> usize {
self.chars()
.map(|char| char.column_count(tab_column_count))
.sum()
}
fn indentation(&self) -> Option<&str> {
self.char_indices()
.find(|(_, char)| !char.is_whitespace())
.map(|(index, _)| &self[..index])
}
fn longest_common_prefix(&self, other: &str) -> &str {
&self[..self
.char_indices()
.zip(other.chars())
.find(|((_, char_0), char_1)| char_0 == char_1)
.map(|((index, _), _)| index)
.unwrap_or_else(|| self.len().min(other.len()))]
}
fn graphemes(&self) -> Graphemes<'_> {
Graphemes { string: self }
}
fn grapheme_indices(&self) -> GraphemeIndices<'_> {
GraphemeIndices {
graphemes: self.graphemes(),
start: self.as_ptr() as usize,
}
}
fn split_whitespace_boundaries(&self) -> SplitWhitespaceBoundaries<'_> {
SplitWhitespaceBoundaries { string: self }
}
}
#[derive(Clone, Debug)]
pub struct Graphemes<'a> {
string: &'a str,
}
impl<'a> Iterator for Graphemes<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
if self.string.is_empty() {
return None;
}
let mut end = 1;
while !self.string.is_char_boundary(end) {
end += 1;
}
let (grapheme, string) = self.string.split_at(end);
self.string = string;
Some(grapheme)
}
}
impl<'a> DoubleEndedIterator for Graphemes<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.string.is_empty() {
return None;
}
let mut start = self.string.len() - 1;
while !self.string.is_char_boundary(start) {
start -= 1;
}
let (string, grapheme) = self.string.split_at(start);
self.string = string;
Some(grapheme)
}
}
#[derive(Clone, Debug)]
pub struct GraphemeIndices<'a> {
graphemes: Graphemes<'a>,
start: usize,
}
impl<'a> Iterator for GraphemeIndices<'a> {
type Item = (usize, &'a str);
fn next(&mut self) -> Option<Self::Item> {
let grapheme = self.graphemes.next()?;
Some((grapheme.as_ptr() as usize - self.start, grapheme))
}
}
impl<'a> DoubleEndedIterator for GraphemeIndices<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
let grapheme = self.graphemes.next_back()?;
Some((grapheme.as_ptr() as usize - self.start, grapheme))
}
}
#[derive(Clone, Debug)]
pub struct SplitWhitespaceBoundaries<'a> {
string: &'a str,
}
impl<'a> Iterator for SplitWhitespaceBoundaries<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
if self.string.is_empty() {
return None;
}
let mut prev_char_is_whitespace = None;
let index = self
.string
.char_indices()
.find_map(|(index, next_char)| {
let next_char_is_whitespace = next_char.is_whitespace();
let is_whitespace_boundary = prev_char_is_whitespace
.map_or(false, |prev_char_is_whitespace| {
prev_char_is_whitespace != next_char_is_whitespace
});
prev_char_is_whitespace = Some(next_char_is_whitespace);
if is_whitespace_boundary {
Some(index)
} else {
None
}
})
.unwrap_or(self.string.len());
let (string_0, string_1) = self.string.split_at(index);
self.string = string_1;
Some(string_0)
}
}
|
Markdown | UTF-8 | 2,811 | 3.234375 | 3 | [] | no_license | # Spring courses at Pluralsight
This repository contains the code written while following [Spring Java Framework](https://spring.io/) at [Pluralsight](https://app.pluralsight.com/).
## Repository Structure
There's a folder in this repository for each project created while following the Spring courses available at **Pluralsight**. All these projects can be imported to an [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment).
At **Pluralsight** the courses are grouped in [paths](https://www.pluralsight.com/product/paths) and the courses that were followed are listed here and grouped by its respective *paths*.
## Pluralsight paths
### Core Spring
1. [Spring: The Big Picture](https://app.pluralsight.com/library/courses/spring-big-picture/table-of-contents);
2. [Spring Fundamentals](https://app.pluralsight.com/library/courses/spring-fundamentals/table-of-contents);
The code written following this course is stored in the folder [`spring-fundamentals`](./spring-fundamentals) of this repository.
3. [Introduction to Spring MVC](https://app.pluralsight.com/library/courses/springmvc-intro/table-of-contents);
The code written following this course is stored in the folder [`spring-mvc-introduction`](./spring-mvc-introduction) of this repository.
4. [Introduction to Spring MVC 4](https://app.pluralsight.com/library/courses/spring-mvc4-introduction/table-of-contents);
The code written following this course is stored in the folder [`spring-mvc-4`](./spring-mvc-4) of this repository.
5. [Building Applications Using Spring JDBC](https://app.pluralsight.com/library/courses/building-applications-spring-jdbc/table-of-contents);
The code written following this course is stored in the folder [`spring-jdbc`](./spring-jdbc) of this repository.
### Spring Framework: Data Access with Spring
1. [Building Applications Using Spring JDBC](https://app.pluralsight.com/library/courses/building-applications-spring-jdbc/table-of-contents);
This course is also included in the *path* **Core Spring** and the code written following it is stored in the folder [`spring-jdbc`](./spring-jdbc) of this repository.
### Spring Framework: Building Web Applications and Services
1. [Introduction to Spring MVC](https://app.pluralsight.com/library/courses/springmvc-intro/table-of-contents);
This course is also included in the *path* **Core Spring** and the code written following it is stored in the folder [`spring-mvc-introduction`](./spring-mvc-introduction) of this repository.
2. [Introduction to Spring MVC 4](https://app.pluralsight.com/library/courses/spring-mvc4-introduction/table-of-contents);
This course is also included in the *path* **Core Spring** and the code written following it is stored in the folder [`spring-mvc-4`](./spring-mvc-4) of this repository.
|
Java | UTF-8 | 616 | 2.890625 | 3 | [] | no_license | package night;
import java.util.Iterator;
import java.util.LinkedList;
public class LightList {
private LinkedList<Light> ligths;
private LightList() {
ligths = new LinkedList<Light>();
}
private final static LightList instance = new LightList();
public static final LightList getInstance() {
return instance;
}
public static void add(Light light) {
instance.ligths.add(light);
}
public static void clear() {
instance.ligths.clear();
}
public static Iterator<Light> iterator() {
return instance.ligths.iterator();
}
}
|
JavaScript | UTF-8 | 225 | 3.296875 | 3 | [
"MIT"
] | permissive | var nombre = "Julián", edad = "37";
function GetName(n,e) {
console.log(`${n} tiene ${e}`);
}
const nombreYEdad = (n, e) => {
console.log(`${n} tiene ${e}`);
};
nombreYEdad(nombre,edad);
GetName(nombre, edad);
|
PHP | UTF-8 | 632 | 2.75 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Mohammed Elamin
* Date: 02/12/2018
* Time: 06:01
*/
class Sanitizer
{
public function sanitizeString($data)
{
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$data = $conn->real_escape_string($data);
$data = self::removeHtmlStuff($data);
return $data;
}
public function removeHtmlStuff($data)
{
$data = stripslashes($data);
$data = htmlentities($data);
$data = strip_tags($data);
return $data;
}
} |
C++ | UTF-8 | 8,523 | 3.125 | 3 | [] | no_license | /*
* TriangleSet.cpp -- implementation of the triangle matching algorithm
*
* (c) 2016 Prof Dr Andreas Müller, Hochschule Rapperswil
*/
#include <AstroTransform.h>
#include <cmath>
namespace astro {
namespace image {
namespace transform {
/**
* \brief Triangle set constructor
*/
TriangleSet::TriangleSet() {
_allow_mirror = false;
_tolerance = 0.01;
}
/**
* \brief Find triangle closest to a given triangle
*
* This uses the distance function to find the closes triangle using a
* linear search.
*/
const Triangle& TriangleSet::closest(const Triangle& other) const {
auto candidate = begin();
double distance = other.distance(*candidate);
auto ptr = begin();
for (ptr++; ptr != end(); ptr++) {
double d = other.distance(*ptr);
if (d < distance) {
candidate = ptr;
distance = d;
}
}
return *candidate;
}
class TrianglePair : public std::pair<Triangle, Triangle> {
public:
TrianglePair(const Triangle& t1, const Triangle& t2)
: std::pair<Triangle, Triangle>(t1, t2) {
}
std::string toString() const {
return stringprintf("%s ~ %s, d=%f, rotate=%f, scale=%f",
first.toString().c_str(), second.toString().c_str(),
first.distance(second),
first.rotate_to(second) * 180 / M_PI,
first.scale_to(second));
}
};
class PairFunction {
public:
virtual double operator()(const TrianglePair& pair) const = 0;
};
class RotateTo : public PairFunction {
public:
virtual double operator()(const TrianglePair& pair) const {
return pair.first.rotate_to(pair.second);
}
};
class ScaleTo : public PairFunction {
public:
virtual double operator()(const TrianglePair& pair) const {
return log(pair.first.scale_to(pair.second));
}
};
template<int n>
class CharacteristicValue {
PairFunction& _pairfunction;
double _min;
double _max;
double _delta;
int counts[n];
int _maxindex;
public:
double delta() const { return _delta; }
private:
int index(double v) const {
if (v < _min) {
return 0;
}
if (v > _max) {
return n - 1;
}
return trunc((v - _min) / _delta);
}
public:
CharacteristicValue(PairFunction& pairfunction, double min, double max)
: _pairfunction(pairfunction), _min(min), _max(max) {
_delta = (_max - _min) / n;
std::fill_n(counts, n, 0);
}
void add(const TrianglePair& pair) {
double v = _pairfunction(pair);
counts[index(v)]++;
}
void evaluate() {
int count = -1;
for (int i = 0; i < n; i++) {
debug(LOG_DEBUG, DEBUG_LOG, 0, "counts[%d] = %d, %f", i,
counts[i], _min + _delta * (i + 0.5));
if (counts[i] > count) {
_maxindex = i;
count = counts[_maxindex];
}
}
debug(LOG_DEBUG, DEBUG_LOG, 0, "characteristic bin: %d (%d)",
_maxindex, count);
}
double value() const {
return _min + (_maxindex + 0.5) * _delta;
}
bool faroff(const TrianglePair& pair) const {
double v = _pairfunction(pair);
int i = index(v);
if ((n - 1) == _maxindex) {
return ((i > 0) && (i < n - 2));
}
if (0 == _maxindex) {
return ((i > 1) && (i < n - 1));
}
return (std::abs(_maxindex - i) > 1);
}
};
double angle_reduce(double a) {
while (a > M_PI) {
a -= 2 * M_PI;
}
while (a < -M_PI) {
a += 2 * M_PI;
}
return a;
}
/**
* \brief Find the closest transform from a set of triangles
*/
Transform TriangleSet::closest(const TriangleSet& other) const {
debug(LOG_DEBUG, DEBUG_LOG, 0, "finding transform from %d to %d "
"triangles", size(), other.size());
// for each triangle find a close triangle in the other set, the
// parameter _tolerance decides how close is close enough
std::list<TrianglePair> trianglepairs;
for (auto ptr = begin(); ptr != end(); ptr++) {
Triangle b = other.closest(*ptr);
// reject pairs with that imply mirror images
if (!_allow_mirror) {
if (b.mirror_to(*ptr)) {
continue;
}
}
// reject pairs that are not close enough
double d = ptr->distance(b);
if (d > _tolerance) {
continue;
}
// add the pair to the set
TrianglePair pair(*ptr, b);
debug(LOG_DEBUG, DEBUG_LOG, 0, "closest triangle: %s",
pair.toString().c_str());
trianglepairs.push_back(pair);
}
// stop if we have no suitable triangle pairs
if (trianglepairs.size() == 0) {
std::string msg = stringprintf("no close triangles at "
"tolerance %f found", _tolerance);
debug(LOG_ERR, DEBUG_LOG, 0, "%s", msg.c_str());
throw std::runtime_error(msg);
}
// some of the triangle pairs may have scales or rotation angles
// that are completely off, so we now find common scales and rotation
// angles using a histogram
RotateTo anglefunction;
CharacteristicValue<256> anglehistogram(anglefunction,
0, 2 * M_PI);
for (auto p = trianglepairs.begin(); p != trianglepairs.end(); p++) {
anglehistogram.add(*p);
}
anglehistogram.evaluate();
debug(LOG_DEBUG, DEBUG_LOG, 0, "characteristic angle: %f",
anglehistogram.value() * 180 / M_PI);
// remove all triangle pairs that are far off the common values
int counter = 0;
auto ptr = trianglepairs.begin();
while (ptr != trianglepairs.end()) {
if (anglehistogram.faroff(*ptr)) {
debug(LOG_DEBUG, DEBUG_LOG, 0, "exclude %s",
ptr->toString().c_str());
ptr = trianglepairs.erase(ptr);
counter++;
} else {
ptr++;
}
}
debug(LOG_DEBUG, DEBUG_LOG, 0,
"%d pairs excluded: rotation angle far from %f",
counter, anglehistogram.value() * 180 / M_PI);
// remove all triangles for which the angle is far off.
double rotatebase = anglehistogram.value();
double rotatesum = 0, rotate2sum = 0;
ptr = trianglepairs.begin();
while (ptr != trianglepairs.end()) {
double r = ptr->first.rotate_to(ptr->second) - rotatebase;
r = angle_reduce(r);
rotatesum += r;
rotate2sum += r * r;
ptr++;
}
counter = 0;
ptr = trianglepairs.begin();
double mean = rotatesum / trianglepairs.size() + rotatebase;
double stddev = sqrt(rotate2sum / trianglepairs.size());
debug(LOG_DEBUG, DEBUG_LOG, 0, "rotate mean: %f, stddev: %f",
mean * 180 / M_PI, stddev * 180 / M_PI);
while (ptr != trianglepairs.end()) {
double r = ptr->first.rotate_to(ptr->second) - mean;
r = angle_reduce(r);
if (fabs(r) > stddev) {
ptr = trianglepairs.erase(ptr);
counter++;
} else {
ptr++;
}
}
debug(LOG_DEBUG, DEBUG_LOG, 0, "%d pairs excluded for too large "
"rotation angle", counter);
// collect scale values
ScaleTo scalefunction;
CharacteristicValue<101> scalehistogram(scalefunction, -1, 1);
for (auto p = trianglepairs.begin(); p != trianglepairs.end(); p++) {
scalehistogram.add(*p);
}
scalehistogram.evaluate();
debug(LOG_DEBUG, DEBUG_LOG, 0, "characteristic scale: %f",
exp(scalehistogram.value()));
// remove the triangle pairs that have bad scale
counter = 0;
ptr = trianglepairs.begin();
while (ptr != trianglepairs.end()) {
if (scalehistogram.faroff(*ptr)) {
debug(LOG_DEBUG, DEBUG_LOG, 0, "exclude %s",
ptr->toString().c_str());
ptr = trianglepairs.erase(ptr);
counter++;
} else {
ptr++;
}
}
debug(LOG_DEBUG, DEBUG_LOG, 0,
"%d pairs excluded: scale factor far from %f",
counter, exp(scalehistogram.value()));
// compute the mean and variance of the scale
double scalesum = 0, scale2sum = 0;
ptr = trianglepairs.begin();
while (ptr != trianglepairs.end()) {
double s = ptr->first.scale_to(ptr->second);
scalesum += s;
scale2sum += s * s;
ptr++;
}
mean = scalesum / trianglepairs.size();
stddev = sqrt((scale2sum / trianglepairs.size()) - mean * mean);
counter = 0;
ptr = trianglepairs.begin();
while (ptr != trianglepairs.end()) {
double s = ptr->first.scale_to(ptr->second);
if ((fabs(s - mean) / stddev) > 1) {
ptr = trianglepairs.erase(ptr);
counter++;
} else {
ptr++;
}
}
debug(LOG_DEBUG, DEBUG_LOG, 0, "%d pairs eliminated for scale variance",
counter);
// display the triangles we plan to use for transform computation
std::list<TrianglePair>::const_iterator tp;
int i;
for (i = 0, tp = trianglepairs.begin();
tp != trianglepairs.end(); i++, tp++) {
debug(LOG_DEBUG, DEBUG_LOG, 0, "using triangle pair %d: %s",
i, tp->toString().c_str());
}
// now that we have triangles that we know match, we can also
// construct a set of points that should match
debug(LOG_DEBUG, DEBUG_LOG, 0, "found %d matching triangles",
trianglepairs.size());
std::vector<Point> from;
std::vector<Point> to;
for (tp = trianglepairs.begin(); tp != trianglepairs.end(); tp++) {
for (int i = 0; i < 3; i++) {
from.push_back(tp->first[i]);
to.push_back(tp->second[i]);
}
}
TransformFactory tf;
return tf(from, to);
}
} // namespace transform
} // namespace image
} // namespace astro
|
TypeScript | UTF-8 | 793 | 2.546875 | 3 | [
"MIT"
] | permissive | import request from "supertest";
const server = request("http://localhost:3000/dev");
describe("Handler with error handler middleware", () => {
describe("with a search query method", () => {
const query = "/hello?search=x";
it("returns 500 and JSON with an Internal server error message", async () => {
const response = await server.get(query).expect(500);
expect(response.body.message).toEqual("Internal server error");
});
});
describe("without a search query method", () => {
const query = "/hello";
it('returns 400 and JSON with a "Query has to include a search" error message', async () => {
const response = await server.get(query).expect(400);
expect(response.body.message).toEqual("Query has to include a search");
});
});
});
|
JavaScript | UTF-8 | 1,779 | 2.59375 | 3 | [
"MIT"
] | permissive | 'use strict'
const expect = require('chai').expect
const pathUtils = require('../../../lib/utils/path')
const ValueWrapper = pathUtils.ValueWrapper
describe('utils/path', () => {
describe('ValueWrapper class', () => {
var wrapper
beforeEach(function () {
wrapper = new ValueWrapper({
foo: {
bar1: {
baz: {
quux: 'test 1',
must: {
go: {
deeper: true
}
}
}
},
bar2: {
baz: {
quux: 'test 2'
}
}
}
}, 'foo.bar1.baz')
})
it('keeps track of a value within a larger object', function () {
expect(wrapper.get()).to.eql({
quux: 'test 1',
must: {
go: {
deeper: true
}
}
})
})
describe('get method', function () {
it('gets properties from a path in the base object', function () {
expect(wrapper.get('foo.bar1.baz.quux')).to.eql('test 1')
})
it('can handle relative paths', function () {
expect(wrapper.get('./baz.quux')).to.eql('test 1')
expect(wrapper.get('../bar2.baz.quux')).to.eql('test 2')
var newWrapper = wrapper.pushPath('must.go.deeper')
expect(newWrapper.get('../../quux')).to.eql('test 1')
})
})
describe('pushPath method', function () {
var newWrapper
beforeEach(function () {
newWrapper = wrapper.pushPath('must.go.deeper')
})
it('appends to the contained path', function () {
expect(newWrapper.get()).to.eql(true)
})
it('returns a new object', function () {
expect(newWrapper).to.not.equal(wrapper)
})
})
})
})
|
Java | UTF-8 | 2,851 | 2.234375 | 2 | [] | no_license | package template.solainteractive.com.androidsolatemplate.Utils;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import template.solainteractive.com.androidsolatemplate.R;
import template.solainteractive.com.androidsolatemplate.view_interface.SnackBarOnClick;
/**
* Created by BillySaputra on 23-Aug-17.
*/
public class Utils {
public static void showSnackBar(View view, String message) {
Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
textView.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
snackbar.show();
}
public static void showInfiniteSnackBar(View view, String message, String button, final SnackBarOnClick snackBarOnClick) {
Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_INDEFINITE);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
textView.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
snackbar.setActionTextColor(Color.RED);
snackbar.setAction(button, new View.OnClickListener() {
@Override
public void onClick(View v) {
snackBarOnClick.onSnackBarClick();
}
});
snackbar.show();
}
public static void intentWithClearTask(AppCompatActivity mActivity, Class<?> classDestination){
Intent intent = new Intent(mActivity, classDestination);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
overridePendingTransition(mActivity);
mActivity.startActivity(intent);
}
private static void overridePendingTransition(AppCompatActivity mActivity) {
mActivity.overridePendingTransition(0, 0);
}
public static void setupAppToolbarForActivity(final AppCompatActivity mActivity, Toolbar toolbar, String title) {
TextView tvTitle = mActivity.findViewById(R.id.tvToolbar);
tvTitle.setText(title);
mActivity.setSupportActionBar(toolbar);
mActivity.getSupportActionBar().setTitle("");
mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public static void setupAppToolbarForActivity2(final AppCompatActivity mActivity, String title){
TextView tvTitle = mActivity.findViewById(R.id.tvToolbar);
tvTitle.setText(title);
}
}
|
Markdown | UTF-8 | 628 | 2.84375 | 3 | [] | no_license | # Terraform-Aws
Course URL : https://www.youtube.com/watch?v=Hh2LMacslms
Terraform basics & usage with AWS.
Step 1 : copy the terraform.exe inside your local directory ex: C:\terraform (folder)
Step 2 : Add the path C:\terraform to the system/user environment variable.
Step 3 : Open command prompt and type terraform version. terraform version will be displayed in output.
Step 4 : type terraform console. terraform console where we are going to run the terraform HCL commands.
Step 5 : type var.admin & see the ouput.
Step 6 : type var.mymap & see the output.
Step 7 : type var.mymap["mykey"] & see the output.
|
Java | UTF-8 | 686 | 2.296875 | 2 | [] | no_license | package com.example.joke.controllers;
import com.example.joke.services.JokesServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class JokeController {
private JokesServices jokesServices ;
@Autowired
public JokeController(JokesServices jokesServices) {
this.jokesServices = jokesServices;
}
@RequestMapping({"/", ""})
public String showJoke(Model model ){
model.addAttribute("joke", jokesServices.getJoke()) ;
return "chucknorris" ;
}
}
|
Java | UTF-8 | 2,690 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright © 2020 IBM Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package dev.ebullient.dnd.combat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import dev.ebullient.dnd.mechanics.Ability;
import dev.ebullient.dnd.mechanics.Dice;
class EncounterCondition {
Dice.Constraint onAttack = Dice.Constraint.NONE;
Dice.Constraint asTarget = Dice.Constraint.NONE;
final Set<Ability> advantage = new HashSet<>();
final Set<Ability> disadvantage = new HashSet<>();
int duration;
boolean singleAttack;
int maxHitPointsDecrease;
EncounterCondition setDisadvantage(List<Ability> abilities) {
if (abilities != null && !abilities.isEmpty()) {
for (Ability a : abilities) {
this.disadvantage.add(a);
}
}
return this;
}
EncounterCondition setDisadvantage(Ability... abilities) {
for (Ability a : abilities) {
this.disadvantage.add(a);
}
return this;
}
EncounterCondition setForDuration(int duration) {
this.duration = duration;
return this;
}
EncounterCondition setAttackRollConstraint(Dice.Constraint constraint) {
this.onAttack = constraint;
return this;
}
EncounterCondition setTargetRollConstraint(Dice.Constraint constraint) {
this.asTarget = constraint;
return this;
}
EncounterCondition setSingleAttackLimit() {
this.singleAttack = true;
return this;
}
void setMaxHitPointsDecrease(int damageAmount) {
this.maxHitPointsDecrease = damageAmount;
}
Dice.Constraint getAbilityCheckConstraint(Ability ability) {
if (disadvantage.contains(ability)) {
return Dice.Constraint.DISADVANTAGE;
}
return Dice.Constraint.NONE;
}
Dice.Constraint getAttackConstraint() {
return onAttack;
}
Dice.Constraint getTargetConstraint() {
return asTarget;
}
boolean isSingleAttackLimit() {
return singleAttack;
}
int getMaxHitPointsDecrease() {
return maxHitPointsDecrease;
}
}
|
C++ | UTF-8 | 3,968 | 3.875 | 4 | [
"MIT"
] | permissive | // https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
#include <bits/stdc++.h>
using namespace std;
class SinglyLinkedListNode {
public:
int data;
SinglyLinkedListNode *next;
SinglyLinkedListNode(int node_data) {
this->data = node_data;
this->next = nullptr;
}
};
class SinglyLinkedList {
public:
SinglyLinkedListNode *head;
SinglyLinkedListNode *tail;
SinglyLinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
void insert_node(int node_data) {
SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data);
if (!this->head) {
this->head = node;
} else {
this->tail->next = node;
}
this->tail = node;
}
};
void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) {
while (node) {
fout << node->data;
node = node->next;
if (node) {
fout << sep;
}
}
}
void free_singly_linked_list(SinglyLinkedListNode* node) {
while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;
free(temp);
}
}
// Complete the reverse function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
SinglyLinkedListNode* reverse(SinglyLinkedListNode* head) {
/* We have two conditions in this if statement.
This first condition immediately returns null
when the list is null. The second condition returns
the final node in the list. That final node is sent
into the "remaining" Node below.
-----------------------------------------------------*/
if (head == nullptr || head->next == nullptr) {
return head;
}
/* When the recursion creates the stack for A -> B -> C
(RevA(RevB(RevC()))) it will stop at the last node and
the recursion will end, beginning the unraveling of the
nested functions from the inside, out.
-----------------------------------------------------*/
SinglyLinkedListNode* remaining = reverse(head->next);
/* Now we have the "remaining" node returned and accessible
to the node prior. This remaining node will be returned
by each function as the recursive stack unravels.
Assigning head to head.next.next where A is the head
and B is after A, (A -> B), would set B's pointer to A,
reversing their direction to be A <- B.
-----------------------------------------------------*/
head->next->next = head;
/* Now that those two elements are reversed, we need to set
the pointer of the new tail-node to null.
-----------------------------------------------------*/
head->next = nullptr;
/* Now we return remaining so that remaining is always
reassigned to itself and is eventually returned by the
first function call.
-----------------------------------------------------*/
return remaining;
}
int main(){
ofstream fout(getenv("OUTPUT_PATH"));
int tests;
cin >> tests;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int tests_itr = 0; tests_itr < tests; tests_itr++) {
SinglyLinkedList* llist = new SinglyLinkedList();
int llist_count;
cin >> llist_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < llist_count; i++) {
int llist_item;
cin >> llist_item;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
llist->insert_node(llist_item);
}
SinglyLinkedListNode* llist1 = reverse(llist->head);
print_singly_linked_list(llist1, " ", fout);
fout << "\n";
free_singly_linked_list(llist1);
}
fout.close();
return 0;
}
|
JavaScript | UTF-8 | 1,015 | 2.890625 | 3 | [] | no_license | import humps from 'humps'
/**
* Transform Object with camelCase keys
* into object with snake_case keys
*/
export function decamelizeObjectKeys (obj) {
return Object.keys(obj).reduce((newObj, camelKey) => {
newObj[humps.decamelize(camelKey)] = obj[camelKey]
return newObj
}, {})
}
/**
* Transform Object with snake_case keys
* into object with camelCase keys
*/
export function camelizeObjectKeys (obj) {
return Object.keys(obj).reduce((newObj, uKey) => {
newObj[humps.camelize(uKey)] = obj[uKey]
return newObj
}, {})
}
/**
* Transform a JSON Web Token into a User object
*/
export function tokenToUser (token) {
// throws JSON Parse error if badly formed token
return JSON.parse(window.atob(token.split('.')[1]))
}
/**
* Transform a date to mm/dd/yyyy
*/
export function formatDateString(date) {
var mm = date.getMonth() + 1
var dd = date.getDate()
var yyyy = date.getFullYear()
var yy = yyyy.toString().substr(2,2);
return mm + '/' + dd + '/' + yy
}
|
C++ | UTF-8 | 3,598 | 3.90625 | 4 | [] | no_license | /**
* Array-Based Union-Find Datastructure
*
* Author: Spencer Whitt
*/
#ifndef UNION_FIND_H
#define UNION_FIND_H
#include <vector>
#include <iostream>
using namespace std;
class UFarray {
private:
// Array which holds label -> set equivalences.
// The array index is the node
// The value at that index is the parent.
vector<unsigned> P;
public:
UFarray(unsigned num_labels) {
// Preallocate vector for efficiency
P.resize(num_labels);
// Initialize each node to be its own tree
for(unsigned i = 0; i < P.size(); i++) {
P[i] = i;
}
}
/**
* Traverse the path between node i and the root of the tree.
* For each node in that path, change its parent to newroot.
* This process collapses the tree to 1 level deep.
* Regularly collapsing the tree keeps it efficient.
*/
void setRoot(unsigned i, unsigned newroot) {
// The root of the tree is its own parent, so P[i] < i is false at the
// root. For the rest of the elements, it is true, as an element is
// always larger than its parent.
// Traverse up the tree towards the root, while simultaneously
// collapsing it
while( P[i] < i ) {
int j = P[i];
P[i] = newroot;
i = j;
}
// Set the actual root element
P[i] = newroot;
}
/**
* Traverse from node i, up the tree to the root, then return the root
*/
unsigned findRoot(unsigned i) {
while( P[i] < i ) {
i = P[i];
}
return i;
}
/**
* Same as findRoot, but with an optimization to help keep the tree flat.
*/
unsigned find(unsigned i) {
// Get the root element
unsigned root = findRoot(i);
// Optimization to keep the tree flat + efficient
setRoot(i, root);
// Deliver on what we came for
return root;
}
/**
* Join (union) the two trees containing nodes i and j
*/
unsigned join(unsigned i, unsigned j) {
// Get the root of i and j's respective trees
unsigned rooti = find(i);
unsigned rootj = find(j);
// Ensure rooti is the smaller of the two values
// a node's parent must always be smaller than the node
if (rooti > rootj) rooti = rootj;
// Make the trees children of the same root, so that they are joined
setRoot(i, rooti);
setRoot(j, rooti);
// The new root
return rooti;
}
/**
* Flatten the tree.
*/
void flatten() {
// Set each index in the array to its parent
//
// Because of the fact that we iterate from left to right, this
// flattens the trees in one pass.
for(unsigned n=1; n < P.size(); n++) {
P[n] = P[P[n]];
}
}
/**
* Flatten the tree while simultaneously relabeling the nodes.
*
* The relabeled nodes are incremental: 0,1,2...
*/
vector<unsigned> flattenL() {
unsigned k = 1;
for (unsigned i = 1; i < P.size(); i++) {
if (P[i] < i) {
// i is not the root, flatten it
P[i] = P[P[i]];
} else {
// i is the root, so relabel it to be incremental
P[i] = k;
k++;
}
}
return P;
}
void print() {
for (unsigned i = 0; i < P.size(); i++) {
std::cout << P[i] << " ";
}
std::cout << std::endl;
}
};
#endif
|
Java | UTF-8 | 1,041 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package Main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main_PhysicsMomentum extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
Momentum m = new Momentum();
Main_PhysicsMomentum()
{
setSize(Support.Width,Support.Height);
setLocationRelativeTo(null);
setResizable(false);
super.setTitle("Conservation of momentum (By Moh Yaghoub)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setUndecorated(true);
add(m);
addActionListenerForQuitButton();
setVisible(true);
}
public void addActionListenerForQuitButton()
{
m.getQuit().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Main_PhysicsMomentum.this.dispatchEvent(new WindowEvent(Main_PhysicsMomentum.this, WindowEvent.WINDOW_CLOSING));
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main_PhysicsMomentum();
}
}
|
JavaScript | UTF-8 | 506 | 4.4375 | 4 | [] | no_license | //Create a load event to show the object on screen
document.addEventListener('load',objectCreation(),false);
function objectCreation(){
//Create the object then print to the screen
function person (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
var andyF = new person("Andy", "Faulkner");
document.getElementById("output").innerHTML = "My name is " + andyF.fullName();
} |
Java | UTF-8 | 2,067 | 3.140625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | /*
* MIT License
* Copyright (c) 2021 cegredev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package main;
import io.github.cegredev.josi.OS;
public class HowsItWork {
public static void likeThis() {
// The io.github.cegredev.josi.OS enum is the heart of the library. It contains the current operating system:
OS os = OS.current();
// ...which can be anything from WIN_95 to WIN_10 to any Mac version to a Linux based system. This is as
// specific as it gets for this library.
// The more useful information is the *family* of the operating system, i.e. Windows, Mac, Linux or Other
// You can get it like this:
OS.Family family = os.getFamily();
// ...and the use it to execute code based on it:
switch (family) {
case WINDOWS:
// ...
case MAC:
// ...
case LINUX:
// ...
case OTHER:
// ...
}
// This is pretty much all you need to know, but I strongly encourage you to take a look at the other examples
// to explore some of the utility methods Josi has to offer!
}
}
|
C++ | UTF-8 | 4,417 | 2.59375 | 3 | [] | no_license | #include "level.h"
namespace core { namespace tmx {
Level::Level(TmxMap* tmxMap, std::string filePath, unsigned int winWidth, unsigned int winHeight)
{
std::string directory = StringUtils::getFolderFromPath(filePath);
this->m_TileSetName = tmxMap->getTileset()->getName();
this->m_TileSetWidth = tmxMap->getTileset()->getTileWidth();
this->m_TileSetHeight = tmxMap->getTileset()->getTileHeight();
this->m_TileSetCount = tmxMap->getTileset()->getTileCount();
this->m_TileSetColumns = tmxMap->getTileset()->getColumns();
this->m_TileSetImagePath = directory + tmxMap->getTileset()->getImage()->getSource();
this->m_TileSetImageWidth = tmxMap->getTileset()->getImage()->getWidth();
this->m_TileSetImageHeight = tmxMap->getTileset()->getImage()->getHeight();
this->m_LevelWidth = tmxMap->getWidth() * m_TileSetWidth;
this->m_LevelHeight = tmxMap->getHeight() * m_TileSetHeight;
for (auto const& layer : tmxMap->getLayers()) {
int tileId = 0;
int columnIdx = 0;
int rowIdx = 0;
for (auto const& tile : layer->getTiles()) {
tileId = tile.getGid();
int destX = 0;
int destY = 0;
if (columnIdx == tmxMap->getWidth() - 1)
{
destX = columnIdx * this->m_TileSetWidth;
destY = rowIdx * this->m_TileSetHeight;
columnIdx = 0;
rowIdx++;
}
else {
destX = columnIdx * this->m_TileSetWidth;
destY = rowIdx * this->m_TileSetHeight;
columnIdx++;
}
if (tileId == 0) {
continue;
}
int tileSetX = ((tileId % this->m_TileSetColumns) - 1) * this->m_TileSetWidth;
int tileSetY = ((int)tileId / this->m_TileSetColumns) * this->m_TileSetHeight;
if (tileSetX < 0)
{
tileSetX = this->m_TileSetImageWidth - this->m_TileSetWidth;
tileSetY -= this->m_TileSetHeight;
}
if (tileSetY < 0)
{
tileSetY = 0;
}
std::pair<SDL_Rect, SDL_Rect> tileRects;
tileRects.first = { tileSetX, tileSetY, this->m_TileSetWidth, this->m_TileSetHeight };
tileRects.second = { destX, destY, this->m_TileSetWidth, this->m_TileSetHeight };
if (layer->getName() == "layer_0" || layer->getName() == "layer_1")
{
this->m_TilesLayer1.push_back(tileRects);
}
else if (layer->getName() == "layer_2")
{
this->m_TilesLayer2.push_back(tileRects);
}
}
}
for (auto const& objectGroup : tmxMap->getObjectGroups()) {
if (objectGroup->getName() == "collisions")
{
for (auto const& collision : objectGroup->getObjects())
{
TmxPolyline polyline = collision.getPolyline();
std::vector<TmxPoint> points = polyline.getPoints();
if (points.size() > 0)
{
for (auto const& point : points)
{
this->m_Slopes.push_back(glm::vec2(point.x, point.y));
}
}
else {
this->m_Collisions.push_back({ collision.getX(), collision.getY(), collision.getWidth(), collision.getHeight() });
}
}
}
else if (objectGroup->getName() == "player")
{
TmxProperty playerProp = objectGroup->getObjects()[0].getProperties().getProperty("speed");
if (playerProp.type == "int")
{
this->m_PlayerSpeed = std::stoi(playerProp.value);
}
this->m_PlayerPosition = glm::vec2(objectGroup->getObjects()[0].getX(), objectGroup->getObjects()[0].getY());
}
else if (objectGroup->getName() == "camera")
{
int cameraX = objectGroup->getObjects()[0].getX() - winWidth / 2;
int cameraY = objectGroup->getObjects()[0].getY() - winHeight / 2;
TmxProperty cameraProp = objectGroup->getObjects()[0].getProperties().getProperty("speed");
if (cameraProp.type == "int")
{
this->m_CameraSpeed = std::stoi(cameraProp.value);
}
if (cameraX < 0) {
cameraX = 0;
}
if (cameraY < 0) {
cameraY = 0;
}
if (cameraX + winWidth >= this->getLevelWidth()) {
cameraX = this->getLevelWidth() - winWidth;
}
if (cameraY + winHeight >= this->getLevelHeight()) {
cameraY = this->getLevelHeight() - winHeight;
}
this->m_Camera = { cameraX, cameraY, (int) winWidth, (int) winHeight };
}
else if (objectGroup->getName() == "triggers")
{
for (auto const& trigger : objectGroup->getObjects())
{
this->m_Triggers.push_back(Trigger(trigger.getName(), trigger.getX(), trigger.getY(), trigger.getWidth(), trigger.getHeight()));
}
}
}
}
Level::~Level()
{
this->m_Triggers.clear();
}
} } |
Python | UTF-8 | 3,982 | 2.78125 | 3 | [] | no_license | import datetime
import psycopg2
class DBManager:
dbname = None
user = None
password = None
host = 'localhost'
cursor = None
conn = None
def __init__(self, dbname, user, password):
self.dbname = dbname
self.user = user
self.password = password
self.conn = psycopg2.connect(dbname=self.dbname, user=self.user, password=self.password, host=self.host,
port='5432')
self.cursor = self.conn.cursor()
def _is_uid_exists(self, uid):
self.cursor.execute('SELECT id from admin.users WHERE id = {}'.format(uid))
result = self.cursor.fetchone()
if result is None:
return False
return True
def set_user_info(self, func):
"""Метод записывает в БД инфу про юзера"""
cur_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def wrapper(message):
if not self._is_uid_exists(message.from_user.id):
self.cursor.execute('INSERT INTO admin.users(id, user_name, last_online) VALUES (%s, %s, %s);',
(message.from_user.id,
message.from_user.first_name + ' ' + message.from_user.last_name,
cur_date))
else:
self.cursor.execute('UPDATE admin.users SET last_online=%s WHERE id = %s',
(cur_date, message.from_user.id))
self.conn.commit()
func(message)
return wrapper
def set_unknown_message_info(self, message):
"""Метод записывает информацию о нераспознанном сообщении в базу"""
cur_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.cursor.execute("SELECT id from admin.unknown_messages order by id desc limit 1")
result = self.cursor.fetchone()
# Проверяем id. Если база пустая, задаем id = 1 Для избежания ошибки при записи
if result is None:
message_id = 1
else:
message_id = result[0] + 1
last_user_name = ' ' + message.from_user.last_name if message.from_user.last_name else ''
self.cursor.execute('INSERT INTO admin.unknown_messages('
'id, uid, name, message, message_time) VALUES ('
'%s, %s, %s, %s, %s);', (
message_id, message.from_user.id,
last_user_name,
message.text, cur_date))
self.conn.commit()
def get_unknown_massage_info(self):
"""Метод выдает информацию о нераспознанном сообщении из базы"""
self.cursor.execute('SELECT id, uid, name, message, message_time '
'FROM admin.unknown_messages;')
self.conn.commit()
result = self.cursor.fetchall()
if result:
my_unknown_msg = 'Неопознанные сообщения:\n\n'
for line in result:
my_unknown_msg += '[{}] Гость {} написал "{}" \n'.format(line[4], line[2], line[3])
else:
my_unknown_msg = 'Неопознанных сообщений нет'
return my_unknown_msg
def delete_all_unknown_messages(self):
"""Метод очищает всю таблицу"""
self.cursor.execute('TRUNCATE admin.unknown_messages')
self.conn.commit()
def is_admin_id(self, user_id):
"""Метод проверяет, id админа передано или нет"""
self.cursor.execute("SELECT id FROM admin.users WHERE user_name = 'Святослав Ященко';")
self.conn.commit()
return self.cursor.fetchone()[0] == user_id
|
Java | UTF-8 | 2,138 | 2.34375 | 2 | [] | no_license | package service;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
/**
* 追踪地理位置的服务
*
* @author gao
*
*/
public class LocationService extends Service {
private LocationManager mLm;
private MyListener mListener;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mLm = (LocationManager) getSystemService(LOCATION_SERVICE);
mListener = new MyListener();
Criteria criteria = new Criteria();
// 获取高精度
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
// 联网
criteria.setCostAllowed(true);
// 获取当时最好的位置提供者
String provider = mLm.getBestProvider(criteria, true);
mLm.requestLocationUpdates(provider, 0, 0, mListener);
}
class MyListener implements LocationListener {
// 位置发生改变
@Override
public void onLocationChanged(Location location) {
String longitude = "j:" + location.getLongitude() + "\n";//获取经度
String latitude = "w:" + location.getLatitude() + "\n";//获取纬度
String accuracy = "a" + location.getAccuracy() + "\n";//获取精度
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("lastlocation",longitude +latitude+ accuracy);
editor.commit();
}
//位置提供者状态变化
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
@Override
public void onDestroy() {
super.onDestroy();
mLm.removeUpdates(mListener);
mListener=null;
}
}
|
Java | UTF-8 | 3,459 | 2.640625 | 3 | [] | no_license | package com.java.coolsound.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.sun.istack.NotNull;
/**
*
* @author raban Clase Comentario
*
*/
@Entity
@Table(name = "Comentario")
public class Comentario {
/** Codigo del Comentario */
@Id
@Column(name = "COMENTARIO_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idComentario;
/** Texto del Comentario */
@Column(name = "TEXTO", unique = true)
@NotNull
private String texto;
/** Usuario */
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "USUARIO_ID")
private Usuario usuario;
/** Hilo */
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "HILO_ID")
private Hilo hilo;
/** Getter del Id del Comentario */
public int getIdComentario() {
return idComentario;
}
/** Setter del Id del Comentario */
public void setIdComentario(int idComentario) {
this.idComentario = idComentario;
}
/** Getter del Texto del Comentario */
public String getTexto() {
return texto;
}
/** Setter del Texto del Comentario */
public void setTexto(String texto) {
this.texto = texto;
}
/** Getter del Usuario */
public Usuario getUsuario() {
return usuario;
}
/** Setter del Usuario */
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
/** Getter del Hilo */
public Hilo getHilo() {
return hilo;
}
/** Setter del Hilo */
public void setHilo(Hilo hilo) {
this.hilo = hilo;
}
/** Constructor por defecto de la clase Comentario */
public Comentario() {
super();
}
/** Constructor de la clase Comentario*/
public Comentario(int idComentario, String texto, Usuario usuario, Hilo hilo) {
super();
this.idComentario = idComentario;
this.texto = texto;
this.usuario = usuario;
this.hilo = hilo;
}
/** ToString de la clase Comentario */
@Override
public String toString() {
return "Comentario [idComentario=" + idComentario + ", texto=" + texto + ", usuario=" + usuario + ", hilo="
+ hilo + "]";
}
/** HashCode de la clase Comentario */
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((hilo == null) ? 0 : hilo.hashCode());
result = prime * result + idComentario;
result = prime * result + ((texto == null) ? 0 : texto.hashCode());
result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
return result;
}
/** Equals de la clase Comentario */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Comentario other = (Comentario) obj;
if (hilo == null) {
if (other.hilo != null)
return false;
} else if (!hilo.equals(other.hilo))
return false;
if (idComentario != other.idComentario)
return false;
if (texto == null) {
if (other.texto != null)
return false;
} else if (!texto.equals(other.texto))
return false;
if (usuario == null) {
if (other.usuario != null)
return false;
} else if (!usuario.equals(other.usuario))
return false;
return true;
}
}
|
Java | UTF-8 | 285 | 2.765625 | 3 | [] | no_license |
public class Link extends Object
{
Point px;
Point py;
public Link (Point p1, Point p2)
{
// un lien est composé de deux point
px = p1;
py = p2;
}
void affiche()
{
System.out.println(px.h+"=>"+py.h);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.