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
| 9,431
| 1.773438
| 2
|
[] |
no_license
|
package com.eventmanage.seating.actions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.event.dbhelpers.EventDB;
import com.event.dbhelpers.EventHelperDB;
import com.event.dbhelpers.SpecialFeeDB;
import com.event.dbhelpers.TicketShowHideDB;
import com.eventbee.beans.Entity;
import com.eventmanage.seating.beans.Section;
import com.eventmanage.seating.beans.Venue;
import com.eventmanage.seating.dbhelpers.SeatingDB;
import com.eventmanage.seating.helpers.SeatingJsonHelper;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class SeatingAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 2406028177432273164L;
//------------------------------------------Properties-----------------------
private String eid;
private String venueid;
private String sectionid;
private ArrayList<Entity> venueList=new ArrayList<Entity>();
private ArrayList<Entity> sectionsList;
private JSONObject messageJson=new JSONObject();
private ArrayList<Entity> eventdates=new ArrayList<Entity>();
private String eventdate="";
private boolean hasvenue;
private String msg="";
private String colorCode="";
private String tckts="";
private Venue venue=new Venue();
private ArrayList alltickets=new ArrayList();
private ArrayList seltickets=new ArrayList();
private LinkedHashMap<String, ArrayList<String>> supportedcolors=new LinkedHashMap<String, ArrayList<String>>();
private String powerType="";
private String isrecurring="";
private int regcount=0;
private boolean showvenue;
private String lockedData="";
private String seatColorData="";
public String getSeatColorData() {
return seatColorData;
}
public void setSeatColorData(String seatColorData) {
this.seatColorData = seatColorData;
}
private String tid="";
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getLockedData() {
return lockedData;
}
public void setLockedData(String lockedData) {
this.lockedData = lockedData;
}
//------------------------------------------Setters and Getters-------------
public String getEventdate() {
return eventdate;
}
public void setEventdate(String eventdate) {
this.eventdate = eventdate;
}
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getVenueid() {
return venueid;
}
public void setVenueid(String venueid) {
this.venueid = venueid;
}
public String getSectionid() {
return sectionid;
}
public void setSectionid(String sectionid) {
this.sectionid = sectionid;
}
public ArrayList<Entity> getVenueList() {
return venueList;
}
public void setVenueList(ArrayList<Entity> venueList) {
this.venueList = venueList;
}
public ArrayList<Entity> getSectionsList() {
return sectionsList;
}
public void setSectionsList(ArrayList<Entity> sectionsList) {
this.sectionsList = sectionsList;
}
public JSONObject getMessageJson() {
return messageJson;
}
public void setMessageJson(JSONObject messageJson) {
this.messageJson = messageJson;
}
public boolean isHasvenue() {
return hasvenue;
}
public void setHasvenue(boolean hasvenue) {
this.hasvenue = hasvenue;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getColorCode() {
return colorCode;
}
public void setColorCode(String colorCode) {
this.colorCode = colorCode;
}
public String getTckts() {
return tckts;
}
public void setTckts(String tckts) {
this.tckts = tckts;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public ArrayList getAlltickets() {
return alltickets;
}
public void setAlltickets(ArrayList alltickets) {
this.alltickets = alltickets;
}
public ArrayList getSeltickets() {
return seltickets;
}
public void setSeltickets(ArrayList seltickets) {
this.seltickets = seltickets;
}
public String getPowerType() {
return powerType;
}
public void setPowerType(String powerType) {
this.powerType = powerType;
}
public LinkedHashMap<String, ArrayList<String>> getSupportedcolors() {
return supportedcolors;
}
public void setSupportedcolors(
LinkedHashMap<String, ArrayList<String>> supportedcolors) {
this.supportedcolors = supportedcolors;
}
public String getIsrecurring() {
return isrecurring;
}
public void setIsrecurring(String isrecurring) {
this.isrecurring = isrecurring;
}
public ArrayList<Entity> getEventdates() {
return eventdates;
}
public void setEventdates(ArrayList<Entity> eventdates) {
this.eventdates = eventdates;
}
public boolean isShowvenue() {
return showvenue;
}
public void setShowvenue(boolean showvenue) {
this.showvenue = showvenue;
}
public int getRegcount() {
return regcount;
}
public void setRegcount(int regcount) {
this.regcount = regcount;
}
//------------------------------------------Action Methods-----------------
public String execute(){
populateData();
return "success";
}
void populateData(){
hasvenue=false;
eventdates=TicketShowHideDB.getEventDates(eid);
venueid=SeatingDB.getVenue(eid);
if("".equals(venueid) || venueid==null) hasvenue=false;
else hasvenue=true;
if(hasvenue) populateSections();
regcount=SeatingDB.getRegCount(eid);
venueList=SeatingDB.getUserVenues(EventDB.getUserId(eid));
ArrayList lockedList=SeatingDB.getLockedSeatsData(eid);
lockedData=SeatingJsonHelper.getLockedJSONData(lockedList);
seatColorData=SeatingDB.getAllSeatColors(eid);
//else populateVenues();
}
public String releaseSeats(){
System.out.println("the eid is::"+eid);
System.out.println("the tid is::"+tid);
SeatingDB.realeseSeats(eid,tid);
return "ajaxjson";
}
public String getSections(){
sectionsList=SeatingDB.GetVenueSections(venueid);
return "sections";
}
public void populateVenues(){
venueList=SeatingDB.getVenueList();
//venueList=SeatingDB.getUserVenues(EventDB.getUserId(eid));
}
public void populateSections(){
showvenue=SeatingDB.getShowVenue(eid);
venue=SeatingDB.getVenueDetails(venueid);
sectionsList=SeatingDB.GetVenueSections(venueid);
}
public String getSectionDetails(){
messageJson=SeatingJsonHelper.getSectionSeatingDetails(sectionid, eid,eventdate,isrecurring);
msg=messageJson.toString();
return "ajaxjson";
}
public String addVenue(){
// adding for special fee start
String mgrId=ActionContext.getContext().getParameters().get("mgrId").toString();
SpecialFeeDB.chekingSpecialFee(eid,mgrId,"300","Venue Seating");
// special fee end.
SeatingDB.addVenue(eid, venueid);
return execute();
}
public String getTicketsandColors(){
supportedcolors=SeatingDB.getSupportedSeatColors(eid, sectionid);
if(supportedcolors.size()<1){
msg=supportedcolors.size()+"";
return "ajaxjson";
}
else{
alltickets=EventDB.getEventTickets(eid);
return "addseat";
}
}
public String addSeat(){
SeatingDB.addSeat(alltickets, colorCode, eid, venueid);
EventHelperDB.removeGLobalEventCache(eid+"_"+venueid, "remove", "seatingvenuedetails");
populateData();
return "success";
}
public String deleteSeat(){
SeatingDB.deleteSeat(colorCode, eid, venueid);
EventHelperDB.removeGLobalEventCache(eid+"_"+venueid, "remove", "seatingvenuedetails");
populateData();
return "success";
}
public String getSeatColors(){
JSONObject seattypes=SeatingJsonHelper.getSeatColorsJson(eid,powerType);
msg=seattypes.toString();
return "ajaxjson";
}
public String saveSeats(){
try{
JSONObject obj=new JSONObject();
obj=(JSONObject)new JSONTokener(msg).nextValue();
JSONArray ja=obj.getJSONArray("seating");
SeatingDB.saveSeats(eid, venueid, sectionid, ja);
}catch (Exception e) {
}
msg="success";
EventHelperDB.removeGLobalEventCache(eid, "remove", "eventinfo");
EventHelperDB.removeGLobalEventCache(eid+"_"+venueid, "remove", "seatingvenuedetails");
return "ajaxjson";
}
public String getTicketsForColor(){
alltickets=SeatingDB.getEventTickets(eid);
if(alltickets.size()<1)
{
msg="notickets";
return "ajaxjson";
}else{
seltickets=SeatingDB.getselectedTickets(eid, colorCode);
return "showtickets";
}
}
public String updateSeatTickets(){
SeatingDB.updateSeatTickets(seltickets, eid, venueid, colorCode);
EventHelperDB.removeGLobalEventCache(eid+"_"+venueid, "remove", "seatingvenuedetails");
populateData();
return "success";
}
public String addManual(){
populateData();
return "addmanual";
}
public String saveManual(){
try{
JSONObject obj=new JSONObject();
obj=(JSONObject)new JSONTokener(msg).nextValue();
JSONArray ja=obj.getJSONArray("seating");
SeatingDB.saveAddManual(eid, venueid, sectionid, ja,eventdate);
}catch (Exception e) {
}
msg="success";
return "ajaxjson";
}
public String showvenue(){
SeatingDB.showVenue(eid, showvenue, venueid);
msg="success";
return "ajaxjson";
}
}
|
Markdown
|
UTF-8
| 850
| 2.796875
| 3
|
[] |
no_license
|
# About
My demo application for Code BootCamp 2021. It is a web search engine for upcoming movies on tv.
This application uses following libraries:
- ORM: SQLAlchemy
- Flask for web application development
- Beautiful Soup for pulling data out of HTML pages
- Pipenv for managing dependencies
Application can be easily deployed to Heroku or DigitalOcean. Have been tested only on Python 3.
# Config file
Make sure to create .env file in your project root (see .env_example) which contains your personal API KEY for accessing api data.
# Database
The application communicates with PostgreSQL database, running on Heroku.
# Running application
```shell
# Optional if you don't have pipenv installed
pip install pipenv
pipenv install
pipenv shell
python app.py
```
# Documentation
Documentation can be found in doc folder.
# Author
Mika Pulliainen
|
Ruby
|
UTF-8
| 844
| 2.59375
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Table do
let(:table) { Table.new("test_table", "id")}
context "#initialize" do
it "initializes a table with name" do
table.name.should == "test_table"
end
it "initializes a table with a primary key" do
table.columns.should include("id")
end
it "sets a primary key" do
table.primary_key.should == "id"
end
end
it "adds a column to the table" do
table.add_column("name")
table.columns.should include("name")
end
it "add a row into a table" do
row = Row.new([])
mock(row).values { {"id" => 1, "name" => "itable"} }
table.add(row)
table.rows.keys.should include(1)
table.rows.values.should include(row)
end
it "stringifies the table" do
table.to_s.should == %{Table{name='test_table', rows={}, columns=["id"]}};
end
end
|
Java
|
UTF-8
| 934
| 2.3125
| 2
|
[] |
no_license
|
package io.threestacks.packerapi.budget;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BudgetService {
@Autowired
private BudgetRepository budgetRepository;
public List<Budget> getAllBudgets(){
List<Budget> budgets = new ArrayList<>();
budgetRepository.findAll().forEach(budgets::add);
return budgets;
}
public Budget getBudget(long id){
return budgetRepository.findOne(id);
}
public List<Budget> getPacksBudget(int packId){
List<Budget> budgets = new ArrayList<>();
budgetRepository.findByPackId(packId).forEach(budgets::add);
return budgets;
}
public Budget addBudget(Budget budget) {
budgetRepository.save(budget);
return budget;
}
public Budget deleteBudget(long id) {
Budget bud = getBudget(id);
budgetRepository.delete(id);
return bud;
}
}
|
Java
|
UTF-8
| 4,100
| 2.203125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.yn.repository.impl;
import com.yn.pojo.Booking;
import com.yn.pojo.Customer;
import com.yn.pojo.Employee;
import com.yn.pojo.Tour;
import com.yn.pojo.User;
import com.yn.repository.BookingRepository;
import com.yn.service.UserService;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Huynh Thi Tuyet Ngoc
*/
@Repository
public class BookingRepositoryImpl implements BookingRepository {
@Autowired
private LocalSessionFactoryBean sessionFactory;
@Autowired
private UserService userService;
@Override
@Transactional
public void addBooking(Booking b) {
Session s = this.sessionFactory.getObject().getCurrentSession();
long millis = System.currentTimeMillis();
java.sql.Date dateCreated = new java.sql.Date(millis);
b.setBookingDay(dateCreated);
//set nguoi nao đat
Customer cus = new Customer();
User ua = this.userService.getUsersAuth();
cus = s.get(Customer.class, ua.getId());
System.out.println(cus);
b.setCustomerId(cus);
s.save(b);
}
@Override
@Transactional
public BigDecimal getDoanhThu(int thang, int nam) {
Session session = this.sessionFactory.getObject().getCurrentSession();
Query q = session.createQuery("SELECT sum(totalMoney) FROM Booking where month(bookingDay) = :thang and year(bookingDay) = :nam");
q.setParameter("thang", thang);
q.setParameter("nam", nam);
return (BigDecimal) q.getResultList().get(0);
}
@Override
@Transactional
public Long getTourDaDat(int thang, int nam) {
Session session = this.sessionFactory.getObject().getCurrentSession();
Query q = session.createQuery("SELECT COUNT(*) FROM Booking where month(bookingDay) = :thang and year(bookingDay) = :nam");
q.setParameter("thang", thang);
q.setParameter("nam", nam);
return (Long) q.getResultList().get(0);
}
@Override
@Transactional
public BigDecimal getPrice(Tour t, Booking b) {
return t.getGia().multiply(new BigDecimal(b.getSoNguoiLonDi()))
.add(t.getGia().multiply(new BigDecimal(b.getSoNguoiNhoDi())).multiply(new BigDecimal(0.5)));
}
@Override
@Transactional
public Long getSoLuongTourDatDat(int i) {
Session session = this.sessionFactory.getObject().getCurrentSession();
Query q = session.createQuery("SELECT sum(soNguoiLonDi) FROM Booking where tour_id =:idtour");
q.setParameter("idtour", i);
if(q.getResultList().get(0)== null)
return new Long(0);
Long tong1 = (Long) q.getResultList().get(0);
Query q2 = session.createQuery("SELECT sum(soNguoiLonDi) FROM Booking where tour_id =:idtour");
q2.setParameter("idtour", i);
Long tong2 = (Long) q.getResultList().get(0);
return tong1 + tong2;
}
@Override
@Transactional
public List<Booking> getBooking() {
Session session = this.sessionFactory.getObject().getCurrentSession();
Query q = session.createQuery("FROM Booking");
return q.getResultList();
}
@Override
@Transactional
public void nhantour(int tour) {
//tim booking
Session session = this.sessionFactory.getObject().getCurrentSession();
Booking booking= session.get(Booking.class, tour);
Employee eloy = new Employee();
User ua = this.userService.getUsersAuth();
eloy = session.get(Employee.class, ua.getId());
booking.setNhanvien(eloy);
session.update(booking);
}
}
|
Go
|
UTF-8
| 475
| 3.234375
| 3
|
[] |
no_license
|
package main
import (
"fmt"
"time"
)
func printHour() {
t := time.Now()
switch {
case t.Hour() < 23:
fmt.Printf("%v Boa noite\n", t.Hour())
case t.Hour() < 22:
fmt.Printf("%v Boa noite\n", t.Hour())
case t.Hour() < 18:
fmt.Printf("%v Boa noite\n", t.Hour())
case t.Hour() < 12:
fmt.Printf("%v Boa tarde\n", t.Hour())
case t.Hour() < 6:
fmt.Printf("%v Bom dia\n", t.Hour())
default:
fmt.Printf("%v Indefinido\n", t)
}
}
func main() {
printHour()
}
|
C#
|
UTF-8
| 3,236
| 2.859375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Algorithm.Graph;
namespace Algorithm.Test
{
/**
* .
*
* @author John V. Sichi
*/
public abstract class ShortestPathTestCase
{
// ~ Static fields/initializers ---------------------------------------------
public static String V1 = "v1";
public static String V2 = "v2";
public static String V3 = "v3";
public static String V4 = "v4";
public static String V5 = "v5";
// ~ Instance fields --------------------------------------------------------
public DefaultWeightedEdge e12;
public DefaultWeightedEdge e13;
public DefaultWeightedEdge e15;
public DefaultWeightedEdge e24;
public DefaultWeightedEdge e34;
public DefaultWeightedEdge e45;
// ~ Methods ----------------------------------------------------------------
/**
* .
*/
public void testPathBetween()
{
List<DefaultWeightedEdge> path;
Graph<String, DefaultWeightedEdge> g = create();
path = findPathBetween(g, V1, V2);
//assertEquals(Arrays.asList(new DefaultWeightedEdge[] { e12 }), path);
path = findPathBetween(g, V1, V4);
//assertEquals(Arrays.asList(new DefaultWeightedEdge[] { e12, e24 }), path);
path = findPathBetween(g, V1, V5);
//assertEquals(Arrays.asList(new DefaultWeightedEdge[] { e12, e24, e45 }), path);
path = findPathBetween(g, V3, V4);
//assertEquals(Arrays.asList(new DefaultWeightedEdge[] { e13, e12, e24 }), path);
}
protected abstract List<DefaultWeightedEdge> findPathBetween(Graph<String, DefaultWeightedEdge> g, String src, String dest);
protected Graph<String, DefaultWeightedEdge> create()
{
return createWithBias(true);
}
protected Graph<String, DefaultWeightedEdge> createWithBias(bool negate)
{
Graph<String, DefaultWeightedEdge> g;
double bias = 1;
if (negate)
{
// negative-weight edges are being tested, so only a directed graph
// makes sense
g = new SimpleDirectedWeightedGraph<string, DefaultWeightedEdge>(typeof(DefaultWeightedEdge));
bias = 1;
}
else
{
// by default, use an undirected graph
g = new SimpleWeightedGraph<string, DefaultWeightedEdge>(typeof(DefaultWeightedEdge));
}
g.addVertex(V1);
g.addVertex(V2);
g.addVertex(V3);
g.addVertex(V4);
g.addVertex(V5);
e12 = Graphs.addEdge(g, V1, V2, bias * 2);
e13 = Graphs.addEdge(g, V1, V3, bias * 3);
e24 = Graphs.addEdge(g, V2, V4, bias * 5);
e34 = Graphs.addEdge(g, V3, V4, bias * 20);
e45 = Graphs.addEdge(g, V4, V5, bias * 5);
e15 = Graphs.addEdge(g, V1, V5, bias * 100);
return g;
}
}
// End ShortestPathTestCase.java
}
|
Python
|
UTF-8
| 1,822
| 3.671875
| 4
|
[] |
no_license
|
"""The input module, containing the input class."""
from input_output.terminal_output import Output
class Input:
"""The input class, containing functions related to user input."""
valid_commands = [
"create person",
"list people",
"open ticket",
"close ticket",
"assign ticket",
"list open tickets",
"list all tickets",
"exit"
]
@classmethod
def get_person_name(cls):
"""Request the person name from the user."""
Output.print_bold("What is the name of the person?")
user_input = input()
return user_input
@classmethod
def get_ticket_name(cls):
"""Request the person name from the user."""
Output.print_bold("What is the title of the ticket?")
ticket_name = input()
return ticket_name
@classmethod
def get_ticket_id(cls):
"""Request the person name from the user."""
Output.print_bold("What is the ticket ID?")
ticket_id = input()
return int(ticket_id)
@classmethod
def get_ticket_owner(cls):
"""Request the person name from the user."""
Output.print_bold("Who would you like to assign it to?")
ticket_owner = input()
return ticket_owner
@classmethod
def get_input(cls):
"""Get input from the command line and verfies its content."""
user_input = input()
if user_input not in cls.valid_commands:
Output.print_error(f"'{user_input}' is not a valid command.")
cls.print_help()
return user_input
@classmethod
def print_help(cls):
"""Print a list of valid commands to stdout."""
Output.print_bold("Valid commands:")
for command in cls.valid_commands:
print(command)
|
Python
|
UTF-8
| 1,387
| 2.90625
| 3
|
[] |
no_license
|
import cv2
import numpy as np
img = cv2.imread("../img/shapes.png")
# 그레이 스케일 변환
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 바이너리 스케일 변환
ret, th = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY_INV)
# 컨투어 찾기
contours, hierachy = cv2.findContours(th, cv2.RETR_EXTERNAL, \
cv2.CHAIN_APPROX_SIMPLE)[-2:]
# 각 도형의 컨투어에 대한 루프
for c in contours:
# 모멘트 계산
mmt = cv2.moments(c)
# m10/m00, m01/m00 중심점 계산
cx = int(mmt['m10']/mmt['m00'])
cy = int(mmt['m01']/mmt['m00'])
# 영역 넓이
a = mmt['m00']
# 영역 외곽선 길이
l = cv2.arcLength(c, True)
# 중심점에 노란색 점 그리기
cv2.circle(img, (cx, cy), 5, (0, 255, 255), -1)
# 중심점 근처에 넓이 그리기
cv2.putText(img, "A:%.0f"%a, (cx, cy+20) , cv2.FONT_HERSHEY_PLAIN, \
1, (0,0,255))
# 컨투어 시작점에 길이 그리기
cv2.putText(img, "L:%.2f"%l, tuple(c[0][0]), cv2.FONT_HERSHEY_PLAIN, \
1, (255,0,0))
# 함수로 컨투어 넓이 계산해서 출력
print("area:%.2f"%cv2.contourArea(c, False))
# 결과 출력
cv2.imshow('center', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
C
|
UTF-8
| 2,913
| 3.59375
| 4
|
[] |
no_license
|
/**
\file : client_task2_3.c
\author : Sreeram Sadasivam
\brief : Task 2.3 for Operating Systems:Dependability & Trust Lab -
Design a client program to send client requests.
\copyright : Copyrights reserved @2016
*/
/**Standard Headerfiles*/
#include <stdio.h>
#include <stdlib.h>
/**Headerfiles for Family of Wait system calls*/
#include <sys/wait.h>
/**Headerfiles defined for the system types encountered.*/
#include <sys/types.h>
/**usleep Header file*/
#include <unistd.h>
/**String Header file*/
#include <string.h>
/**Directory Header File*/
#include <dirent.h>
/**time header for random number seed*/
#include <time.h>
int removeRequest(char *req_file_name) {
if (unlink(req_file_name)!=0)
{
fprintf(stderr, "Error:Unlink failed.");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int createRequest(char *req_file_name) {
FILE *fp = fopen(req_file_name,"w");
if(fp == NULL) {
fprintf(stderr, "Error:File Open failed.");
return EXIT_FAILURE;
}
printf("Client %d creating request %s\n", getpid(), req_file_name);
fclose(fp);
return EXIT_SUCCESS;
}
int client() {
DIR *dirp;
struct dirent *dp;
printf("Client Process has begun sending the requests...\n");
while(1) {
char request_file_name[100],request_name[100];
int isRequestIDSame = 0;
int ret_val_usleep;
/**Open the current directory.*/
dirp = opendir("./requests");
if(sprintf(request_name,"req_%d",rand()%10000)<0) {
fprintf(stderr, "Error:STDOUT failed.");
return EXIT_FAILURE;
}
while(dirp) {
if ((dp = readdir(dirp)) != NULL) {
//printf("Directory Name: %s\n", dp->d_name);
if (strcmp(dp->d_name,request_name)==0)
{
isRequestIDSame = 1;
}
}
else {
break;
}
}
/**Close the requests directory.*/
closedir(dirp);
if(!isRequestIDSame) {
int random_number;
srand(time(NULL));
random_number = rand();
if (random_number % 2 == 0){
if(sprintf(request_file_name,"./requests/%s_fail",request_name)<0) {
fprintf(stderr, "Error:STDOUT failed.");
return EXIT_FAILURE;
}
}
else {
if(sprintf(request_file_name,"./requests/%s",request_name)<0) {
fprintf(stderr, "Error:STDOUT failed.");
return EXIT_FAILURE;
}
}
if(createRequest(request_file_name)==EXIT_FAILURE) {
fprintf(stderr, "Error:createRequest function failed.\n");
return EXIT_FAILURE;
}
ret_val_usleep = usleep(500000);
/**Failure in usleep call*/
if(ret_val_usleep<0) {
fprintf(stderr, "Error:Usleep function failed.\n");
/**Process returns and terminates with error*/
return EXIT_FAILURE;
}
}
}
return EXIT_SUCCESS;
}
int main(int argc, char const *argv[])
{
/**Invoking the request creation method.*/
if(client()==EXIT_SUCCESS) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}
}
|
TypeScript
|
UTF-8
| 349
| 2.640625
| 3
|
[] |
no_license
|
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({
name: 'reducedDescription'
})
export class ReducedDescription implements PipeTransform {
transform(texto: string): string {
let endOn: number = 15
if(texto.length > endOn) {
return texto.substr(0, endOn) + '...';
}
return texto;
}
}
|
C++
|
UTF-8
| 2,072
| 2.59375
| 3
|
[] |
no_license
|
//////////////////////////////////////////////////////////////////////
// Process.h
//
// Abin
// 2016-03-12
//////////////////////////////////////////////////////////////////////
#ifndef __PROCESS_H__
#define __PROCESS_H__
class CProcess
{
public:
CProcess();
virtual ~CProcess();
virtual BOOL Create(LPCTSTR lpszExePath, LPCTSTR lpszParams, LPCTSTR lpszLocation, BOOL bHasWindow = TRUE);
virtual void Terminate(BOOL bForceKill);
virtual BOOL Attach(DWORD dwProcessID, BOOL bHasWindow = TRUE);
virtual void Detach();
virtual HWND UpdateWindow(BOOL bVisibleOnly = TRUE);
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam = 0, BOOL bVisibleOnly = TRUE) const; // Enumerates all windows created by this process
DWORD GetID() const;
DWORD GetExitCode() const;
BOOL IsAlive() const;
HWND IsWindow() const;
BOOL IsIdle() const;
BOOL IsResponsive() const;
DWORD GetLastResponse() const;
DWORD GetHungTime() const; // Time elapsed since the last time the window was responsive
static BOOL GetProcessFilePath(DWORD dwProcessID, LPTSTR lpszBuff, int nMaxLen, BOOL bDirectoryOnly = FALSE);
static DWORD FindProcessByName(LPCTSTR lpszName);
static BOOL KillProcess(DWORD dwProcessID, DWORD dwExitCode = 0);
static DWORD GetProcessIDFromHandle(HANDLE hProcess);
protected:
// Overrides
virtual void OnCreate() {}
virtual void OnTerminate() {}
virtual void OnAttach() {}
virtual void OnDetach() {}
virtual BOOL CompareWindow(HWND hWnd) const { return TRUE; } // Return TRUE if hWnd is our main window
private:
void _AttachInfo(DWORD dwProcessID, HANDLE hProcess, BOOL bHasWindow, BOOL bCreate);
void _DetachInfo(BOOL bTerminate);
static BOOL CALLBACK _FindMainWndProc(HWND hWnd, LPARAM lParam);
DWORD m_dwProcessID; // Process ID
HANDLE m_hProcess; // Process handle
HWND m_hMainWnd; // Process main window
DWORD m_dwStartTime; // Process attaching time
DWORD m_dwLastResponse; // Last time the process main window was responsive
BOOL m_bHasWindow; // Whether we need to check process main window
};
#endif // __PROCESS_H__
|
Java
|
UTF-8
| 223
| 2.375
| 2
|
[] |
no_license
|
package kata.supermarket;
import java.math.BigDecimal;
public interface IItem {
Product getproduct();
BigDecimal getPrice();
int getQuantity();
void addItem(int qty);
void subtractItem(int qty);
}
|
C
|
UTF-8
| 6,495
| 2.6875
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] |
permissive
|
/* Generated by re2j */
#line 1 "condition_06.cs.re"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BSIZE 8192
typedef struct Scanner
{
FILE *fp;
unsigned char *cur, *tok, *lim, *eof;
unsigned char buffer[BSIZE];
} Scanner;
int fill(Scanner *s, int len)
{
if (!len)
{
s->cur = s->tok = s->lim = s->buffer;
s->eof = 0;
}
if (!s->eof)
{
int got, cnt = s->tok - s->buffer;
if (cnt > 0)
{
memcpy(s->buffer, s->tok, s->lim - s->tok);
s->tok -= cnt;
s->cur -= cnt;
s->lim -= cnt;
}
cnt = BSIZE - cnt;
if ((got = fread(s->lim, 1, cnt, s->fp)) != cnt)
{
s->eof = &s->lim[got];
}
s->lim += got;
}
else if (s->cur + len > s->eof)
{
return 0; /* not enough input data */
}
return -1;
}
void fputl(const char *s, size_t len, FILE *stream)
{
while(len-- > 0)
{
fputc(*s++, stream);
}
}
#line 57 "<stdout>"
enum YYCONDTYPE {
EStateNormal,
EStateComment,
EStateSkiptoeol,
EStateString,
};
#line 54 "condition_06.cs.re"
void scan(Scanner *s)
{
int cond = EStateNormal;
fill(s, 0);
for(;;)
{
s->tok = s->cur;
#line 78 "<stdout>"
{
unsigned char yych;
if (cond < 2) {
if (cond < 1) {
goto yyc_Normal;
} else {
goto yyc_Comment;
}
} else {
if (cond < 3) {
goto yyc_Skiptoeol;
} else {
goto yyc_String;
}
}
/* *********************************** */
yyc_Comment:
if ((s->lim - s->cur) < 2) { if(fill(s, 2) >= 0) break; }
yych = *s->cur;
if (yych != '*') goto yy5;
++s->cur;
if ((yych = *s->cur) == '/') goto yy6;
yy4:
#line 149 "condition_06.cs.re"
{
goto yyc_Comment;
}
#line 106 "<stdout>"
yy5:
yych = *++s->cur;
goto yy4;
yy6:
++s->cur;
#line 145 "condition_06.cs.re"
{
continue;
}
#line 116 "<stdout>"
/* *********************************** */
yyc_Normal:
if ((s->lim - s->cur) < 3) { if(fill(s, 3) >= 0) break; }
yych = *s->cur;
if (yych <= '.') {
if (yych == '"') goto yy13;
goto yy15;
} else {
if (yych <= '/') goto yy12;
if (yych != '?') goto yy15;
}
yych = *(s->tok = ++s->cur);
if (yych == '?') goto yy20;
yy11:
#line 140 "condition_06.cs.re"
{
fputc(*s->tok, stdout);
continue;
}
#line 136 "<stdout>"
yy12:
yych = *++s->cur;
if (yych == '*') goto yy18;
if (yych == '/') goto yy16;
goto yy11;
yy13:
++s->cur;
#line 134 "condition_06.cs.re"
{
fputc(*s->tok, stdout);
state = EStateString;
continue;
}
#line 150 "<stdout>"
yy15:
yych = *++s->cur;
goto yy11;
yy16:
++s->cur;
#line 130 "condition_06.cs.re"
{
goto yyc_Skiptoeol;
}
#line 160 "<stdout>"
yy18:
++s->cur;
#line 126 "condition_06.cs.re"
{
goto yyc_Comment;
}
#line 167 "<stdout>"
yy20:
yych = *++s->cur;
switch (yych) {
case '!': goto yy36;
case '\'': goto yy34;
case '(': goto yy22;
case ')': goto yy24;
case '-': goto yy38;
case '/': goto yy32;
case '<': goto yy26;
case '=': goto yy30;
case '>': goto yy28;
default: goto yy21;
}
yy21:
s->cur = s->tok;
goto yy11;
yy22:
++s->cur;
#line 81 "condition_06.cs.re"
{
fputc('[', stdout);
continue;
}
#line 192 "<stdout>"
yy24:
++s->cur;
#line 86 "condition_06.cs.re"
{
fputc(']', stdout);
continue;
}
#line 200 "<stdout>"
yy26:
++s->cur;
#line 91 "condition_06.cs.re"
{
fputc('{', stdout);
continue;
}
#line 208 "<stdout>"
yy28:
++s->cur;
#line 96 "condition_06.cs.re"
{
fputc('}', stdout);
continue;
}
#line 216 "<stdout>"
yy30:
++s->cur;
#line 101 "condition_06.cs.re"
{
fputc('#', stdout);
continue;
}
#line 224 "<stdout>"
yy32:
++s->cur;
#line 106 "condition_06.cs.re"
{
fputc('\\', stdout);
continue;
}
#line 232 "<stdout>"
yy34:
++s->cur;
#line 111 "condition_06.cs.re"
{
fputc('^', stdout);
continue;
}
#line 240 "<stdout>"
yy36:
++s->cur;
#line 116 "condition_06.cs.re"
{
fputc('|', stdout);
continue;
}
#line 248 "<stdout>"
yy38:
++s->cur;
#line 121 "condition_06.cs.re"
{
fputc('~', stdout);
continue;
}
#line 256 "<stdout>"
/* *********************************** */
yyc_Skiptoeol:
if ((s->lim - s->cur) < 5) { if(fill(s, 5) >= 0) break; }
yych = *s->cur;
if (yych <= '>') {
if (yych == '\n') goto yy45;
goto yy47;
} else {
if (yych <= '?') goto yy42;
if (yych == '\\') goto yy44;
goto yy47;
}
yy42:
yych = *(s->tok = ++s->cur);
if (yych == '?') goto yy52;
yy43:
#line 165 "condition_06.cs.re"
{
goto yyc_Skiptoeol;
}
#line 277 "<stdout>"
yy44:
yych = *(s->tok = ++s->cur);
if (yych == '\n') goto yy50;
if (yych == '\r') goto yy48;
goto yy43;
yy45:
++s->cur;
#line 161 "condition_06.cs.re"
{
continue;
}
#line 289 "<stdout>"
yy47:
yych = *++s->cur;
goto yy43;
yy48:
yych = *++s->cur;
if (yych == '\n') goto yy50;
yy49:
s->cur = s->tok;
goto yy43;
yy50:
++s->cur;
#line 157 "condition_06.cs.re"
{
goto yyc_Skiptoeol;
}
#line 305 "<stdout>"
yy52:
yych = *++s->cur;
if (yych != '/') goto yy49;
yych = *++s->cur;
if (yych == '\n') goto yy55;
if (yych != '\r') goto yy49;
yych = *++s->cur;
if (yych != '\n') goto yy49;
yy55:
++s->cur;
#line 153 "condition_06.cs.re"
{
goto yyc_Skiptoeol;
}
#line 320 "<stdout>"
/* *********************************** */
yyc_String:
if ((s->lim - s->cur) < 2) { if(fill(s, 2) >= 0) break; }
yych = *s->cur;
if (yych == '"') goto yy61;
if (yych != '\\') goto yy63;
++s->cur;
if ((yych = *s->cur) != '\n') goto yy64;
yy60:
#line 179 "condition_06.cs.re"
{
fputc(*s->tok, stdout);
continue;
}
#line 335 "<stdout>"
yy61:
++s->cur;
#line 174 "condition_06.cs.re"
{
fputc(*s->tok, stdout);
continue;
}
#line 343 "<stdout>"
yy63:
yych = *++s->cur;
goto yy60;
yy64:
++s->cur;
#line 169 "condition_06.cs.re"
{
fputl((const char*)s->tok, 2, stdout);
continue;
}
#line 354 "<stdout>"
}
#line 183 "condition_06.cs.re"
}
}
int main(int argc, char **argv)
{
Scanner in;
char c;
if (argc != 2)
{
fprintf(stderr, "%s <file>\n", argv[0]);
return 1;;
}
memset((char*) &in, 0, sizeof(in));
if (!strcmp(argv[1], "-"))
{
in.fp = stdin;
}
else if ((in.fp = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr, "Cannot open file '%s'\n", argv[1]);
return 1;
}
scan(&in);
if (in.fp != stdin)
{
fclose(in.fp);
}
return 0;
}
|
C
|
UTF-8
| 4,388
| 2.78125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <graphics.h>
#include <prints.h>
#include <syscall.h>
#include <chess_piece.h>
#include <chess.h>
#include <shell.h>
#include <timeRTC.h>
#define WHITE 0xFFFFFF
#define BLACK 0x000000
#define SCREENWIDTH 1024
#define SCREENHEIGHT 768
#define BOARDSIZE 760
#define SQUARESIZE 87
#define STARTX 157
#define ENDX 847
#define STARTY 4
#define ENDY 700
void drawPixel(int x, int y, int color){
syscalls(DRAW,0,0,color,0,x,y);
}
void drawBoard(int matrix[][8],uint64_t color1, uint64_t color2, int rotation){
int currentLetter = 6;
int numCount = 14;
int ficha;
int actualColor = color2;
for(int h=0 ; h<SCREENHEIGHT ; h++){
for(int w=0 ; w<SCREENWIDTH; w++){
if((w>=STARTX && w<=ENDX) && (h>=STARTY && h<= ENDY)){
if(((w-STARTX)%87==0) && (w<ENDX)){
if((h-STARTY)%87==0 && h < ENDY){
if(rotation == 0){
ficha = matrix[(h-STARTY)/87][(w-STARTX)/87];
}else if(rotation==1){
ficha = matrix[8-1 -(w-STARTX)/87][(h-STARTY)/87];
}else if(rotation==2){
ficha = matrix[8-1-(h-STARTY)/87][8-1-(w-STARTX)/87];
}else{
ficha = matrix[(w-STARTX)/87][8-1-(h-STARTY)/87];
}
pieces(ficha, w, h, actualColor);
}
}
actualColor = (actualColor == color2)? color1 :color2;
}
if(w==(STARTX - 87) && h%87==0 && h<=ENDY){
if(numCount <= 21){
drawPiece(numCount,w,h,WHITE,BLACK);
numCount++;
}
}
if (h==ENDY && w%87 == 0 && w>=STARTX){
if(currentLetter <= 13){
drawPiece(currentLetter, w-15,h,WHITE,BLACK);
currentLetter++;
}
}
}
}
}
void pieces(int ficha, int w, int h, int actualColor){
if(ficha >= 10 && ficha <= 17){
drawPiece(PAWN,w,h,WHITE,actualColor);
}
else if(ficha >= -17 && ficha <= -10){
drawPiece(PAWN,w,h,BLACK,actualColor);
}
else{
switch(ficha){
case WROOK:
drawPiece(ROOK,w,h,WHITE,actualColor);
break;
case WHORSE:
drawPiece(KNIGHT,w,h,WHITE,actualColor);
break;
case WBISHOP:
drawPiece(BISHOP,w,h,WHITE,actualColor);
break;
case WQUEEN:
drawPiece(QUEEN,w,h,WHITE,actualColor);
break;
case WKING:
drawPiece(KING,w,h,WHITE,actualColor);
break;
case BROOK:
drawPiece(ROOK,w,h,BLACK,actualColor);
break;
case BHORSE:
drawPiece(KNIGHT,w,h,BLACK,actualColor);
break;
case BBISHOP:
drawPiece(BISHOP,w,h,BLACK,actualColor);
break;
case BQUEEN:
drawPiece(QUEEN,w,h,BLACK,actualColor);
break;
case BKING:
drawPiece(KING,w,h,BLACK,actualColor);
break;
default:
drawPiece(SQUARE,w,h,BLACK,actualColor);
}
}
}
void drawPiece(int piece, int x, int y, int pieceColor, int bgColor){
int auxX=x;
int auxY=y;
const char * char_map = chess_bitMap(piece);
for(int i=0 ; i<CHAR_WIDTH * CHAR_HEIGHT ; i++ ){
switch (char_map[i])
{
case ',':
auxY++;
auxX=x;
break;
case '_': //fondo
drawPixel(auxX,auxY,bgColor);
auxX++;
break;
default:
drawPixel(auxX,auxY,pieceColor);
auxX++;
break;
}
}
}
|
Go
|
UTF-8
| 252
| 3.1875
| 3
|
[] |
no_license
|
package main
import (
"bytes"
"fmt"
)
func joinString2(strings ...string) string {
var buf bytes.Buffer
for _, str := range strings {
buf.WriteString(str + " ")
}
return buf.String()
}
func main() {
fmt.Println(joinString2("aaa", "bbb"))
}
|
Markdown
|
UTF-8
| 2,118
| 4.0625
| 4
|
[
"MIT"
] |
permissive
|
# Typing
In Rusty.js types are extremely simple
There are only three kinds of data.
- Absolute
- Optional
- Result
## Absolute
An absolute value is any kind of information that would be held in a JavaScript variable
save for `null` and `undefined`, which is used as `None`.
It is any data that is guaranteed not `None`.
Absolutes are denoted by a `!`.
`fn function(param!) -> !`
The `!` can be omitted in cases other than return types.
`fn function(param) -> !`
## Optional
An optional value is any kind of data that might be null. It also can't be used directly.
Its value must be unwrapped before use.
Optionals are denoted by a `?`.
`fn function(param?) -> ?`
The inner absolute can be extracted by several methods.
```js
let my_optional = some_function();
// Method 1 - Pattern Matching
let my_absolute = match my_optional {
Some(value) => value,
None => return,
};
// Method 2 - If Statement
if Some(value) = my_optional {
// use value
}
// Method 3 - Optional Chaining
let my_absolute = my_optional?;
// This will cause the function we're in to return if `my_optional` is `None`
```
## Result
A Result value is any kind of data that also might be null.
The difference between an optional and a result is a result comes with error info.
For now, this information is just a string, though in the future it could also contain a stack trace.
Results are denoted by a `*`.
`fn function(param*) -> *`
The inner absolute is extracted in a similar manner to optionals.
```js
let my_result = some_function();
// Method 1 - Pattern Matching
let my_absolute = match my_result {
Ok(value) => value,
Err(err) => {
console.log(err);
return;
}
};
// Method 2 - If Statement
if let Ok(value) = my_result {
// use value
}
// Method 3 - Result / Optional Chaining
let my_absolute = my_result?;
// If the result ends up being `Err` the function will return.
// If the function returns an optional, `None` will return.
// If the function returns a result, the containing `Err` will return.
// If the function returns void, the function will simply return.
```
|
C++
|
UTF-8
| 1,934
| 2.859375
| 3
|
[] |
no_license
|
#include "Funcoes.hpp"
CvPoint gira(CvPoint entrada, CvPoint meio, double angulo) {
double seno, coseno;
CvPoint saida;
seno = sin(angulo * M_PI / 180);
coseno = cos(angulo * M_PI / 180);
saida.x = entrada.x * coseno - entrada.y * seno + meio.x - meio.x * coseno
+ meio.y * seno;
saida.y = entrada.x * seno + entrada.y * coseno + meio.y - meio.y * coseno
- meio.x * seno;
return saida;
}
bool pixelReal(IplImage* color, int valueCor, int x, int y, Cor* cores) {
int soma = 0;
uchar* ptr;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) // 0 0, 0 -1, -1 0, -1 -1;
{
ptr = cvPtr2D(color, y - i, x - j, NULL);
if (cores->verificaCor(ptr[0], ptr[1], ptr[2], valueCor))
soma++;
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) // 0 0, 0 +1, +1 0, +1 +1;
{
ptr = cvPtr2D(color, y + i, x + j, NULL);
if (cores->verificaCor(ptr[0], ptr[1], ptr[2], valueCor))
soma++;
}
}
ptr = cvPtr2D(color, y + 1, x - 1, NULL);
if (cores->verificaCor(ptr[0], ptr[1], ptr[2], valueCor))
soma++;
ptr = cvPtr2D(color, y - 1, x + 1, NULL);
if (cores->verificaCor(ptr[0], ptr[1], ptr[2], valueCor))
soma++;
if (soma == 10)
return true;
else
return false;
}
float produtoEscalar(CvPoint direcao, CvPoint centro, CvPoint objetivo) {
CvPoint2D32f vetorDirecao;
CvPoint2D32f vetorObjetivo;
float tam;
vetorDirecao.x = centro.x - direcao.x;
vetorDirecao.y = centro.y - direcao.y;
tam = tamanhoVetor(vetorDirecao);
vetorDirecao.x = vetorDirecao.x / tam;
vetorDirecao.y = vetorDirecao.y / tam;
vetorObjetivo.x = centro.x - objetivo.x;
vetorObjetivo.y = centro.y - objetivo.y;
tam = tamanhoVetor(vetorObjetivo);
vetorObjetivo.x = vetorObjetivo.x / tam;
vetorObjetivo.y = vetorObjetivo.y / tam;
return vetorDirecao.x * vetorObjetivo.x + vetorDirecao.y * vetorObjetivo.y;
}
|
Java
|
UTF-8
| 479
| 2.0625
| 2
|
[] |
no_license
|
package com.genesys.challenge.client.util;
import com.genesys.challenge.client.configuration.ServerConfiguration;
public class GameUtils {
public final static int row_size = Integer.parseInt(ServerConfiguration.prop.getProperty("game.rowSize"));
public final static int col_size = Integer.parseInt(ServerConfiguration.prop.getProperty("game.colSize"));
public final static int count_win = Integer.parseInt(ServerConfiguration.prop.getProperty("game.winSize"))-1;
}
|
Java
|
UTF-8
| 1,186
| 3.171875
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Main2606 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int M = Integer.parseInt(br.readLine());
ArrayList<Integer>[] arr = new ArrayList[N+1];
for(int i=1;i<=N;i++) {
arr[i] = new ArrayList<>();
}
for(int i=0;i<M;i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
arr[a].add(b);
arr[b].add(a);
}
boolean[] visit = new boolean[N+1];
visit[1] = true;
dfs(1,arr,visit);
System.out.println(cnt);
}
static int cnt = 0;
static void dfs(int n,ArrayList<Integer>[] arr,boolean[] visit) {
ArrayList<Integer> l = arr[n];
int size= l.size();
for(int i=0;i<size;i++) {
if(!visit[l.get(i)]) {
visit[l.get(i)] =true;
cnt++;
dfs(l.get(i),arr,visit);
}
}
}
}
|
Java
|
UTF-8
| 627
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
package com.baz.app.dps.Factory;
public class ShapeFactory {
public Shape getShape(String shape) {
if("square".equals(shape))
return new Square();
if("rectangle".equals(shape))
return new Rectangle();
if("circle".equals(shape))
return new Circle();
return null;
}
public void test(ShapeFactory shapeFactory){
Shape rec = shapeFactory.getShape("rectangle");
rec.draw();
Shape cir = shapeFactory.getShape("circle");
cir.draw();
Shape squ = shapeFactory.getShape("square");
squ.draw();
}
}
|
Python
|
UTF-8
| 2,363
| 3.171875
| 3
|
[] |
no_license
|
# problem24.py
#
# Copyright 2015 John Stafford <john@jkms.me>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
#!/usr/bin/env python
MyString="0123456789"
import math
def process_string(MyString='0123456789',findex=[0,0]):
#~ print "findex", findex
column=len(MyString)-2
sections=MyString[:column-findex[0]], MyString[column-findex[0]], MyString[column-findex[0]+1:]
remainder=sections[1]+sections[2]
column_char=remainder[findex[1]]
remainder=list(remainder)
remainder=sorted(remainder)
#~ print "init remind", remainder
remainder.remove(column_char)
remainder=''.join(remainder)
#~ print sections[0],column_char,remainder
reorder=sections[0]+column_char+remainder
return reorder
factorial=[]
for i in range(1,len(MyString)):
factorial.append(math.factorial(i))
def check_column(iteration):
iteration-=1
if iteration < 0:
iteration=0
column_return=[]
while iteration:
for factor in reversed(factorial):
#~ print "checking factor", factor
while iteration >= factor:
#~ print "check_column:",iteration, factor
if not (iteration%factor):
#~ print "hit!"
column_return.append([factorial.index(factor),(iteration/factor)])
iteration=0
else:
column_return.append([factorial.index(factor),(iteration/factor)])
iteration %= factor
return column_return
def check_string(String="012345679",iteration=1):
mods = check_column(iteration)
#~ print mods
String_Iteration=String
for mod in mods:
#~ print String_Iteration, iteration, mod
String_Iteration = process_string(String_Iteration,mod)
return String_Iteration
#~ print check_string(MyString,100)
print "the answer is", check_string(MyString,1000000)
|
Java
|
UTF-8
| 3,122
| 2.796875
| 3
|
[] |
no_license
|
package com.example.krys.traindroid;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* This is a simple Android mobile client
* This application read any string massage typed on the text field and
* send it to the server when the Send button is pressed
* Author by Lak J Comspace
*
*/
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private DataInputStream diReader;
private TextView textField;
private Button button;
private String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (TextView) findViewById(R.id.text_view_id); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//message = textField.getText().toString(); // get the text message on the text field
//textField.setText(""); // Reset the text field to blank
GetMessage getMessageTask = new GetMessage();
getMessageTask.execute();
}
});
}
private class GetMessage extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("127.0.0.1", 10001); // connect to the server
diReader = new DataInputStream(client.getInputStream());
while(true){
while(message.length() < 32) {
message += diReader.readUTF();
}
try{
textField.setText(message);
}
catch( Exception e) {
e.printStackTrace();
}
//diReader.close();
//client.close(); // closing the connection
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.slimple_text_client, menu);
return true;
}
}
|
C
|
UTF-8
| 200
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// strlen.c
//
//
// Created by Nils-erik Engen on 18.09.2017.
//
//
#include "strlen.h"
int strlen(char *s){
int n;
for(n = 0; *s != '\0'; s++){
n++;
}
return n;
}
|
Ruby
|
UTF-8
| 267
| 3.265625
| 3
|
[] |
no_license
|
#DRAW?
#Build a method #draw? that accepts a board and returns true if the board has not
#been won and is full and false if the board is not won and the board is not full,
#and false if the board is won.
# Helper Method
def draw?(board)
!won?(board) && full?(board)
|
Java
|
UTF-8
| 2,423
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2021 Emmanuel Bourg
*
* 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 net.jsign;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import static net.jsign.KeyStoreType.*;
import static org.junit.Assert.*;
public class KeyStoreTypeTest {
@Test
public void testGetType() throws Exception {
assertEquals(PKCS12, KeyStoreType.of(new File("keystore.p12")));
assertEquals(PKCS12, KeyStoreType.of(new File("keystore.pfx")));
assertEquals(JCEKS, KeyStoreType.of(new File("keystore.jceks")));
assertEquals(JKS, KeyStoreType.of(new File("keystore.jks")));
assertNull(KeyStoreType.of(new File("keystore.unknown")));
}
@Test
public void testGetTypePKCS12FromHeader() throws Exception {
File source = new File("target/test-classes/keystores/keystore.p12");
File target = new File("target/test-classes/keystores/keystore.p12.ext");
FileUtils.copyFile(source, target);
assertEquals(PKCS12, KeyStoreType.of(target));
}
@Test
public void testGetTypeJCEKSFromHeader() throws Exception {
File source = new File("target/test-classes/keystores/keystore.jceks");
File target = new File("target/test-classes/keystores/keystore.jceks.ext");
FileUtils.copyFile(source, target);
assertEquals(JCEKS, KeyStoreType.of(target));
}
@Test
public void testGetTypeJKSFromHeader() throws Exception {
File source = new File("target/test-classes/keystores/keystore.jks");
File target = new File("target/test-classes/keystores/keystore.jks.ext");
FileUtils.copyFile(source, target);
assertEquals(JKS, KeyStoreType.of(target));
}
@Test
public void testGetTypeUnknown() throws Exception {
assertNull(KeyStoreType.of(new File("target/test-classes/keystores/jsign-root-ca.pem")));
}
}
|
Python
|
UTF-8
| 1,320
| 3.0625
| 3
|
[] |
no_license
|
__author__ = 'lenovo'
# coding=utf-8
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def threeSum(self, nums):
map={}
result=[]
for i in nums:
map.setdefault(i,0)
map[i]+=1
alist=sorted(map.iteritems(),key=lambda num:num[0])
map2={}
for i in range(len(alist)):
map2[alist[i][0]]=i
for i in range(len(alist)):
arr1=alist[i]
if arr1[1]>=2:
keys=-arr1[0]*2
if map2.has_key(keys) and map2[keys]<i:
continue
if arr1[0]!=keys and map.has_key(-arr1[0]*2):
result.append([arr1[0],arr1[0],-arr1[0]*2])
elif arr1[0]==keys and map[arr1[0]]>=3:
result.append([keys,keys,keys])
for j in range(i+1,len(alist)):
arr2=alist[j]
keys=-arr1[0]-arr2[0]
if map2.has_key(keys) and map2[keys]<j:
continue
if arr2[0]!=keys and map.has_key(keys):
result.append([arr1[0],arr2[0],keys])
elif arr2[0]==keys and map[keys]>=2:
result.append([arr1[0],keys,keys])
return result
sol=Solution()
print sol.threeSum([0,0])
|
Python
|
UTF-8
| 4,481
| 2.90625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
"""
Script to generate new train test splits
"""
import pandas as pd
import numpy as np
import random
import argparse
total_frames = 1950
def get_df_all(data_path):
names = ['path', 'x1', 'y1', 'x2', 'y2', 'class_name']
df_annotations_train = pd.read_csv('{}/annotation_train.csv'.format(data_path), names=names)
df_annotations_val = pd.read_csv('{}/annotation_val.csv'.format(data_path), names=names)
df_annotations_test = pd.read_csv('{}/annotation_test.csv'.format(data_path), names=names)
df_all = pd.concat([df_annotations_train, df_annotations_val, df_annotations_test])
# Isolate image name in path
df_all['path'] = df_all['path'].map(lambda x: x.split('/')[-1])
# Sort alphabetically
df_all = df_all.sort_values('path').reset_index().drop('index', axis=1)
# Add video src column
df_all['video'] = df_all['path'].apply(lambda x: x[-22: -11])
return df_all
def get_new_splits(df_all, seed, cutoff_train, cutoff_val, path, save=False):
random.seed(seed)
groups = [df for _, df in df_all.groupby('video')]
random.shuffle(groups)
df_all_s = pd.concat(groups).reset_index(drop=True)
# Get cutoffs for splits
last_frame = df_all_s['path'][0]
last_video = df_all_s['video'][0]
n_frame = 0
for i in range(1, df_all_s.shape[0]):
current_frame = df_all_s['path'][i]
current_video = df_all_s['video'][i]
if n_frame > cutoff_train:
if current_video != last_video:
cutoff_num_train = i
cutoff_train = float('inf') # no more
elif n_frame > cutoff_val and current_video != last_video:
cutoff_num_val = i
cutoff_val = float('inf')
if last_frame != current_frame:
n_frame += 1
last_frame = current_frame
last_video = current_video
# Finally assign splits
df_split_train = df_all_s.iloc[0:cutoff_num_train]
df_split_val = df_all_s.iloc[cutoff_num_train:cutoff_num_val]
df_split_test = df_all_s.iloc[cutoff_num_val:]
# Add img as path prefix
df_split_train['path'] = df_split_train['path'].apply(lambda x: 'img/{}'.format(x))
df_split_val['path'] = df_split_val['path'].apply(lambda x: 'img/{}'.format(x))
df_split_test['path'] = df_split_test['path'].apply(lambda x: 'img/{}'.format(x))
# Remove video
df_split_train.drop('video', axis=1, inplace=True)
df_split_val.drop('video', axis=1, inplace=True)
df_split_test.drop('video', axis=1, inplace=True)
# Shuffle
df_split_train = df_split_train.sample(frac=1).reset_index(drop=True)
df_split_val = df_split_val.sample(frac=1).reset_index(drop=True)
df_split_test = df_split_test.sample(frac=1).reset_index(drop=True)
# Save and get train_val split
df_split_train_val = pd.concat([df_split_train, df_split_val])
# Save
if save:
df_split_train.to_csv('{}/annotation_train-s={}.csv'.format(path, seed), float_format='%.0f', index=False, header=False)
df_split_val.to_csv('{}/annotation_val-s={}.csv'.format(path, seed), float_format='%.0f', index=False, header=False)
df_split_test.to_csv('{}/annotation_test-s={}.csv'.format(path, seed), float_format='%.0f', index=False, header=False)
df_split_train_val.to_csv('{}/annotation_train_val-s={}.csv'.format(path, seed), float_format='%.0f', index=False, header=False)
return df_split_train, df_split_val, df_split_test, df_split_train_val
def main(args=None):
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--seed', type=int, help='Random seed for shuffling')
parser.add_argument('--train_split', type=float, default=0.5, help='Train split ratio')
parser.add_argument('--val_split', type=float, default=0.2, help='Val split ratio')
parser.add_argument('--test_split', type=float, default=0.3, help='Test split ratio')
parser.add_argument('--total_num', type=int, default=1950)
parser.add_argument('--data_path', type=str, default='../hand-detection-dataset')
args = parser.parse_args(args)
names = ['path', 'x1', 'y1', 'x2', 'y2', 'class_name']
df_all = get_df_all(args.data_path)
cutoff_train = args.total_num * args.train_split
cutoff_val = args.total_num * (args.train_split + args.val_split)
get_new_splits(df_all, args.seed, cutoff_train, cutoff_val, args.data_path, save=True)
print('New splits generated!')
if __name__ == '__main__':
main()
|
C
|
UTF-8
| 559
| 2.671875
| 3
|
[] |
no_license
|
#ifndef __EFFECTLIST_H
#define __EFFECTLIST_H
#include "ff.h"
typedef struct _effect_node {
Effect *info;
struct _effect_node *next;
}effect_node;
typedef struct _EffectList {
effect_node *first;
effect_node *last;
int size;
}EffectList;
EffectList EffectList_Create();
void EffectList_Add(EffectList *l, Effect *x);
Bool EffectList_IsEmpty(const EffectList *l);
int EffectList_Size(const EffectList *l);
Effect* EffectList_Get(const EffectList *l, const int index); /* 1 <= index <= size*/
void EffectList_Print(const EffectList *l);
#endif
|
C#
|
UTF-8
| 2,785
| 2.515625
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using TechTalk.SpecFlow.Assist;
using TechTalk.SpecFlow.Assist.ValueRetrievers;
using TechTalk.SpecFlow.RuntimeTests.AssistTests.ValueRetrieverTests;
using Xunit;
namespace TechTalk.SpecFlow.RuntimeTests.AssistTests.SituationalTests.EnumberableValueRetrieverIntegrationTests
{
public class Example
{
public IList<int?> MyExampleValues { get; set; }
}
public class ListOfNullablesWithCustomNullValueRetrieverTests
{
private const string Val = "1, <null>";
private TableRow testRow = new TableRow(new Table("Value"), new string[] {"list", Val});
[Fact]
public void CanRetrieveAListThatContainsValuesThatShouldBeRetrievedByACustomValueRetriever()
{
Service.Instance.ValueRetrievers.Register(new NullValueRetriever("<null>"));
var retriever_under_test = Service.Instance.GetValueRetrieverFor(testRow, typeof(object), typeof(IList<Nullable<int>>));
retriever_under_test.Should().NotBeNull();
var can = retriever_under_test.CanRetrieve(Val, typeof(IList<Nullable<int>>));
can.Should().BeTrue();
var returned_list = retriever_under_test.Retrieve(new KeyValuePair<string, string>("Value", Val), typeof(object), typeof(IList<Nullable<int>>));
returned_list.Should().NotBeNull();
var listOfNullableInts = returned_list as IList<Nullable<int>>;
listOfNullableInts.Should().NotBeNull();
listOfNullableInts.Count.Should().Be(2);
listOfNullableInts[0].Should().Be(1);
listOfNullableInts[1].Should().BeNull();
}
public static IEnumerable<object[]> EnumerableRetrieverWithNullableValueRetriever_TestCases() =>
new List<object[]>
{
new object[] { "1, 2", new List<int?> {1, 2 } },
new object[] { "1, <null>", new List<int?> { 1, null} },
new object[] { "<null>, 2", new List<int?> { null, 2} }
};
[Theory]
[MemberData(nameof(EnumerableRetrieverWithNullableValueRetriever_TestCases))]
public void IntegrationOfEnumerableRetrieverWithNullableValueRetriever(string input, IEnumerable<int?> expectedValues)
{
Service.Instance.ValueRetrievers.Register(new NullValueRetriever("<null>"));
var table = new Table("Field", "Value");
table.AddRow("MyExampleValues", input);
var expected = expectedValues.ToList();
var test = table.CreateInstance<Example>();
test.MyExampleValues.Should().BeEquivalentTo(expected);
}
}
}
|
C#
|
UTF-8
| 848
| 3.78125
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
public static class Calculator
{
public static int Add(int x,int y)
{
if (x < 0)
{
throw new ArgumentException($"The value of x ({x}) is less than 0.");
}
else if (y < 0)
{
throw new ArgumentException($"The value of y ({y}) is less than 0.");
}
return x + y;
}
public static int Subtract(int x, int y)
{
return x - y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
public static int Division(int x, int y)
{
return x / y;
}
}
}
|
Java
|
UTF-8
| 8,224
| 2.265625
| 2
|
[] |
no_license
|
package com.example.medicine_analytics.service;
import com.example.medicine_analytics.model.PatientCard;
import com.example.medicine_analytics.model.MedicalType;
import com.example.medicine_analytics.repository.PatientCardRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class PatientCardService implements IPatientCardService {
private static final Logger LOGGER = LoggerFactory.getLogger(PatientCardService.class);
@Autowired
PatientCardRepository repository;
@Override
public List<PatientCard> findAll() {
LOGGER.debug("Searching all person cards without criteria" );
return repository.findAll();
}
@Override
public List<PatientCard> findUserByGenderAndId(Long patientId, String patientGender) {
return repository.findUserByGenderAndId(patientId, patientGender);
}
@Override
public List<PatientCard> findBySum_moneyGreaterThan(float sum_money) {
return repository.findBySumMoneyIsGreaterThan(sum_money);
}
@Override
public List<String> filterCancerTypeCut() {
return repository.filterCancerTypeCut();
}
@Override
public List<Object> findPatientCardByCard(PatientCard patientCard) {
List<List<Object>> items = repository.findPatientCardByCard(patientCard);
List<MedicalType> res = new ArrayList<>();
Map<String, List<MedicalType>> groupedByOperation = items
.stream()
.map(item -> new MedicalType(
(Integer) item.get(0),
(String) item.get(1),
(Float) item.get(2),
(Integer) item.get(3)))
.collect(Collectors.groupingBy(MedicalType::getTreatmentOperation));
List<Object> response = new ArrayList<>();
DecimalFormat moneyDF = new DecimalFormat("#.##");
DecimalFormat probabilityDF = new DecimalFormat("#.##");
groupedByOperation.forEach((treatmentOperationId, medicalTypeList) -> {
int typeListSize = medicalTypeList.size();
Map<String, Object> responseItem = new HashMap<>();
responseItem.put("id", treatmentOperationId);
responseItem.put("name", treatmentOperationId);
responseItem.put("count", medicalTypeList
.stream()
.mapToInt(MedicalType::getCnt)
.sum());
Map<Integer, List<MedicalType>> groupedByTarget = medicalTypeList
.stream()
.collect(Collectors.groupingBy(MedicalType::getTarget));
responseItem.put("price", moneyDF.format(medicalTypeList
.stream()
.mapToDouble(MedicalType::getSumMoney)
.average()
.orElse(Double.NaN)));
responseItem.put("bad", 0);
responseItem.put("normal", 0);
responseItem.put("good", 0);
groupedByTarget.forEach((k, v) -> {
String key = "";
switch (k.toString()) {
case "1":
key = "good";
break;
case "0":
key = "normal";
break;
case "-1":
key = "bad";
break;
}
responseItem.put(key, probabilityDF.format(((double) v.size()/(double) typeListSize)* 100));
});
response.add(responseItem);
});
return response;
}
@Override
public List<Object> FilterDashboard() {
List<Object> filterDashboard = new ArrayList<Object>();
HashMap<String, Object> enter = new HashMap<String, Object>();
HashMap<String, Object> medical = new HashMap<String, Object>();
enter.put("name", "Входные параметры");
medical.put("name", "Параметры лечения");
List<Object> enterParam = new ArrayList<Object>();
List<Object> medicalParam = new ArrayList<Object>();
HashMap<String, Object> registryTerritoryCode = new HashMap<String, Object>();
registryTerritoryCode.put("id", "registryTerritoryCode");
registryTerritoryCode.put("name", "Регион");
registryTerritoryCode.put("items", repository.filterRegistryTerritoryCode());
enterParam.add(registryTerritoryCode);
HashMap<String, Object> cancerTypeCut = new HashMap<>();
cancerTypeCut.put("id", "cancerTypeCut");
cancerTypeCut.put("name", "Вид рака");
cancerTypeCut.put("items", repository.filterCancerTypeCut());
enterParam.add(cancerTypeCut);
HashMap<String, Object> cancerStageCut = new HashMap<>();
cancerStageCut.put("id", "cancerStageCut");
cancerStageCut.put("name", "Стадия рака");
cancerStageCut.put("items", repository.filterCancerStageCut());
enterParam.add(cancerStageCut);
HashMap<String, Object> registryZapZslForPom = new HashMap<>();
registryZapZslForPom.put("id", "registryZapZslForPom");
registryZapZslForPom.put("name", "Вид помощи");
registryZapZslForPom.put("items", repository.filterRegistryZapZslForPom());
enterParam.add(registryZapZslForPom);
HashMap<String, Object> reasonOfAppeal = new HashMap<>();
reasonOfAppeal.put("id", "reasonOfAppeal");
reasonOfAppeal.put("name", "Неотложная");
reasonOfAppeal.put("items", repository.filterReasonOfAppeal());
enterParam.add(reasonOfAppeal);
HashMap<String, Object> gender = new HashMap<>();
gender.put("id", "gender");
gender.put("name", "Пол");
gender.put("items", repository.filterGender());
enterParam.add(gender);
HashMap<String, Object> ageBins = new HashMap<>();
ageBins.put("id", "ageBins");
ageBins.put("name", "Возростная группа");
ageBins.put("items", repository.filterAgeBins());
enterParam.add(ageBins);
HashMap<String, Object> kdzBins = new HashMap<>();
kdzBins.put("id", "kdzBins");
kdzBins.put("name", "Продолжительность госпитализации");
kdzBins.put("items", repository.filterKdzBins());
medicalParam.add(kdzBins);
HashMap<String, Object> sumBins = new HashMap<>();
sumBins.put("id", "sumBins");
sumBins.put("name", "Стоимость лечения");
sumBins.put("items", repository.filterSumBins());
medicalParam.add(sumBins);
HashMap<String, Object> radiationDozeBins = new HashMap<>();
radiationDozeBins.put("id", "radiationDozeBins");
radiationDozeBins.put("name", "Доза радиации");
radiationDozeBins.put("items", repository.filterRadiationDozeBins());
medicalParam.add(radiationDozeBins);
HashMap<String, Object> daysStartNprBins = new HashMap<>();
daysStartNprBins.put("id", "daysStartNprBins");
daysStartNprBins.put("name", "Количество дней до даты направления на лечение");
daysStartNprBins.put("items", repository.filterDaysStartNprBins());
medicalParam.add(daysStartNprBins);
HashMap<String, Object> metastasisBins = new HashMap<>();
metastasisBins.put("id", "metastasisBins");
metastasisBins.put("name", "Количество дней до даты направления на лечение");
metastasisBins.put("items", repository.filterMetastasisBins());
medicalParam.add(metastasisBins);
enter.put("params", enterParam);
medical.put("params", medicalParam);
filterDashboard.add(enter);
filterDashboard.add(medical);
return filterDashboard;
}
}
|
Markdown
|
UTF-8
| 1,231
| 2.625
| 3
|
[] |
no_license
|
---
layout: post
title: "February 16, 2016 DropWizard"
---
DropWizard
This talk will cover the basics of DropWizard. The goal is to describe what it is, what it does, and some of it's capabilities. We'll go through a working example of a DropWizard Service. Finally, I'd like to share with you how we are using it and how we got into it.
Michael Kolakowski:
Michael has been a software developer in and out of the Omaha area for the past 8 years. He currently works for McCallie and Associates at Northrop Grumman in Bellevue. His interests include Linux, Java + Groovy, Vim, and community involvement.
Location:Blue Cross and Blue Shield of Nebraska, 1919 Aksarben Dr, Omaha, NE 68180
Agenda:
5:30 Networking
6:00 Food – Courtesy of TekSystems
6:30 Presentation
8-ish Drinks and more at DJ’s Dugout (Aksarben)
Please RSVP at MeetUp.com (http://www.meetup.com/omahajava/events/227228046/) Also, in the FREE STUFF department, JetBrains has signed up to be an additional sponsor, and is giving us 1 free IntelliJ IDEA license to raffle away EVERY MONTH! So stick around for the drawing at the end of the meeting before we head to DJ’s!
(This past event was exported from Meetup.com)
(65 people had RSVP'd to this event in Meetup)
|
Python
|
UTF-8
| 139
| 3.625
| 4
|
[] |
no_license
|
list1 = ["Gold", "Silver", "White", "Black", "Pink"]
list1.append("fluorescent orange")
list1.pop(0)
print(len(list1))
print(list1[1])
|
JavaScript
|
UTF-8
| 2,206
| 3.09375
| 3
|
[] |
permissive
|
import * as constants from "./constants.js";
import { GridEntity } from "./grid-entity.js";
import { Fire } from "./fire.js";
import * as world from "./world.js";
import { Character } from "./character.js";
export class Bomb extends GridEntity {
fuseTime = constants.BOMB_FUSE_TIME;
power = 1;
/** @param {number} power the number of tiles the flames will span in each direction */
constructor(power, row, column) {
super(row, column);
this.power = power;
world.getEntitiesInArea(this.getBoundingBox()).forEach(
entity => {
if (entity instanceof Character) {
entity.overlapingBombs.push(this);
}
}
);
this.startAnimation("idle");
}
/** @returns {string} the type of entity */
getType() { return "bomb"; }
update(dt) {
super.update(dt);
this.fuseTime -= dt;
if (this.fuseTime <= 0) {
this.explode();
}
}
explode() {
this.destroy();
// create central fire
new Fire("center", this.row, this.column)
// go out from the center and create the flames
let directions = {
Up: { blocked: false, dx: 0, dy: -1 },
Down: { blocked: false, dx: 0, dy: 1 },
Left: { blocked: false, dx: -1, dy: 0 },
Right: { blocked: false, dx: 1, dy: 0 },
};
for (let i=0; i<this.power; i++) {
for (let dirKey in directions) {
const dir = directions[dirKey];
if (dir.blocked) {
continue;
}
const fRow = this.row + dir.dy * (i+1);
const fColumn = this.column + dir.dx * (i+1);
const cellType = world.getMapCell(fRow, fColumn);
if ([-1, 2].includes(cellType)) {
// we got outside of map or hit an indestructible brick
dir.blocked = true;
continue;
}
// if we hit a regular brick, we stop here and destroy the brick
if (cellType === 1) {
dir.blocked = true;
world.destroyBrick(fRow, fColumn);
} else {
// spawn the right type of fire
const isCap = i === this.power-1 || cellType === 1;
const fireType = isCap ? `cap${dirKey}` : (
["Up", "Down"].includes(dirKey) ? "middleV" : "middleH"
);
new Fire(fireType, fRow, fColumn);
}
}
}
}
/** @override we've been fried by another explosion, so chain-reaction! */
fry() {
this.explode();
}
}
|
Markdown
|
UTF-8
| 6,591
| 3.25
| 3
|
[] |
no_license
|
## [资治通鉴:难办的事,领导问你啥意见,这种回答方式很油滑!](https://zhuanlan.zhihu.com/p/328787331)
**《资治通鉴》第20卷 汉纪十二**
**汉武帝 元鼎六年(庚午,公元前111年)**
### 【原文】(可直接跳过看解析)
> 初,司马相如病且死,有遗书,颂功德,言符瑞,劝上封泰山。上感其言,会得宝鼎,上乃与公卿诸生议封禅。(中间太长省略了,感兴趣的朋友可以自己看《资治通鉴》)上乃自制仪,颇采儒术以文之。上为封禅祠器,以示群儒,或曰“不与古同”,于是尽罢诸儒不用。上又以古者先振兵释旅,然后封禅。
### 【译文】(可直接跳过看解析)
> 当初,司马相如病重将死,临终时留下遗书,称颂汉武帝的功德,并谈及祥瑞之事,劝汉武帝到泰山封禅祭祀天地。汉武帝深受感动,适逢获得宝鼎,他便与公卿大臣和儒生们商议封禅之事。(中间太长省略了,感兴趣的朋友可以自己看《资治通鉴》)于是汉武帝自定礼仪,多采用儒家学说加以修饰。又制作封禅用的祭器,拿给儒生们观看,有的儒生说:“与古代的不一样。”于是汉武帝将儒生一律罢斥不用。又按着古代的作法,首先振奋军威,用酒食飨众,然后举行封禅大典。
## 【解析】
先说一下这段材料的背景。
司马相如很多人都知道,西汉著名大才子,写《凤求凰》追才女卓文君留下一段佳话。
他在汉武帝朝时期主要工作是负责蜀地以及西南夷方向,做的很不错。
在他死前,上书歌功颂德汉武帝的功绩,并且提出,汉武帝这么牛逼应该要去封禅。
汉武帝信了,让群臣商讨封禅要什么礼仪。
这事商量来商量去,各持己见难以统一,搞得汉武帝非常烦躁。
汉武帝于是问儿宽,有什么看法。
说实话这个问题不好回答。
其一,在职权上,儿宽不过是做左内史(相当于直辖市或者首都地区行政长官),而封禅已经有人负责,而且以儒家诸生在负责,儿宽说话算是对别人的工作指手画脚。
其二,关系上,这事情已经各持己见,没有个统一意见,儿宽表态如果说赞成谁,那就是站队,必然另外一方就要不爽,这算是得罪人。
其三,责任上,就算儿宽头铁,不惧怕得罪人,说了自己的看法。但是问题也来了,如果汉武帝真这么搞了一旦出事,亦或者别人拿着儿宽的话寻章摘句挑错,儿宽大概率是没好果子吃。
所以,对于这种事情,远远的看,别轻易入局就是最好的办法。
不过汉武帝开口问了,儿宽必须作答。
上面的材料中,我把儿宽的作答给删了,放在下面逐句分析背后的妙用。
> 宽曰:封泰山,禅梁父,昭姓考瑞,帝王之盛节也;然享荐之义,不著于《经》。
不用纠结字面意思,其这一小段的含义是。
首先,封禅这事是皇帝陛下您的大好事(高度赞扬、认同,表示和汉武帝站一起。)
其次,怎么干,没有成例,更没有相关记载(群臣商议的没有理论基础,这算是为其他人吵这么久没定数开脱。既然都没有资料可以查,自然就是公说公有理婆说婆有理。而秦始皇的封禅,则被认为是失败封禅不能作为参考)
> 臣以为封禅告成,合祛于天地神祗,唯圣主所由,制定其当,非群臣之所能列。
继续不纠结字面意思。
在高度张扬、认同之后,儿宽表示,封禅的本质其实是沟通天地神祇。
而至于怎么干、怎么沟通,区别都是细节上的差别,各有个的说法,只要心诚就OK了。
既然如此,那么这事就必须皇帝你自己来干才行。
一方面封禅是汉武帝你的大事,另一方面,也能体现汉武帝你的诚心。
其实意思就是,怎么封禅,应该是汉武帝你来定。
如果说之前高度赞扬,是表示立场,那么这就表明了儿宽的观点,并且把球又提回去了。
接下来就是儿宽的理由了。
> 今将举大事,优游数年,使群臣得人人自尽,终莫能成。唯天子建中和之极,兼总条贯,金声而玉振之,以顺成天庆,垂万世之基。”
依然不纠结字面意思。
其实汇聚成一点,从现状、权力、意义三个方面来论证,由汉武帝来制定礼仪的合理性。
现状:汉武帝让群臣商量来商量去没个结果,继续如此依然商量不出来,想要推下去,就不能继续这样搞。
权力:皇帝有最终的决策、拍板权,决定怎么搞那是理所应当的。
意义:这次封禅意义重大,需要做成一次样板以为后世参考。
显然,这样的说法,汉武帝是接受了,于是自己制定相应的封禅制礼仪。
后面发生的事情就不说了。
儿宽的应对其实非常有参考意义,和之前提到的李悝应对魏文侯问询国相人选、萧何应对汉惠帝问询丞相人选、陈平周勃应对吕后询问分封诸吕有一定的相似性。
即,领导给的选项,是个开放性问题,即并非是与不是的问题,需要你提供主观判断。
但是呢,按照当时具体情况,如果你顺着领导的话给自己的看法,未必是最好的选择,甚至会带来不必要的麻烦。
所以,解决方法也很简单,之前的文章分析中也提到过。
### 【启发】
领导问你,无非有三个可能。
其一,用问题来试探你。
其二,希望你表态支持。
其三,真的想听你的看法。
但是你不可能问领导到底是想干啥,所以最好的办法不要在对方给的框架或选项中回答。
儿宽回答汉武帝的方式,其实就最具有参考性,尤其是你摸不准领导到底想干嘛。
首先,高度赞扬,捧一捧领导,表示支持认同(当然你的知道这的确是领导提的,而不是领导正话反说。通常领导能这样问你,说明你和领导关系比较近)。
其次,找到事情的本质,即关键性问题是什么。一来展现你眼光有思考,二来点明核心。
最后,表示这事情必须是高举高打,要有高层提纲挈领来抓大方向,这样才能把事情做好。
当然,如果这事情的确和你的工作有关、有交集,在你的职权范围内稍微点一点也是没问题。
但如果这事情是别人的事,说话就要注意了。
|
Java
|
UTF-8
| 805
| 3.4375
| 3
|
[] |
no_license
|
package Model;
import java.awt.*;
import java.util.Random;
public abstract class Vehicle {
int x, y; //can't make it private, needs to access from child classes
private final static Random random = new Random();
int xDir, yDir, ySpeed, xSpeed;//can't make it private, needs to access from child classes
Vehicle(int x, int y) {
this.x = x;
this.y = y;
xDir = 0;
yDir = 0;
xSpeed += 5;
ySpeed += 6;
}
static int randomSpeed() {
return random.nextInt(10) + 1; //Random speed for Vehicles
}
public void move() {
x += xSpeed * xDir;
y += xSpeed * yDir;
}
public abstract void update(int width, int height, TrafficLight.State state);
public abstract void paintComponent(Graphics g);
}
|
Java
|
UTF-8
| 670
| 2.53125
| 3
|
[] |
no_license
|
package com.epam.protocol.builder;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import com.epam.protocol.domain.message.Message;
public abstract class MessageBuilder<T extends Message> {
public abstract T buildMessage(ByteBuffer byteBuffer);
public String getString(ByteBuffer byteBuffer) {
String result = "";
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
try {
result = decoder.decode(byteBuffer).toString();
} catch (CharacterCodingException e) {
e.printStackTrace();
}
return result;
}
}
|
C#
|
UTF-8
| 1,449
| 2.8125
| 3
|
[] |
no_license
|
namespace Core
{
using System;
using System.Collections.Generic;
/// <summary>
/// Монеты
/// </summary>
public class Coin
{
public int id { get; set; }
public int price { get; set; }
public bool blocked { get; set; }
public int Available
{
get
{
return Bank.CoinCount(id);
}
}
public void Increase(int size)
{
Bank bnk = new Bank();
bnk.coin_id = this.id;
bnk.qty = size;
bnk.Save();
}
public void Decrease(int size)
{
this.Increase(-1 * size);
}
public static IEnumerable<Coin> getList()
{
return Data.Data.Instance.CoinDataStorage.GetList();
}
public static IEnumerable<Coin> availableList()
{
return Data.Data.Instance.CoinDataStorage.GetAvailableCoins();
}
public static Coin GetEntityById(int id)
{
return Data.Data.Instance.CoinDataStorage.GetByID(id);
}
public static Coin GetEntityByValue(int value)
{
return Data.Data.Instance.CoinDataStorage.GetByValue(value);
}
public void Save()
{
Data.Data.Instance.CoinDataStorage.Save(this);
}
}
}
|
Markdown
|
UTF-8
| 1,057
| 2.625
| 3
|
[] |
no_license
|
# Dragee
[dragee.github.io](http://dragee.github.io) - drag&drop library for desktop and touch devices
# Dragee.Draggable
```javascript
Draggable(element[, options])
```
##### Example:
```javascript
function boundPoint(point, size){ return point; }
that.draggable = new Dragee.Draggable(that.element, {
bound: boundPoint,
onMove: that.moveCorners.bind(this),
onEnd: onEnd
});
```
# Dragee.Target
```javascript
Target(element, draggables[, options])
```
##### Example:
```javascript
var target = new Dragee.Target(element, draggables, {
parent: targetAreaElement,
positioning: Dragee.positionFactory(Dragee.positionType.notCrossing)(function(){
return target.getRectangle();
}),
sorting: Dragee.sortingFactory(Dragee.positionType.notCrossing)(),
onAdd: function(draggable){
draggable.element.addClass("ontarget");
},
onRemove: function(draggable){
draggable.element.removeClass("ontarget");
}
});
```
# Development
## install
`npm install`
## commands
`npm run build`
`npm run dev`
|
Markdown
|
UTF-8
| 4,030
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
# deppy [](https://travis-ci.com/pilagod/deppy) [](https://coveralls.io/github/pilagod/deppy?branch=master)
Dependency injection framework for Python
## Installation
```shell
$ pip install deppy
```
## Usage
### Concrete class
```python
from deppy import container, injectable
@injectable()
class Greeter:
def greet(self) -> str:
return "Hello"
g = container.get(Greeter)
g.greet() # Hello
```
### Implementation for abstract class
```python
import abc
from deppy import container, injectable
# Should raise NotImplementedError instead of abc.abstractmethod decorator for abstract method due to following mypy issue:
# https://github.com/python/mypy/issues/5374#issuecomment-582093112
class Greeter(abc.ABC):
def greeter(self) -> str:
raise NotImplementedError()
@injectable(Greeter)
class GreeterImpl(Greeter):
def greeter(self) -> str:
return "Hello"
g = container.get(Greeter)
g.greet() # Hello
# If class is on behalf of abstract class, the class cannot get by itself from container
# check `Multiple implementations` section for more complex use case.
container.get(GreeterImpl) # KeyError
```
### Multiple implementations
```python
import abc
from enum import Enum
from deppy from container, injectable
class Greeter(abc.ABC):
def greet(self) -> str:
raise NotImplementedError()
class GreeterType(Enum):
A = "A"
B = "B"
@injectable(Greeter, tag=GreeterType.A)
class GreeterA(Greeter):
def greet(self) -> str:
return "A"
@injectable(Greeter, tag=GreeterType.B)
class GreeterB(Greeter):
def greet(self) -> str:
return "B"
a = container.get(Greeter, tag=GreeterType.A)
a.greet() # A
b = container.get(Greeter, tag=GreeterType.B)
b.greet() # B
```
### Dependency injection
```python
from deppy import container, injectable
@injectable()
class Greeter:
def greet(self) -> str:
return "Hello"
@injectable()
class GreeterWorld:
def __init__(self, greeter: Greeter):
self._greeter = greeter
def greet(self) -> str:
return self._greeter.greet() + " World"
gw = container.get(GreeterWorld)
gw.greet() # Hello World
```
### Dependency injection with selected implementation
```python
import abc
from enum import Enum
from deppy import container, injectable
class Greeter(abc.ABC):
def greet(self) -> str:
raise NotImplementedError()
class GreeterType(Enum):
A = "A"
B = "B"
@injectable(Greeter, tag=GreeterType.A)
class GreeterA(Greeter):
def greet(self) -> str:
return "A"
@injectable(Greeter, tag=GreeterType.B)
class GreeterB(Greeter):
def greet(self) -> str:
return "B"
@injectable(
params={
"a": GreeterType.A,
"b": GreeterType.B
}
)
class GreeterManager:
def __init__(self, a: Greeter, b: Greeter):
self._a = a
self._b = b
def greet(self) -> str:
return self._a.greet() + self._b.greet()
gm = container.get(GreeterManager)
gm.greet() # AB
```
## Caveat
In order to avoid circular import, it is common to separate interfaces and implementations into different packages.
Package comsumers usually depend only on interfaces,
resulting in no one to import implementations and thus `injectable` is never called.
For me, I usually put implemetations under `impls` directory besides interfaces. Implemetations can be registered into container by an independent composition root, and just import it and initialize it on application startup:
```python
# composition_root.py
import glob
import importlib
def init():
impls = glob.glob("**/impls", recursive=True)
for impl in impls:
importlib.import_module(impl.replace("/", ".").replace("\\", "."))
```
## License
© Cyan Ho (pilagod), 2021-NOW
Released under the [MIT License](https://github.com/pilagod/deppy/blob/master/LICENSE)
|
Python
|
UTF-8
| 164
| 2.921875
| 3
|
[] |
no_license
|
input_list=[1,1,2,2,3,3,4,4,5,5,6,6,7]
def my_function(input_list):
return list(dict.fromkeys(input_list))
mylist = my_function(input_list)
print(mylist)
|
Java
|
UTF-8
| 1,668
| 2.328125
| 2
|
[] |
no_license
|
package testsuite.api;
import beans.Beans;
import executers.BaseExecutor;
import io.qameta.allure.Feature;
import model.api.registration.RegistrationResponse;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import util.LogListener;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
@Listeners(LogListener.class)
@Feature("Тестирование регистрации")
public class RegistrationTest extends Beans {
@Test(dataProvider = "registrationDataFields", description = "Регистрация пользователя с некорректными данными")
public void registrationTestFailed(String email, String password, String first_name, String last_name, String tz, int expectedResultCode) {
RegistrationResponse response = baseExecutor.registerInvalidDataPost(email, password, first_name, last_name, tz, expectedResultCode);
assertEquals(response.getCode(), expectedResultCode, "Код ответа не совпадает с ожидаемым");
assertFalse(response.isSuccessful(), "Неверное значение поля result");
}
@DataProvider
public static Object[][] registrationDataFields() {
return new Object[][]{
{"valderama1@yandex.ru", "123456", "linus", "torvalds", "Europe/Moscow", 4},
{"notvalidemail@.email", "123456", "linus", "torvalds", "Europe/Moscow", 19},
{"tester@yandex.ru", "12345", "linus", "torvalds", "Europe/Moscow", 29},
{"tester2@yandex.ru", "123456", "", "torvalds", "Europe/Moscow", 12}
};
}
}
|
C++
|
UTF-8
| 1,523
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Created by frabe808 on 15/12/16.
//
#include "SlipperyObstacle.h"
#include "../objects/Object.h"
#include "PlayerComponent.h"
#include "PlayerController.h"
/**
* Initializes SlipperObstacle component.
*/
void SlipperyObstacle::Init()
{
_collisionComponent = _parent->Fetch<Collision>();
if (!_collisionComponent)
{
throw std::runtime_error(
"SlipperyObstacle can not work without a Collision component!");
}
}
/**
* Deconstructor for SlipperyObstacle
*/
SlipperyObstacle::~SlipperyObstacle()
{
_collisionComponent = nullptr;
}
/**
* Updates the SlipperyObstacle component.
* @param time - Amount of elapsed time since last game tick.
*/
void SlipperyObstacle::Update(double time)
{
if( _hasCollided )
return;
//did anything collide with us?
if(auto col =_collisionComponent->HasCollided())
{
//was it the player?
if(auto player = col->Fetch<PlayerComponent>())
{
if (player->IsJumping())
return;
ApplyEffect(*col);
_hasCollided = true;
}
}
}
/**
* Handles the events for SlipperyObstacle
* @param event - Event to handle
*/
void SlipperyObstacle::HandleEvent(sf::Event event)
{
}
/**
* Applies an effect to object that collided with the obstacle.
* @param hit - The object that collided with the obstacle.
*/
void SlipperyObstacle::ApplyEffect(Object & hit)
{
//is it the player?
if( auto pc = hit.Fetch<PlayerController>() )
{
// if not lowest speed
if(hit.Fetch<Moveable>()->GetVelocity() > pc->GetGearSpeed() )
{
pc->Fall();
}
}
}
|
JavaScript
|
UTF-8
| 1,317
| 2.609375
| 3
|
[] |
no_license
|
const toggleButton = document.querySelector('.hamburger');
const navLinks = document.querySelector('.menu_nav');
const menuContainer = document.querySelector('.menu')
const hamSpans = document.querySelectorAll('.ham-span');
toggleButton.addEventListener('click', ()=>{
navLinks.classList.toggle('active')
menuContainer.classList.toggle('wider')
hamSpans.forEach((item) => {
item.classList.toggle('span-cross')
} )
})
// scrolling
const main = document.querySelector('#main');
const why = document.querySelector('#why');
const benefits = document.querySelector('#benefits');
const prices = document.querySelector('#prices');
const contact = document.querySelector('#contact');
const best = document.querySelector('.logo_best_shop');
const toWhy = document.querySelector('.to-why');
const toBens = document.querySelector('.to-bens');
const toPrices = document.querySelector('.to-prices');
const toCont = document.querySelector('.to-cont');
const toTop = document.querySelector('.to-top');
function Smooth(from, to){
to.addEventListener('click', ()=>{
from.scrollIntoView({behavior: "smooth"});
console.log(from, to);
})
};
Smooth(why, toWhy);
Smooth(benefits, toBens);
Smooth(prices, toPrices);
Smooth(contact, toCont);
Smooth(main, toTop);
Smooth(main, best);
|
Markdown
|
UTF-8
| 1,885
| 2.859375
| 3
|
[] |
no_license
|
## Homepage: Collection of Color Palettes

## Color Palette Creator

## A single Palette View

## Single Color Palette consisting various shades of a single color

## Screen overlay whenever a color has been copied to clipboard

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
Java
|
UTF-8
| 836
| 2.25
| 2
|
[] |
no_license
|
package com.timemanager.client.view;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
public class AppViewImpl extends Composite implements AppView {
VerticalPanel menupanel;
SimpleLayoutPanel panelmain;
public AppViewImpl( ) {
DockLayoutPanel panel = new DockLayoutPanel(Unit.PX);
menupanel = new VerticalPanel();
panel.addNorth(menupanel, 40);
panelmain = new SimpleLayoutPanel();
panel.addWest(panelmain, 800);
initWidget(panel);
}
public SimpleLayoutPanel getMainPanel() {
return panelmain;
}
public VerticalPanel getMenuPanel() {
return menupanel;
}
}
|
C#
|
UTF-8
| 727
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
namespace PI.Utilities.Mail.Interfaces
{
/// <summary>
/// An interface for a a message builder to use
/// </summary>
public interface IMessageBuilder
{
/// <summary>
/// Generates a message from the IMailMessage object
/// </summary>
/// <param name="message">An IMailMessage object to generate the MailMessage from</param>
/// <param name="model">An optional model to bind to the parameters of the MailMessage</param>
/// <returns>A generated System.Net.Mail.MailMessage</returns>
MailMessage Generate(IMailMessage message, object model = null);
}
}
|
Java
|
UTF-8
| 1,841
| 3.0625
| 3
|
[] |
no_license
|
package org.lgbt_news.analysis.sentiment.aggregation;
import org.lgbt_news.analysis.sentiment.SentimentCategory;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Specific elements of the list of elements/ predictions are seen as elite.
* They have more strength in the aggregation.
* E.g.: {POS, NEG, NEG} with POS as elite yields POS due to (elite) majority vote
* with stength of 3 (or greater): 3 votes for POS, 2 votes for NEG.
*
* @author max
*/
public class AggregationEliteGroup implements Aggregation {
private final int STRENGTH_OF_ELITE;
private Set<Integer> indicesOfElite;
private AggregationMajorityVote majorityVote;
public AggregationEliteGroup(int strengthOfElite) {
STRENGTH_OF_ELITE = (strengthOfElite < 2) ? 2 : strengthOfElite;
indicesOfElite = new HashSet<>();
majorityVote = new AggregationMajorityVote();
}
public void setIndicesOfElite(Set<Integer> indicesOfElite) {
this.indicesOfElite = indicesOfElite;
}
@Override
public SentimentCategory aggregateCategories(List<SentimentCategory> categories) {
for (int index : indicesOfElite) {
SentimentCategory eliteCategory = categories.get(index);
for (int i = 0; i < STRENGTH_OF_ELITE; i++) {
categories.add(eliteCategory);
}
}
return majorityVote.aggregateCategories(categories);
}
@Override
public double[] aggregatePredictions(List<double[]> predictions) {
for (int index : indicesOfElite) {
double[] elitePrediction = predictions.get(index);
for (int i = 0; i < STRENGTH_OF_ELITE; i++) {
predictions.add(elitePrediction);
}
}
return majorityVote.aggregatePredictions(predictions);
}
}
|
Java
|
UTF-8
| 522
| 2.3125
| 2
|
[] |
no_license
|
package model;
public class MenuMeal {
private int mealId;
private int menuId;
private int userId;
public int getMealId() {
return mealId;
}
public void setMealId(int mealId) {
this.mealId = mealId;
}
public int getMenuId() {
return menuId;
}
public void setMenuId(int menuId) {
this.menuId = menuId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
Markdown
|
UTF-8
| 760
| 2.640625
| 3
|
[] |
no_license
|
# 查询缓存(了解)
## 什么是查询缓存
很多数据库产品都能够缓存查询的执行计划,对于相同类型的SQL就可以跳过SQL解析和执行计划
分成阶段。MySQL在某种场景下也可以实现,但是MySQL还有另一种不同的缓存类型:缓存完成
的SELECT查询结果,也就是查询缓存。
MySQL将缓存存放在一个引用表中,类似于HashMap的数据结构,Key查询SQL语句,Value则是
查询结果。当发起查询时,会使用SQL语句去缓存中查询,如果命中则立即返回缓存的结果集.

*1.* *可以使用 SQL_NO_CACHE 在 SELECT 中禁止缓存查询结果,例如:SELECT SQL_NO_CACHE ...*
*2.* *MySQL 8.0已删除查询缓存功能*
|
C#
|
UTF-8
| 2,706
| 3.140625
| 3
|
[] |
no_license
|
using MySql.Data.MySqlClient;
using Service_ProCp.Models;
using System;
using System.Collections.Generic;
using System.Transactions;
/* This Class is meant for connecting the database, writing on database as well as reading with datbase */
namespace Service_ProCp.BusinessLogic
{
public class DataHelper
{
/*Start of Class Members */
//Attribute
// private string connectionInfo;
private string dBConnstring;
private MySqlConnection connectionToDB;
// private Car car;
//private Order order;
/// <summary>
/// constructor of the class, connects to iris server
/// </summary>
public DataHelper()
{
connectionToDB = new MySqlConnection();
dBConnstring = "server = studmysql01.fhict.local; " + "Uid = dbi341965; " + "Database = dbi341965; " + "Pwd = Fontys123; ";
}
/// <summary>
/// Boolen Method to check the database connection, if its false, it opens and return true
/// </summary>
/// <returns></returns>
public bool DatabaseConnection()
{
//creating database connection
bool result = false;
try
{
connectionToDB.ConnectionString = dBConnstring;
connectionToDB.Open();
result = true;
}
catch (Exception ex)
{
Console.WriteLine("Exception Message: " + ex.Message);
result = false;
connectionToDB.Close();
}
return result;
}
public void CloseDatabase()
{
connectionToDB.Close();
}
public void WriteToBase(List<Car> myCar)
{
//Create Connection
using (TransactionScope scope = new TransactionScope())
{
if (DatabaseConnection())
{
for (int i = 0; i < myCar.Count; i++)
{
string sqlIns = "INSERT INTO dbi341965.car (car_id, car_type, car_number) VALUES (@name, @cartype, @number)";
MySqlCommand cmdIns = new MySqlCommand(sqlIns, connectionToDB);
cmdIns.Parameters.AddWithValue("@name", myCar[i].CarID);
cmdIns.Parameters.AddWithValue("@cartype", myCar[i].CarType);
cmdIns.Parameters.AddWithValue("@number", myCar[i].PlateNumber);
cmdIns.ExecuteNonQuery();
}
scope.Complete();
}
}
}
}
}
/* End of DataBase Class */
|
Java
|
WINDOWS-1258
| 787
| 3.25
| 3
|
[] |
no_license
|
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Jugar j = new Jugar();
Scanner sc = new Scanner(System.in);
System.out.println("Quieres jugar? Si/No");
String play = sc.nextLine();
if(play.equalsIgnoreCase("si")) {
j.jugar();
}else if (play.equalsIgnoreCase("no")) {
System.out.println("Has salido del juego.");
System.exit(0);
}
while (play.equalsIgnoreCase("si")){
System.out.println("Quieres volver a jugar? Si/No");
String play2 = sc.nextLine();
if(play2.equalsIgnoreCase("si")) {
j.volverJugar();
}else if (play2.equalsIgnoreCase("no")) {
System.out.println("Has salido del juego.");
System.exit(0);
}
}
sc.close();
}
}
|
Python
|
UTF-8
| 551
| 3.03125
| 3
|
[] |
no_license
|
file = open("data3.txt", "r")
m = []
for i, val in enumerate(file.readlines()):
m.append(list())
for x in val:
if x != "\n":
m[i].append(x)
n = len(m)-1
res=1
steps = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
for h, v in steps:
add = 0
count = 0
row = 0
while row < n:
i = 0
i -= add
while i < len(m[row])-h and row < n-v+1:
i += h
row += v
if m[row][i] == "#":
count += 1
add = len(m[row])-i
res *= count
print(res)
|
Python
|
UTF-8
| 226
| 3.265625
| 3
|
[] |
no_license
|
from Car import Car
class Bomb(Car):
def drive(self, distance):
if distance > self.fuel:
distance = self.fuel
self.fuel = 0
else:
self.fuel -= distance
return 0
|
Python
|
UTF-8
| 572
| 2.859375
| 3
|
[] |
no_license
|
import cv2
import imutils
# Load ảnh ở chế độ 1: giữ nguyên ban đầu
img = cv2.imread('image.jpg', 1)
# Resize image
# img = cv2.resize(img, dsize=(400,400)) # Chuyển ảnh về 400x400 pixel
img = cv2.resize(img, (0,0), fx=2., fy=2.) # Phóng to ảnh gấp đôi
# Rotate image (import imutils)
img = imutils.rotate(img,70) # xoay 70 độ ngược chiều kim đồng hồ
# Lưu ảnh
cv2.imwrite('img_new.jpg', img)
# Hiển thị ảnh
cv2.imshow('image', img)
# Đợi người dùng nhập để thoát
cv2.waitKey()
cv2.destroyAllWindows()
|
Java
|
UTF-8
| 247
| 1.867188
| 2
|
[] |
no_license
|
package pageObjects;
import org.openqa.selenium.By;
public class Login_Objects {
public static By txt_UserName = By.id("ap_email");
public static By txt_Password = By.id("ap_password");
public static By btn_Login = By.id("signInSubmit");
}
|
C++
|
UTF-8
| 3,724
| 3.5
| 4
|
[] |
no_license
|
#include "gtest/gtest.h"
#include "Complex.h"
#include <iostream>
#include <string>
TEST (Test, createEmptyConstructor) {
EXPECT_EQ(Complex(), Complex(0, 0));
}
TEST (Test, createBasicConstructor) {
Complex result;
result.setComplex(1.3333333333, 2.44444444);
EXPECT_EQ(Complex(1.33, 2.44), result);
}
TEST (Test, addTwoComplex) {
Complex z1(10, 5);
Complex z2(5, 0);
EXPECT_EQ(z1 + z2, Complex(15, 5));
}
TEST (Test, substractTwoComplex) {
Complex z1(5, 1);
Complex z2(3, 5);
EXPECT_EQ(z1 - z2, Complex(2, -4));
}
TEST (Test, multiplicationConstansAndComplex) {
Complex z1(2, 5);
Complex result;
result = (Complex) 5 * z1;
EXPECT_EQ(result, Complex(10, 25));
}
TEST (Test, multiplicationTwoComplex) {
Complex z1(2, -5);
Complex z2(3, 10);
EXPECT_EQ(z1 * z2, Complex(56, 5));
}
TEST (Test, divisionConstantsAndComplex) {
Complex z1(30, 30);
Complex result;
result = z1 / (Complex) 30;
EXPECT_EQ(result, Complex(1, 1));
}
TEST (Test, divisionZeroTest) {
Complex z1(1, 8);
Complex z2(0, 0);
EXPECT_THROW(z1 / z2, std::exception);
}
TEST (Test, divisionTwoComplex) {
Complex z1(1, 8);
Complex z2(2, 3);
EXPECT_EQ(z1 / z2, Complex(2, 1));
}
TEST (Test, showInformationAboutComplexNumber) {
Complex z1(2, 5);
Complex z2(0, -3);
Complex z3(-5, 0);
Complex z4(0, -1);
Complex z5(3, 1);
Complex z6(0, 1);
Complex z7(10, -7);
std::stringstream os;
os << z1;
ASSERT_EQ("(2+5i)", os.str());
os = std::stringstream();
os << z2;
ASSERT_EQ("(-3i)", os.str());
os = std::stringstream();
os << z3;
ASSERT_EQ("(-5)", os.str());
os = std::stringstream();
os << z4;
ASSERT_EQ("(-i)", os.str());
os = std::stringstream();
os << z5;
ASSERT_EQ("(3+i)", os.str());
os = std::stringstream();
os << z6;
ASSERT_EQ("(i)", os.str());
os = std::stringstream();
os << z7;
ASSERT_EQ("(10-7i)", os.str());
}
TEST (Test, getComplexFromCin) {
Complex z1;
std::stringstream is;
is << "(51+55.2i)";
is >> z1;
ASSERT_EQ(z1, Complex(51, 55.2));
is << "(10-5i)";
is >> z1;
ASSERT_EQ(z1, Complex(10, -5));
is << "(-3-1i)";
is >> z1;
ASSERT_EQ(z1, Complex(-3, -1));
is << "(0-1i)";
is >> z1;
ASSERT_EQ(z1, Complex(0, -1));
is << "(1.5+0i)";
is >> z1;
ASSERT_EQ(z1, Complex(1.5, 0));
}
TEST (Test, shorterVersionComplex) {
Complex z1;
std::stringstream is;
is << "(-i)";
is >> z1;
ASSERT_EQ(z1, Complex(0, -1));
z1 = Complex();
is << "(i)";
is >> z1;
ASSERT_EQ(z1, Complex(0, 1));
z1 = Complex();
is << "(2i)";
is >> z1;
ASSERT_EQ(z1, Complex(0, 2));
z1 = Complex();
is << "(2)";
is >> z1;
ASSERT_EQ(z1, Complex(2, 0));
z1 = Complex();
is << "(-4i)";
is >> z1;
EXPECT_EQ(z1, Complex(0, -4));
z1 = Complex();
is << "(3-i)";
is >> z1;
EXPECT_EQ(z1, Complex(3, -1));
z1 = Complex();
}
TEST (Test, unfamiliarSyntaxErrorComplex) {
Complex z1;
std::stringstream is;
is << "5+6i)";
EXPECT_THROW(is >> z1, std::exception);
is = std::stringstream();
is << "(5+6i";
EXPECT_THROW(is >> z1, std::exception);
is = std::stringstream();
is << "(5+6";
EXPECT_THROW(is >> z1, std::exception);
is = std::stringstream();
is << "(5+6)";
EXPECT_THROW(is >> z1, std::exception);
is = std::stringstream();
is << "(5%6i";
EXPECT_THROW(is >> z1, std::exception);
is = std::stringstream();
is << "(a+6i)";
EXPECT_THROW(is >> z1, std::exception);
is = std::stringstream();
}
|
C++
|
UTF-8
| 1,621
| 2.5625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
/*~--------------------------------------------------------------------------~*
* Copyright (c) 2015 Los Alamos National Security, LLC
* All rights reserved.
*~--------------------------------------------------------------------------~*/
#ifndef flecsi_topology_serial_entity_storage_policy_h
#define flecsi_topology_serial_entity_storage_policy_h
#include <vector>
#include <cassert>
///
/// \file
/// \date Initial file creation: Apr 04, 2017
///
namespace flecsi {
namespace topology {
template<typename T>
using topology_storage__ = std::vector<T>;
class offset_storage_{
public:
const size_t
operator[](size_t i)
const
{
return s_[i];
}
void
set(size_t i, size_t offset)
{
s_[i] = offset;
}
size_t
next(size_t i)
const
{
return s_[i + 1];
}
std::pair<size_t, size_t>
range(size_t i)
const
{
return {s_[i], s_[i + 1]};
}
size_t
count(size_t i)
const
{
return s_[i + 1] - s_[i];
}
void
clear()
{
s_.clear();
}
auto&
storage()
{
return s_;
}
void
push_back(size_t offset)
{
s_.push_back(offset);
}
void
resize(size_t n)
{
s_.resize(n);
}
size_t
size()
const
{
return s_.size();
}
private:
std::vector<size_t> s_;
};
} // namespace topology
} // namespace flecsi
#endif // flecsi_topology_serial_entity_storage_policy_h
/*~-------------------------------------------------------------------------~-*
* Formatting options for vim.
* vim: set tabstop=2 shiftwidth=2 expandtab :
*~-------------------------------------------------------------------------~-*/
|
C++
|
UTF-8
| 755
| 3.71875
| 4
|
[] |
no_license
|
#include<iostream>
using namespace std;
class node2
{
public:
int data;
node2 *next;
};
class node1
{
public:
node2 *temp;
node2 *start=NULL;
node2 *newnode;
void createnode()
{
cout<<"element:-";
newnode=new node2();
cin>>newnode->data;
newnode->next=NULL;
}
void insertion_in_end()
{
int n;
cout<<"Enter the number of elements:";
cin>>n;
for(int i=0;i<n;i++)
{
createnode();
if(start==NULL)
{
start=newnode;
}
else
{
temp=start;
while(temp->next!=NULL)
temp=temp->next;
temp->next=newnode;
}
}
}
void display()
{
temp=start;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
};
int main()
{
node1 n;
n.insertion_in_end();
n.display();
}
|
Python
|
UTF-8
| 2,347
| 2.546875
| 3
|
[] |
no_license
|
from __future__ import print_function
import numpy as np
import cPickle as pickle
from imgpreproc import resizing
from mltools import svmclassifier
WANTED_KERNEL = svmclassifier.KERNEL_LINEAR
def test_svm():
# svm_clf_poly = svmclassifier.SVMClassifier(test_size=0.20, test_mode=True)
classifiers = []
total = len(resizing.RESIZE_LIST) * len(svmclassifier.KERNEL_LIST) * 5
i = 1
for kernel in svmclassifier.KERNEL_LIST:
if kernel == WANTED_KERNEL:
for r_method in resizing.RESIZE_LIST:
for test_size in range(1, 6):
c = svmclassifier.SVMClassifier(test_size=test_size / 10.0, test_mode=True, kernel=kernel,
scaling=True,
resize_method=r_method)
classifiers.append(c)
# print("\rProgress: %d/%d " % (i, total), end='')
i = i + 1
acc = {}
for r in resizing.RESIZE_LIST:
acc[r] = []
for c in classifiers:
if c.kernel == WANTED_KERNEL:
"""
print ("Resize: " + str(c.resize_method))
print ("Training size: " + str(c.test_size))
print (c.accuracy)
"""
acc[c.resize_method].append(c.accuracy)
# print svm_clf_rbf.accuracy
# print type(svm_clf_rbf.summary)
# print svm_clf_rbf.conf_matrix
for a in acc:
print(a)
print(acc[a])
if a == resizing.RESIZE_NEAREST:
l = "Nearest Neighbour"
if a == resizing.RESIZE_BILINEAR:
l = "Bilinear interpolation"
if a == resizing.RESIZE_BICUBIC:
l = "Bicubic interpolation"
if a == resizing.RESIZE_PW:
l = "Pad and Slide"
# plt.plot([i / 10.0 for i in range(1, 6)], acc[a], label=l)
def test_NN():
# plt.title("Linear Kernel - Accuracy based on training set size and Resizing method")
model_1 = pickle.load(open("results/CNN6502BC.p", "rb"))
accuracy = model_1['accuracy']
print(np.max(accuracy))
print("Iterations:", len(accuracy))
accuracy = accuracy[-1]
c_e = model_1['cross_entropy']
summary = model_1['report']
c_m = model_1['conf_mat']
print("Accuracy", accuracy)
print(summary)
print(c_m)
|
Java
|
UTF-8
| 769
| 2.34375
| 2
|
[] |
no_license
|
package com.inka.netsync.view.dialog;
import android.app.AlertDialog;
import android.content.Context;
import com.inka.netsync.R;
public class SimpleMessageDialog {
private Context mContext = null;
private String mMessage = "";
private String mTitle = "";
public SimpleMessageDialog(Context context, String title, String message) {
mContext = context;
mMessage = message;
mTitle = title;
}
public void show() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(mTitle);
builder.setMessage(mMessage);
builder.setPositiveButton(mContext.getString(R.string.dialog_ok), null);
AlertDialog dialog = builder.create();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
|
Java
|
UTF-8
| 3,044
| 1.945313
| 2
|
[] |
no_license
|
package com.bionische.swastiktruckage.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class GetVoucherReport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="voucher_id")
private int voucherId;
@Column(name="memo_header_id")
private int memoHeaderId;
@Column(name="memo_no")
private int memoNo;
@Column(name="veh_id")
private int vehId;
@Column(name="driver_id")
private int driverId;
@Column(name="office_id")
private int officeId;
@Column(name="to_id")
private int toId;
@Column(name="staff_id")
private int staffId;
@Column(name="veh_no")
private String vehNo;
@Column(name="office_address")
private String officeAddress;
@Column(name="to_address")
private String toAddress;
@Column(name="create_date")
private String createDate;
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public int getVoucherId() {
return voucherId;
}
public void setVoucherId(int voucherId) {
this.voucherId = voucherId;
}
public int getMemoHeaderId() {
return memoHeaderId;
}
public void setMemoHeaderId(int memoHeaderId) {
this.memoHeaderId = memoHeaderId;
}
public int getMemoNo() {
return memoNo;
}
public void setMemoNo(int memoNo) {
this.memoNo = memoNo;
}
public int getVehId() {
return vehId;
}
public void setVehId(int vehId) {
this.vehId = vehId;
}
public int getDriverId() {
return driverId;
}
public void setDriverId(int driverId) {
this.driverId = driverId;
}
public int getOfficeId() {
return officeId;
}
public void setOfficeId(int officeId) {
this.officeId = officeId;
}
public int getToId() {
return toId;
}
public void setToId(int toId) {
this.toId = toId;
}
public int getStaffId() {
return staffId;
}
public void setStaffId(int staffId) {
this.staffId = staffId;
}
public String getVehNo() {
return vehNo;
}
public void setVehNo(String vehNo) {
this.vehNo = vehNo;
}
public String getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(String officeAddress) {
this.officeAddress = officeAddress;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
@Override
public String toString() {
return "GetVoucherReport [voucherId=" + voucherId + ", memoHeaderId=" + memoHeaderId + ", memoNo=" + memoNo
+ ", vehId=" + vehId + ", driverId=" + driverId + ", officeId=" + officeId + ", toId=" + toId
+ ", staffId=" + staffId + ", vehNo=" + vehNo + ", officeAddress=" + officeAddress + ", toAddress="
+ toAddress + ", createDate=" + createDate + "]";
}
}
|
C++
|
UTF-8
| 564
| 2.796875
| 3
|
[] |
no_license
|
class Solution {
public:
vector<int> lexicalOrder(int n) {
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
vector<int>vec;
int number = 1;
for(int i=0; i<n; i++){
vec.push_back(number);
if(number * 10 <= n){
number *= 10;
}else{
if(number == n)
number /= 10;
number += 1;
while(number % 10 == 0)
number /= 10;
}
}
return vec;
}
};
|
C#
|
UTF-8
| 765
| 4.09375
| 4
|
[] |
no_license
|
using System;
using System.Linq;
class Program
{
public static string ReverseText(string text)
{
char[] charArray = text.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public static bool Palindrom(string i)
{
return i.SequenceEqual(i.Reverse());
}
static void Main()
{
Console.WriteLine("Please enter a word to spell it backwards and to see if it's a palindrome\n");
string word = Console.ReadLine();
word = word.ToLower();
Console.Write("\nHere is your word spelled backwards: \n\n" + ReverseText(word) + "\n");
Console.WriteLine("\n Is your word a palindrome? \n\n" + Palindrom(word) + "\n");
}
}
|
Shell
|
UTF-8
| 433
| 3.671875
| 4
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
set -e
if [ -z "$TRAVIS_OS_NAME" ]; then
TRAVIS_OS_NAME=linux
fi
if [ "$TRAVIS_OS_NAME" = "linux" ]; then
if [ ! -f "$TRAVIS_BUILD_DIR/ninja/ninja" ]; then
git clone https://github.com/ninja-build/ninja.git && cd ninja
git checkout release
./configure.py --bootstrap
cd ..
else
echo 'Using cached ninja directory.';
fi
else
echo "Unknown OS ($TRAVIS_OS_NAME). Stopping build ..."
exit 1
fi
|
Python
|
UTF-8
| 7,627
| 2.671875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
#
# License: This module is released under the terms of the LICENSE file
# contained within this applications INSTALL directory
"""
Abstracts and simplifies publishing reports (and catalogues) from different databases
with the insights service API
"""
# -- Coding Conventions
# http://www.python.org/dev/peps/pep-0008/ - Use the Python style guide
# http://sphinx.pocoo.org/rest.html - Use Restructured Text for
# docstrings
# -- Public Imports
import os
import yaml
import pytz
from datetime import datetime, timedelta, date
# -- Private Imports
from nsa.hub.api import Insights
from connector import DBConnector
# -- Globals
# -- Exception classes
# -- Functions
# -- Classes
class CatalogueGenerator:
"""
This class takes in a Database config and catalogue source
and returns the catalogue with values
"""
def __init__(self, config):
self.path = config['path']
self.dbconnector = DBConnector(config)
# Load catalogues
self._files = [f for f in os.listdir(
self.path) if os.path.isfile(os.path.join(self.path, f))]
def catalogue(self):
"""
This function yields a catalogue, complete with its values
"""
for filename in self._files:
self.cur_file = filename
dirname = os.path.dirname(__file__)
filepath = os.path.join(self.path, filename)
stream = open(filepath, 'r')
self.catalogues = yaml.load(stream)
for cat in self.catalogues:
# Get data
cat['values'] = self.dbconnector.fetch(cat['query'])
# TODO for localhost DB reports only
# Converting integer to timestamp for Cyclical reports
if cat['resolution'] == 'hour of day':
then = datetime.utcnow() - timedelta(days=1)
then = then.replace(
hour=0, minute=0, second=0, microsecond=0)
for i in range(len(cat['values'])):
cat['values'][i]['datetime'] = pytz.UTC.localize(
then.replace(hour=i))
yield cat
class ReportGenerator:
"""
This class takes in a Database config and catalogue source
and returns the report with values
"""
def __init__(self, path):
self.path = path
# Load reports
self._files = [f for f in os.listdir(
self.path) if os.path.isfile(os.path.join(self.path, f))]
def report(self):
"""
This funtion yields a report based in config provided in input/reports/
"""
for filename in self._files:
self.cur_file = filename
dirname = os.path.dirname(__file__)
filepath = os.path.join(self.path, filename)
stream = open(filepath, 'r')
self.reports = yaml.load(stream)
for report in self.reports:
yield report
class Publisher:
"""
This class takes in a catalogue and publishes it
to the target destination.
"""
def __init__(self, config):
self._env = config['env']
self._username = config['username']
self._password = config['password']
self.target = Insights(
self._username, self._password, environment=self._env)
def publish_context(self, path):
"""
This function publishes the report context provided in inputs/report_context/
"""
stream = open(path, 'r')
contexts = yaml.load(stream)
context_dict = {}
for i in contexts:
context_dict[i['classification']] = i['contexts']
cs = self.target.contextsequence
for c in cs:
c['contexts'] = context_dict[c['classification']]
c.save()
def publish_catalogue(self, meta_catalogue):
"""
This function publishes a catalogue to the defined target
"""
type = meta_catalogue['type']
origin = meta_catalogue['origin']
metric = meta_catalogue['metric']
tag = meta_catalogue['tag']
resolution = meta_catalogue['resolution']
aggregation = meta_catalogue['aggregation']
name = meta_catalogue['name']
# Get catalogue
cats = self.target.catalogues.get(
type=type,
origin=origin,
metric=metric,
tag=tag,
resolution=resolution,
aggregation=aggregation,
name=name
)
if cats:
catalogue = cats[0]
else:
try:
# Create Catalogue
catalogue = self.target.catalogues.create(
type=type,
origin=origin,
metric=metric,
tag=tag,
resolution=resolution,
aggregation=aggregation,
name=name
)
except Exception as e:
print "Failed creating catalogue: {}, error: {}".format(meta_catalogue, e)
pass
# Clear and delete Catalogue
series = catalogue.series.get()
series.delete()
try:
if meta_catalogue['values']:
series = catalogue.series.create(*meta_catalogue['values'])
except Exception as e:
print "Failed creating series: {}, error: {}".format(meta_catalogue, e)
pass
def publish_report(self, meta_report):
"""
This function publishes a report to the defined target
"""
type = meta_report['type']
classification = meta_report['classification']
context = meta_report['context']
name = meta_report['name']
description = meta_report['description']
privilege = meta_report["privilege"]
extras = meta_report["extras"]
report = self.target.reports.get(
type=type,
classification=classification,
context=context,
name=name,
extras=extras,
description=description,
privilege=privilege
)
if not report:
try:
report = self.target.reports.create(
type=type,
classification=classification,
context=context,
name=name,
extras=extras,
description=description,
privilege=privilege
)
except Exception as e:
print "Failed creating report: {} error: {}".format(meta_report['name'], e)
pass
else:
report[0].catalogues = []
report = report[0]
cat_to_add = []
for cat_id in meta_report['catalogue']:
try:
catalogue = self.target.catalogues.get(
origin=cat_id['origin'],
metric=cat_id['metric'],
resolution=cat_id['resolution'],
aggregation=cat_id['aggregation'],
tag=cat_id['tag'],
)
cat_to_add = cat_to_add + catalogue
except Exception as e:
print "Failed getting catalogue: {} for application report id: {} error: {}".format(cat_id, meta_report['name'], e)
pass
# Assign Catalogue to Report
report.catalogues = cat_to_add
|
PHP
|
UTF-8
| 706
| 2.984375
| 3
|
[] |
no_license
|
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
echo "<div style='font-size:22px;'>";
echo "The result table:";
echo "</div>";
$num1 = $_POST['name'];
if ( $num1 > 12 )
$num1 = 12;
if ( $num1 < 2 )
$num1 = 2;
$num2 = $_POST['name2'];
if ( $num2 > 12 )
$num2 = 12;
if ( $num2 < 2 )
$num2 = 2;
echo "<table border=\"1\" align=\"center\">";
for ( $counter = 1; $counter <= $num1; $counter += 1) {
echo "<tr>";
for ( $counter2 = 1; $counter2 <= $num2; $counter2 += 1) {
echo "<td>";
echo $counter * $counter2;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
|
Markdown
|
UTF-8
| 789
| 2.71875
| 3
|
[] |
no_license
|
# metro-tsconfig-paths
Load `tsconfig.json` modules from locally developed packages, and help Metro
resolve imports using their `paths` objects.
## Usage
Add the following to your `metro.config.js` module:
```js
const withTSConfig = require('metro-tsconfig-paths')
module.exports = withTSConfig({
/* Metro configuration goes here */
})
```
## How it works
It uses [`get-dev-paths`][1] to find any locally developed packages. Then it uses
[`tsconfig-paths`][2] to load `tsconfig.json` modules and convert their `paths`
objects into "matcher functions". Then it hooks into your Metro config and applies
the relevant matcher function (if any) to whichever dependency is being resolved.
[1]: https://github.com/aleclarson/get-dev-paths
[2]: https://github.com/dividab/tsconfig-paths
|
Markdown
|
UTF-8
| 2,455
| 3.921875
| 4
|
[] |
no_license
|
# [Add Binary][title]
## Description
Given two binary strings, return their sum (also a binary string).
The input strings are both **non-empty** and contains only characters `1` or `0`.
**Example 1:**
```
Input: a = "11", b = "1"
Output: "100"
```
**Example 2:**
```
Input: a = "1010", b = "1011"
Output: "10101"
```
**Tags:** Math, String
## 思路
题意是给你两个二进制串,求其和的二进制串。我们就按照小学算数那么来做,用 `carry` 表示进位,从后往前算,依次往前,每算出一位就插入到最前面即可,直到把两个二进制串都遍历完即可。
```swift
func addBinary(_ a: String, _ b: String) -> String {
var result = String()
var aLastIndex = a.count - 1
var bLastIndex = b.count - 1
var carray: Int = 0
while aLastIndex >= 0 && bLastIndex >= 0 {
carray = carray + (aLastIndex >= 0 ? Int(String(a[a.index(a.startIndex, offsetBy: aLastIndex)]))! : 0)
carray = carray + (bLastIndex >= 0 ? Int(String(b[b.index(b.startIndex, offsetBy: bLastIndex)]))! : 0)
let tempString = String(carray % 2)
result.insert(tempString[tempString.startIndex], at: result.startIndex)
carray = carray >> 1
aLastIndex -= 1
bLastIndex -= 1
}
while aLastIndex >= 0 {
carray = carray + (aLastIndex >= 0 ? Int(String(a[a.index(a.startIndex, offsetBy: aLastIndex)]))! : 0)
let tempString = String(carray % 2)
result.insert(tempString[tempString.startIndex], at: result.startIndex)
carray = carray >> 1
aLastIndex -= 1
}
while bLastIndex >= 0 {
carray = carray + (bLastIndex >= 0 ? Int(String(b[b.index(b.startIndex, offsetBy: bLastIndex)]))! : 0)
let tempString = String(carray % 2)
result.insert(tempString[tempString.startIndex], at: result.startIndex)
carray = carray >> 1
bLastIndex -= 1
}
if carray > 0 {
result.insert("1", at: result.startIndex)
}
return result
}
let a1 = "11", b1 = "1"
print("\(a1) + \(b1) = \(addBinary(a1, b1))")
let a2 = "1010", b2 = "1011"
print("\(a2) + \(b2) = \(addBinary(a2, b2))")
```
## 结语
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-swift-leetcode][zgpeace]
[title]: https://leetcode.com/problems/add-binary
[zgpeace]: https://github.com/zgpeace/awesome-swift-leetcode
|
C#
|
UTF-8
| 475
| 3.46875
| 3
|
[] |
no_license
|
public class A
{
public int MyProperty { get; set; }
}
public static class B
{
static B()
{
MyInstance = new A();
MyInstance.MyProperty = 10;
}
public static A MyInstance { get; set; }
}
public class C
{
// not sure what your intention is here
public C()
{
System.Console.WriteLine(B.MyInstance.MyProperty.ToString()); // "10\n"
}
}
|
C#
|
UTF-8
| 666
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Trucks.Application.Attributes
{
/// <summary>
/// Attribute to validate if Enum is defined.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class EnumValidateExistsAttribute : DataTypeAttribute
{
public EnumValidateExistsAttribute()
: base("Enumeration")
{
}
public override bool IsValid(object value)
{
var enumType = value.GetType();
return enumType.IsEnum && Enum.IsDefined(enumType, value);
}
}
}
|
Java
|
UTF-8
| 324
| 1.695313
| 2
|
[] |
no_license
|
package com.xzx.xzxms.inquiry.bean.extend;
import com.xzx.xzxms.inquiry.bean.InquiryPool;
public class InquiryPoolExtend extends InquiryPool {
private String proName;
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
}
|
Markdown
|
UTF-8
| 839
| 2.65625
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: New iPhone 5
date: 2012-09-28
---

I'm pretty stoked.
Thankfully, Paddy was there to document this great occasion.
I really like the new iPhone. The taller form factor is actually pretty nice.
The one problem I'm having with the taller screen is applications that are still letterboxed. The keyboard has the black bar beneath it, which has the effect of raising the keyboard by 44 points (the height of a nav bar).
So I have to mentally translate where my fingers touch to type in apps. The _really_ frustrating thing is the space bar, since it's at the bottom. I wish that Apple had made the hit target for the spacebar extend _below_ the frame of the application, since that's where I'm finding I'm tapping. I get a lot of sentenceswithwordsrunningtogether and it's a pain.
|
Go
|
UTF-8
| 531
| 2.96875
| 3
|
[] |
no_license
|
package main
import "fmt"
import "bufio"
import "os"
import "strings"
import "strconv"
func main() {
var slicelen int
var targetnum int
fmt.Scanln(&slicelen, &targetnum)
var scanner = bufio.NewScanner(os.Stdin)
scanner.Scan()
var arraytext = scanner.Text()
var inputArr = strings.Split(arraytext, " ")
inputArr = inputArr[:slicelen]
var targetnumtemp string = strconv.Itoa(targetnum)
var index int = -1
for p := 0; p < len(inputArr); p++ {
if inputArr[p] == targetnumtemp {
index = p
}
}
fmt.Println(index)
}
|
Python
|
UTF-8
| 1,083
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
def calc_rmsd(ref_coords, coords, idxs=None):
"""Calculate the RMSD between the reference and query coordinates.
Parameters
----------
ref_coords : arraylike
The refence coordinates that will be aligned to.
coords : arraylike
The coordinates that will be rotated to match ref_coords.
idxs : arraylike of int
Indices of the atoms in the coords to actually compute the
RMSD for.
"""
# make sure the coords are the same size
assert len(ref_coords.shape) == len(coords.shape), "rank of coords are not the same"
assert ref_coords.shape[0] == coords.shape[0], \
"Number of coordinates are not the same"
# make sure the number of dimensions is 3
assert (ref_coords.shape[1] == 3) and (coords.shape[1] == 3), \
"Number of dimensions are not the same"
if idxs is None:
idxs = np.arange(ref_coords.shape[0])
rmsd = np.sqrt(np.sum(np.square(coords[idxs, :] - ref_coords[idxs, :]),
axis=(0,1))/idxs.shape[0])
return rmsd
|
C#
|
UTF-8
| 6,011
| 2.890625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace Daemon.Modules {
/// <summary>日志模块</summary>
public class LoggerModule:IDisposable {
/// <summary>计时器</summary>
private readonly Timer Timer;
/// <summary>日志根目录,没有"/"</summary>
private readonly String LogsDirectory;
/// <summary>日志</summary>
private Dictionary<String,StringBuilder> Logs;
/// <summary>计时器触发间隔</summary>
private readonly Int32 TimerInterval;
/// <summary>
/// 构造
/// </summary>
/// <param name="logsDirectory"></param>
public LoggerModule(String logsDirectory,Int32 writeInterval){
if(!Directory.Exists(logsDirectory)){
try{
Directory.CreateDirectory(logsDirectory);
}catch(Exception exception){
throw new Exception("无法创建日志根目录,"+exception.Message);
}
}
this.LogsDirectory=logsDirectory;
this.TimerInterval=writeInterval<1000?1000:writeInterval;
this.Logs=new Dictionary<String,StringBuilder>();
//this.Logs["Daemon"]=new StringBuilder();
this.Timer=new Timer{AutoReset=true,Enabled=true,Interval=this.TimerInterval};
this.Timer.Elapsed+=this.Timer_Elapsed;
}
#region IDisposable Support
private bool disposedValue = false; // 要检测冗余调用
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
// TODO: 释放托管状态(托管对象)。
this.Timer.Elapsed-=this.Timer_Elapsed;
this.Timer.Enabled=false;
this.Timer.Dispose();
}
// TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
// TODO: 将大型字段设置为 null。
this.Logs=null;
disposedValue=true;
}
}
// TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
~LoggerModule() {
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(false);
}
// 添加此代码以正确实现可处置模式。
public void Dispose() {
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(true);
// TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// 定时写入日志
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Timer_Elapsed(object sender,ElapsedEventArgs e) {
this.Timer.Enabled=false;
if(this.Logs==null || this.Logs.Count<1){return;}
String datetime=DateTime.Now.ToString("yyyy-MM-dd");
foreach (KeyValuePair<String,StringBuilder> log in this.Logs) {
if(log.Value==null || log.Value.Length<1){continue;}
String directory;
if(log.Key.IndexOf(".")>-1){
directory=this.LogsDirectory+Path.DirectorySeparatorChar+log.Key.Replace('.',Path.DirectorySeparatorChar);
} else {
directory=this.LogsDirectory;
}
if(!Directory.Exists(directory)) {
try {
Directory.CreateDirectory(directory);
}catch(Exception exception) {
ConsoleColor cc=Console.ForegroundColor;
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine($"Modules.LoggerModule => 写入日志时目录异常 | {exception.Message} | {exception.StackTrace}");
Console.ForegroundColor=cc;
continue;
}
}
String filePath=directory+Path.DirectorySeparatorChar+datetime+".log";
FileStream fs=null;
try{
fs=File.Open(filePath,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.Read);
fs.Seek(0,SeekOrigin.End);
ReadOnlySpan<Byte> bytes=Encoding.UTF8.GetBytes(log.Value.ToString());
fs.Write(bytes);
log.Value.Clear();
} catch (Exception exception) {
ConsoleColor cc=Console.ForegroundColor;
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine($"Modules.LoggerModule => 写入日志时文件异常 | {exception.Message} | {exception.StackTrace}");
Console.ForegroundColor=cc;
continue;
} finally {
if(fs!=null){fs.Dispose();}
}
}
this.Timer.Enabled=true;
}
/// <summary>
/// 记录
/// </summary>
/// <param name="title"></param>
/// <param name="text"></param>
public void Log(String title,String text){
if(String.IsNullOrWhiteSpace(title) || String.IsNullOrWhiteSpace(title)){return;}
if(!this.Logs.ContainsKey(title) || this.Logs[title]==null){this.Logs[title]=new StringBuilder();}
//this.Logs[title].Append("[").Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Append("]\n").Append(text).Append("\n");
this.Logs[title].Append($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}]\n{text}\n\n");
}
}
}
|
C++
|
UTF-8
| 625
| 2.65625
| 3
|
[] |
no_license
|
#ifndef SRC_EPI_CHAPTER5_SWAPBITS_HPP_
#define SRC_EPI_CHAPTER5_SWAPBITS_HPP_
#include "../../Solution.h"
#include "../../SmartPtr.h"
#include "../../SolutionCollection.h"
namespace epi {
namespace chapter5 {
class SwapBits : public myutils::Solution {
friend class myutils::SmartPtr;
public:
SwapBits():
Solution("EPI Chapter 5.2",
"Swap Bits",
"Swap bits at i and j. "
"LSB as 0, and MSB as 31.") { }
bool test();
~SwapBits() { }
long swapBits(long x, int i, int j);
};
} // chapter5
} // eip
#endif /* SRC_EPI_CHAPTER5_SWAPBITS_HPP_ */
|
SQL
|
UTF-8
| 1,143
| 3.8125
| 4
|
[] |
no_license
|
-- create table Description
create table if not exists ThreeDMap.object_description (
id bigint Primary Key,
name varchar(50) not null
);
create index name_index on ThreeDMap.object_description (name);
comment on table ThreeDMap.object_description is 'This table describes 3D objects.';
-- Change table object_location
-- add id field
alter table ThreeDMap.object_location add column id bigint;
-- add link to an object description
alter table ThreeDMap.object_location add column object_id bigint;
alter table ThreeDMap.object_location alter column object_id set not null;
-- change primary key
alter table ThreeDMap.object_location drop constraint object_location_pkey;
alter table ThreeDMap.object_location add primary key (id);
create index object_id_index on ThreeDMap.object_location (object_id);
-- drop column name
alter table ThreeDMap.object_location drop column name;
--alter table ThreeDMap.object_location alter column name set not null;
--create index name_index on ThreeDMap.object_location (name);
-- create sequence
create sequence ThreeDMap.location_sequence start 1;
create sequence ThreeDMap.description_sequence start 1;
|
Python
|
UTF-8
| 350
| 3.1875
| 3
|
[] |
no_license
|
# Uses python3
import sys
input = sys.stdin.readline
def solve(n):
n1 = 0
n2 = 1
a = []
for i in range(n - 1):
a.append(n1 + n2)
n1, n2 = n2, n1 + n2
if len(a) != 0:
return (max(a) % 10)
else:
return 0
n = int(input())
print(solve(n))
|
C
|
UTF-8
| 2,444
| 2.734375
| 3
|
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ppavlich <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/23 18:52:29 by ppavlich #+# #+# */
/* Updated: 2017/03/23 19:32:38 by ppavlich ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_checkstr(char **str, char **line)
{
char *p;
char *tmp;
if (*str != NULL)
{
if ((p = ft_strchr(*str, '\n')) != NULL)
{
*p = '\0';
*line = ft_strdup(*str);
tmp = ft_strdup(p + 1);
free(*str);
*str = tmp;
return (1);
}
}
return (0);
}
static int ft_supp(int f, char **buff, char **str, char **line)
{
char *p;
char *tmp;
if (*str == NULL)
*str = ft_strdup("");
if (f == 1)
if ((p = ft_strchr(*buff, '\n')) != NULL)
{
*p = '\0';
*line = ft_strdup(ft_strjoin(*str, *buff));
free(*str);
*str = ft_strdup(p + 1);
ft_strdel(buff);
return (1);
}
if (f == 2)
{
tmp = ft_strdup(*str);
free(*str);
*str = ft_strjoin(tmp, *buff);
free(tmp);
}
return (0);
}
int ft_read(int fd, char **line, char **buff, char **str)
{
int rs;
int f;
f = 0;
while ((rs = read(fd, *buff, BUFF_SIZE)) > 0)
{
(*buff)[rs] = '\0';
if (ft_supp(1, buff, str, line))
{
f++;
return (1);
}
else if (ft_supp(2, buff, str, line))
;
}
if (rs == 0 && f == 0 && *str != NULL && ft_strlen(*str) != 0)
{
*line = ft_strdup(*str);
free(*str);
*str = NULL;
return (1);
}
return (rs);
}
int get_next_line(const int fd, char **line)
{
char *buff;
static char *str;
int res;
if (BUFF_SIZE < 1 || fd < 0 || !line)
return (-1);
if ((buff = ft_strnew(BUFF_SIZE + 1)) == NULL)
return (0);
if (ft_checkstr(&str, line))
return (1);
res = ft_read(fd, line, &buff, &str);
if (res == 0)
{
ft_strdel(&str);
}
ft_strdel(&buff);
return (res);
}
|
Markdown
|
UTF-8
| 1,213
| 2.625
| 3
|
[] |
no_license
|
# Master X Data Science ,Paris 2019-2020
# Introduction-to-Bayesian-Learning
Place: Télécom ParisTech
Programming Language : R
<b>Syllabus</b>:
<br>
Week 1: Bayesian learning: basics.
Bayesian model, prior-posterior, examples.
Point and interval estimation.
<br>
Prior choice, examples, exponential family
A glimpse at asymptotics and at computational challenges
Reading: Berger (2013), chapter 1; Bishop (2006) chapters 1 and 2, Robert
(2007) chapter 1, Ghosh et al. (2007), chapter 2 and Robert and Casella (2010),
chapter 1 for basic R programming.
<br>
Week 2: Bayesian modeling and decision theory
Naïve Bayes, KNN
Bayesian Linear Regression
Bayesian decision theory.
Reading: Bishop (2006), chapter 3; Berger (2013) chapter 4; Robert (2007)
chapter 2.
<br>
Week 3: Lab session
<br>
Weeks 4: Approximation methods EM and Variational Bayes, examples.
Reading: Bishop (2006), Chapter 10.
<br>
Week 5 : Sampling methods Monte-Carlo methods, importance samplnig,
MCMC (Metropolis-Hastings and Gibs), examples.
If time allows it: sequential methods (particle filtering)
Reading Robert and Casella (2010), (bits of) chapters 3, 4, 6, 7, 8.<br>
Week 6: Lab session.
approximation and sampling methods
|
Java
|
UTF-8
| 7,367
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.levigo.jadice.format.jpeg2000.internal.codestream;
import com.levigo.jadice.format.jpeg2000.JPEG2000Exception;
import com.levigo.jadice.format.jpeg2000.internal.io.MarkerReader;
import com.levigo.jadice.format.jpeg2000.internal.marker.Marker;
import com.levigo.jadice.format.jpeg2000.internal.marker.SOT;
import com.levigo.jadice.format.jpeg2000.internal.marker.TLM;
import com.levigo.jadice.format.jpeg2000.msg.CodestreamMessages;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;
public class TilePartPointerProvider {
private static class TilePartIndexComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1 > o2 ? -1 : o1 < o2 ? 1 : 0;
}
}
private static class TLMIndexComparator implements Comparator<TLM> {
@Override
public int compare(TLM o1, TLM o2) {
return o1.Ztlm < o2.Ztlm ? -1 : o1.Ztlm > o2.Ztlm ? 1 : 0;
}
}
/**
* Data structure containing {@link TilePartPointer} objects ordered by its tile-part index ({@link
* TilePartPointer#tilePartIdx}).
*/
public TreeMap<Integer, List<TilePartPointer>> tilePartPointers;
private TreeSet<TLM> tlmMarkers;
public boolean fromTLM;
public TilePartPointerProvider() {
tilePartPointers = new TreeMap<>(new TilePartIndexComparator());
fromTLM = false;
}
/**
* Use this method to register {@link TLM} marker segments which has been signalled in {@link Codestream}'s main
* header. To ensure all information is saved correctly call {@link #finish(long)} if the main header is expected to
* be fully read.
*
* @param tlm a {@link TLM} marker segment object which should be registered for later application.
*/
public void registerTLM(TLM tlm) {
if (tlmMarkers == null) {
tlmMarkers = new TreeSet<>(new TLMIndexComparator());
}
tlmMarkers.add(tlm);
}
/**
* Saves all information of previously registered {@link TLM} marker segments into the persistent and publicly
* accessible {@link #tilePartPointers} data structure. After all information has been processed all references to
* registered {@link TLM} marker segment objects will be released and these objects are free to be garbage collected.
* <p>
* Call this method only if the {@link Codestream}'s main header signalled {@link TLM} marker segments which has
* previously been registered via {@link #registerTLM(TLM)}-method.
* <p>
* To find out if there are any registered {@link TLM} marker segments use {@link #hasTLM()}.
*
* @param firstTilePartPosition the position in the {@link Codestream}'s source where the first {@link SOT} marker
* segment is expected.
*/
public void finish(long firstTilePartPosition) {
long tilePartStart = firstTilePartPosition;
int tilePartIdx = 0;
for (TLM tlm : tlmMarkers) {
final Iterator<Integer> tileIndices = getIndexIterator(tlm);
final Iterator<Integer> tilePartLengths = getLengthIterator(tlm);
while (tileIndices.hasNext() && tilePartLengths.hasNext()) {
final int tileIdx = tileIndices.next();
final int tilePartLength = tilePartLengths.next();
final List<TilePartPointer> pointers = getPointers(tileIdx);
pointers.add(new TilePartPointer(tilePartIdx++, tilePartStart, tilePartLength, tileIdx));
tilePartStart += tilePartLength;
}
}
fromTLM = true;
tlmMarkers = null;
}
private Iterator<Integer> getIndexIterator(TLM tlm) {
if (tlm.Ttlm == null) {
return new TilePartSequence();
} else {
return tlm.Ttlm.iterator();
}
}
private Iterator<Integer> getLengthIterator(TLM tlm) {
return tlm.Ptlm.iterator();
}
/**
* Use this method to determine if any {@link TLM} marker segment has been registered.
*
* @return <code>true</code> if the internally maintained store for {@link TLM} marker segment has been initialized
* and contains at least one object; otherwise <code>false</code>.
*/
public boolean hasTLM() {
return tlmMarkers != null && !tlmMarkers.isEmpty();
}
/**
* Registers a tile-part directly from a read {@link SOT} marker segment. The implementation creates a new {@link
* TilePartPointer} object and stores it directly into {@link #tilePartPointers}.
*
* @param sot the found {@link SOT} marker segment signalled as the beginning of a new tile-part.
* @param tilePartStart the position in {@link Codestream}'s source where the tile-part begins.
* @return <code>true</code> if the new tile-part information was successfully stored; otherwise <code>false</code>.
*/
public boolean registerSOT(SOT sot, long tilePartStart) {
final TilePartPointer pointer = new TilePartPointer(sot.TPsot, tilePartStart, sot.Psot, sot.Isot);
final List<TilePartPointer> pointers = getPointers(sot.Isot);
if (!pointers.isEmpty() && pointers.contains(pointer)) {
return false;
}
return pointers.add(pointer);
}
private List<TilePartPointer> getPointers(int tileIdx) {
return getPointers(tileIdx, true);
}
private List<TilePartPointer> getPointers(int tileIdx, boolean create) {
List<TilePartPointer> pointers = tilePartPointers.get(tileIdx);
if (pointers == null && create) {
tilePartPointers.put(tileIdx, pointers = new ArrayList<>(2));
}
return pointers;
}
/**
* Retrieves a {@link java.util.List} of {@link TilePartPointer}s which belong to a specific tile.
*
* @param tileIdx the tile's absolute index.
* @return a {@link java.util.List} of {@link TilePartPointer}s which belong to a specific tile or <code>null</code>
* if not yet available.
*/
public List<TilePartPointer> getTilePartPointers(int tileIdx) {
return getPointers(tileIdx, false);
}
public SOT findTileHeader(int tileIdx, Codestream codestream) throws IOException, JPEG2000Exception {
final MarkerReader markerReader = new MarkerReader();
final SOT sot = new SOT();
Marker marker;
do {
codestream.source.seek(codestream.nextTilePartAddress);
marker = markerReader.next(codestream.source);
if (marker == Marker.EOC) {
return null;
}
if (marker != Marker.SOT) {
throw new JPEG2000Exception(CodestreamMessages.INVALID_SOT_ADDRESS, codestream.nextTilePartAddress);
}
sot.read(codestream.source, codestream, false);
registerSOT(sot, codestream.nextTilePartAddress);
codestream.nextTilePartAddress += sot.Psot;
} while (sot.Isot != tileIdx);
return sot;
}
private class TilePartSequence implements Iterator<Integer> {
private int next;
public TilePartSequence() {
next = 0;
}
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
return next++;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
|
C++
|
UTF-8
| 4,508
| 2.984375
| 3
|
[] |
no_license
|
#include "Window.h"
Window::Window(unsigned int width
, unsigned int height
, const std::string title
, PaintData* paintData)
: m_window(sf::VideoMode(width, height), title)
, m_paintData(paintData)
{
m_title = title;
m_width = width;
m_height = height;
createWindow();
}
Window::~Window()
{
closeWindow();
}
//Calls sf::RenderWindow::create to create a window and hides the default mouse cursor
//so that custom ones could be used
void Window::createWindow()
{
m_window.create({ m_width, m_height }, m_title);
m_window.setMouseCursorVisible(false);
m_isOpen = true;
}
void Window::closeWindow()
{
m_window.close();
m_isOpen = false;
}
//Method to process window events
void Window::update()
{
m_window.clear();
sf::Event event;
while (m_window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
closeWindow();
break;
case sf::Event::MouseButtonPressed:
std::cout << (m_paintData->state == State::COLOR_PICKER) << std::endl;
std::cout << "isPicking: " << (m_paintData->isColorPicking) << std::endl;
std::cout << "isPicked: " << (m_paintData->isColorPicked) << std::endl;
if (event.mouseButton.button == sf::Mouse::Left)
{
m_paintData->mouseLeftButtonState = ButtonState::PRESSED;
if (m_paintData->state == State::LINE)
{
//If the button was pressed in the drawing field
if (sf::Mouse::getPosition(m_window).x > m_paintData->menuBar.getBarWidth())
{
m_paintData->isDrawing = true;
//Save a snapshot of the current drawing and the starting cooordinates when the user starts drawing a line
//Snapshot is needed to avoid creating a new line with each change of mouse coordinates
m_paintData->imageSnapshot = m_paintData->image;
m_paintData->lineStartCoords = m_paintData->prevLine = sf::Mouse::getPosition(m_window);
}
}
if (m_paintData->state == State::COLOR_PICKER && !m_paintData->isColorPicking)
{
std::cout << "open color pick img " << std::endl;
m_paintData->isColorPicking = true;
m_paintData->isColorPicked = false;
//Size of colorPicker image
m_paintData->colorPicker.setSize({ 512,511 });
//Set the position right next to the mouse pointer soit doesnt detect the mouse press as if a color was picked
m_paintData->colorPicker.setPosition(sf::Vector2f(getMouseCoords().x + 1, getMouseCoords().y + 1));
}
}
break;
case sf::Event::MouseButtonReleased:
if (event.mouseButton.button == sf::Mouse::Left)
{
m_paintData->mouseLeftButtonState = ButtonState::RELEASED;
if (m_paintData->state == State::LINE)
{
//If the button was pressed in the drawing field
if (sf::Mouse::getPosition(m_window).x > m_paintData->menuBar.getBarWidth())
{
m_paintData->isDrawing = false;
//m_paintData->isColorPicked = false;
}
}
}
//if (m_paintData->state == State::COLOR_PICKER && m_paintData->isColorPicking)
//{
// m_paintData->isColorPicking = false;
//}
break;
case sf::Event::MouseMoved:
//Move the custom cursor over the mouse's actual position
updateCursorPos(event.mouseMove.x, event.mouseMove.y);
break;
}
}
}
void Window::updateCursorPos(int x, int y)
{
switch (m_paintData->state)
{
case State::ERASE:
//Set eraser's center is over the mouse's tip
m_paintData->mouse.setPosition(sf::Vector2f(x - m_paintData->eraserSize, y - m_paintData->eraserSize));
break;
case State::PENCIL:
//Offset y coordinate due to the position of the pencil tip in the pencil image
m_paintData->mouse.setPosition(sf::Vector2f(x, y - 32));
break;
default:
m_paintData->mouse.setPosition(sf::Vector2f(x, y));
}
}
void Window::draw(sf::Drawable& drawable)
{
m_window.draw(drawable);
}
sf::RenderWindow& Window::getWindow()
{
return m_window;
}
bool Window::isOpen()
{
return m_isOpen;
}
void Window::display()
{
m_window.display();
}
sf::Vector2u Window::getSize()
{
return m_window.getSize();
}
sf::Vector2i Window::getPosition()
{
return m_window.getPosition();
}
//Gets mouse coordinates relative to the window
sf::Vector2i Window::getMouseCoords()
{
return sf::Mouse::getPosition(m_window);
}
|
Java
|
UTF-8
| 908
| 1.6875
| 2
|
[] |
no_license
|
package com.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestCommonConfig.class, PropertyPlaceholderAutoConfiguration.class })
@ActiveProfiles("dev")
public class AppTest {
static {
System.setProperty("spring.profiles.active", "dev");
}
// @Autowired
// private JedisConnectionFactory jedisConnectionFactory;
// @Autowired
// private UserService userService;
@Test
public void testJedisSpring() throws Exception {
// List<User> usersList=userService.selectPoBySo(new UserSearchSo());
// System.out.println(usersList);
}
}
|
Markdown
|
UTF-8
| 28,840
| 2.734375
| 3
|
[] |
no_license
|
# CC71Q-MEPC
CC71Q - Data Mining - Mars Express Power Challenge
My take on https://kelvins.esa.int/mars-express-power-challenge/ for my Data Mining Computer Science Course.
Introducción
============
El *Mars Express Orbiter* (MEX) es un satélite de exploración científica
de la Agencia Espacial Europea, lanzado en junio del 2003 y colocado en
la órbita de Marte. Recolecta información científica sobre la ionósfera
y la composición de la sub-superficie del planeta rojo.
El MEX está provisto de siete sensores, entre estos, una cámara estéreo
que ha permitido capturar imágenes sin precedentessobre el planeta.
Mucha de la información recolectada por el MEX ha sido crucial para las
misiones posteriores de exploración de Marte (*Curiosity*,
*Opportunity*, etc.). La mayoría de los sensores en la nave deben
mantenerse en un rango de 10-20 $^{\circ}$C. Adicional a esto tiene dos
sensores: el PFS (*Planetary Fourier Spectrometer*) y OMEGA (*Visible
and Infra Red Mineralogical Mapping Spectrometer*) que deben mantenerse
a -180 $^{\circ}$C.
\
Figura 1. Imágen con cotas del valle *Ancient Atlantis*
El MEX es operado por la ESA desde su centro de operaciones en
Darmstadt, Alemania. Desde ahí se analizan los datos recibidos así como
también se monitorea cuidadosamente el estado del satélite, con el fin
de planificar mejor las misiones de observación y evitar problemas en el
suministro eléctrico.
Los operadores del MEX mantienen registros de su consumo de energía
termal. La nave utiliza energía eléctrica, proveniente de paneles
solares (o baterías, durante eclipses) no solo para alimentar los
sensores y cámaras, sino también para mantener la temperatura del
satélite dentro de rangos óptimos de funcionamiento. El resto de la
energía que no se ocupa se puede derivar para realizar las transmisiones
de datos.
$E_{Telecomunicaciones} = E_{Generada} - E_{Sensores} - E_{Climatizacion}$
El Mars Express Power Challenge se enfoca en predecir el consumo de
energía destinada a la calefacción. El concurso provee datos de tres
años (marcianos) como un set de entrenamiento y un cuarto año para
pruebas. El éxito del concurso permitirá al MEX entregar información por
periodos más largos de tiempo.
Descripción de los datos
========================
Los datos para este proyecto son entregados por la Agencial Espacial
Europea en formato CSV (2 GBytes) para los últimos cuatro años
marcianos. Cada año marciano corresponde a 687 días terrestes.
Los tres primeros años están destinados para entrenamiento de un sistema
predictivo y tienen información sobre el consumo eléctrico del sistema
termal. El cuarto año no tiene información sobre el consumo eléctrico
del sistema termal.
Contextos
---------
Los datos se encuentran separados según el tipo (o contexto) de
información que contienen. Así, existen cinco tipos de contextos de
datos: Solar Aspect Angles (SAAF), Detailed Mission Operations Plan
(DMOP), Flight Dynamics Timeline (FTL), Other Events(EVTF), Long Term
Data such as Sun-Mars Distance (LTDATA).
Cada uno de los tipos de contexto tienen diversas categorías (o
columnas).
### SAAF: Aspectos solares
Los ángulos entregan información sobre la incidencia de los rayos del
sol sobre los paneles solares. Los ángulos se miden con respecto a la
línea Sol-MEX.
### DMOP: Detalles de la planificación de operación
Los archivos DMOP entregan información sobre los comandos que han sido
activados en cada sistema. Cada comando incluye el nombre del sistema y
el nombre del comando. Debido a la cantidad de comandos, estos no se
explican, sin embargo cada uno tiene distintos efectos sobre la
temperatura en los distintos subsistemas, y por esto afectando el
sistema termal. En estos comandos se encuentran el encendio y apagado
del sistema de telecomunicaciones y de los instrumentos científicos.
### FTL: Eventos de la trayectoria de la nave
Los eventos listados en estos datos pueden impactar el comportamiento
del satélite ya que pueden afectar los ángulos de incidencia, así como
también tener relación con el encendido o apagado de algunos
instrumentos.
### EVTF: Otros eventos
Este set de datos contiene varios eventos. Contiene información sobre
eventos del FTL y la complementa con información sobre otros eventos,
como por ejemplo eclipses y sus fases (Penumbra y umbra).
### LTDATA: Información de periodos extendidos
Incluye información sobre la distancia entre el Sol y Marte, distancia a
la Tierra, duración de los eclipses, etc.
Consumo energético
------------------
En estos sets se incluye información sobre la corriente medida en los 33
circuitos eléctricos de la nave. Cada medición se realiza cada 30 o 60
segundos.
El objetivo de la competencia es predecir el consumo promedio por hora
del satélite, por lo que la información sobre el consumo eléctrico solo
está presente en los datos de entrenamiento.
Exploración inicial
===================
Como se mencionó anteriormente, el objetivo de la competencia es
predecir el consumo energético de los sistemas termicos de la nave a
partir de los otros datos que se tienen. La exploración inicial de los
datos consistirá en analizar los datos de consumo energético y
relacionarlos con los otros datos de estado de los sistemas, incidencia
solar y posición del satélite.
Luego de importar los datos en R, lo primero que llama la atención es la
cantidad de datos. El conjunto de datos que intuitivamente contiene más
información es el de los datos del consumo energético. Éstos se
muestrean cada 30 o 60 segundos. Para el primer año existen 1.830.121
regitros.
Al graficar este conjunto de datos se puede apreciar que existen niveles
de comportamiento. Por la cantidad de datos que existen, el gráfico se
aprecia como una mancha continua con secciones de rangos. Debido a esto
se procede a graficar en rangos más pequeños.
 
\
Figura 2. Consumo energético del sistema termal para el primer año\
Figuras 3 y 4. Consumo energético del sistema termal en intervalos
menores
Al graficar en rangos de mil datos, se puede apreciar mejor el
comportamiento de los datos a lo largo del tiempo. Cabe notar que los
datos anteriores corresponden a la suma total de los datos de consumo.
Se intuye que al revisar los datos del consumo, se encontrará evidencia
de la existencia de clusters de circuitos, es decir, de los 33
circuitos, deben haber varios grupos, divididos entre
refrigeración/calefacción y entre los distintos sensores y secciones del
satélite.
Una parte importante del trabajo consistirá en encontrar estos clusters.
Una vez agrupados los datos se podrá proceder a relacionarlos con
comandos enviados remotamente para el encendido y apagado de interfaces
y así determinar una relación directa entre estos.
De la misma forma, de la primera observación de los datos, se prevee que
pueda existir una relación con la distancia con el sol, similar a las
estaciones del año. Esto podría influir en el consumo energético de
forma significativa.
Con respecto a los otros set de datos, se considera importante el ángulo
de incidencia solar.
 
\
Figura 5. Curvas de incidencia solar en la Tierra\
Figura 6. Datos de incidencia solar del satélite para el primer año\
Figura 7. Datos de incidencia solar del satélite en un intervalo menor
Al graficar el total de datos de ángulos de incidencia sobre el tiempo,
se puede apreciar que el comportamiento es aparentemente similar a una
sinusoide. Al compararlo con gráficas de ángulos de incidencia en la
Tierra (figura izquierda), se infiere que el comportamiento debería ser,
efectivamente, una sinusoide.
Se puede apreciar que los registros de incidencia solar presentan una
laguna significativa y varias irregularidades. Se pretende buscar alguna
relación entre estos datos y los comandos recibidos remotamente. De la
misma manera, se espera que exista una relación directa con los
distintos eventos como eclipses que puedan haber sucedido.
El resto de los datos corresponden a eventos puntuales, salvo los datos
sobre información de vuelo y de distancia con el sol. Estos se
utilizarán posteriomente para relacionar los valores de consumo y de
incidencia solar.
Propuesta de trabajo
====================
Debido al tamaño de los datos, se considera poco viable analizar toda la
información en conjunto. Lo anterior principalmente debido a que al
intentar visualizar todas las mediciones de los sistemas térmicos, se
tuvo problemas en la capacidad computacional del equipo en donde se
realizaba la tarea (i7-4600m Quad-2.9GHz, 8GB RAM).
Se considera entonces la opción de realizar segmentación de la
información por rangos según los eventos visibles en cuanto a la
recepción de luz. A partir de esta segmentación se propone buscar la
superposición entre los datos para verificar si existen relaciones y
posteriormente procesar los datos de forma más depurada.
Considerando lo anterior, se propone realizar las siguientes tareas:
- Preparar y segmentar la información de incidencia solar y compararla
con la información sobre eclipses, distancias con el sol, dirección
de la nave y comandos enviados.
- Preparar la información de consumo energético para realizar
clustering. El proposito de esto será encontrar los sistemas que
sean de calefacción/refrigeración y así también separar idealmente
los 33 circuitos térmicos según los 7 sensores que lleva la nave.
Lo anterior permitirá generar una estimación de relación de los datos.
Se entiende que esta estimación puede no ser correcta debido al poco
conocimiento específico del dominio del problema. Debido a lo anterior,
se propone iterar con secciones de los datos para buscar la validación
de las relaciones.
Si bien, se es consciente de la falta de experiencia en el proceso, se
pretende que posterior a lo anterior sea posible introducir los datos a
WEKA o R y se probará con distintos algoritmos para buscar una
clasificación adecuada y construir un modelo que pueda enviado al
concurso para su evaluación.
Estado del Arte
===============
Tanto la Agencia Espacial Europea como la NASA han lanzado anteriormente
varios concursos públicos de investigación. Entre algunos de estos hay
algoritmos de optimización, algoritmos de detección planetaria,
prototipos de robots de exploración, desarrollo de aplicaciones móviles,
etc.
En relación a los ángulos de incidencia solar, existe una amplia
bibliografía sobre la incidencia solar sobre la superficie terrestre.
Según el Ngram de Google, este tiene su peak alrededor de 1980, por lo
que se considera que estos conceptos tienen una madurez suficiente.
\
Figura 8. Resultados de búsquedas de incidencia solar e irradiación
solar
Para el caso de este proyecto, la incidencia debe ser calculada sobre un
satelite, por lo que se prevee se puedan extender los conceptos
anteriores.
Con respecto a la información de los sistemas a bordo de la nave, sus
comandos y el funcionamiento de los mismos, es poca la información
disponible en la página del concurso. Se prevee que el entendimiento de
estos sean de poca relevancia, sin embargo se considera que en la medida
enque se profundize sobre los datos, se tenga una mejor comprensión
sobre los datos anteriores.
Introducción
============
El Mars Express Power Challenge tiene como objetivo predecir el consumo
de los circuitos eléctricos de calefacción y refrigeración de un
satélite de exploración en la órbita de Marte, necesarios para el
correcto funcionamiento de los equipos de exploración científica de la
nave.
Para realizar dicha predicción se tienen un set de entrenamiento
correspondiente a los datos de tres años marcianos (q año marciano son
687 días terrestres) y un set de pruebas correspondiente al cuarto año.
Cada set está compuesto por cinco subsets de datos de entrenamiento y un
subset de los valores que se desean predecir. Los datos para
entrenamiento tienen que ver con comandos que se envían a la nave,
ángulos de incidencia solar, posición del satélite con respecto a marte
y la tierra, eventos tales como eclipses. Los datos a predecir indican
el valor de corriente de cada uno de los 33 circuitos eléctricos.
La forma de evaluar la predicción consiste en enviar un archivo de
predicción, con promedios por cada hora, para un año y los 33 circuitos.
La precisión de la medición se calculará mediante el *Root Mean Square
Error (RMSE)* que se calcula de la siguiente forma:
$\epsilon = \sqrt[]{\frac{1}{NM}\sum{(c_{ij}-r_{ij})^{2}}}$
$\epsilon$: root mean square error $c_{ij}$: valor i-ésimo de predicción
en el cuarto año$r_{ij}$: valor i-ésimo de referencia en el cuarto año
$N$: número total de muestras para un año $i \in [1,N]$ with $N<=16488$
$M$: número total de parámetros $j \in [1,M]$ with $M=33$
Para poder realizar una predicción, se utilizó un método de predicción
de valores continuos. A esta categoría de predicción se le conoce como
regresión. Existen varias técnicas de regresión, como primer
acercamiento se aplicó RandomForest, visto en clase para clasificación,
el cual tiene también aplicaciones sobre regresión.
Para la visualización y la implementación del algoritmo se utilizó R en
RStudio. Lo anterior no descarta que puedan aplicarse otras herramientas
como Python o MatLab para realizar el (pre) procesamiento de los datos.
Visualización
=============
Con el objetivo de obtener una primera impresión de los datos, se
procedió a graficar y tabular estos en bruto y buscar correlaciones
superficiales entre los datos. De los sets de datos entregados, algunos
se pueden visualizar:
**POWER: Consumo energético, variable a predecir**
 **Figura 1.** Suma de potencias para el
primer año $power$
**SAAF: Aspectos solares**
 **Figura 2.** Incidencia Solar
para el primer año $saaf\$sa$
**LTDATA: Información de periodos extendidos**
 **Figura 3.** Distancia Sol-Marte para
el primer año
Los otros sets del problema tienen datos que no se pueden visualizar de
forma directa. Estos están estructurados en el siguiente formato:
**DMOP: Detalles de la planificación de operación**
**Tabla 1.** Muestra registros de dmop.csv\
ut\_ms subsystem
--------------- -----------
1219363211000 AXXX301A
1219364909000 AAAAF20C1
1219364924000 AAAAF60A1
1219366035000 AXXX380A
1219366635000 ASEQ4200
1219367381000 ATTTF301E
\
**FTL: Eventos de la trayectoria de la nave**
**Tabla 2.** Muestra registros de ftl.csv\
utb\_ms ute\_ms type flagcomms
--------------- --------------- ------- -----------
1219363213000 1219365494000 EARTH FALSE
1219369619000 1219370253000 SLEW FALSE
1219370253000 1219373093000 NADIR FALSE
1219373093000 1219374563000 SLEW FALSE
1219376633000 1219381144000 EARTH TRUE
\
**EVTF: Otros eventos**
**Tabla 3.** Muestra registros de evtf.csv\
ut\_ms description
--------------- ----------------------------------------------------------------------------------------
1219365755000 “NNO\_AOS\_05\_/\_RTLT\_02373”
1219368640000 “4000\_KM\_DESCEND”
1219369280000 “MRB\_/\_RANGE\_06000KM\_START”
1219369855000 “OCC\_MARS\_200KM\_START\_/\_RA\_181.68\_/\_OMP\_(296.35 -46.48)\_/\_SZA\_077”
1219369949000 “OCC\_MARS\_START\_/\_RA\_181.69\_/\_DE\_-00.08\_/\_OMP\_(299.32 -43.44)\_/\_SZA\_076”
\
Al graficar los valores de potencia, los datos de incidencia solar y los
datos de misión, se puede apreciar que existe una ligera correlación
entre los anteriores, por lo que se procedió a trabajar sobre estos
datos en primera instancia.
Hipótesis
=========
La hipótesis inicial es que existe una predicción *gruesa* y una
predicción *fina*. La predicción gruesa tiene que ver con los datos de
incidencia solar y eventos de la nave. La predicción fina tiene que ver
con los datos de eventos y de comandos de la nave.
Los datos de comandos y de eventos se dejarán por fuera en esta primera
instancia. Se considera que el procesamiento sobre estos datos debe ser
mayor, ya que requiere generar periodos de ventana, lo cual se considera
más complejo, ya que requiere identificar correlaciones entre los
distintos circuitos y entre los distintos comandos, los cuales no están
especificados como ’ON’ y ’OFF’ o de forma similar, como se puede
apreciar en las Tablas 1, 2 y 3.
Visualización
=============
Con el objetivo de obtener una impresión de los datos, se procedió a
graficar estos en bruto y buscar correlaciones entre los datos.
Los sets del problema tienen los siguientes datos: SAAF: Aspectos
solares DMOP: Detalles de la planificación de operación FTL: Eventos de
la trayectoria de la nave EVTF: Otros eventos LTDATA: Información de
periodos extendidos POWER: Consumo energético
Al graficar distintas variables por separado, se pueden obtener los
siguientes gráficas:
Al graficar los valores de potencia, los datos de incidencia solar y los
datos de misión, se puede apreciar que existe una correlación entre los
anteriores, por lo que se procedió a trabajar sobre estos datos en
primera instancia.
Hipótesis
=========
La hipótesis inicial es que existe una predicción gruesa y una
predicción fina. La predicción gruesa tiene que ver con los datos de
incidencia solar y eventos de la nave. La predicción fina tiene que ver
con los datos de eventos y de comandos de la nave.
Los datos de comandos y de eventos se dejarán por fuera en esta primera
instancia. Se considera que el procesamiento sobre estos datos debe ser
mayor, ya que requiere generar periodos de ventana, lo cual se considera
más complejo, ya que requiere identificar correlaciones entre los
distintos circuitos y entre los distintos comandos, los cuales no están
especificados como ’ON’ y ’OFF’ o de forma similar.
En este trabajo se avanzará sobre la hipótesis de la predicción gruesa.
Para poder realizar predicción sobre los datos es necesario pre-procesar
los datos para colocarlos en escalas de tiempos similares. Para esto se
requerirá realizar un match en la escala temporal (’ut~m~s’) de los
valores de incidencia solar con los de de potencia de entrada. Esta
escala se encuentra en tiempo UNIX de milisegundos(POSIX), por lo que
será necesario convertirlos a DateTime para facilitar su análisis.
Debido a que los valores para predicción se deben entregar como promedio
por hora, será necesario calcular el promedio de los datos de
entrenamiento, agrupados por hora y crear un nuevo dataframe con estos.
Posteriormente se realizará un merge sobre las tablas de valores antes
calculadas para tener una sola tabla sobre la cual se entrenará al
sistema.
Con el fin de poder realizar una correcta predicción, es necesario
interpolar los valores faltantes para los valores de la misión de la
nave, ya que estos últimos se reciben una vez al día.
Con la intención de probar que el modelo ha sido correctamente
entrenado, se entrenará al sistema con un conjunto de los datos y se
evaluará con otro conjunto. Para este fin se ha dividido el set de un
año en dos.
Finalmente se realizarán mediciones para comprobar si este esquema de
predicción es satisfactorio.
Pre-procesamiento
=================
Para convertir la escala temporal de los datos se utiliza el comando
as.POSIXct, con inicio de valores en 1970-01-01.( =======
Pre-procesamiento de los datos
==============================
Escala temporal
---------------
Para convertir la escala temporal de los datos se utiliza el comando
as.POSIXct, considerando el cambio entre milisegundos a segundos y con
inicio de valores en 1970-01-01.[^1]
``` {.r language="R"}
power1DT <- power1
power1DT$ut_ms <- as.POSIXct((((power1['ut_ms'])/1000)[,]), origin="1970-01-01")
```
**Tabla 4.** Conversión de la escala temporal\
old(ut\_ms) new(DateTime)
------------------ ---------------------
1.2193632130E+12 21/08/2008 20:00:13
1.2193632350E+12 21/08/2008 20:00:35
1.2193632950E+12 21/08/2008 20:01:35
1.2193633550E+12 21/08/2008 20:02:35
Agrupación por hora
-------------------
Se agruparon los valores por horas con dos intenciones. En primera
instancia, el resultado de las predicciones debe entregarse en promedios
por hora. Si bien, se considera que las predicciones pueden ser mucho
más adecuadas si se utilizan todos los valores existentes, por motivos
de capacidad computacional se decidió promediar para disminuir la
cantidad de valores en los dataFrames, con lo que el procesamiento se
puede acelerar.
Para agrupar los valores por hora, se ocupa el comando *cut*, seguido de
*group\_by*[^2]:
``` {.r language="R"}
power1DT$ut_ms <- cut(power1DT$ut_ms, breaks="hour")
power1DTHourMean <- power1DT %>% group_by(ut_ms) %>% summarise_each(funs(mean))
```
El resultado de esta operación disminuyó, para el frame *power*, el
número de filas de *1830121* a *16454*.
Match de escalas temporales
---------------------------
Para poder entrenar el modelo, es necesario que los valores estén en el
mismo instante temporal, de lo contrario, un valor de potencia en un
instante *t* podría tener un valor de incidencia solar *NA*. El match se
hace considerando como origen el tiempo del vector de potencias.
``` {.r language="R"}
power1DTHourMeanMS <- power1DTHourMean$ut_ms
for (i in 1:nrow(ltdata1DTHM)) {
nearest <- findInterval(ltdata1DTHM$ut_ms[i],power1DTHMms)
ltdata1DTHM$ut_ms[i] <- power1DTHMms[nearest]
}
```
El resultado de esta operación busca en *ltdata* y *saaf* el valor de
*ut\_ms* más cercando en *power* y lo reemplaza.
Interpolación de valores faltantes
----------------------------------
Los valores de *ltdata* se entregan originalmente uno por día. Para una
correcta predicción es necesario interpolar estos valores para cada
hora. Como se trata de distancias y angulos entre planetas y el sol, se
puede interpolar linearmente todos los puntos faltantes. Lo anterior se
realiza mediante *na.spline* y *na.approx*[^3]
``` {.r language="R"}
ltdata1DTHM$sunmars_km <- na.spline(ltdata1DTHM[,2],na.rm = FALSE)
ltdata1DTHM$earthmars_km <- na.spline(ltdata1DTHM[,3],na.rm = FALSE)
ltdata1DTHM$sunmarsearthangle_deg <- na.spline(ltdata1DTHM[,4],na.rm = FALSE)
ltdata1DTHM$solarconstantmars <- na.spline(ltdata1DTHM[,5],na.rm = FALSE)
ltdata1DTHM$occultationduration_min <- na.spline(ltdata1DTHM[,6],na.rm = FALSE)
ltdata1DTHM$eclipseduration_min <- na.approx(ltdata1DTHM[,7],na.rm = FALSE, rule=2)
```
Unión de valores
----------------
Posterior a realizar todos los cambios en los frames *power*, *ltdata* y
*saaf*, se deben unir estos valores para tener un solo dataframe para
entrenamiento. Esto se puede realizar mediante *merge*:
``` {.r language="R"}
power1DTHM<-merge(x=power1DTHM, y=saaf1DTHM, by="ut_ms", all.x=TRUE)
power1DTHM<-merge(x=power1DTHM, y=ltdata1DTHM, by="ut_ms", all.x=TRUE)
```
El resultado es un frame que tiene la escala de tiempo, todas las
columnas de *power*, *ltdata* y *saaf*. \>\>\>\>\>\>\>
8b5b14284ae74b723b867a49161463a10792aa7e
[^1]: UNIX TIME: <https://en.wikipedia.org/wiki/Unix_time>
[^2]: group\_by: library(dplyr)
[^3]: na.spline, na.approx: library(zoo)
En este trabajo se avanzará sobre la hipótesis de la predicción gruesa.
Para poder realizar predicción sobre los datos es necesario pre-procesar
los datos para colocarlos en escalas de tiempos similares. Para esto se
requerirá realizar un match en la escala temporal ($'ut\_ms'$) de los
valores de incidencia solar con los de de potencia de entrada. Esta
escala se encuentra en tiempo UNIX de milisegundos(POSIX), por lo que
será necesario convertirlos a DateTime para facilitar su análisis.
Debido a que los valores para predicción se deben entregar como promedio
por hora, será necesario calcular el promedio de los datos de
entrenamiento, agrupados por hora y crear un nuevo dataframe con estos.
Posteriormente se realizará un merge sobre las tablas de valores antes
calculadas para tener una sola tabla sobre la cual se entrenará al
sistema.
Con el fin de poder realizar una correcta predicción, es necesario
interpolar los valores faltantes para los valores de la misión de la
nave, ya que estos últimos se reciben una vez al día.
Con la intención de probar que el modelo ha sido correctamente
entrenado, se entrenará al sistema con un conjunto de los datos y se
evaluará con otro conjunto. Para este fin se ha dividido el set de un
año en dos.
Finalmente se realizarán mediciones para comprobar si este esquema de
predicción es satisfactorio.
Procesamiento de los datos
==========================
Random Forest
-------------
Para la regresión se ocupó *Random Forest*[^1]. La forma de ocupar la
librería es intuitiva, se debe entrenar el modelo con un set y probarlo
con otro. La forma de entrenar el set está dado por el siguiente código:
``` {.r language="R"}
predictField <- 5 #Indice de la columna que se va a predecir
predictCols <- colnames(power1DT[,-1])
train <- power1DTHourMean[1:12000,-1]
test <- power1DTHourMean[12001:16000,-1]
colName <- predictCols[predictField]
rf <- randomForest(as.formula(paste(colName," ~ .")) ,data=train, ntree=10)
```
Para utilizar el modelo generado se utiliza el comando *predict*.
``` {.r language="R"}
predicted <- predict(rf, test)
```
Existen varias limitantes encontradas durante el procesamiento de los
datos, estas se discutirán en las conclusiones, sin embargo, se
consiguió lograr un error bajo para varios campos, por lo que se
consideró aceptable el método empleado.
Calculo de error
----------------
Para el cálculo del error es necesario definir la función entregada por
la evaluación del Mars Challenge.
``` {.r language="R"}
RMSE = function(predicted, reference){
sqrt(mean((predicted - reference)^2))
}
```
Para emplear dicha función, se requieren los valores predichos y la
columna de los valores originales. De la misma manera se propone
graficar los puntos de entrenamiento versus el cálculo obtenido para un
análisis y comparación visual.
``` {.r language="R"}
r2 <- RMSE(predCol, predicted)
p <- ggplot(aes(x=actual, y=pred),
data=data.frame(actual=predCol, pred=predict(rf, test)))
p + geom_point() +
geom_abline(color="red") +
ggtitle(paste("RandomForest Regression RMSE=", r2, sep=""))
```
[^1]: library(randomforest)
Resultados y Conclusiones
=========================
Al aplicar el método anterior se puede realizar una predicción bastante
acertada para varios de los circuitos eléctricos. A continuación se
presentan algunos resultados.
 
\
Figuras 4, 5, 6. Predicción en buenos casos
 
\
Figuras 7, 8, 9. Predicción en malos casos
 \
Figura 10. Mejor predicción: $\epsilon=2.0744e^{-08}$\
Figura 11. Peor predicción: $\epsilon=0.10185$
Como se puede apreciar, la predicción realizada tiene valores de error
muy bajos. En el mejor de los casos, se pudo predecir con un $\epsilon$
de $2.0744e^{-08}$. En el peor de los casos, el error fue de $0.10185$.
Al sumar el error para los 33 circuitos se pudo llegar a un error de
$0.05079785$, lo cual se considera suficiente para esta experiencia.
Como conclusión directa de lo anterior se desprende que el consumo de
potencia tiene una estrecha relación con la cantidad de energía
generada, lo que es intuitivo. Esta idea afirma la hipótesis de que
existe una predicción gruesa y una fina.
Para poder considerar los otros sets de datos se considera realizar un
pre-procesamiento adicional a los datos, como por ejemplo, encontrar la
relación entre el consumo de los circuitos y la emisión de los comandos.
De la misma manera, la incidencia solar tiene una dependencia sobre los
eclipses solares. Este también sería una hipótesis sobre la cual
avanzar.
Durante el (pre)procesamiento de los datos se encontraron varias
dificultades, principalmente relacionadas con las capacidades
computaciones. Procesar todos los datos sin agruparlos por hora conllevó
tiempos extendidos, este tradeoff seguramente podría incrementar los
valores de predicción, sin embargo se descarta para el desarrollo de
este trabajo.
|
Java
|
UTF-8
| 1,668
| 2.5
| 2
|
[] |
no_license
|
package dcms.c;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tool {
public static boolean validDate(String input) {
String pat = "\\d{8}" ;
Pattern p = Pattern.compile(pat) ;
Matcher m = p.matcher(input) ;
return m.matches();
}
public static void printF(String server) {
List<F> flight = FData.getInstance().init(server);
for(F f:flight) {
System.out.println(f.getRecordID()+"\t"+f.getDeparture()+"\t"+f.getDestination()+"\t"+f.getDepartureDate()
+"\t"+f.getBalanceFirstTickets()+"/"+f.getBalanceBusinessTickets()+"/"+f.getBalanceEconomyTickets());
}
}
public static byte[] convert(Object ts) {
byte[] data = null;
try {
data = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));
oos.writeObject(ts);
oos.flush();
data = bos.toByteArray();
oos.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static Object resolve(byte[] data) {
Object ts = null;
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(data)));
ts = ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ts;
}
}
|
SQL
|
UTF-8
| 45,482
| 2.9375
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 11-02-2020 a las 20:52:28
-- Versión del servidor: 10.4.6-MariaDB
-- Versión de PHP: 7.1.32
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `desgodb`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `acabados_ec`
--
CREATE TABLE `acabados_ec` (
`ID_AC` int(11) NOT NULL,
`PISO_AC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`PUERTAS_AC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`VENTANA_AC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`REVESTIMIENTOPARED_AC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`REVESTIMIENTOCUBIERTA_AC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TUMBADO_AC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ENERGIAELECTRICAP_AC` char(100) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ELRMINACIONEXCRETAS_AC` char(100) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOACABADO_AC` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `caracteristicasconstruccionlote`
--
CREATE TABLE `caracteristicasconstruccionlote` (
`ID_CCLOTE` int(11) NOT NULL,
`ID_PH_CCLOTE` int(11) NOT NULL,
`ID_CBP_CCLOTE` int(11) NOT NULL,
`ID_DDB_CCLOTE` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `caracterizacionlote`
--
CREATE TABLE `caracterizacionlote` (
`ID_CLOTE` int(11) NOT NULL,
`ID_II_CLOTE` int(11) NOT NULL,
`AREA_CLOTE` decimal(10,0) DEFAULT NULL,
`DIMENSIONFRENTE_CLOTE` decimal(10,0) DEFAULT NULL,
`LOCALIZACIONMANZANA_CLOTE` char(2) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `circulo_m`
--
CREATE TABLE `circulo_m` (
`ID_CC` int(11) NOT NULL,
`ID_M` int(11) NOT NULL,
`LATITUD_CC` decimal(10,0) DEFAULT NULL,
`LONGITUD_CC` decimal(10,0) DEFAULT NULL,
`X_CC` decimal(10,0) DEFAULT NULL,
`Y_CC` decimal(10,0) DEFAULT NULL,
`Z_CC` decimal(10,0) DEFAULT NULL,
`AREA_CC` decimal(10,0) DEFAULT NULL,
`DIAMETRO_CC` decimal(10,0) DEFAULT NULL,
`PERIMETRO` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `clavebloquepiso_cclote`
--
CREATE TABLE `clavebloquepiso_cclote` (
`ID_CBP_CCLOTE` int(11) NOT NULL,
`CODIGOUBICACION_CBP_CCLOTE` char(16) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CODIGOBLOQUE_CBP_CCLOTE` char(3) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CODIGOPISO_CBP_CCLOTE` char(2) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CODIGOUNIDAD_CBP_CCLOTE` char(3) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CLAVEBLOQUEPISO_CBP_CCLOTE` char(24) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `conyuge_pnpro`
--
CREATE TABLE `conyuge_pnpro` (
`ID_PNPRO2` int(11) NOT NULL,
`ID_PNPRO` int(11) DEFAULT NULL,
`NAPELLIDO_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NDIDENTIFICACION_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TELEFONO_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CORREO_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOIDENTIFICACION_CON_PNPRO` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CONDICIONFISICA_CON_PNPRO` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `coopropietarios_illote`
--
CREATE TABLE `coopropietarios_illote` (
`ID_COP_ILLOTE` int(11) NOT NULL,
`NAPELLIDOS_COP_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NDIDENTIFICACION_COP_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`PORCENTAJE_COP_ILLOTE` decimal(10,0) DEFAULT NULL,
`ALICUOTA_COP_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`FESCRITURA_COP_ILLOTE` date DEFAULT NULL,
`FINSCRIPCION_COP_ILLOTE` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cuadrado_m`
--
CREATE TABLE `cuadrado_m` (
`ID_C` int(11) NOT NULL,
`ID_M` int(11) NOT NULL,
`LATITUD_C` decimal(10,0) DEFAULT NULL,
`LONGITUD_C` decimal(10,0) DEFAULT NULL,
`X_C` decimal(10,0) DEFAULT NULL,
`Y_C` decimal(10,0) DEFAULT NULL,
`Z_C` decimal(10,0) DEFAULT NULL,
`AREA_C` decimal(10,0) DEFAULT NULL,
`PERIMETRO_C` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `datosdescriptivosbloque_cclote`
--
CREATE TABLE `datosdescriptivosbloque_cclote` (
`ID_DDB_CCLOTE` int(11) NOT NULL,
`NIVELPISO_DDB_CCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CONDICIONFISICA_DDB_CCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`VALORCULTURAL_DDB_CCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ESTADOCONSERVACION_DDB_CCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ANIOCONSTRUCCION_DDB_CCLOTE` int(11) DEFAULT NULL,
`ANIORESTAURACION_DDB_CCLOTE` int(11) DEFAULT NULL,
`AREACONSTRUIDA_DDB_CCLOTE` decimal(10,0) DEFAULT NULL,
`USOCONSTRUCTIVOPISO_DDB_CCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `datosdunidad_vclote`
--
CREATE TABLE `datosdunidad_vclote` (
`ID_DDU_VCLOTE` int(11) NOT NULL,
`CLASIFICACIONVIVIENDA_DDU_VCLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPODOCUMENTO_DDU_VCLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOVIVIENDA_DDU_VCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CONDICIONOCUPACION_DDU_VCLOTE` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`DESCRIPCIONDOCIDEN_DDU_VCLOTE` char(255) COLLATE utf8_spanish2_ci DEFAULT NULL,
`APJEFEHGAR_DDU_VCLOTE` char(255) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `ddescriptivospredio_iulote`
--
CREATE TABLE `ddescriptivospredio_iulote` (
`ID_DDPLOTE` int(11) NOT NULL,
`ID_DLOTE` int(11) NOT NULL,
`NOMBRESECTOR_DDPLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NOMBREEDIFICIO_DDPLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`USOPREDIO_DDPLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOPREDIO_DDPLOTE` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL,
`REGIMENTENECIA_DDPLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `direccion_ddplote`
--
CREATE TABLE `direccion_ddplote` (
`ID_DLOTE` int(11) NOT NULL,
`CALLEP_DLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NO_DLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`INTERSECCION_DLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `direccion_illote`
--
CREATE TABLE `direccion_illote` (
`ID_DIR_ILLOTE` int(11) NOT NULL,
`PAIS_DIR_ILLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CIUDAD_DIR_ILLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CALLEP_DIR_ILLOTE` char(100) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NO_DIR_ILLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`INTERSECCIOM_DIR_ILLOTE` char(100) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CELULAR_DIR_ILLOTE` char(15) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CONVENCIONAL_DIR_ILLOTE` char(15) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CORREO` char(100) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `documentotitulopro_illote`
--
CREATE TABLE `documentotitulopro_illote` (
`ID_DOC_ILLOTE` int(11) NOT NULL,
`NNOTARIA_DOC_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CANTONITITULO_DOC_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`FECHAINSCRIPCION_DOC_ILLOTE` date DEFAULT NULL,
`FECHAPROTOCOLIZACION_DOC_ILLOTE` date DEFAULT NULL,
`INCRIPCIONTITULO_DOC_ILLOTE` char(4) COLLATE utf8_spanish2_ci DEFAULT NULL,
`AREA_DOC_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`UNIDADES_DOC_ILLOTE` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `economialote`
--
CREATE TABLE `economialote` (
`ID_ELOTE` int(11) NOT NULL,
`AVALUOTIERRA_ELOTE` decimal(10,0) DEFAULT NULL,
`AVALUOCON_ELOTE` decimal(10,0) DEFAULT NULL,
`AVALUOTOTAL_ELOTE` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `economialote`
--
INSERT INTO `economialote` (`ID_ELOTE`, `AVALUOTIERRA_ELOTE`, `AVALUOCON_ELOTE`, `AVALUOTOTAL_ELOTE`) VALUES
(1, '2', '150', '152'),
(2, '11', '150', '161');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `elementosconstructivos`
--
CREATE TABLE `elementosconstructivos` (
`ID_EC` int(11) NOT NULL,
`ID_EST` int(11) NOT NULL,
`ID_AC` int(11) NOT NULL,
`NB_EC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NP_EC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`UC_EC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CUBIERTA_EC` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`USOCONSTRUCCION_EC` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `estructura_ec`
--
CREATE TABLE `estructura_ec` (
`ID_EST` int(11) NOT NULL,
`COLUMNAS_EST` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`VIGA_EST` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`PARED_EST` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ENTREPISO_EST` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `formulario`
--
CREATE TABLE `formulario` (
`ID_FORMULARIO` int(11) NOT NULL,
`ID_CLOTE` int(11) NOT NULL,
`ID_ELOTE` int(11) NOT NULL,
`ID_VCLOTE` int(11) NOT NULL,
`ID_RLOTE` int(11) NOT NULL,
`ID_MLOTE` int(11) NOT NULL,
`ID_LLOTE` int(11) NOT NULL,
`ID_ILLOTE` int(11) NOT NULL,
`ID_GPLOTE` int(11) NOT NULL,
`ID_EC` int(11) NOT NULL,
`ID_IULOTE` int(11) NOT NULL,
`ID_CCLOTE` int(11) NOT NULL,
`ID_M` int(11) NOT NULL,
`ID_USUARIO` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `graficosprediolote`
--
CREATE TABLE `graficosprediolote` (
`ID_GPLOTE` int(11) NOT NULL,
`PLANOPREDIO_GPLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`FOTOGRAFIAFACHADA` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `identificacionlegallote`
--
CREATE TABLE `identificacionlegallote` (
`ID_ILLOTE` int(11) NOT NULL,
`ID_PRO` int(11) NOT NULL,
`ID_PRE_ILLOTE` int(11) NOT NULL,
`ID_COP_ILLOTE` int(11) NOT NULL,
`ID_DIR_ILLOTE` int(11) NOT NULL,
`ID_DOC_ILLOTE` int(11) NOT NULL,
`FORMAADQUISICION` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `identificacionubicacionlote`
--
CREATE TABLE `identificacionubicacionlote` (
`ID_IULOTE` int(11) NOT NULL,
`ID_DDPLOTE` int(11) NOT NULL,
`CLAVECATASTRALANTIGUO_IULOTE` char(26) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NUMEROPREDIO_IULOTE` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CLAVECATASTRALNUEVO_IULOTE` char(26) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `infraestructurainst_clote`
--
CREATE TABLE `infraestructurainst_clote` (
`ID_II_CLOTE` int(11) NOT NULL,
`AGUA_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ALCANTARILLADO_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ENERGIAELECTRICA_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`VIAURBANA_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOVIAACCESO` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`INFRAESTRUCTURAVIAL_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`OTROSSERVICIOS_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TELEFONO_II_CLOTE` char(30) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `instalacionnivelv_vclote`
--
CREATE TABLE `instalacionnivelv_vclote` (
`ID_INV_VCLOTE` int(11) NOT NULL,
`ACABADOPISO_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`EACABADOPISO_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`AGUAP_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`AGUAR_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`EEXCRETAS_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ENERGIAEP_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ELIMINACIONBASURA_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TENENCIAVIVIENDA_INV_VCLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NUMEROHABITACION_INV_VCLOTE` int(11) DEFAULT NULL,
`NUMERODORMITORIO_INV_VCLOTE` int(11) DEFAULT NULL,
`ESPACIODUCHARSE_INV_VCLOTE` int(11) DEFAULT NULL,
`NUMEROHABITANTES` int(11) DEFAULT NULL,
`NUMEROHOGARES_INV_VCLOTE` int(11) DEFAULT NULL,
`TELEFONOCONVENCIONAL_INV_VCLOTE` tinyint(1) DEFAULT NULL,
`NUMEROCELULARES_INV_VCLOTE` int(11) DEFAULT NULL,
`SERVICIOINTERNET_INV_VCLOTE` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `limiteslote`
--
CREATE TABLE `limiteslote` (
`ID_LLOTE` int(11) NOT NULL,
`NOMBRECOLINDANTES_LLOTE` char(255) COLLATE utf8_spanish2_ci DEFAULT NULL,
`AREAESCRITURA_LLOTE` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `lineas_m`
--
CREATE TABLE `lineas_m` (
`ID_L` int(11) NOT NULL,
`ID_M` int(11) NOT NULL,
`LATITUD_L` decimal(10,0) DEFAULT NULL,
`LONGITUD_L` decimal(10,0) DEFAULT NULL,
`X_L` decimal(10,0) DEFAULT NULL,
`Y_L` decimal(10,0) DEFAULT NULL,
`Z_L` decimal(10,0) DEFAULT NULL,
`DISTANCIA_L` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `mapa`
--
CREATE TABLE `mapa` (
`ID_M` int(11) NOT NULL,
`NAME_M` varchar(60) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ADDRESS_M` varchar(80) COLLATE utf8_spanish2_ci DEFAULT NULL,
`LAT_M` float(10,6) DEFAULT NULL,
`LNG_M` float(10,6) DEFAULT NULL,
`TYPE_M` varchar(30) COLLATE utf8_spanish2_ci DEFAULT NULL,
`X_M` float DEFAULT NULL,
`Y_M` float DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `mejoraslote`
--
CREATE TABLE `mejoraslote` (
`ID_MLOTE` int(11) NOT NULL,
`TIPOOBRA_MLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`MATERIALES_MLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`AREA_MLOTE` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `persona`
--
CREATE TABLE `persona` (
`ID_PERSONA` int(11) NOT NULL,
`PNOMBRE_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`SNOMBRE_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`PAPELLIDO_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`SAPELLIDO_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TELEFONO_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CORREO_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CARGO_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`PROFESION_PERSONA` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CEDULA_PERSONA` varchar(10) COLLATE utf8_spanish2_ci NOT NULL,
`FOTO_PERSONA` varchar(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`EMPRESA_PERSONA` varchar(100) COLLATE utf8_spanish2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `persona`
--
INSERT INTO `persona` (`ID_PERSONA`, `PNOMBRE_PERSONA`, `SNOMBRE_PERSONA`, `PAPELLIDO_PERSONA`, `SAPELLIDO_PERSONA`, `TELEFONO_PERSONA`, `CORREO_PERSONA`, `CARGO_PERSONA`, `PROFESION_PERSONA`, `CEDULA_PERSONA`, `FOTO_PERSONA`, `EMPRESA_PERSONA`) VALUES
(1, 'Edwin', 'Giovanny', 'Cuichan', 'Tipan', '0984467071', 'egct@outlook.es', 'Administrador', 'Ingeniero', '1723953053', 'http://lacarpa.com.mx/wp-content/uploads/2019/06/whats-appfoto-perfil.png', 'DESGO'),
(2, 'Alexander', 'Sebastian', 'Portilla', 'Bravo', '0984467072', 'alexander@outlook.es', 'Root', 'Ingeniero sistemas', '1723953054', 'http://lacarpa.com.mx/wp-content/uploads/2019/06/whats-appfoto-perfil.png', 'DESGO'),
(7, 'Carlos', 'Alexis', 'Cabascango', 'Arias', '022385592', 'ca@outlook.es', 'root', 'Desarrollador', '1723953055', NULL, 'DESGO'),
(13, 'Carla', 'Alexa', 'Cab', 'Ari', '022385593', 'cabs@outlook.es', 'root', 'Desarrollador', '1723953056', 'http://lacarpa.com.mx/wp-content/uploads/2019/06/whats-appfoto-perfil.png', 'EMAPSQ'),
(17, 'egct2', 'edwin', 'cuichan', 'egct2', '0984467073', 'egct2@outlook.es', 'Superisor', 'Ingeniero', '1723953054', 'topologiaredTotal.png', 'EMAPSQ');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `personajuridica_pro`
--
CREATE TABLE `personajuridica_pro` (
`ID_PJURI` int(11) NOT NULL,
`RAZONSOCIAL_PJURI` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`RUC_PJURI` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`LUGARINSCRIPCION_PJURI` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NACUERDOREGISTRO_PJURI` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NOMBREREPRESENTANTE_PJURI` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`INSCRITO_PJURI` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOIDENTIFICACION_PJURI` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `personanatural_pro`
--
CREATE TABLE `personanatural_pro` (
`ID_PNPRO` int(11) NOT NULL,
`NAPELLIDO_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NDIDENTIFICACION_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TELEFONO_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CORREO_CON_PNPRO` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ESTADOCIVIL_PNPRO` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`TIPOIDENTIFICACION_CON_PNPRO` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CONDICIONFISICA_CON_PNPRO` char(20) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `ph_cclote`
--
CREATE TABLE `ph_cclote` (
`ID_PH_CCLOTE` int(11) NOT NULL,
`ALICUOTA_PH_CCLOTE` decimal(10,0) DEFAULT NULL,
`AREADECLARADA_PH_CCLOTE` decimal(10,0) DEFAULT NULL,
`UNIDADMEDIDA_PH_CCLOTE` char(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`AREAAUEMENTOCONSTRUCTIVO_PH_CCLOTE` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `poligono_m`
--
CREATE TABLE `poligono_m` (
`ID_POL` int(11) NOT NULL,
`ID_M` int(11) NOT NULL,
`LATITUD_POL` decimal(10,0) DEFAULT NULL,
`LONGITUD_POL` decimal(10,0) DEFAULT NULL,
`X_POL` decimal(10,0) DEFAULT NULL,
`Y_POL` decimal(10,0) DEFAULT NULL,
`Z_POL` decimal(10,0) DEFAULT NULL,
`AREA_POL` decimal(10,0) DEFAULT NULL,
`PERIMETRO_POL` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `prediotitulo_illote`
--
CREATE TABLE `prediotitulo_illote` (
`ID_PRE_ILLOTE` int(11) NOT NULL,
`REQUIEREPERF_PRE_ILLOTE` tinyint(1) DEFAULT NULL,
`ANIOSSINPER_PRE_ILLOTE` char(4) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ANIOSPOS_PRE_ILLOTE` char(4) COLLATE utf8_spanish2_ci DEFAULT NULL,
`NOMBREPUEBLO_PRE_ILLOTE` char(250) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `propietariotipoj`
--
CREATE TABLE `propietariotipoj` (
`ID_PJURI` int(11) NOT NULL,
`ID_PRO` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `propietariotipon`
--
CREATE TABLE `propietariotipon` (
`ID_PNPRO` int(11) NOT NULL,
`ID_PRO` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `propietario_illote`
--
CREATE TABLE `propietario_illote` (
`ID_PRO` int(11) NOT NULL,
`TIPOPROPIETARIO_PER` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL,
`PERSONERIAJURIDICA_PER` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `punto_m`
--
CREATE TABLE `punto_m` (
`ID_P` int(11) NOT NULL,
`ID_M` int(11) NOT NULL,
`LATITUD_P` decimal(10,0) DEFAULT NULL,
`LONGITUD_P` decimal(10,0) DEFAULT NULL,
`X_P` decimal(10,0) DEFAULT NULL,
`Y_P` decimal(10,0) DEFAULT NULL,
`Z_P` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `responsableslote`
--
CREATE TABLE `responsableslote` (
`ID_RLOTE` int(11) NOT NULL,
`ACTUALIZADORCEDULAPASAPORTE_RLOTE` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL,
`ACTUALIZADORFECHA_RLOTE` date DEFAULT NULL,
`ACTUALIZADORFIRMA_RLOTE` char(255) COLLATE utf8_spanish2_ci DEFAULT NULL,
`FISCALIZADORCEDULAPASAPORTE_RLOTE` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL,
`FISCALIZADORFECHA_RLOTE` date DEFAULT NULL,
`FISCALIZADORFIRMA_RLOTE` char(255) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tipousuario`
--
CREATE TABLE `tipousuario` (
`ID_TIPOUSUARIO` int(11) NOT NULL,
`NIVEL_TIPOUSUARIO` char(40) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `tipousuario`
--
INSERT INTO `tipousuario` (`ID_TIPOUSUARIO`, `NIVEL_TIPOUSUARIO`) VALUES
(1, 'Administrador'),
(2, 'Visualizador'),
(3, 'Gestor');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario`
--
CREATE TABLE `usuario` (
`ID_USUARIO` int(11) NOT NULL,
`ID_TIPOUSUARIO` int(11) NOT NULL,
`ID_PERSONA` int(11) NOT NULL,
`USUARIO_USUARIO` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`CONTRASENIA_USUARIO` char(100) COLLATE utf8_spanish2_ci DEFAULT NULL,
`EMPRESA_USUARIO` char(25) COLLATE utf8_spanish2_ci DEFAULT NULL,
`SALT_USUARIO` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `usuario`
--
INSERT INTO `usuario` (`ID_USUARIO`, `ID_TIPOUSUARIO`, `ID_PERSONA`, `USUARIO_USUARIO`, `CONTRASENIA_USUARIO`, `EMPRESA_USUARIO`, `SALT_USUARIO`) VALUES
(1, 1, 1, 'egct', 'f9d4e342924e42f41f4833df59e19a8e417a7c7b955796ddcaadea1400fd133b', 'DESGO', 100),
(2, 2, 2, 'aspb', 'aspb', 'DESGO', 0),
(6, 2, 7, 'cabas', 'cabas', 'DESGO', 0),
(9, 2, 13, 'cab', 'cab', 'DESGO', 0),
(13, 2, 17, 'egct2', 'egct2', 'DESGO', 0),
(14, 2, 7, 'ca', 'f58593ec0e0de29e091db9b23e19fd5d9c24423b503db0460c45a1b9ae3efa0c', 'DESGO', 620),
(16, 2, 1, 'edwinegct', 'e794d5287493453db702ed5a925d8aaee9a1d6395e5d7cca8f8fbc8a16521d26', 'DESGO', 1705),
(17, 1, 1, 'edwin4', '3a98e531dd2c780c83f81b4a97417f4909b0de2f9fc172ce56bcffd4c8424e12', 'DESGO', 5755);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `viviendacensallote`
--
CREATE TABLE `viviendacensallote` (
`ID_VCLOTE` int(11) NOT NULL,
`ID_DDU_VCLOTE` int(11) NOT NULL,
`ID_INV_VCLOTE` int(11) NOT NULL,
`CODIGOUNIDAD_VCLOTE` char(10) COLLATE utf8_spanish2_ci DEFAULT NULL,
`OBSERVACION_VCLOTE` text COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `acabados_ec`
--
ALTER TABLE `acabados_ec`
ADD PRIMARY KEY (`ID_AC`);
--
-- Indices de la tabla `caracteristicasconstruccionlote`
--
ALTER TABLE `caracteristicasconstruccionlote`
ADD PRIMARY KEY (`ID_CCLOTE`),
ADD KEY `FK_CARACTERISTICAPH` (`ID_PH_CCLOTE`),
ADD KEY `FK_CLAVECARACTERISTICA` (`ID_CBP_CCLOTE`),
ADD KEY `FK_DDESCRIPTIVOCARACTERISTICA` (`ID_DDB_CCLOTE`);
--
-- Indices de la tabla `caracterizacionlote`
--
ALTER TABLE `caracterizacionlote`
ADD PRIMARY KEY (`ID_CLOTE`),
ADD KEY `FK_INFRAESTRUCTURACARACTERIZACION` (`ID_II_CLOTE`);
--
-- Indices de la tabla `circulo_m`
--
ALTER TABLE `circulo_m`
ADD PRIMARY KEY (`ID_CC`),
ADD KEY `FK_CIRCULOM` (`ID_M`);
--
-- Indices de la tabla `clavebloquepiso_cclote`
--
ALTER TABLE `clavebloquepiso_cclote`
ADD PRIMARY KEY (`ID_CBP_CCLOTE`);
--
-- Indices de la tabla `conyuge_pnpro`
--
ALTER TABLE `conyuge_pnpro`
ADD PRIMARY KEY (`ID_PNPRO2`),
ADD KEY `FK_CONYUGEPERSONA` (`ID_PNPRO`);
--
-- Indices de la tabla `coopropietarios_illote`
--
ALTER TABLE `coopropietarios_illote`
ADD PRIMARY KEY (`ID_COP_ILLOTE`);
--
-- Indices de la tabla `cuadrado_m`
--
ALTER TABLE `cuadrado_m`
ADD PRIMARY KEY (`ID_C`),
ADD KEY `FK_CUADRADOM` (`ID_M`);
--
-- Indices de la tabla `datosdescriptivosbloque_cclote`
--
ALTER TABLE `datosdescriptivosbloque_cclote`
ADD PRIMARY KEY (`ID_DDB_CCLOTE`);
--
-- Indices de la tabla `datosdunidad_vclote`
--
ALTER TABLE `datosdunidad_vclote`
ADD PRIMARY KEY (`ID_DDU_VCLOTE`);
--
-- Indices de la tabla `ddescriptivospredio_iulote`
--
ALTER TABLE `ddescriptivospredio_iulote`
ADD PRIMARY KEY (`ID_DDPLOTE`),
ADD KEY `FK_DIRECCIONDESCRIPTIVO` (`ID_DLOTE`);
--
-- Indices de la tabla `direccion_ddplote`
--
ALTER TABLE `direccion_ddplote`
ADD PRIMARY KEY (`ID_DLOTE`);
--
-- Indices de la tabla `direccion_illote`
--
ALTER TABLE `direccion_illote`
ADD PRIMARY KEY (`ID_DIR_ILLOTE`);
--
-- Indices de la tabla `documentotitulopro_illote`
--
ALTER TABLE `documentotitulopro_illote`
ADD PRIMARY KEY (`ID_DOC_ILLOTE`);
--
-- Indices de la tabla `economialote`
--
ALTER TABLE `economialote`
ADD PRIMARY KEY (`ID_ELOTE`);
--
-- Indices de la tabla `elementosconstructivos`
--
ALTER TABLE `elementosconstructivos`
ADD PRIMARY KEY (`ID_EC`),
ADD KEY `FK_ACABADOSEC` (`ID_AC`),
ADD KEY `FK_ESTRUCTURAEC` (`ID_EST`);
--
-- Indices de la tabla `estructura_ec`
--
ALTER TABLE `estructura_ec`
ADD PRIMARY KEY (`ID_EST`);
--
-- Indices de la tabla `formulario`
--
ALTER TABLE `formulario`
ADD PRIMARY KEY (`ID_FORMULARIO`),
ADD KEY `FK_CARACTERIZACIONFORMULARIO` (`ID_CLOTE`),
ADD KEY `FK_CCFORMULARIO` (`ID_CCLOTE`),
ADD KEY `FK_ECFORMULARIO` (`ID_EC`),
ADD KEY `FK_ECONOMIAFORMULARIO` (`ID_ELOTE`),
ADD KEY `FK_GRAFICOSFORMULARIO` (`ID_GPLOTE`),
ADD KEY `FK_IDENTIFICACIONLEGALFORMULARIO` (`ID_ILLOTE`),
ADD KEY `FK_IDENTIFICACIONUBICACIONFORMULARIO` (`ID_IULOTE`),
ADD KEY `FK_LIMITEFORMULARIO` (`ID_LLOTE`),
ADD KEY `FK_MAPAFORMULARIO` (`ID_M`),
ADD KEY `FK_MEJORASFORMULARIO` (`ID_MLOTE`),
ADD KEY `FK_RESPONSABLEFORMULARIO` (`ID_RLOTE`),
ADD KEY `FK_USUARIOFORMULARIO` (`ID_USUARIO`),
ADD KEY `FK_VIVIENDACENSALFORMULARIO` (`ID_VCLOTE`);
--
-- Indices de la tabla `graficosprediolote`
--
ALTER TABLE `graficosprediolote`
ADD PRIMARY KEY (`ID_GPLOTE`);
--
-- Indices de la tabla `identificacionlegallote`
--
ALTER TABLE `identificacionlegallote`
ADD PRIMARY KEY (`ID_ILLOTE`),
ADD KEY `FK_COOPROPIETARIOIDENTIFICACION` (`ID_COP_ILLOTE`),
ADD KEY `FK_DIRECCIONIDENTIFICACION` (`ID_DIR_ILLOTE`),
ADD KEY `FK_DOCUMENTOIDENTIFICACION` (`ID_DOC_ILLOTE`),
ADD KEY `FK_IDENTIFICACIONPREDIO` (`ID_PRE_ILLOTE`),
ADD KEY `FK_PROPIETARIOINDETIFICACION` (`ID_PRO`);
--
-- Indices de la tabla `identificacionubicacionlote`
--
ALTER TABLE `identificacionubicacionlote`
ADD PRIMARY KEY (`ID_IULOTE`),
ADD KEY `FK_IDENTIFICACIONDIRECCION` (`ID_DDPLOTE`);
--
-- Indices de la tabla `infraestructurainst_clote`
--
ALTER TABLE `infraestructurainst_clote`
ADD PRIMARY KEY (`ID_II_CLOTE`);
--
-- Indices de la tabla `instalacionnivelv_vclote`
--
ALTER TABLE `instalacionnivelv_vclote`
ADD PRIMARY KEY (`ID_INV_VCLOTE`);
--
-- Indices de la tabla `limiteslote`
--
ALTER TABLE `limiteslote`
ADD PRIMARY KEY (`ID_LLOTE`);
--
-- Indices de la tabla `lineas_m`
--
ALTER TABLE `lineas_m`
ADD PRIMARY KEY (`ID_L`),
ADD KEY `FK_LINEAM` (`ID_M`);
--
-- Indices de la tabla `mapa`
--
ALTER TABLE `mapa`
ADD PRIMARY KEY (`ID_M`);
--
-- Indices de la tabla `mejoraslote`
--
ALTER TABLE `mejoraslote`
ADD PRIMARY KEY (`ID_MLOTE`);
--
-- Indices de la tabla `persona`
--
ALTER TABLE `persona`
ADD PRIMARY KEY (`ID_PERSONA`);
--
-- Indices de la tabla `personajuridica_pro`
--
ALTER TABLE `personajuridica_pro`
ADD PRIMARY KEY (`ID_PJURI`);
--
-- Indices de la tabla `personanatural_pro`
--
ALTER TABLE `personanatural_pro`
ADD PRIMARY KEY (`ID_PNPRO`);
--
-- Indices de la tabla `ph_cclote`
--
ALTER TABLE `ph_cclote`
ADD PRIMARY KEY (`ID_PH_CCLOTE`);
--
-- Indices de la tabla `poligono_m`
--
ALTER TABLE `poligono_m`
ADD PRIMARY KEY (`ID_POL`),
ADD KEY `FK_POLIGONOM` (`ID_M`);
--
-- Indices de la tabla `prediotitulo_illote`
--
ALTER TABLE `prediotitulo_illote`
ADD PRIMARY KEY (`ID_PRE_ILLOTE`);
--
-- Indices de la tabla `propietariotipoj`
--
ALTER TABLE `propietariotipoj`
ADD PRIMARY KEY (`ID_PJURI`,`ID_PRO`),
ADD KEY `FK_PROPIETARIOTIPOJ2` (`ID_PRO`);
--
-- Indices de la tabla `propietariotipon`
--
ALTER TABLE `propietariotipon`
ADD PRIMARY KEY (`ID_PNPRO`,`ID_PRO`),
ADD KEY `FK_PROPIETARIOTIPON2` (`ID_PRO`);
--
-- Indices de la tabla `propietario_illote`
--
ALTER TABLE `propietario_illote`
ADD PRIMARY KEY (`ID_PRO`);
--
-- Indices de la tabla `punto_m`
--
ALTER TABLE `punto_m`
ADD PRIMARY KEY (`ID_P`),
ADD KEY `FK_PUNTOM` (`ID_M`);
--
-- Indices de la tabla `responsableslote`
--
ALTER TABLE `responsableslote`
ADD PRIMARY KEY (`ID_RLOTE`);
--
-- Indices de la tabla `tipousuario`
--
ALTER TABLE `tipousuario`
ADD PRIMARY KEY (`ID_TIPOUSUARIO`);
--
-- Indices de la tabla `usuario`
--
ALTER TABLE `usuario`
ADD PRIMARY KEY (`ID_USUARIO`),
ADD KEY `FK_GENERAL` (`ID_PERSONA`),
ADD KEY `FK_TIPOUSUARIO` (`ID_TIPOUSUARIO`);
--
-- Indices de la tabla `viviendacensallote`
--
ALTER TABLE `viviendacensallote`
ADD PRIMARY KEY (`ID_VCLOTE`),
ADD KEY `FK_DDVIVIENDA` (`ID_DDU_VCLOTE`),
ADD KEY `FK_INVVIVIENDA` (`ID_INV_VCLOTE`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `acabados_ec`
--
ALTER TABLE `acabados_ec`
MODIFY `ID_AC` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `caracteristicasconstruccionlote`
--
ALTER TABLE `caracteristicasconstruccionlote`
MODIFY `ID_CCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `caracterizacionlote`
--
ALTER TABLE `caracterizacionlote`
MODIFY `ID_CLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `circulo_m`
--
ALTER TABLE `circulo_m`
MODIFY `ID_CC` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `clavebloquepiso_cclote`
--
ALTER TABLE `clavebloquepiso_cclote`
MODIFY `ID_CBP_CCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `conyuge_pnpro`
--
ALTER TABLE `conyuge_pnpro`
MODIFY `ID_PNPRO2` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `coopropietarios_illote`
--
ALTER TABLE `coopropietarios_illote`
MODIFY `ID_COP_ILLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `cuadrado_m`
--
ALTER TABLE `cuadrado_m`
MODIFY `ID_C` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `datosdescriptivosbloque_cclote`
--
ALTER TABLE `datosdescriptivosbloque_cclote`
MODIFY `ID_DDB_CCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `datosdunidad_vclote`
--
ALTER TABLE `datosdunidad_vclote`
MODIFY `ID_DDU_VCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `ddescriptivospredio_iulote`
--
ALTER TABLE `ddescriptivospredio_iulote`
MODIFY `ID_DDPLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `direccion_ddplote`
--
ALTER TABLE `direccion_ddplote`
MODIFY `ID_DLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `direccion_illote`
--
ALTER TABLE `direccion_illote`
MODIFY `ID_DIR_ILLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `documentotitulopro_illote`
--
ALTER TABLE `documentotitulopro_illote`
MODIFY `ID_DOC_ILLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `economialote`
--
ALTER TABLE `economialote`
MODIFY `ID_ELOTE` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `elementosconstructivos`
--
ALTER TABLE `elementosconstructivos`
MODIFY `ID_EC` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `estructura_ec`
--
ALTER TABLE `estructura_ec`
MODIFY `ID_EST` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `formulario`
--
ALTER TABLE `formulario`
MODIFY `ID_FORMULARIO` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `graficosprediolote`
--
ALTER TABLE `graficosprediolote`
MODIFY `ID_GPLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `identificacionlegallote`
--
ALTER TABLE `identificacionlegallote`
MODIFY `ID_ILLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `identificacionubicacionlote`
--
ALTER TABLE `identificacionubicacionlote`
MODIFY `ID_IULOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `infraestructurainst_clote`
--
ALTER TABLE `infraestructurainst_clote`
MODIFY `ID_II_CLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `instalacionnivelv_vclote`
--
ALTER TABLE `instalacionnivelv_vclote`
MODIFY `ID_INV_VCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `limiteslote`
--
ALTER TABLE `limiteslote`
MODIFY `ID_LLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `lineas_m`
--
ALTER TABLE `lineas_m`
MODIFY `ID_L` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `mapa`
--
ALTER TABLE `mapa`
MODIFY `ID_M` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `mejoraslote`
--
ALTER TABLE `mejoraslote`
MODIFY `ID_MLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `persona`
--
ALTER TABLE `persona`
MODIFY `ID_PERSONA` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42;
--
-- AUTO_INCREMENT de la tabla `personajuridica_pro`
--
ALTER TABLE `personajuridica_pro`
MODIFY `ID_PJURI` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `personanatural_pro`
--
ALTER TABLE `personanatural_pro`
MODIFY `ID_PNPRO` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `ph_cclote`
--
ALTER TABLE `ph_cclote`
MODIFY `ID_PH_CCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `poligono_m`
--
ALTER TABLE `poligono_m`
MODIFY `ID_POL` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `prediotitulo_illote`
--
ALTER TABLE `prediotitulo_illote`
MODIFY `ID_PRE_ILLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `propietario_illote`
--
ALTER TABLE `propietario_illote`
MODIFY `ID_PRO` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `punto_m`
--
ALTER TABLE `punto_m`
MODIFY `ID_P` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `responsableslote`
--
ALTER TABLE `responsableslote`
MODIFY `ID_RLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `tipousuario`
--
ALTER TABLE `tipousuario`
MODIFY `ID_TIPOUSUARIO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `usuario`
--
ALTER TABLE `usuario`
MODIFY `ID_USUARIO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
--
-- AUTO_INCREMENT de la tabla `viviendacensallote`
--
ALTER TABLE `viviendacensallote`
MODIFY `ID_VCLOTE` int(11) NOT NULL AUTO_INCREMENT;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `caracteristicasconstruccionlote`
--
ALTER TABLE `caracteristicasconstruccionlote`
ADD CONSTRAINT `FK_CARACTERISTICAPH` FOREIGN KEY (`ID_PH_CCLOTE`) REFERENCES `ph_cclote` (`ID_PH_CCLOTE`),
ADD CONSTRAINT `FK_CLAVECARACTERISTICA` FOREIGN KEY (`ID_CBP_CCLOTE`) REFERENCES `clavebloquepiso_cclote` (`ID_CBP_CCLOTE`),
ADD CONSTRAINT `FK_DDESCRIPTIVOCARACTERISTICA` FOREIGN KEY (`ID_DDB_CCLOTE`) REFERENCES `datosdescriptivosbloque_cclote` (`ID_DDB_CCLOTE`);
--
-- Filtros para la tabla `caracterizacionlote`
--
ALTER TABLE `caracterizacionlote`
ADD CONSTRAINT `FK_INFRAESTRUCTURACARACTERIZACION` FOREIGN KEY (`ID_II_CLOTE`) REFERENCES `infraestructurainst_clote` (`ID_II_CLOTE`);
--
-- Filtros para la tabla `circulo_m`
--
ALTER TABLE `circulo_m`
ADD CONSTRAINT `FK_CIRCULOM` FOREIGN KEY (`ID_M`) REFERENCES `mapa` (`ID_M`);
--
-- Filtros para la tabla `conyuge_pnpro`
--
ALTER TABLE `conyuge_pnpro`
ADD CONSTRAINT `FK_CONYUGEPERSONA` FOREIGN KEY (`ID_PNPRO`) REFERENCES `personanatural_pro` (`ID_PNPRO`);
--
-- Filtros para la tabla `cuadrado_m`
--
ALTER TABLE `cuadrado_m`
ADD CONSTRAINT `FK_CUADRADOM` FOREIGN KEY (`ID_M`) REFERENCES `mapa` (`ID_M`);
--
-- Filtros para la tabla `ddescriptivospredio_iulote`
--
ALTER TABLE `ddescriptivospredio_iulote`
ADD CONSTRAINT `FK_DIRECCIONDESCRIPTIVO` FOREIGN KEY (`ID_DLOTE`) REFERENCES `direccion_ddplote` (`ID_DLOTE`);
--
-- Filtros para la tabla `elementosconstructivos`
--
ALTER TABLE `elementosconstructivos`
ADD CONSTRAINT `FK_ACABADOSEC` FOREIGN KEY (`ID_AC`) REFERENCES `acabados_ec` (`ID_AC`),
ADD CONSTRAINT `FK_ESTRUCTURAEC` FOREIGN KEY (`ID_EST`) REFERENCES `estructura_ec` (`ID_EST`);
--
-- Filtros para la tabla `formulario`
--
ALTER TABLE `formulario`
ADD CONSTRAINT `FK_CARACTERIZACIONFORMULARIO` FOREIGN KEY (`ID_CLOTE`) REFERENCES `caracterizacionlote` (`ID_CLOTE`),
ADD CONSTRAINT `FK_CCFORMULARIO` FOREIGN KEY (`ID_CCLOTE`) REFERENCES `caracteristicasconstruccionlote` (`ID_CCLOTE`),
ADD CONSTRAINT `FK_ECFORMULARIO` FOREIGN KEY (`ID_EC`) REFERENCES `elementosconstructivos` (`ID_EC`),
ADD CONSTRAINT `FK_ECONOMIAFORMULARIO` FOREIGN KEY (`ID_ELOTE`) REFERENCES `economialote` (`ID_ELOTE`),
ADD CONSTRAINT `FK_GRAFICOSFORMULARIO` FOREIGN KEY (`ID_GPLOTE`) REFERENCES `graficosprediolote` (`ID_GPLOTE`),
ADD CONSTRAINT `FK_IDENTIFICACIONLEGALFORMULARIO` FOREIGN KEY (`ID_ILLOTE`) REFERENCES `identificacionlegallote` (`ID_ILLOTE`),
ADD CONSTRAINT `FK_IDENTIFICACIONUBICACIONFORMULARIO` FOREIGN KEY (`ID_IULOTE`) REFERENCES `identificacionubicacionlote` (`ID_IULOTE`),
ADD CONSTRAINT `FK_LIMITEFORMULARIO` FOREIGN KEY (`ID_LLOTE`) REFERENCES `limiteslote` (`ID_LLOTE`),
ADD CONSTRAINT `FK_MAPAFORMULARIO` FOREIGN KEY (`ID_M`) REFERENCES `mapa` (`ID_M`),
ADD CONSTRAINT `FK_MEJORASFORMULARIO` FOREIGN KEY (`ID_MLOTE`) REFERENCES `mejoraslote` (`ID_MLOTE`),
ADD CONSTRAINT `FK_RESPONSABLEFORMULARIO` FOREIGN KEY (`ID_RLOTE`) REFERENCES `responsableslote` (`ID_RLOTE`),
ADD CONSTRAINT `FK_USUARIOFORMULARIO` FOREIGN KEY (`ID_USUARIO`) REFERENCES `usuario` (`ID_USUARIO`),
ADD CONSTRAINT `FK_VIVIENDACENSALFORMULARIO` FOREIGN KEY (`ID_VCLOTE`) REFERENCES `viviendacensallote` (`ID_VCLOTE`);
--
-- Filtros para la tabla `identificacionlegallote`
--
ALTER TABLE `identificacionlegallote`
ADD CONSTRAINT `FK_COOPROPIETARIOIDENTIFICACION` FOREIGN KEY (`ID_COP_ILLOTE`) REFERENCES `coopropietarios_illote` (`ID_COP_ILLOTE`),
ADD CONSTRAINT `FK_DIRECCIONIDENTIFICACION` FOREIGN KEY (`ID_DIR_ILLOTE`) REFERENCES `direccion_illote` (`ID_DIR_ILLOTE`),
ADD CONSTRAINT `FK_DOCUMENTOIDENTIFICACION` FOREIGN KEY (`ID_DOC_ILLOTE`) REFERENCES `documentotitulopro_illote` (`ID_DOC_ILLOTE`),
ADD CONSTRAINT `FK_IDENTIFICACIONPREDIO` FOREIGN KEY (`ID_PRE_ILLOTE`) REFERENCES `prediotitulo_illote` (`ID_PRE_ILLOTE`),
ADD CONSTRAINT `FK_PROPIETARIOINDETIFICACION` FOREIGN KEY (`ID_PRO`) REFERENCES `propietario_illote` (`ID_PRO`);
--
-- Filtros para la tabla `identificacionubicacionlote`
--
ALTER TABLE `identificacionubicacionlote`
ADD CONSTRAINT `FK_IDENTIFICACIONDIRECCION` FOREIGN KEY (`ID_DDPLOTE`) REFERENCES `ddescriptivospredio_iulote` (`ID_DDPLOTE`);
--
-- Filtros para la tabla `lineas_m`
--
ALTER TABLE `lineas_m`
ADD CONSTRAINT `FK_LINEAM` FOREIGN KEY (`ID_M`) REFERENCES `mapa` (`ID_M`);
--
-- Filtros para la tabla `poligono_m`
--
ALTER TABLE `poligono_m`
ADD CONSTRAINT `FK_POLIGONOM` FOREIGN KEY (`ID_M`) REFERENCES `mapa` (`ID_M`);
--
-- Filtros para la tabla `propietariotipoj`
--
ALTER TABLE `propietariotipoj`
ADD CONSTRAINT `FK_PROPIETARIOTIPOJ` FOREIGN KEY (`ID_PJURI`) REFERENCES `personajuridica_pro` (`ID_PJURI`),
ADD CONSTRAINT `FK_PROPIETARIOTIPOJ2` FOREIGN KEY (`ID_PRO`) REFERENCES `propietario_illote` (`ID_PRO`);
--
-- Filtros para la tabla `propietariotipon`
--
ALTER TABLE `propietariotipon`
ADD CONSTRAINT `FK_PROPIETARIOTIPON` FOREIGN KEY (`ID_PNPRO`) REFERENCES `personanatural_pro` (`ID_PNPRO`),
ADD CONSTRAINT `FK_PROPIETARIOTIPON2` FOREIGN KEY (`ID_PRO`) REFERENCES `propietario_illote` (`ID_PRO`);
--
-- Filtros para la tabla `punto_m`
--
ALTER TABLE `punto_m`
ADD CONSTRAINT `FK_PUNTOM` FOREIGN KEY (`ID_M`) REFERENCES `mapa` (`ID_M`);
--
-- Filtros para la tabla `usuario`
--
ALTER TABLE `usuario`
ADD CONSTRAINT `FK_GENERAL` FOREIGN KEY (`ID_PERSONA`) REFERENCES `persona` (`ID_PERSONA`),
ADD CONSTRAINT `FK_TIPOUSUARIO` FOREIGN KEY (`ID_TIPOUSUARIO`) REFERENCES `tipousuario` (`ID_TIPOUSUARIO`);
--
-- Filtros para la tabla `viviendacensallote`
--
ALTER TABLE `viviendacensallote`
ADD CONSTRAINT `FK_DDVIVIENDA` FOREIGN KEY (`ID_DDU_VCLOTE`) REFERENCES `datosdunidad_vclote` (`ID_DDU_VCLOTE`),
ADD CONSTRAINT `FK_INVVIVIENDA` FOREIGN KEY (`ID_INV_VCLOTE`) REFERENCES `instalacionnivelv_vclote` (`ID_INV_VCLOTE`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 9,248
| 1.695313
| 2
|
[] |
no_license
|
package com.siloyou.jmsg.modules.sms.task.handler.listener;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.marre.sms.SmsAlphabet;
import org.marre.sms.SmsMsgClass;
import org.marre.sms.SmsTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.google.common.collect.Maps;
import com.siloyou.core.common.utils.FstObjectSerializeUtil;
import com.siloyou.core.common.utils.SpringContextHolder;
import com.siloyou.core.common.utils.StringUtils;
import com.siloyou.core.modules.sys.entity.User;
import com.siloyou.core.modules.sys.utils.UserUtils;
import com.siloyou.jmsg.common.message.SmsMtMessage;
import com.siloyou.jmsg.common.storedMap.BDBStoredMapFactoryImpl;
import com.siloyou.jmsg.common.utils.BlacklistUtils;
import com.siloyou.jmsg.common.utils.CacheKeys;
import com.siloyou.jmsg.common.utils.GatewayUtils;
import com.siloyou.jmsg.common.utils.KeywordsUtils;
import com.siloyou.jmsg.common.utils.PhoneUtils;
import com.siloyou.jmsg.common.utils.SignUtils;
import com.siloyou.jmsg.modules.account.service.JmsgAccountService;
import com.siloyou.jmsg.modules.sms.dao.JmsgSmsSendDao;
import com.siloyou.jmsg.modules.sms.entity.GatewayResult;
import com.siloyou.jmsg.modules.sms.entity.JmsgSmsSend;
import com.siloyou.jmsg.modules.sms.service.SmsSendService;
import com.siloyou.jmsg.modules.sms.task.impl.SmsPushExecutor;
@Service
public class SmsUMTListener implements MessageListenerConcurrently {
public static Logger logger = LoggerFactory.getLogger(SmsUMTListener.class);
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Autowired
private JmsgAccountService jmsgAccountService;
@Autowired
private JmsgSmsSendDao jmsgSmsSendDao ;
@Autowired
private SmsSendService smsSendService;
private static Map<String, Serializable> umtMap = BDBStoredMapFactoryImpl.INS.buildMap("SMS", "UMTTASK");
public int findPayCount(String smsContent) {
SmsTextMessage sms = null;
if (com.siloyou.core.common.utils.StringUtils.haswidthChar(smsContent)) {
sms = new SmsTextMessage(smsContent, SmsAlphabet.UCS2, SmsMsgClass.CLASS_UNKNOWN);
} else {
sms = new SmsTextMessage(smsContent, SmsAlphabet.LATIN1, SmsMsgClass.CLASS_UNKNOWN);
}
return sms.getPdus().length;
}
private GatewayResult gatewayMap(int signFlag, String groupId, String phoneType, String provinceId, String sign,
String userId) {
GatewayResult entity = new GatewayResult();
if (1 == signFlag) {
entity = GatewayUtils.getGateway(userId, groupId, phoneType, provinceId, sign);
} else {
entity = GatewayUtils.getGateway(groupId, phoneType, provinceId);
}
return entity;
}
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
logger.info("umt listener recv message: topic:{}, tags:{}, msgid:{}, key:{}", msg.getTopic(), msg.getTags(),
msg.getMsgId(), msg.getKeys());
long startTime = System.currentTimeMillis();
try {
SmsMtMessage smsRtMessage = (SmsMtMessage) FstObjectSerializeUtil.read(msg.getBody());
smsRtMessage.setMsgContent(SignUtils.formatContent(smsRtMessage.getMsgContent()));
logger.info("CMPP模拟网关,开始处理放库发送: 任务ID:{}, 用户:{}, 手机号码:{}, 接收时间:{} ", smsRtMessage.getTaskid(), smsRtMessage.getUserid(), smsRtMessage.getPhone(), startTime);
String dataId = "99";
String taskId = smsRtMessage.getTaskid();
String userId = smsRtMessage.getUserid();
String phones = smsRtMessage.getPhone();
String smsContent = smsRtMessage.getMsgContent();
String reportGaetewayId = smsRtMessage.getUserReportGateWayID();
String spNumber = smsRtMessage.getSpNumber();
String pushFlag = smsRtMessage.getUserReportNotify();
String topic = CacheKeys.getSmsBatchTopic();
User user = UserUtils.get(userId);
String sign = SignUtils.get(smsContent);
int payCount = findPayCount(smsContent);
String smsType = payCount > 1 ? "2" : "1";
String payType = UserUtils.getPayMode(userId, "sms");
String payStatus = "1";
int money = 0;
int index = 0;
String[] phoneList = phones.split(",");
SqlSession sqlSession = this.sqlSessionFactory.openSession(ExecutorType.BATCH, false);
try {
for (String phone : phoneList) {
JmsgSmsSend jmsgSmsSend = new JmsgSmsSend();
jmsgSmsSend.setDataId(dataId);
jmsgSmsSend.setTaskId(taskId);
jmsgSmsSend.setPhone(phone);
jmsgSmsSend.setSmsContent(smsContent);
jmsgSmsSend.setSmsType(smsType);
jmsgSmsSend.setPayCount(payCount);
jmsgSmsSend.setUser(user);
String sendStatus = "P000";
// 1:校验 0: 不校验
if (user.getSysBlacklistFlag() == 1 && BlacklistUtils.isExistSysBlackList(phone))
{
// 判断是否系统黑名单
sendStatus = "F002";
}
else if (user.getUserBlacklistFlag() == 1 && BlacklistUtils.isExistUserBlackList(phone))
{
// 判断是否营销黑名单
sendStatus = "F008";
}
if("1".equals(user.getFilterWordFlag())){//过滤敏感词
String keywords = KeywordsUtils.keywords(smsContent.trim());
if(StringUtils.isNotBlank(keywords)) {
sendStatus = "F020";
}
}
Map<String, String> phoneMap = PhoneUtils.get(phone);
String phoneType = "";
String cityCode = "";
if ((phoneMap == null) || (phoneMap.size() < 2)) {
sendStatus = "F0170";
jmsgSmsSend.setSendDatetime(new Date());
} else {
phoneType = PhoneUtils.getPhoneType(phoneMap);
cityCode = PhoneUtils.getCityCode(phoneMap);
if ((StringUtils.isBlank(cityCode)) || (StringUtils.isBlank(phoneType))) {
sendStatus = "F0170";
jmsgSmsSend.setSendDatetime(new Date());
} else {
GatewayResult gatewayResult = gatewayMap(user.getSignFlag(), user.getGroupId(),
phoneType, cityCode.substring(0, 2), sign, userId);
if (gatewayResult.isExists()) {
jmsgSmsSend.setChannelCode(gatewayResult.getGatewayId());
String tdSpNumber = gatewayResult.getSpNumber();
if ((StringUtils.isNotBlank(spNumber)) && (spNumber.startsWith(tdSpNumber))) {
tdSpNumber = spNumber;
}
if(StringUtils.isNotBlank(tdSpNumber) && tdSpNumber.length() > 20) {
tdSpNumber = tdSpNumber.substring(0, 20);
}
jmsgSmsSend.setSpNumber(tdSpNumber);
} else {
sendStatus = gatewayResult.getErrorCode();
jmsgSmsSend.setSendDatetime(new Date());
}
}
}
jmsgSmsSend.setPhoneType(phoneType);
jmsgSmsSend.setAreaCode(cityCode);
jmsgSmsSend.setPayType(payType);
jmsgSmsSend.setPayStatus(payStatus);
jmsgSmsSend.setPushFlag(pushFlag);
jmsgSmsSend.setSendStatus(sendStatus);
jmsgSmsSend.setSubmitMode(reportGaetewayId);
jmsgSmsSend.setTopic(topic);
jmsgSmsSend.setReportGatewayId(reportGaetewayId);
money += payCount;
//入库
jmsgSmsSendDao.insert(jmsgSmsSend);
Map<String,String> map = Maps.newHashMap();
map.put("id", jmsgSmsSend.getId());
if(StringUtils.startsWith(sendStatus, "F")) { //更新结果
map.put("sendStatus", sendStatus);
map.put("msgid", "0000");
} else { //发送队列
map = smsSendService.sendHandler(jmsgSmsSend);//发送短信处理
}
index++;
sqlSession.update("com.siloyou.jmsg.modules.sms.dao.JmsgSmsSendDao.batchUpdate",map);
// sqlSession.insert("com.siloyou.jmsg.modules.sms.dao.JmsgSmsSendDao.insert", jmsgSmsSend);
if (index % 100 == 0) {
sqlSession.commit();
}
}
sqlSession.commit();
logger.info("CMPP模拟网关,发送结束: 任务ID:{}, 耗时:{}s",smsRtMessage.getTaskid(), (System.currentTimeMillis() - startTime)/1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
if (money > 0) {
// this.jmsgAccountService.consumeMoney(userId, "02", money, "sms", "" + taskId + ")", userId, taskId);
//推送
// SmsPushExecutor smsPushExecutor = new SmsPushExecutor(taskId);
// smsPushExecutor.run();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}
|
Markdown
|
UTF-8
| 42,861
| 2.8125
| 3
|
[] |
no_license
|
Java (이것이 자바다, 신용권 지음)
Effective-Java (이펙티브 자바, 죠슈아 블로크 지음)
## 문법
[variable]()
[mathod]()
[number]()
[boolean]()
[if]()
[Switch Case]()
[charAt(int) indexOf(str) substring(int1, int2) length()]()
[while]()
[Collection](https://github.com/tesschung/Java/blob/master/09_Collection.md)
[Stream]()
[Input&Output]()
정리중
---
[TOC]
# 참고
[생활코딩 자료정리](http://tcpschool.com/java/java_collectionFramework_stackQueue)
[자바의 정석](https://www.youtube.com/user/MasterNKS)
# 자바
**"한 번만 작성하면, 어디서든 동작한다. (Write Once, Run Anywhere.)"**
'`자바 가상머신`'이라는 것만 설치되면, 어느 운영체제이든, 어느 디바이스이든, 동일하게 동작합니다. (자바 가상머신, Java Virtual Machine, **JVM**)
**JRE** (Java Runtime Environment) JVM을 사용해서 마음껏 개발할 수 있는 환경
내 컴퓨터에 이런 환경을 만들기 위해서는 **JDK** (Java Development Kit) 라는 것을 설치
**객체 지향 프로그래밍 (Object Oriented Programming, OOP)**은 프로그램을 작성하는 기법
- 부품에 해당하는 객체 (Object)를 먼저 만들고, 이것들을 하나씩 조립 및 연결해서 전체 프로그램을 완성하는 기법
`Java project` 생성 -> `Class` 생성 순
Class의 변수명은 항상 대문자로 시작
Eclipse 삽질했다.
Package명을 꼭 작성하고 시작할 것.
- package
- 클래스를 계층적으로 분리해서 저장하는 방식
- .으로 구분하고 이름의 유일성을 보장하기 위해 인터넷 도메인 명을 뒤집에서 사용한다.
- `ArithmeticException` 산술/연산예외
```java
try {
int z = 10%0;
System.out.println(z);
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없다.");
}
```
그렇다고 해서 실수 타입인 0.0 또는 0.0f로 나누면 `ArithmeticException`이 발생하는 것이 아니라 `Infinity`(/ 경우)와 `NaN`(% 경우)이 산출되어 데이터가 엉망이 된다.
```java
double x = 0.0;
int a = 10;
double z = a % x;
if (Double.isInfinite(z) || Double.isNaN(z)) {
System.out.println("값 산출 불가.");
} else {
System.out.println(z);
}
```
- Str1.`equals(str2)`
원본 문자열과 매개 값으로 주어진 비교 문자열이 동일한지 비교한 후 true 또는 false를 리턴한다. (즉, 객체가 참조하고 있는 주소값과는 상관없이 변수가 담고있는 값만을 비교한다.)
- Arrays.`deepEquals`(a, b) && Objects.`deepEquals`(a, b)
객체 깊은 비교
- Arrays.`equals`(a, b) && Objects.`equals`(a, b)
객체 얕은 비교
- `sout` == System.out.println()
- 표현할 수 있는 범위에 따라 정해짐
- 뒤로갈 수록 표현할 수 있는 범위가 작다
`double` - `float` - `long` - `int` - `short` - `byte`
```java
int i = 10;
if (i % 3 == 0) { // i < 20 : 불린 식, 변수, 메소드
System.out.println("C 구역입니다.");
} else if (1 % 3 == 1) {
System.out.println("A 구역입니다.");
} else {
System.out.println("B 구역입니다.");
}
switch (i % 3) { // i : 불린이 아닌 식, 변수, 메소드
case 0:
System.out.println("C 구역입니다.");
break;
case 1:
System.out.println("A 구역입니다.");
break;
default:
System.out.println("B 구역입니다.");
break;
}
```
- `.toCharArray`()
```java
// 스트링을 배열로 만든다.
char[] charArray = dna.toCharArray();
```
- 함수
- 함수와 메서드
- 메서드 파라미터 전달 방식 비교
- Java에서 함수와 메소드는 동일하게 사용
- 메소드가 좀 더 기술적으로 맞는 묭어
- 클래스 내부에 있는 함수를 특별히 메소드라고 함
- Main 메소드가 길어지면 클래스로 분리 또는 여러 함수로 분리 가능
```java
메소드 구조
- 반환값 타입(없으면 void)
- 메소드 이름
- 파라미터 타입과 이름
- 메소드 구현부
- 반환할 결과가 있으면 return
가변인자
public static double average(double... values) {
double sum = 0;
for (double v : values) sum += v;
return values.Length == 0 ? 0 : sum / values.Length;
}
```
- Call by Value(Primitive) vs Call by Reference
- 기본 primitive
- 기본 자료형에 적용
- 변수에 값 자체를 저장
- 변수를 복사하면 값 자체를 복사
- 객체 reference
- 배열이나 객체를 참조
- 변수에는 값이 아니라 객체의 주소 참조값이 저장
- 변수를 복사하면 주소가 복사되어 하나의 객체를 참조
- 객체지향프로그래밍 **OOP** Object Oriented Programming
정보와 동작들을 객체 단위로 묶고, 이런 객체들을 연결시키면서 정리하는 프로그래밍 방식
**'객체'**는 '속성'들과 '동작'들의 묶음
속성은 **'변수'**로 나타내고, 동작은 **'메소드(함수)'**로 나타낸다.
- 클래스란
객체의 설계도
- Property
- Method
- 클래스에 있는 함수
- 인스턴스
- 클래스를 기반으로 만들어진 객체
- Song - 걱정말아요 그대, 거위의 꿈
- Person - 김신의, 문종모, 성태호
- 기본형 **Primitive Type** VS 참조형 **Reference Type**
- 기본형 **Primitive Type**
- Int, boolean, char, double
- 변수가 그 값을 직접적으로 보관
- 참조형 **Reference Type** // 배열을 포함한 객체
- Person, String, int[]
- 실제 값은 메모리에 저장, 변수는 그 영역을 가르킨다.
- null은 참조형 변수만 가질 수 있는 값이다.
- `null`을 보관하고 있는 변수의 메소드를 호출하려고 하면 `NullPointerException`이라는 오류가 난다.
```java
Person[] people = new Person[5];
people[0] = new Person("김신의", 28);
people[2] = new Person("문종모", 26);
people[3] = new Person("서혜린", 21);
for (int i = 0; i < people.length; i++) {
Person p = people[i];
if (p != null) {
System.out.println(p.getName());
} else {
System.out.println(i + "번 자리는 비었습니다.");
}
}
```
- Short-Circuit Evaluation
- And 연산 &&
```java
boolean newBoolean = m1() && m2() && m3();
```
`newBoolean`이 `true`가 되기 위해서는 `m1()`, `m2()`, `m3()`가 모두 `true`를 리턴
따라서 `m1()`이 `false`를 리턴하면 `m2()`와 `m3()`의 결과와 상관 없이 `newBoolean`은 `false`
실제로 자바는 효율성을 위해서 `m1()`이 `false`를 리턴하면 `m2()`와 `m3()`를 실행하지 않는다.
이렇게 식의 결과값이 이미 결정된 경우 미리 멈추는 것을 **'숏서킷 연산(Short-circuit evaluation)'**.
- Or 연산 ||
```java
boolean newBoolean = m1() || m2() || m3();
```
`newBoolean`이 `false`이기 위해서는 `m1()`, `m2()`, `m3()`의 리턴값이 모두 `false`이어야한다.
따라서 `m1()`이 `true`를 리턴하면 `m2()`와 `m3()`는 실행되지 않고 `newBoolean`은 `true`가 된다.
- 기본형 참조형
- 2
- 4
- [person, null] [26, 0]. 1
- [27,0] [person, person] [28,0] 3
- `"".isEmpty()`의 결과값은 `true`이고 `"abc".isEmpty()`의 결과값은 `false`
- null 퀴즈
- 3
- `s`는 `null`이기 때문에, `if`문의 첫 번째 조건`s != null`의 값은 `false`입니다.
앞쪽 메소드가 `false`를 리턴하면 뒤쪽 메소드도 실행됩니다. 그런데 `s`가 `null`인 상황에서 `s.isEmpty()`는 `NullPointerException` 에러
- - ```java
String s = null;
// s.isEmpty() => true
// => !true -> false
if (s != null || !s.isEmpty()) {
System.out.println("Answer A");
} else {
System.out.println("Answer B");
}
```
-
- 2
- if문의 첫 번째 조건부터 봅시다. `str != null`은 원소가 `null`인지 체크하는 조건
- `null`이 아니라면 `true`를 리턴
두 번째 조건`!str.isEmpty()`은 문자열 `str`이 빈 문자열인지 확인합니다. `strings[2].isEmpty()`의 경우 `true`를 리턴하겠죠.
그런데, 두 조건이 and 연산(`&&`)으로 연결
숏서킷 연산에 의해 첫 번째 조건이 `true`인 경우, 즉 `str`이 `null`이 아닌 경우에만 두 번째 조건을 수행
그렇기 때문에 앞 문제에서처럼 `NullPointerException`은 발생하지 않는다.
자, 두 조건문을 연결해서 생각해보면, 이 if문은:
1. `str`이 `null`이 아니면서 빈 문자열도 아닐 경우 `countA`를 하나 증가
2. `str`이 `null`이거나 빈 문자열(`""`)인 경우 `countB`를 하나 증가
그러므로 `null`인 `strings[1]`, `strings[3]`의 경우, 그리고 빈 문자열인 `strings[2]`의 경우 `countB`가 증가 되어, 최종적으로 `3`이 출력
```java
String[] strings = new String[5];
// [null, null, null, null, null]
strings[0] = "Hello";
strings[2] = "";
strings[4] = "Java";
// ["Hello", null, "", null, "Java"]
// 2, 3
int countA = 0, countB = 0;
for (String str : strings) {
if (str != null && !str.isEmpty()) {
countA++;
} else {
countB++;
}
}
System.out.println(countB);
```
- `final` // 변수 안전하게 만들기
- `변수`를 정의할 때 `final`을 써주면, 그 변수는 '상수'가 된다. 즉, 한 번 정의하고 나서 다시 바꿀 수 없다는 것
```java
final double pi = 3.141592;
pi = 2.54; // java: cannot assign a value to final variable name
```
- `메소드`를 final로 선언하면 서브클래스에서 오버라이딩 불가
- `클래스`를 final로 선언하면 서브클래스를 만들 수 없다.
- 코드안전하게 만들기 `try-catch` 예외처리
- ```java
try {
// 오류를 발생시킬 수 있는 코드
} catch (Exception e) {
// 오류가 발생한 경우 해결
System.out.println(e.getMessage());
}
```
- ```java
int[] smallArray = new int[3];
for (int i=0; i <10; i++) {
try {
smallArray[i] = i;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
// 결과확인
for (int i:smallArray) {
System.out.println(i);
}
```
- 예외처리를 하여 프로그램이 죽지않고 예외부분은 메세지로, 그리고 그 외에 처리된 부분은 정상적으로 처리된 것을 확인 할 수 있다.
- Try-with-resource -> resource를 확실히 닫아주어 코드가 간결해진다.
- Exception re-throwing 예외 다시 던지기
- 예외 발생 시 당장 처리 방법을 모르는 경우
- 시스템 예외를 잡아서 사용자 정의 예외로 다시 던질 때
- Checked Exception을 잡아서 Unchecked Exception으로 다시 던질때
```java
try {
..데이터 베이스에 접근하는 코드..
} catch (SQLException se) {
throw new MyException(se); // 사용자 정의 exception을 만들어서 파라미터로 다시 던짐.
}
1.
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class LilicReader {
public void doJob() {
Path path = Paths.get("tes.txt");
// Scanner이라는 생성자에서 IOException발생하므로
// 예외 처리를 해야한다.
// try-with-resource
try(Scanner in = new Scanner(path, "UTF-8")) { // 자원을 해제할때 문제가 생기는 try-catch를 해결
// try-with-resource 문법으로 in.close() 코드를 작성하지 않고도 파일이 닫아지므로 안정적이다.
in.useDelimiter("\n");
while (in.hasNext()) {
System.out.println(in.next());
}
// 반드시 in.close()를 해줘야 한다.
// 그래야 다른 파일에서 파일을 사용할 수 있기 때문이다.
// in.close();
} catch (IOException ie) {
// 정상적으로 종료
// System.out.println("error occured");
throw new BizException("파일이 없습니다.", ie);
}
}
}
2.
// 사용자 정의로 던진 예외를 받는 곳
public class BizException extends RuntimeException{
public BizException() {
super();
}
public BizException(String msg) {
super(msg);
}
public BizException(Exception e) {
super(e);
}
public BizException(String msg, Exception e) {
super(msg, e);
}
}
3.
import java.io.IOException;
public class ExceptionTest {
public static void main(String[] args) {
LilicReader reader = new LilicReader();
try {
reader.doJob();
} catch (BizException e) {
System.out.println(e);
}
}
}
```
- 인스턴스 변수 vs 클래스 변수
- 인스턴스 변수 버전
- ```java
public class Person {
int count;
}
```
- Person 클래스에 count라는 인스턴스 변수가 있다. 해당 변수는 총 몇개의 Person 인스턴스가 있는지 보관한다.
- ```java
public static void main(String[] args) {
Person p1 = new Person();
p1.count++;
Person p2 = new Person();
p1.count++;
p2.count = p1.count;
Person p3 = new Person();
p1.count++;
p2.count++;
p3.count = p2.count;
Person p4 = new Person();
p1.count++;
p2.count++;
p3.count++;
p4.count = p3.count;
System.out.println(p1.count); // 4
System.out.println(p2.count); // 4
System.out.println(p3.count); // 4
System.out.println(p4.count); // 4
```
- 이 경우 새로운 Person 인스턴스를 생성할때마다 각 count 변수를 바꿔줘야 올바른 값이 나온다.
- 클래스 변수 버전
- 인스턴스화 시키지 않고 사용하고 싶을때 static을 사용한다.
- static value, static method 모두 가능
- 클래스 변수를 정의하기 위해 `static`이라는 키워드를 붙여준다.
- ```java
public class Person {
static int count;
}
```
- 이렇게 `static`으로 해두면 count는 특정 인스턴스에만 해당되는 것이 아니라 Person 클래스 전체에 해당된다. 따라서 count를 부를때는 `클래스이름.count`로 부른다.
```java
public static void main(String[] args) {
Person p1 = new Person();
Person.count++;
Person p2 = new Person();
Person.count++;
Person p3 = new Person();
Person.count++;
Person p4 = new Person();
Person.count++;
System.out.println(Person.count); // 4
}
```
- 하지만, Person.count를 매번 선언해줘야 한다는 단점, 그래서 생성을 할때 내부적으로 count가 가능하게 하면 더욱 깔끔한 코드를 작성할 수 있다.
- ```java
public class Person {
static int count;
public Person() {
count++;
}
}
```
- ```java
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
Person p4 = new Person();
System.out.println(Person.count);
}
```
- 상수
- 좀 더 상수를 상수답게 사용하기
- public `static` `final` double PI = 3.141592653589793;
- static과 final를 함께 써야한다. 왜냐하면 상수는 인스턴트에만 해당하는 것이 아니고 여러 복사본 대신 한 값만 저장해두는 것이 맞기 때문이다.
- 상수이름은 보통 `대문자`로 작성, 단어가 여러개인 경우`_`로 구분 짓는다.
- 클래스 메소드
- `클래스 변수`는 `클래스에 속한 변수`
- `클래스 메소드`는 `클래스에 속한 메소드`
- 인스턴스 메소드는 인스턴스에 속해있어서 인스턴스를 반드시 생성해야 사용할 수 있지만, 클래스 메소드는 클래스에 속한 것이므로 인스턴스를 생성하지 않고 사용할 수 있다.
```java
import java.lang.Math;
public class Driver {
public static void main(String[] args) {
System.out.println(Math.abs(-10)); // 절댓값
System.out.println(Math.max(3, 7)); // 두 값 중 최댓값
System.out.println(Math.random()); // 0.0과 1.0 사이의 랜덤값
}
}
```
Math 클래스에서 바로 메소드를 사용하는 경우를 확인할 수 있다.
```java
public class Counter {
static int count;
public static void increment() {
count++;
}
public static void main(String[] args) {
System.out.println(Counter.count); // 0
Counter.increment();
System.out.println(Counter.count); // 1
Counter.increment();
System.out.println(Counter.count); // 2
Counter.increment();
System.out.println(Counter.count); // 3
}
}
```
- String 클래스
- ```java
String myString = "aBc";
System.out.println(myString.toUpperCase()) // 모두 대문자로
System.out.println(myString.toLowerCase()) // 모두 소문자로
System.out.println(myString) // 그대로
```
```java
String myString = "aBc";
System.out.println(myString.toLowerCase() == "abc");
// false
```
```java
String myString = "aBc";
System.out.println(myString.toLowerCase().equals("abc"));
// true
```
- Math 클래스
```java
import java.lang.Math;
public class Driver {
public static void main(String[] args) {
System.out.println(Math.abs(-10)); // 10
System.out.println(Math.abs(8)); // 8
System.out.println(Math.min(4, 10)); // 최솟값 4
System.out.println(Math.max(4, 10)); // 최댓값 10
}
}
```
- Random 클래스
```java
import java.util.Random;
public class Driver {
public static void main(String[] args) {
Random rand = new Random();
System.out.println(rand.nextInt(10)); // 0 이상 9 이하의 랜덤한 값
// Random rand = new Random();
int min = 10;
int max = 30;
System.out.println(rand.nextInt((max - min) + 1) + min); // 10 이상 30 이하의 랜덤한 값
}
}
```
- Wrapper 클래스
- 기본 자료형을 객체 형식으로 감싸는 역할
- `Integer` 클래스는 `int`형을, `Double` 클래스는 `double`을, `Long` 클래스는 `long`을, `Boolean` 클래스는 `boolean`을 감싸는 것
- 이러한 Wrapper 클래스가 필요한 이유는 기본형 자료형을 참조형처럼 다뤄야 할 경우가 있을때다.
- ```java
Integer i = new Integer(123);
Integer i = 123;
```
```java
System.out.println(123 == 123);
System.out.println(new Integer(123) == new Integer(123));
// true
// false
```
```java
System.out.println(new Integer(123).equals(new Integer(123)));
// true
```
- HashMap
```java
import java.util.ArrayList;
import java.util.HashMap;
public class HashMapPrac {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("이상해");
// HashMap
// Key -> Value
HashMap<String, String> pokedex = new HashMap<String, String>();
pokedex.put("피카츄","피카츄");
pokedex.put("라이츄", "라이츄");
pokedex.remove("이상해풀");
// 찾고자 하는 value에 해당하는 key를 파라미터로 넘겨준다.
String poke003 = pokedex.get("이상해꽃");
// 같은 key에 여러 value를 저장하면 가장 마지막에 저장된 value로 덮어씌워진다.
pokedex.put("피카츄", "피카츄3");
for (String key:pokedex.keySet()) {
System.out.println(key + pokedex);
}
}
}
```
- HashMap의 key는 'hashcode'라는 것으로 관리된다.
- 이 `hashcode`는 모든 클래스의 인스턴스가 가진 고유한 값인데, 인스턴스마다 다르기 때문에 HashMap이 key를 구분하는 값으로 사용된다.
- 여러 인스턴스가 같은 hashcode를 가질 수 있으며, 이 경우 HashMap에선 key.equals(anotherKey)메소드로 구분
- 그런데 `String`은 서로 다른 인스턴스라도 안의 내용이 같으면 같은 hashcode를 갖는다. 그렇기 때문에 `HashMap`의 key로서 `String`이 매우 적합
- Key는 실제 인스턴스보다는 안에 담긴 의미, 내용으로 구분하는 것이 좋기 때문
- 상속 `extends`
- 슈퍼클래스(부모)와 서브클래스(자식)간의 관계가 상속으로 이루어진다.
- is-a 관계
- 잔액이라는 속성과 입금기능은 셋다 가지고 있음
- 출금 또한. 하지만 하나는 다르다.

- MinimumBalanceAccount와 SavingsAccount가 BankAccount를 상속
- 상속받으면 중복된 코드를 상속받으므로 코드가 중복적으로 적힐 필요 없다.
- MinimumBalanceAccount -> 출금을 `@Override`
- `@Override`와 같이 골뱅이(`@`)가 붙어있는 문법을 '어노테이션(Annotation)'. 주석(Comment)과 어느정도 비슷하지만, 어노테이션은 자바에서 추가적인 기능을 제공
- `@Override`를 써줬는데 부모 클래스에 같은 이름의 메소드가 없는 경우, 오류

```java
public class BankAccount {
private int balance;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
// 출금
public boolean withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
return true;
}
return false
}
// 입금
public boolean deposit(int amount) {
balance += amount;
return true;
}
}
```
```java
public class SavingsAccount extends BankAccount {
private double interest;
public void setInterest(double interest) {
this.interest = interest;
}
public double getInterest() {
return interest;
}
public void addInterest() {
// balance는 부모클래스에서 private이므로 부모의 method로 접근해야한다.
setBalance((int) (getBalance() * (1 + interest)));
}
}
```
```java
public class MinimumBalanceAccount extends BankAccount {
private int minimum;
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getMinimum() {
return minimum;
}
// MinimumBalanceAccount의 인스턴스는 BankAccount의 withdraw가 아닌 MinimumBalanceAccount의 withdraw를 호출
@Override
public boolean withdraw(int amount) {
if (getBalance() - amount < minimum) {
System.out.println("적어도 " + minimum + "원은 남겨야 합니다.");
return false;
}
setBalance(getBalance() - amount);
return true;
}
}
```
- super
- 상속을 받은 자식키워드가 사용
- 자식클래스가 1. 부모클래스의 변수, 메소드를 사용할 때 2. 부모클래스의 생성자를 사용할 때
- super(변수) super.메소드()
- **(1)** 자식클래스의 인스턴스 생성시 부모클래스의 생성자는 반드시 불린다. 인스턴스 생성시 생성자 호출은 필수
- ```java
Child c = new Child(); // Child 인스턴스 생성시 Parent의 생성자도 불림
```
- 부모에서 this.balance 자식에서 super(balance)
- **(2)** 부모클래스의 생성자가 없는 경우에 부모클래스의 기본 생성자가 불린다. **즉, 파라미터가 없는 생성자가 없는 경우, 자식 클래스에서 반드시 직접 (코드로 써서) 부모 클래스의 생성자 호출을 시켜줘야한다.**
- 부모에서 ... , 자식에서 this.balance
- ```java
public class Parent {
// 별도로 생성자가 지정되어있는 경우 (파라미터 없는 기본 생성자가 없는 경우)
public Parent(int a, int b) {
...
}
...
}
public class Child extends Parent {
public Child() {
super(0, 0); // 자식 클래스에 생성자를 만들어 'super(int, int)'를 호출해 주어야 함
...
}
}
```
- 부모클래스에 기본 생성자가 없는 경우 자식 클래스에 생성자를 만들어 부모클래스의 생성자를 호출해야한다.
- 부모클래스의 생성자 호출은 맨 윗줄에 적어야 한다.
- 오류
```java
public class Child extends Parent {
public Child() {
int a = 0;
...
super(0, 0); // 이 곳에서 호출할 수 없음. 반드시 첫 번째 줄에 있어야 함.
}
}
```
- 부모의 변수, 메소드를 사용할때
```java
public class BankAccount {
.
.
.
boolean withdraw(int amount) {
...
}
}
public class TransferLimitAccount extends BankAccount {
private int transferLimit;
@Override
boolean withdraw(int amount) { // 정의한 메소드 사용
if (amount > transferLimit) {
return false;
}
return super.withdraw(amount); // 부모의 메소드 사용
}
}
```
- 부모의 생성자를 사용할때
```java
public class BankAccount {
...
public BankAccount(int balance) {
this.balance = balance;
}
}
public class TransferLimitAccount extends BankAccount {
...
public TransferLimitAccount(int balance, int transferLimit) {
super(balance); // 부모클래스의 생성자를 부르는 키워드
this.transferLimit = transferLimit;
}
}
```
```java
public class A {
public A() {
System.out.println("1");
}
public void a() {
System.out.println("2");
}
}
public class B extends A {
// empty class!
}
B b = new B(); // 1
b.a(); // 2
public class C extends A {
@Override
public void a() {
System.out.println("3");
}
}
C c = new C(); // 1
c.a()// 3
public class D extends C {
@Override
public void a() {
System.out.println("4");
super.a(); // 직전의 부모클래스
}
}
D d = new D(); // 1
d.a(); // 4 // 3
public class E extends A {
public E() {
System.out.println("5");
}
public E(int a) {
System.out.println("6");
}
}
E e = new E(1); // 1 // 6
e.a(); // 2
public class H extends E {
public H(int a) {
System.out.println("10");
}
}
H h = new H(1); // 1 // 5 // 10
h.a(); // 2
```
```java
public class F {
// 부모인 F클래스에 기본 생성자가 없어서 자식 클래스는 어떤 생성자를 호출할지 모른다.
// 자식에서 super(1)과 같이 명확하게 호출해줘야 한다.
public F(int a) {
System.out.println("7");
}
public void a() {
System.out.println("8");
}
}
public class G extends F {
public void a() {
super.a();
System.out.println("9");
}
}
G g = new G(); // 오류발생
g.a();
```
```java
public class I extends A {
public I() {
System.out.println("11");
super(); // 부모클래스의 생성자 호출은 자식 클래스 생성자의 맨 첫 줄에서 불려야 한다.
}
}
I i = new I(); // 오류발생
i.a();
```
- protected 접근 제어자
```java
public class BankAccount {
private int balance;
...
}
public class MinimumBalanceAccount extends BankAccount {
...
@Override
public boolean withdraw(int amount) {
// private로 되어있어서 balance에 접근하기 위해서는 부모클래스의 메소드로 get해야 했다. 보호 차원에서는 좋지만, 상속한 클래스에서의 접근성 마저 떨어지게 되어 유연하지 않다고 볼 수 있다.
if (getBalance() - amount < minimum) {
System.out.println("적어도 " + minimum + "원은 남겨야 합니다.");
return false;
}
setBalance(getBalance() - amount);
return true;
}
}
```
이런경우 protected 사용 -> 자식 클래스에서 접근 가능하도록 한다.
상속의 유연함과 private의 보호성을 동시 만족
```java
public class BankAccount {
protected int balance;
...
}
public class MinimumBalanceAccount extends BankAccount {
...
@Override
public boolean withdraw(int amount) {
// if (getBalance() - amount < minimum) {
if (balance - amount < minimum) {
System.out.println("적어도 " + minimum + "원은 남겨야 합니다.");
return false;
}
// setBalance(getBalance() - amount);
balance -= amount;
return true;
}
}
```
상속받는 클래스에서만 접근 가능하나, BankDriver같은 외부 클래스에서 접근이 안되는 것은 여전히 유효하다.
그래서 상속받은 클래스에서 접근이 잦은 경우 protected로 선언하게 된다!
- 객체를 위한 클래스 Object Class
- Object 최상위 클래스, 모든 클래스의 부모클래스
```java
Object object = new Object();
```
- person.toString()
```java
@Override
public String toString() {
return firstName + lastName //이런식으로 재정의 해주면 글자로 잘 나온다.
}
```
- 캐스팅 Casting
- 다운캐스팅
```java
If (account instanceof SavingsAccount) {
((SavingsAccount) account).addInterest();
}
```
- 타입캐스팅
- BankAccount 타입으로 캐스팅 되고 한 번에 묶어서 다룬다.
```java
ArrayList<BankAccount> accounts = new ArrayList<>;
accounts.add(ba);
accounts.add(mba);
accounts.add(sa);
for (BankAccount account : accounts) {
account.deposit(1000);
}
```
- 제너릭 Generic
Generic은 Casting을 보완
```java
public class Box<T> {
private T something;
public void set(T object) {
this.something = object;
}
public T get() {
return something;
}
}
// 아래와 같이 String을 넘겨주면,
Box<String> box = new Box<>();
public class Box<String> { // 이처럼 <T>가 <String>으로 동작한다.
private String object;
public void set(String object) {
this.object = object;
}
public String get() {
return object;
}
}
```
아래 꺽쇠 기호(`<>`) 사이에 있는 `T`를 **'타입 파라미터'**
`Box`와 같이 타입 파라미터를 받는 클래스를 **'제네릭 클래스(Generic Class)'**
`T`(Type)
`E`(Element)
만약 `HashMap`의 경우에는 `K`(Key)와 `V`(Value)
- 제네릭 클래스
- Generic 다양한 타입에도 동작하는 메소드와 클래스 작성이 필요할 때가 있다.
- ArrayList<T> 는 임의의 클래스 T를 요소로 저장한다.
- ArrayList 클래스 : 제네릭
- T : 타입 파라미터
- 제네릭 타입 파라미터는 기본 타입은 지원하지 않는다.
- 무슨 말이냐면, 클래스 타입만 가능하다는 것
- 제네릭 메소드
- ```java
Arrays.swap(friends, 0, 1);
Arrays.<String>swap(friends, 0, 1);
class Arrays {
public static <T> void swap (T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[i] = temp;
}
}
```

? -> 와일드 카드
**서브타입**
?을 사용하면 Employee 타입과 Employee의 하위 타입 모두가 들어간다.
**슈퍼타입**
상위 타입이 들어간다.
**경계 X**
아무 타입이나 들어간다.
- 상속의 개념이 합쳐지면 더 다양한 방식으로 제네릭(generic)을 사용 가능

`PhoneBox` 클래스는 `Phone` 타입을 받는 `Box` 클래스를 상속
```java
public class PhoneBox extends Box<Phone> {
public void handsFreeCall(String numberString) {
object.call(numberString);
}
}
```
개선
- `extends` 키워드를 이용하면 타입을 제한 가능
- `AndroidPhone`이라는 클래스는 `Phone`을 상속 받기 때문에 `PhoneBox`은 가능, 하지만 `PhoneBox`을 쓰면 오류가 발생.
```java
// <T extends Phone>은 T가 Phone의 자식 클래스이어야 한다.
public class PhoneBox<T extends Phone> extends Box<T> {
public void handsFreeCall(String numberString) {
object.call(numberString);
}
}
```
- 인터페이스
- 서비스 공급자(서버)와 사용자(클라이언트)간의 계약을 표현하는 메커니즘
- 계약서, **상수, 빈 메소드(abstract 메소드) 그리고default/static/private 메소드)**의 모음 -- java 8 이후에 많은 업데이트가 이뤄짐
- // abstract method
- public List<Product> getAllProducts();
- // default/static/private method -> 빈 메소드가 아닌 경우
- public interface Shape { double getArea() }
- public Circle implements Shape {
// 사용하겠다고 선언했으면 사용해야 오류가 발생하지 않는다.
Public double getArea() {return PI * radius * radius}
}
- shape이라는 공통된 타입으로 묶어서 다룰 수 있다.
- 인터페이스는 클래스와 달리 다중 상속을 허용
- ```java
public interface 하위인터페이스 extends 상위인터페이스1, 상위인터페이스2 {...}
```
- 추상클래스
- 변수, 메소드, 빈메소드를 모두 가질 수 있다.
```java
public abstract class Shape {
private double x,y;
public double getX() {
return x;
}
public double getY() {
return y;
}
public void move(double x, double y) {
this.x += x;
this.y += y;
}
public abstract double getArea();
public abstract double getPerimeter();
}
```
사전적 의미로의 추상을 생각해보면, 추상은 **실체 간에 공통되는 특성을 추출**한 것을 말한다.
새, 곤충, 물고기 등 실체에서 공통되는 특성은 '동물'이다.
삼성, 현대 등 실체에서 공통되는 특성은 '회사'이다.
즉 객체를 직접 생성할 수 있는 클래스를 실체 클래스라고 하면, 이 클래스들의 공통적인 특성을 추출해서 선언한 클래스를 추상클래스라고 한다.
그래서 추상클래스가 실체클래스보다 상위/부모 클래스가 되어, 연관된 실체클래스는 추상클래스의 변수, 메소드, 빈메소드를 모두 `상속` 받을 수 있다.
추상 클래스의 용도는?
1. 실체 클래스들의 공통된 필드와 메소드의 이름을 통일할 목적
예를들면, Telephone과 Smartphone을 각기 다른 개발자가 코드를 작성한다고 했을때, 사용자의 변수명을 user, owner 이런식으로 각기 다르게 적는 경우가 생기는데, 사실 Telephone과 Smartphone은 공통적으로 사용자를 가지고 있기 때문에, Phone이라는 추상클래스를 상속받아 owner든, user든 하나를 정해서 그것을 사용하면 일관성이 확보된다.
2. 실체 클래스를 작성할 때 시간을 절약
공통된 부분을 상속받아 사용하므로 코드를 중복해서 적을 필요가 없어 시간이 절약된다.
- 익명클래스
- 생성하면서 abstract method를 정의할 수 있다.
- 사용자가 어떤 이름의 클래스를 만들지 모르는 경우, 사용 가능
- comparable 인터페이스
- Collections.sort(nameArrayList) // 작은순서대로
- 안에 원소가 두 가지 이상이면 기준을 정해줘야 한다.
- implements Comparable<Person> -> 선언후 메소드 생성
- 람다 표현식
```java
comparator 인터페이스
int compare(T first, T second);
runnable 인터페이스 // 쓰레드에서 주로 사용
void run();
사용자 인터페이스 콜백
void handle(ActionEvent e);
함수형 인터페이스란? 추상 메소드 하나만 포함하는
import java.util.Arrays;
public class Lamda {
public static void main(String[] args) {
String[] friends = {"park", "kim", "lee"};
// (String first, String second) 라는 함수를 변수에 담아 넘겨준다.
// 함수를 포함한 객체를 넣어야 한다.
// 글자수에 따른 정렬
// 타입이 같은경우
// (String o1, String o2)
// 생략가능
// sort 메소드의 두번째 인자로는 Comparator이 들어가는데, 람다식에서는 자동으로 Comparator의 compare로 인식한다.
// 음수, 0, 양수 로 반환될텐데 이를 가지고 sort에서 처리를 하고 그다음에 string으로 변환해서 정리된 array를 반환한다.
Arrays.sort(friends, (o1, o2) -> o1.length() - o2.length());
for (String item : friends ){
System.out.println(item);
}
}
}
/*
kim
lee
park
*/
```
- 함수를 아주 짧게 표현하는 방식

- Predicate : 이 타입이 참인지 거짓인지 리턴
- Consumer : 데이터 확인, 리턴 값은 없음
- Function : 첫번째 타입을 두번째 타입으로 바꿔준다.
- Supplier : 인자는 없지만 어떤 것을 리턴
# 키워드
#### Stack
```java
// HashMap<T> Character, String, Integer...
// 해시맵은 객체로 선언해주어야 한다.
private HashMap<Character, Character> mappings;
// 자바에서 메모이제이션을 만들려면, 해시맵.put(K, V) 식으로 추가해줘야 한다.
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}
// stack 라이브러리
// .pop(Index)
// 해당 스택의 제일 상단에 있는(제일 마지막으로 저장된) 요소를 반환하고, 해당 요소를 스택에서 제거함.
// .peek()
// 해당 스택의 제일 상단에 있는(제일 마지막으로 저장된) 요소를 반환함.
// .empty() empty면 Boolean 값 반환
// 해당 스택이 비어 있으면 true를, 비어 있지 않으면 false를 반환함.
// .push(V)
// Character을 원소로 담을 스택 생성
Stack<Character> stack = new Stack<Character>();
```
#### ArrayList vs Map
배열의 특징
- 시간복잡도가 ArrayList보다는 적게 든다.
- 같은 타입의 엘레먼트만 사용 가능
- 한번 생성하면 길이를 바꿀 수 없음
ArrayList
- 배열을 사용하기 쉽도록 만든 클래스
- 객체 내부에서 배열을 관리 (자동으로 길이를 조절)
- 데이터를 저장을 인덱스 기반으로 수행
- 데이터의 순서가 있음
- 인덱스는 제로(0) 베이스
````java
ArrayList<String> colors = new ArrayList<>();
colors.add("red"); // 맨 마지막에 추가
colors.get(0); // 인덱스 접근
colors.clear(); // 데이터 모두 삭제
````
Map
- 데이터를 키를 통해 관리
- 데이터를 키/값 쌍으로 저장/ 관리
- 인덱스가 없음, 데이터의 순서가 없음
```java
HashMap<String, Integer> people = new HashMap<>();
people.put("sw", 25); // 데이터 추가
people.get("sw"); // 키 접근
people.clear(); // 데이터 모두 삭제
```
#### Collections.unmodifiableList()
```java
// Immutable list (unmodiriable List)
List<String> readOnlyList = Collections.unmodifiableList(myList);
System.out.println(readOnlyList);
readOnlyList.add("white"); // error
// Java9 of 메소드 사용, Immutable list (unmodiriable List)
// 리스트를 만들면서 바로 엘레먼트를 작성 할 수 있다.
List<String> Java9List = List.of("red", "blue", "green");
// [red, blue, green]
```
- List를 Immutable하게 사용하는 것이 최근
#### LocalDate
```java
LocalDate date = LocalDate.of(2016, 1, 1)
```
#### 컬렉션 프레임워크
- 자료구조와 알고리즘 구현에 적합
- 계층적으로 조직화되어있다.


**Set 집합**
HashSet: 요소에 해시 함수가 구현되어 요소의 식별이 가능
TreeSet: 이진트리로 구현, 요소가 순서가 있어 전체 요소를 순회 가능
```java
Set<String> badWords = new HashSet<>();
badWords.add("smoking");
if (badWords.contains(username.toLowerCase())) {
System.out.println("다른 단어를 사용해주세요.");
}
```
**Map 맵**
키와 값으로 저장
HashMap: 저장되는 순서가 없음
TreeMap: 저장되는 순서가 있음
**List 리스트**
ArrayList: 인덱스를 기준으로 정렬 및 조회
LinkedList: 연결리스트, 각각의 엘레먼트들이 물리적으로 떨어져있음 하지만 앞 단이 뒷 단의 주소값을 갖고 있어 참조를 한다.

**Properties**
설정파일로 사용됨
**Stack**
후입선출
**Queue**
선입선출
**Collection**
외부반복
각 계산식을 만날 때마다 데이터가 계산됨
직접 데이터 핸들링
Eager loading
```java
for(int n : numbers) {
...
}
```
#### Reflection & Annotation
Reflection?
실행시간에 객체의 내용을 조사하고, 해당 객체의 메소드를 호출할 수 있다.
`Field`, `Method`, `Constructor`
Annotation?
@이용한 주석, 자바코드에 달아 특별한 의미를 부여한 것
코드에 정보를 추가하는 정형화된 방법
|
Python
|
UTF-8
| 4,986
| 3.015625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[9]:
import numpy as np # library to handle data in a vectorized manner
import pandas as pd # library for data analsysis
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
import json # library to handle JSON files
get_ipython().system("conda install -c conda-forge geopy --yes # uncomment this line if you haven't completed the Foursquare API lab")
from geopy.geocoders import Nominatim # convert an address into latitude and longitude values
import requests # library to handle requests
from pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe
# Matplotlib and associated plotting modules
import matplotlib.cm as cm
import matplotlib.colors as colors
# import k-means from clustering stage
from sklearn.cluster import KMeans
#!conda install -c conda-forge folium=0.5.0 --yes # uncomment this line if you haven't completed the Foursquare API lab
import folium # map rendering library
import numpy as np
get_ipython().system('pip install BeautifulSoup4')
import requests
print('Libraries imported.')
# In[10]:
from bs4 import BeautifulSoup
# In[19]:
get_ipython().system('pip install lxml')
get_ipython().system('pip install html5lib')
# In[22]:
url='https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M'
req_url= requests.get(url).text
soup = BeautifulSoup(req_url,'html5lib')
# In[24]:
table = soup.find('table')
Postcode = []
Borough = []
Neighbourhood = []
for tr_cell in table.find_all('tr'):
counter = 1
Postcode_var = -1
Borough_var = -1
Neighbourhood_var = -1
for td_cell in tr_cell.find_all('td'):
if counter == 1:
Postcode_var = td_cell.text
if counter == 2:
Borough_var = td_cell.text
tag_a_Borough = td_cell.find('a')
if counter == 3:
Neighbourhood_var = str(td_cell.text).strip()
tag_a_Neighbourhood = td_cell.find('a')
counter +=1
if (Postcode_var == 'Not assigned' or Borough_var == 'Not assigned' or Neighbourhood_var == 'Not assigned'):
continue
try:
if ((tag_a_Borough is None) or (tag_a_Neighbourhood is None)):
continue
except:
pass
if(Postcode_var == -1 or Borough_var == -1 or Neighbourhood_var == -1):
continue
Postcode.append(Postcode_var)
Borough.append(Borough_var)
Neighbourhood.append(Neighbourhood_var)
# In[27]:
unique_p = set(Postcode)
print('number of unique postal codes:', len(unique_p))
Postcode_u = []
Borough_u = []
Neighbourhood_u = []
for postcode_unique_element in unique_p:
p_var = ''; b_var = ''; n_var = '';
for postcode_idx, postcode_element in enumerate(Postcode):
if postcode_unique_element == postcode_element:
p_var = postcode_element;
b_var = Borough[postcode_idx]
if n_var == '':
n_var = Neighbourhood[postcode_idx]
else:
n_var = n_var + ', ' + Neighbourhood[postcode_idx]
Postcode_u.append(p_var)
Borough_u.append(b_var)
Neighbourhood_u.append(n_var)
# In[28]:
toronto = {'Postcode':Postcode_u, 'Borough':Borough_u, 'Neighbourhood':Neighbourhood_u}
df_toronto = pd.DataFrame.from_dict(toronto)
df_toronto.to_csv('toronto_part1.csv')
df_toronto.head(14)
# In[29]:
df_toronto.shape
# In[40]:
latitude=[] #List to collect the latitudes
longitude=[] #List to collect the longitudes
for i in df_toronto['Postcode']: #Iterating through Postalcodes to collect the locations data
j='toronto,'+i
try:
url ="https://maps.googleapis.com/maps/api/geocode/json?key={}&address={}".format(API_key,j)
response = requests.get(url).json() # get response
geographical_data = response['results'][0]['geometry']['location'] # get geographical coordinates
latitude.append(geographical_data['lat'])
longitude.append(geographical_data['lng'])
except:
pass
# In[32]:
pip install geocoder
# In[41]:
import geocoder
# In[42]:
def get_latlng(postal_code):
# initialize your variable to None
lat_lng_coords = None
# loop until you get the coordinates
while(lat_lng_coords is None):
g = geocoder.arcgis('{}, Toronto, Ontario'.format(postal_code))
lat_lng_coords = g.latlng
return lat_lng_coords
get_latlng('M4G')
# In[46]:
postal_codes = df_toronto['Postcode']
coords = [ get_latlng(postal_code) for postal_code in postal_codes.tolist() ]
# In[48]:
df_coords = pd.DataFrame(coords, columns=['Latitude', 'Longitude'])
df_toronto['Latitude'] = df_coords['Latitude']
df_toronto['Longitude'] = df_coords['Longitude']
# In[49]:
df_toronto.head()
# In[ ]:
|
C#
|
UTF-8
| 1,036
| 2.578125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace LvivCinema.Models
{
public class Cinema
{
public int Id { set; get; }
[Required(ErrorMessage = "Ім'я повинно бути обовязково")]
[StringLength(50, MinimumLength = 2, ErrorMessage = "Розмір імені повинен бути в межах [2-50] символів")]
[Display(Name = "Назва")]
public string Name { set; get; }
[Required(ErrorMessage = "Адреса повинна бути вказана")]
[StringLength(1000, MinimumLength = 10, ErrorMessage = "Розмір назви адреси повинен бути в межах [10-1000] символів")]
[Display(Name = "Адреса")]
public string Adress { set; get; }
public ICollection<Hall> Halls { get; set; }
public Cinema()
{
Halls = new List<Hall>();
}
}
}
|
TypeScript
|
UTF-8
| 1,953
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import { stringify } from 'querystring';
import { parseQueryFull } from './parseQueryFull';
describe('parseQueryFull', () => {
it('should parse full query', () => {
const query = stringify({
take: 10,
skip: 0,
search: 'Строка поиска',
relations: 'users,accounts',
sort: 'asc(createdAt),desc(updatedAt)',
where: 'eq(name,Имя пользователя);gt(rating,10)',
});
const parsed = parseQueryFull(query);
expect(parsed).toEqual({
take: 10,
skip: 0,
search: 'Строка поиска',
relations: ['users', 'accounts'],
sort: {
createdAt: 1,
updatedAt: -1,
},
where: {
name: {
field: 'name',
operation: 'eq',
value: 'Имя пользователя',
},
rating: {
field: 'rating',
operation: 'gt',
value: '10',
},
},
});
});
it('should parse empty query', () => {
const parsed = parseQueryFull('');
expect(parsed).toEqual({
take: null,
skip: null,
search: '',
relations: [],
sort: {},
where: {},
});
});
it('should preserve unknown query params', () => {
const query = stringify({
param1: '1',
param2: 'Строка',
});
const parsed = parseQueryFull(query);
expect(parsed).toEqual({
param1: '1',
param2: 'Строка',
take: null,
skip: null,
search: '',
relations: [],
sort: {},
where: {},
});
});
it('should omit wrong values', () => {
const query = stringify({
take: 'десять',
skip: 'ноль',
where: 'test',
sort: 'test',
});
const parsed = parseQueryFull(query);
expect(parsed).toEqual({
take: null,
skip: null,
search: '',
relations: [],
sort: {},
where: {},
});
});
});
|
C#
|
UTF-8
| 1,330
| 2.578125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
using System;
using System.IO;
using System.Text;
using LightBlue.Standalone;
namespace LightBlue.Tests.Standalone
{
public enum DirectoryType
{
Account = 0,
Container = 1,
}
public abstract class StandaloneAzureTestsBase
{
public const string MetadataDirectory = ".meta";
protected readonly string BasePath;
protected StandaloneAzureTestsBase(DirectoryType directoryType)
{
BasePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(BasePath);
if (directoryType == DirectoryType.Container)
{
Directory.CreateDirectory(Path.Combine(BasePath, MetadataDirectory));
}
}
protected Uri BasePathUri
{
get { return new Uri(BasePath); }
}
public void Dispose()
{
if (!string.IsNullOrWhiteSpace(BasePath) && Directory.Exists(BasePath))
{
Directory.Delete(BasePath, true);
}
}
protected static void CreateBlobContent(StandaloneAzureBlockBlob blob)
{
var buffer = Encoding.UTF8.GetBytes("Some content");
blob.UploadFromByteArrayAsync(buffer, 0, buffer.Length).Wait();
}
}
}
|
JavaScript
|
UTF-8
| 3,159
| 2.734375
| 3
|
[] |
no_license
|
const TodoListModel = require('../models/TodoListModel')
const TodoModel = require('../models/TodoModel')
module.exports = {
postTodoListCallback: async (req, res) => {
try {
const body = {
title: req.body.title ? req.body.title : '',
ownerId: req.user._id,
}
const todoList = await TodoListModel.postTodoList(body)
res.json(todoList)
} catch(error) {
res.json('TodoList could not be created')
console.log(error)
}
},
getAllTodoListsCallback: async(req, res) => {
try {
const todoLists = await TodoListModel.getAllTodoLists()
const authTodoLists = await todoLists.authTodos(req.user)
authTodoListsWithTodos = await mapTodosOntoTodoLists(authTodoLists)
res.json(authTodoListsWithTodos)
} catch(error) {
res.json('Todos could not be generated')
console.log(error)
}
},
getTodoListByIdCallback: async (req, res) => {
try {
const id = req.params.id
const todoList = await TodoListModel.getTodoListById(id)
const todos = await TodoModel.getTodosByTodoListId(id)
todoList.isOwner(req.user)
? res.json({
...todoList,
todos
}).status(200)
: res.sendStatus(401)
} catch(error) {
res.json('Something went wrong')
console.log(error)
}
},
updateTodoListTitleByIdCallback: async (req, res) => {
try {
const id = req.params.id
const title = req.body.title ? req.body.title : ''
const todoList = await TodoListModel.getTodoListById(id)
if(todoList.isOwner(req.user)) {
const numUpdated = await TodoListModel.updateTodoListTitleById(id, title)
res.json(numUpdated).status(200)
} else {
res.sendStatus(401)
}
} catch(error) {
res.json('Todo could not be updated')
console.log(error)
}
},
deleteTodoListByIdCallback: async (req, res) => {
try {
const id = req.params.id
const todo = await TodoListModel.getTodoListById(id)
if(todo.isOwner(req.user)) {
const numTodoListsRemoved = await TodoListModel.deleteTodoListById(id)
const numTodosRemoved = await TodoModel.deleteTodosByTodoListId(id)
res.json({
numTodoListsRemoved,
numTodosRemoved
}).status(200)
} else {
res.sendStatus(401)
}
} catch(error) {
res.json(1)
console.log(error)
}
}
}
async function mapTodosOntoTodoLists(authTodoLists) {
for(let i = 0; i < authTodoLists.length; i++) {
const todos = await TodoModel.getTodosByTodoListId(authTodoLists[i]._id)
authTodoLists[i].todos = todos
}
return authTodoLists
}
|
Java
|
UTF-8
| 993
| 2.421875
| 2
|
[] |
no_license
|
package dao;
import java.util.List;
import model.Statistics;
import tools.YeekuHibernateDaoSupport;
public class StatisticsDao extends YeekuHibernateDaoSupport<Statistics>{
public int save(Statistics statistics) {
return (Integer)getHibernateTemplate().save(statistics);
}
public Statistics find(int id) {
return getHibernateTemplate().get(Statistics.class,id);
}
public void update(Statistics statistics) {
getHibernateTemplate().update(statistics);
}
public void delete(Statistics statistics) {
getHibernateTemplate().delete(statistics);
}
public void deleteList(List<Statistics> list){
getHibernateTemplate().deleteAll(list);
}
@SuppressWarnings("unchecked")
public List<Statistics> findList(String hql) {
return getHibernateTemplate().find(hql);
}
public int countRecords(String hql){
return getHibernateTemplate().find(hql).size();
}
@SuppressWarnings("rawtypes")
public List find(String hql) {
return getHibernateTemplate().find(hql);
}
}
|
Java
|
UTF-8
| 4,224
| 2.3125
| 2
|
[
"MIT"
] |
permissive
|
package hudson.plugins.testng.results;
import java.io.Serializable;
import hudson.model.ModelObject;
import hudson.model.Run;
import hudson.plugins.testng.TestNGTestResultBuildAction;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.tasks.test.TabulatedResult;
import hudson.tasks.test.TestResult;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
/**
* Base class that takes care of all the common functionality of the different kinds of
* test results.
*/
@SuppressWarnings("serial")
@ExportedBean
public abstract class BaseResult extends TabulatedResult implements ModelObject, Serializable {
//owner of this build
protected Run<?, ?> run;
//name of this result
protected final String name;
//parent result for this result
protected BaseResult parent;
public BaseResult(String name) {
this.name = name;
}
@Exported(visibility = 999)
@Override
public String getName() {
return name;
}
@Override
public BaseResult getParent() {
return parent;
}
public void setParent(BaseResult parent) {
this.parent = parent;
}
@Override
public Run<?, ?> getRun() {
return run;
}
public void setRun(Run<?, ?> run) {
this.run = run;
}
@Override
public String getTitle() {
return getName();
}
public String getDisplayName() {
return getName();
}
//TODO: @see https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML and fix
public String getUpUrl() {
Jenkins j = Jenkins.getInstance();
return j != null ? j.getRootUrl() + run.getUrl() + getId() : "";
}
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
for (TestResult result : this.getChildren()) {
if (token.equals(result.getName())) {
return result;
}
}
return null;
}
/**
* Explicit override here to ensure that when we are building TestNG reports,
* we are only working with TestNG results (and not results from other test reporters).
*
* Can get into a bad situation if the same job has configured JUnit and TestNG reports
*
* @return
*/
@Override
public AbstractTestResultAction getTestResultAction() {
Run<?, ?> run = getRun();
if (run != null) {
return run.getAction(TestNGTestResultBuildAction.class);
}
return null;
}
/**
* @see BaseResult#getTestResultAction()
* @return
*/
@Override
public AbstractTestResultAction getParentAction() {
return getTestResultAction();
}
@Override
public TestResult findCorrespondingResult(String id) {
if (getId().equals(id) || id == null) {
return this;
}
int sepIdx = id.indexOf('/');
if (sepIdx < 0) {
if (getSafeName().equals(id)) {
return this;
}
} else {
String currId = id.substring(0, sepIdx);
if (!getSafeName().equals(currId)) {
return null;
}
String childId = id.substring(sepIdx + 1);
sepIdx = childId.indexOf('/');
for (TestResult result : this.getChildren()) {
if (sepIdx < 0 && childId.equals(result.getSafeName())) {
return result;
} else if (sepIdx > 0 && result.getSafeName().equals(childId.substring(0, sepIdx))) {
return result.findCorrespondingResult(childId);
}
}
}
return null;
}
/**
* Gets the age of a result
*
* @return the number of consecutive builds for which we have a result for
* this package
*/
public long getAge() {
BaseResult result = (BaseResult) getPreviousResult();
if (result == null) {
return 1;
} else {
return 1 + result.getAge();
}
}
}
|
Java
|
UTF-8
| 15,263
| 1.796875
| 2
|
[] |
no_license
|
package com.hyd.bikepool.bikepooler.bikemap;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.hyd.bikepool.bikepooler.R;
import com.hyd.bikepool.bikepooler.SharedPreferencesUtils;
import com.hyd.bikepool.bikepooler.application.MyApplication;
import com.hyd.bikepool.bikepooler.fragment.ProfileFragment;
import com.hyd.bikepool.bikepooler.webservicehelpers.BikeConstants;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
/**
* A simple {@link Fragment} subclass.
* Use the {@link RideFinderFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RideFinderFragment extends Fragment implements AdapterView.OnItemClickListener,View.OnClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
LinearLayout fromLayout;
View v = null;
AutoCompleteTextView fromLocation;
AutoCompleteTextView toLocation;
String from_address = "";
private static final String LOG_TAG = "GooglePlacesAuto";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "AIzaSyDDV6NVf7bCKELYyrwXHJsN5ugLzzVOAhM";
RelativeLayout parent_date_time;
TextView date_ride,time_ride;
Calendar dateAndTime;
SharedPreferencesUtils prefs;
private String TAG = "RideFinderFragment";
int mContainerId = -1;
JSONObject publishJSON;
public RideFinderFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment RideFinderFragment.
*/
// TODO: Rename and change types and number of parameters
public static RideFinderFragment newInstance(String param1, String param2) {
RideFinderFragment fragment = new RideFinderFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
prefs = new SharedPreferencesUtils();
prefs.saveBooleanPreferences(getActivity(), BikeConstants.BIKE_BOOLEAN_PREFS_DATA, false);
dateAndTime = Calendar.getInstance();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mContainerId = container.getId();
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_ride_finder, container, false);
if(getArguments()!=null) {
if (getArguments().getString("from") != null) {
from_address = getArguments().getString("from");
}
}
fromLayout = (LinearLayout)v.findViewById(R.id.from_layout);
ImageView currentLocation = (ImageView)fromLayout.findViewById(R.id.curloc);
fromLocation = (AutoCompleteTextView)fromLayout.findViewById(R.id.from_location);
fromLocation.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
fromLocation.setOnItemClickListener(this);
toLocation = (AutoCompleteTextView)v.findViewById(R.id.leaving_to);
toLocation.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
toLocation.setOnItemClickListener(this);
currentLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fromLocation.setText(from_address);
}
});
parent_date_time = (RelativeLayout)v.findViewById(R.id.date_time_layout);
date_ride = (TextView)parent_date_time.findViewById(R.id.date_find_ride);
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
Date cDate = new Date();
String fDate = new SimpleDateFormat("dd MMM ,yyyy").format(cDate);
// textView is the TextView view that should display it
date_ride.setText(fDate);
time_ride = (TextView)parent_date_time.findViewById(R.id.time_find_ride);
time_ride.setOnClickListener(this);
Button search = (Button)v.findViewById(R.id.find_rides);
search.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.time_find_ride:
showTimePickerDialog();
break;
case R.id.find_rides:
// moveToPricing();
prepareForPublish();
break;
}
}
private void prepareForPublish(){
if(!TextUtils.isEmpty(prefs.getStringPreferences(getActivity(), "loginType"))){
String loginType = prefs.getStringPreferences(getActivity(), "loginType");
Log.d(TAG,"LoginType:::::"+loginType);
if(!TextUtils.isEmpty(prefs.getStringPreferences(getActivity(), loginType))) {
fetchDataBasedOnLoginType(loginType);
}else{
JSONObject emailXcludingJSON = fetchJSONExcludingEmail();
MyApplication.getInstance().setPublishJSON(emailXcludingJSON);
getFragmentManager().beginTransaction()
.replace(mContainerId, ProfileFragment.newInstance(loginType, "fromridefinder")).addToBackStack(null)
.commit();
}
}
}
private void fetchDataBasedOnLoginType(String loginType){
JSONObject offerRideJOSN = new JSONObject();
publishJSON = new JSONObject();
if(loginType.equalsIgnoreCase("emailProfile") || loginType.equalsIgnoreCase("facebookprofile")) {
if (!TextUtils.isEmpty(prefs.getStringPreferences(getActivity(), loginType))) {
try {
JSONObject profileTypeJSON = new JSONObject(prefs.getStringPreferences(getActivity(), loginType));
String profileEmail = profileTypeJSON.getString("profileEmail");
String profileMobile = profileTypeJSON.getString("profileMobile");
String profileName = profileTypeJSON.getString("profileName");
// String profileBikeNum = profileTypeJSON.getString("profileBikeNum");
if(!TextUtils.isEmpty(profileEmail) && !TextUtils.isEmpty(profileMobile) && !TextUtils.isEmpty(profileName)) {
publishJSON.put("email",profileEmail);
publishJSON.put("mobile", profileMobile);
publishJSON.put("profilename",profileName);
// publishJSON.put("bikeNum",profileBikeNum);
}
if(!TextUtils.isEmpty(fromLocation.getText().toString()) && !TextUtils.isEmpty(toLocation.getText().toString())){
publishJSON.put("from",fromLocation.getText().toString());
publishJSON.put("to",toLocation.getText().toString());
}
if(!TextUtils.isEmpty(time_ride.getText().toString())){
publishJSON.put("pickuptime",time_ride.getText().toString());
}
offerRideJOSN.put("findride",publishJSON);
Log.d("PoolerPricingFragment","OfferRideJSON:::"+offerRideJOSN.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private JSONObject fetchJSONExcludingEmail(){
JSONObject publishJSON = new JSONObject();
try{
if(!TextUtils.isEmpty(fromLocation.getText().toString()) && !TextUtils.isEmpty(toLocation.getText().toString())){
publishJSON.put("from",fromLocation.getText().toString());
publishJSON.put("to",toLocation.getText().toString());
}
/*if(!TextUtils.isEmpty(distanceinkms)&& !TextUtils.isEmpty(duration)){
publishJSON.put("distance",distanceinkms);
publishJSON.put("duration",duration);
}*/
/*if(!TextUtils.isEmpty(charge.getText().toString())){
publishJSON.put("cost",charge.getText().toString());
}*/
if(!TextUtils.isEmpty(time_ride.getText().toString())){
publishJSON.put("pickuptime",time_ride.getText().toString());
}
}catch (JSONException e) {
e.printStackTrace();
}
return publishJSON;
}
private void showTimePickerDialog() {
new TimePickerDialog(getActivity(),
t,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE),
true).show();
}
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
time_ride.setText(new StringBuilder().append(pad(hourOfDay))
.append(":").append(pad(minute)));
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String str = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public Object getItem(int position) {
return resultList.get(position);
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&components=country:ind");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
}
|
C++
|
UTF-8
| 443
| 2.59375
| 3
|
[] |
no_license
|
#include <iostream>
#include <math.h>
#include <windows.h>
using namespace std;
int main()
{
{
double
x;
cout<<"Podaj x"<<endl;
cin>>x;
if (x<1)
cout<<(2*x)<<endl;
else
if (x==1)
cout<<-10<<endl;
else
if (x==3)
cout<<//((x-1)*(x-1)*(x-1)*(x-1))
pow((x-1),4)<<endl;
else
if (x==6)
cout<<(sqrt(x-4))<<endl;
else
cout<<0<<endl;
}
system("pause");
return 0;
}
|
Go
|
UTF-8
| 579
| 3.765625
| 4
|
[] |
no_license
|
package forloop
import (
"fmt"
"testing"
)
type Frame struct {
frame int
}
func NewFrame() *Frame {
return &Frame{
frame: 0,
}
}
func (f *Frame) Next() (int, bool) {
f.frame++
if f.frame < 10 {
return f.frame, true
}
return f.frame, false
}
func Test_ForLoop(t *testing.T) {
// for frame,more=frames.Next(); more; frame,more=frames.Next() {
// // statement
// if !more{
// break
// }
// }
frames := NewFrame()
for frame, more := frames.Next(); more; frame, more = frames.Next() {
fmt.Println(frame)
// if !more {
// break
// }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.