language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 160 | 2.53125 | 3 |
[] |
no_license
|
#include "subject.h"
Subject::Subject( const std::string &name ): name{name} {}
std::string Subject::getName() const { return name; }
Subject::~Subject() {}
|
JavaScript
|
UTF-8
| 5,115 | 3.28125 | 3 |
[] |
no_license
|
// HTML'de yer alan item eklenecek olan listeyi DOM ile bir değişkene atama
var ul = document.querySelector("#list");
// Local Storage tanımlı değil ise Liste Elemanlarını tutmak için listArray isimli boş array tanımlama
var listArray = [];
if (localStorage.getItem("listArray")) {
// Bu blok yani If bloğu Local Storaga içerisinde listArray daha önce tanımlandıysa oradaki listArray'i getirir ve ekrana yazdırır.
// Local Storage içindeki güncel listeyi listArray içerisine alma
listArray = JSON.parse(localStorage.getItem("listArray"));
// Listenin ekrana yazdırılması
for (var i = 0; i < listArray.length; i++) {
let liNew = document.createElement("li");
liNew.innerHTML = listArray[i]
ul.appendChild(liNew);
}
}
else {
// Bu blok yani Else bloğu Local Storaga içinde listArray isimli key tanımlı değil ise çalışır ve Local Storage temizlenmediği sürece bir daha çalışmaz.
// Sayfada default olarak gösterilmesi istenen liste elemanlarını listArray içerisine alma
listArray = ["3 Litre Su İç", "Ödevleri Yap", "En Az 3 Saat Kodlama Yap", "Yemek Yap", "50 Sayfa Kitap Oku"];
// Default olarak gelecek listeyi ekrana yazdırma
for (var i = 0; i < listArray.length; i++) {
let liNew = document.createElement("li");
liNew.innerHTML = listArray[i]
ul.appendChild(liNew);
}
// List Array'i Local Storage'a gönderme
localStorage.setItem("listArray", JSON.stringify(listArray));
}
// Default liste elemanlarına silme işlemi için closeButton ekleme
let liItems = document.querySelectorAll("#list li");
for (let i = 0; i < liItems.length; i++) {
var closeButton = document.createElement("SPAN");
closeButton.innerHTML = "x";
closeButton.className = "close";
liItems[i].appendChild(closeButton);
}
// Default liste elemanlarına tamamlandı işlemi için checked isimli class'ı ekleme
let liCompleted = document.querySelectorAll("li");
for (let i = 0; i < liCompleted.length; i++) {
liCompleted[i].onclick = function () {
this.classList.toggle("checked");
};
};
// Listeden bir maddenin silinmesi ve silinen maddenin Local Storage'dan da kaldırılması
var allContents = document.querySelectorAll(".close");
for (var i = 0; i < allContents.length; i++) {
allContents[i].onclick = function () {
this.parentElement.remove();
var removedContent = this.parentElement.textContent;
// İçeriğin sonunda gelen x karakterini silme
removedContent = removedContent.slice(0, -1)
var removedItemIndex = listArray.indexOf(removedContent);
// // Array'den silinen elemanı çıkartma
listArray.splice(removedItemIndex, 1);
// Ve Listenin yeni halini Local Storage içine gönderme
localStorage.setItem('listArray', JSON.stringify(listArray));
}
}
// Toast Mesajlarının x simgesi tıklanarak kapatılması
let closeToast = document.querySelectorAll(".closeToast");
for (var i = 0; i < closeToast.length; i++) {
closeToast[i].addEventListener("click", function () {
let closeToastBox = document.querySelectorAll(".mr-1")
setTimeout(function () {
$(closeToastBox[i]).addClass('hidden');
}, 0);
setTimeout(function () {
$(closeToastBox[i]).removeClass('hidden');
}, 400);
})
};
// Listeye yeni Liste Elemanı ekleme fonksiyonu
function addNewItem() {
// Yeni list item içeriğini bir değişkene atama
let liContent = document.querySelector("#task").value;
// Yeni içeriği yeni list item içine gönderme
if (liContent == "" || liContent.replace(/^\s+|\s+$/g, "").length === 0) {
$('.error').toast('show'); //Uyarı eklendi
} else {
$('.success').toast('show'); //Uyarı eklendi
// Yeni bir li Tag oluşturma ve içerikle beraber ul içerisine ekleme
let liNew = document.createElement("li");
liNew.innerHTML = liContent
ul.appendChild(liNew);
// Yeni eklenen liste elamanına silme işini yapacak olan closeButton ekleme
var closeButton = document.createElement("SPAN");
closeButton.innerHTML = "x";
closeButton.className = "close";
liNew.appendChild(closeButton);
// Kullanıcının sonradan eklediği Liste içeriğini de list Array'e ekleme
listArray.push(liContent);
// Yeni item eklendikten sonra array'i local storage içine yazma
localStorage.setItem("listArray", JSON.stringify(listArray));
// Yeni eklenen liste elemanının tamamlandı olarak işaretlenmesi
liNew.onclick = function () {
this.classList.toggle("checked");
};
// Yeni eklenen liste elemanının X tıklanarak silinmesi
closeButton.onclick = function () {
this.parentElement.remove();
var removedContent = this.parentElement.textContent;
removedContent = removedContent.slice(0, -1)
var removedItemIndex = listArray.indexOf(removedContent);
listArray.splice(removedItemIndex, 1);
localStorage.setItem('listArray', JSON.stringify(listArray));
}
};
// input içine yazılan metnin Ekle butonu tıklanınca temizlenmesi
document.getElementById("task").value = "";
};
|
PHP
|
UTF-8
| 745 | 2.65625 | 3 |
[] |
no_license
|
<?php
require 'Calculator.php';
use PHPUnit\Framework\TestCase;
class CalculatorTests extends TestCase
{
private $calculator;
protected function setUp()
{
$this->calculator = new Calculator();
}
protected function tearDown()
{
$this->calculator = NULL;
}
public function addDataProvider() {
return array(
array(1,2,5),
array(0,0,5),
array(-1,-1,-4),
);
}
/**
* @dataProvider addDataProvider
*/
public function testAdd($a, $b, $expected)
{
$result = $this->calculator->add($a, $b);
$this->assertNotEquals($expected, $result);
}
}
get('reports', function(){
return 'Report page';
});
?>
|
Java
|
UTF-8
| 757 | 2.78125 | 3 |
[] |
no_license
|
package service.dao;
import org.springframework.stereotype.Component;
import service.models.Point;
import java.util.ArrayList;
import java.util.List;
@Component
public class PointDAO {
private static int POINTS_COUNT;
private List<Point> points;
{
points = new ArrayList<>();
points.add(new Point(++POINTS_COUNT, "Tom", "Some1"));
points.add(new Point(++POINTS_COUNT, "Bob", "Some2"));
points.add(new Point(++POINTS_COUNT, "Mike", "Some3"));
points.add(new Point(++POINTS_COUNT, "Katy", "Some4"));
}
public List<Point> index() {
return points;
}
public Point show(int id) {
return points.stream().filter(point -> point.getId() == id).findAny().orElse(null);
}
}
|
Ruby
|
UTF-8
| 436 | 3.53125 | 4 |
[] |
no_license
|
#write your code here
def add(a,b)
a+b
end
def subtract(a,b)
a - b
end
def sum(numberList)
total = 0
for num in numberList
total += num
end
return total
end
def multiply(numberList)
total = 1
for num in numberList
total *= num
end
return total
end
def power(a,b)
a**b
end
def factorial(num)
current = num
total = 1
while current > 0
total *= current
current -=1
end
return total
end
|
Java
|
UTF-8
| 4,223 | 1.859375 | 2 |
[] |
no_license
|
package com.zozmom.ui;
import com.zozmom.manager.AccountManager;
import com.zozmom.model.UserInfoModel;
import com.zozmom.pic.PhotoLoader;
import com.zozmom.ui.fragment.MeFragment;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
public class BaseTaskActivity<T> extends BaseActivity<T> {
PhotoLoader hLoader;
/**
* 加载动画
*/
public void showListAnimation(View view) {
TranslateAnimation ta = new TranslateAnimation(1, 0f, 1, 0f, 1, 1f, 1,
0f);
ta.setDuration(200);
view.startAnimation(ta);
}
/**
* 隐藏动画,设置透明度
*/
public void hideListAnimation(final View view) {
TranslateAnimation ta = new TranslateAnimation(1, 0f, 1, 0f, 1, 0f, 1,
1f);
ta.setDuration(200);
view.startAnimation(ta);
ta.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
view.setVisibility(8);
}
});
}
public void loadimage(ImageView v, String url) {
if (hLoader == null) {
hLoader = new PhotoLoader(this);
}
hLoader.loadPhoto(url, v);
}
Resources m_resource;
public String getRString(int id) {
if (m_resource == null) {
m_resource = getResources();
}
return m_resource.getString(id);
}
public int getRColor(int id) {
if (m_resource == null) {
m_resource = getResources();
}
return m_resource.getColor(id);
}
public Drawable getRDrawble(int id) {
if (m_resource == null) {
m_resource = getResources();
}
return m_resource.getDrawable(id);
}
public UserInfoModel getLogginUserinfo() {
return AccountManager.getInstance().getLogginUserInfo();
}
public void logout() {
AccountManager.getInstance().logout();
}
public void setLogginUserinfo(UserInfoModel model) {
AccountManager.getInstance().setLogginUserInfo(model);
}
public void updataUserinfo(UserInfoModel model) {
AccountManager.getInstance().updatUser(model);
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
/**
* 点击输入法外,输入框消失
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
outLoactionDo();
}
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public void outLoactionDo() {
}
public boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = {0, 0};
// 获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
|
C++
|
UTF-8
| 1,936 | 3.5 | 4 |
[] |
no_license
|
#include "BigNums.h"
int main()
{
/*BigNumber bn1("99");
BigNumber bn2("10");
BigNumber bn3;
cout << bn2 << endl;
cout << bn2 << ">" <<bn1 << "? " << (bn2 > bn1) << endl;
cout << bn2 << "<" <<bn1 << "? " << (bn2 < bn1) << endl;
cin >> bn3;
cout << bn3 << endl;
bn3 = bn1 + bn2;
cout << bn3 << endl;
BigNumber bn4 = "21644413546598";
BigNumber bn5 = "96385265487513218464";
bn3 = bn4 - bn5;
cout << bn3 << endl;*/
BigNumber n1, n2;
int option;
bool flag = true;
while(flag)
{
cout << "\n\n\nPlease choose option:" << endl;
cout << "\t1. assign a new number (n1)" << endl;
cout << "\t2. assign a new number (n2)" << endl;
cout << "\t3. n1 + n2" << endl;
cout << "\t4. n1 - n2" << endl;
cout << "\t5. n1 > n2 ?" << endl;
cout << "\t6. n1 < n2 ?" << endl;
cout << "\t7. n1 == n2 ?" << endl;
cout << "\t8. print n1" << endl;
cout << "\t9. print n2" << endl;
cin >> option;
switch(option)
{
case 1:
cin >> n1;
break;
case 2:
cin >> n2;
break;
case 3:
cout << (n1 + n2) << endl;
break;
case 4:
cout << (n1 - n2) << endl;
break;
case 5:
cout << (n1 > n2) << endl;
break;
case 6:
cout << (n1 < n2) << endl;
break;
case 7:
cout << (n1 == n2) << endl;
break;
case 8:
cout << n1 << endl;
break;
case 9:
cout << n2 << endl;
break;
default:
flag = false;
break;
}
}
return 0;
}
|
C++
|
UTF-8
| 1,475 | 2.703125 | 3 |
[] |
no_license
|
#ifndef TTCHAT_CONVERSATION_H
#define TTCHAT_CONVERSATION_H
#include "SLPPacket.h"
#include "Client.h"
#include <mutex>
#include <list>
#include <thread>
#include <queue>
using namespace std;
class Chatroom
{
public:
//identyfikator rozmowy
uint64_t id;
private:
//lista klientów należących do rozmowy wraz z mutexem
list < FLP_Connection_t* > clientList;
std::mutex clientListLock;
std::queue <FLP_Connection_t*> waitingList;
std::mutex waitingListLock;
//kolejka wiadomości do obsłużenia przez wątek chatroomu z informacją, który klient ją umieścił
std::queue < std::pair < SLPPacket, FLP_Connection_t* > > chatroomQueue;
//wątek chatroomu
std::thread chatroomThread;
public:
Chatroom(uint64_t id);
void runThread();
void joinThread();
void detachThread();
void addClient(FLP_Connection_t* c);
void removeClient(FLP_Connection_t* c);
void forceRemoveClient(FLP_Connection_t* c);
bool isEmpty();
private:
void chatroomThreadFunc();
void manageQueueMessages();
/*
* funkcje do zarządzania wiadomościami
*/
void SUBREQManage(SLPPacket* msg, FLP_Connection_t* c);
void UNSUBManage(SLPPacket* msg, FLP_Connection_t* c);
void GETINFManage(SLPPacket* msg, FLP_Connection_t* c);
void PULLMSGSManage(SLPPacket* msg, FLP_Connection_t* c);
void MSGCLIManage(SLPPacket* msg, FLP_Connection_t* c);
};
#endif //TTCHAT_CONVERSATION_H
|
Python
|
UTF-8
| 211 | 2.859375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import os
import sys
def read_filenames(directory):
try:
file_names = os.listdir(directory)
return file_names
except:
print("Please use the linux format")
|
Python
|
UTF-8
| 5,154 | 2.671875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as etree
from pyconizer.lib.api.sld.v1_0_0.classes import PropertyIsLikeType
from pyconizer.lib.api.structure import Rule, NamedLayer
from pyconizer.lib.api.svg import create_svg_icon
# python 3 compatibility
from future.moves.urllib.request import urlopen
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def FactoryFromString(sld_content, encoding=None):
"""
Args:
sld_content (str): The content of an SLD to check for version and parse with the found module.
encoding (str): The encoding which is used to encode the XML. Standard is None. This means the
encoding is taken from the XML content itself. Only use this parameter if your XML content has no
encoding set.
Returns:
pyconizer.lib.api.sld.v1_0_0.classes.StyledLayerDescriptor: The complete objectified representation
of the SLD.
"""
parser = etree.XMLParser(encoding=encoding)
tree = etree.fromstring(sld_content, parser)
version = tree.attrib.get('version')
if version == '1.0.0':
from pyconizer.lib.api.sld.v1_0_0 import classes
found_version = classes
else:
raise LookupError('Version is not supported. Version of SLD was: {0}'.format(version))
output = StringIO(sld_content)
parsed_sld = found_version.parse(output, parser)
return parsed_sld
# def Factory(sld_file_path):
# """
#
# Args:
# sld_file_path (str): The SLD file to check for version and parse with the found module.
#
# Returns:
# pyconizer.lib.api.sld.v1_0_0.classes.StyledLayerDescriptor: The complete objectified representation
# of the SLD.
# """
# content = open(sld_file_path).read()
# return FactoryFromString(content)
def check_xml_version(sld_content):
"""
Small check for xml definition in first line of SLD xml content. For convenience reason we should use
this method to provide a correct xml for further processing.
Args:
sld_content (str): The xml string which should be checked for the magic first xml tag.
Returns:
str: The maybe updated xml string.
"""
if not str(sld_content).lstrip().startswith('<?xml '):
sld_content = '<?xml version="1.0" encoding="UTF-8" ?>\n{0}'.format(sld_content)
return sld_content
def load_sld_content(url):
"""
Load the SLD from the passed url.
Args:
url (str): The URL which should return a SLD generated from WMS.
Returns:
str: The SLD as XML in a simple string.
"""
response = urlopen(url)
return check_xml_version(response.read())
def extract_rules(sld_content, encoding=None):
"""
Extract all Rules with its name and classes.
Args:
sld_content (str): The SLD you want to split up in all its svg symbol definitions.
encoding (str): The encoding which is used to encode the XML. Standard is None. This means the
encoding is taken from the XML content itself. Only use this parameter if your XML content has no
encoding set.
Returns:
list of pyconizer.lib.api.structure.NamedLayer: A list of named layers and their image
configs all wrapped in application structure.
"""
sld_content = FactoryFromString(sld_content, encoding=encoding)
layers = []
for named_layer in sld_content.NamedLayer:
named_layer_name = named_layer.Name
rules = []
for user_style in named_layer.UserStyle:
for feature_type_style in user_style.FeatureTypeStyle:
for rule in feature_type_style.Rule:
# only comparison ops are supported now, if rule has no filter => What is this????
if not rule.Filter and rule.Name:
structure_rule = Rule(class_name=rule.Name)
structure_rule.set_svg(create_svg_icon(rule.Symbolizer))
rules.append(structure_rule)
elif rule.Filter and not rule.Name:
structure_rule = Rule(
filter_class=rule.Filter.comparisonOps.expression[1].get_valueOf_()
)
structure_rule.set_svg(create_svg_icon(rule.Symbolizer))
rules.append(structure_rule)
elif rule.Filter and rule.Name:
if isinstance(rule.Filter.comparisonOps, PropertyIsLikeType):
classifier = rule.Filter.comparisonOps.Literal.get_valueOf_()
else:
classifier = rule.Filter.comparisonOps.expression[1].get_valueOf_()
structure_rule = Rule(
class_name=rule.Name,
filter_class=classifier
)
structure_rule.set_svg(create_svg_icon(rule.Symbolizer))
rules.append(structure_rule)
layers.append(NamedLayer(name=named_layer_name, rules=rules))
return layers
|
Swift
|
UTF-8
| 1,864 | 2.71875 | 3 |
[] |
no_license
|
//
// NavigationMenuView.swift
// SwiftUIMovieDbMac
//
// Created by Djuro Alfirevic on 22/06/20.
// Copyright © 2020 Djuro Alfirevic. All rights reserved.
//
import SwiftUI
struct NavigationMenuView: View {
@ObservedObject var searchState = MovieSearchState()
@State var selection: String? = "Home"
// Remove Focus on Search Field when selected
private let cellProxy = ListCellProxy()
var body: some View {
List(selection: $selection) {
NavigationLink(destination: MovieSearchView().environmentObject(self.searchState), tag: "Search", selection: self.$selection) {
SearchFieldView(text: self.$searchState.query, onFocusChange: { focus in
if focus {
self.selection = "Search"
}
}) }
// .background(ListCellHelper(proxy: ListCellProxy()))
.padding(.vertical)
Section(header: Text("Discover")) {
NavigationLink(destination: HomeView(), tag: "Home", selection: self.$selection) {
Text("Home")
}
}.collapsible(false)
Section(header: Text("Browse")) {
ForEach(MovieListEndpoint.allCases) { endpoint in
NavigationLink(destination: NavigationDetailView(endpoint: endpoint), tag: endpoint.rawValue, selection: self.$selection) {
Text(endpoint.description)
}
}
}
.collapsible(false)
}
.listStyle(SidebarListStyle())
.frame(minWidth: 200, idealWidth: 200, maxWidth: 248, maxHeight: .infinity)
}
}
struct NavigationMenuView_Previews: PreviewProvider {
static var previews: some View {
NavigationMenuView()
}
}
|
Java
|
UTF-8
| 575 | 2.125 | 2 |
[] |
no_license
|
package org.scriptbox.box.jmx.proc;
import org.scriptbox.box.exec.AbstractExecBlock;
import org.scriptbox.box.exec.ExecRunnable;
import org.scriptbox.box.jmx.conn.JmxConnections;
public abstract class JmxProcessProvider extends AbstractExecBlock<ExecRunnable> {
private String name;
protected JmxConnections connections;
public JmxProcessProvider( JmxConnections connections, String name ) {
this.connections = connections;
this.name = name;
}
public JmxConnections getConnections() {
return connections;
}
public String getName() {
return name;
}
}
|
C++
|
GB18030
| 3,721 | 3.90625 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void test() {
string str("1234567890");
int size = str.size();
int cap = str.capacity();
//reserve(n) : n > capacityʱ,,һݺsize
str.reserve(20);
int size1 = str.size();
int cap1 = str.capacity();
//reserve(n) : С: n < sizeʱ,κβ,capacity > n > sizeʱ,мС
str.reserve(5);
int size2 = str.size();
int cap2 = str.capacity();
cout << size << endl;
cout << cap << endl;
cout << size1 << endl;
cout << cap1 << endl;
cout << size2 << endl;
cout << cap2 << endl;
}
void test2() {
string str("1234567890");
int ret1 = str.size(); //Чַĸ
int ret2 = str.length(); //Чַĸ
int ret3 = str.capacity(); //ԴŵЧַ
str.clear(); //ֻݲı
int ret = str.empty(); //ַǷΪմ,true, false
cout << ret << endl;
}
void test5() {
string str("1234567890");
//ɶд
//
string::iterator it = str.begin();
while (it != str.end()) {
cout << *it << " ";
//*it = 'x';
++it;
}
cout << endl;
//
string::reverse_iterator rit = str.rbegin();
while (rit != str.rend()) {
cout << *rit << " ";
++rit;
}
cout << endl;
}
void test6() {
string str("1234567890");
//const:֧д,Ϊֻ
string::const_iterator cit = str.cbegin();
while (cit != str.cend()) {
cout << *cit << " ";
++cit;
}
cout << endl;
string::const_reverse_iterator crt = str.crbegin();
while (crt != str.crend()) {
cout << *crt << " ";
++crt;
}
cout << endl;
}
void test7() {
string str("1234567890");
//
string::iterator it = str.begin();
while (it != str.end()) {
cout << *it << " ";
++it;
}
cout << endl;
//operator[]:ɶдӿ,Խ,Ƿ
for (int i = 0; i < str.size(); ++i) {
cout << str.operator[](i) << " ";
}
cout << endl;
//operator[]д:
for (int i = 0; i < str.size(); ++i) {
cout << str[i] << " ";
}
cout << endl;
//at:ɶд,ǿɶԲǿ,Խ,׳쳣
for (int i = 0; i < str.size(); ++i) {
cout << str.at(i) << " ";
}
cout << endl;
//Χfor:ֶ֧д, ҪģΪ
//ײͨʵ
for ( auto& ch : str) {
cout << ch << " ";
}
cout << endl;
}
//ַ
void test8() {
string str1;
str1.push_back('a'); //a
str1.append(2, 'b'); //abb
str1.append("cde"); //abbcde
string str2;
str2.append(str1); //abbcde
string str3;
str3.append(str1, 3, 2); //cd
char strArr[] = "1234";
str3.append(strArr, strArr + 2); //cd12
str3.append(str2.begin(), str2.end()); //cd12abbcde
string str4;
str4 += '1'; //1
str4 += "234"; //1234
str4 += str1; //1234abbcde
}
void test9() {
string str("aaaaaaaaa");
size_t pos = str.find('b'); //,ҵһƥλþͽ
size_t pos2 = str.find('a'); //,ҵһƥλþͽ
string filel = "test.tar.gz.zip";
pos = filel.rfind('.');
//substr(pos,len) :lenڴposλõַ,ʣַȫȡ
string str2 = filel.substr(pos + 1, filel.size() - 1 - pos);
string str3 = filel.substr(pos + 1);
cout << str2 << endl;
cout << str3 << endl;
}
void test10() {
string s1 = "9";
string s2 = "123";
string s3 = "1234";
/*bool ret = s1 > s2;
ret = s2 > s3;
ret = s1 > s3;*/
string s;
//cin >> s;
getline(cin, s);
cout << s;
}
int main() {
test10();
return 0;
}
|
Java
|
UTF-8
| 7,178 | 1.78125 | 2 |
[
"MIT"
] |
permissive
|
package betterquesting.client.gui2.party;
import betterquesting.api.api.QuestingAPI;
import betterquesting.api.enums.EnumPacketAction;
import betterquesting.api.network.QuestingPacket;
import betterquesting.api.questing.party.IParty;
import betterquesting.api.utils.RenderUtils;
import betterquesting.api2.client.gui.GuiScreenCanvas;
import betterquesting.api2.client.gui.controls.IPanelButton;
import betterquesting.api2.client.gui.controls.PanelButton;
import betterquesting.api2.client.gui.controls.PanelButtonStorage;
import betterquesting.api2.client.gui.controls.PanelTextField;
import betterquesting.api2.client.gui.controls.filters.FieldFilterString;
import betterquesting.api2.client.gui.events.IPEventListener;
import betterquesting.api2.client.gui.events.PEventBroadcaster;
import betterquesting.api2.client.gui.events.PanelEvent;
import betterquesting.api2.client.gui.events.types.PEventButton;
import betterquesting.api2.client.gui.misc.GuiAlign;
import betterquesting.api2.client.gui.misc.GuiPadding;
import betterquesting.api2.client.gui.misc.GuiRectangle;
import betterquesting.api2.client.gui.misc.GuiTransform;
import betterquesting.api2.client.gui.panels.CanvasTextured;
import betterquesting.api2.client.gui.panels.bars.PanelVScrollBar;
import betterquesting.api2.client.gui.panels.content.PanelTextBox;
import betterquesting.api2.client.gui.panels.lists.CanvasScrolling;
import betterquesting.api2.client.gui.themes.presets.PresetColor;
import betterquesting.api2.client.gui.themes.presets.PresetTexture;
import betterquesting.api2.utils.QuestTranslation;
import betterquesting.network.PacketSender;
import betterquesting.network.PacketTypeNative;
import betterquesting.questing.party.PartyManager;
import betterquesting.storage.NameCache;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.nbt.NBTTagCompound;
import org.lwjgl.input.Keyboard;
import java.util.List;
import java.util.UUID;
public class GuiPartyInvite extends GuiScreenCanvas implements IPEventListener
{
private IParty party;
private PanelTextField<String> flName;
public GuiPartyInvite(GuiScreen parent)
{
super(parent);
}
@Override
public void initPanel()
{
super.initPanel();
UUID playerID = QuestingAPI.getQuestingUUID(mc.player);
this.party = PartyManager.INSTANCE.getUserParty(playerID);
if(party == null)
{
mc.displayGuiScreen(parent);
return;
}
PEventBroadcaster.INSTANCE.register(this, PEventButton.class);
Keyboard.enableRepeatEvents(true);
// Background panel
CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture());
this.addPanel(cvBackground);
cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back")));
PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.party_invite", party.getName())).setAlignment(1);
txTitle.setColor(PresetColor.TEXT_HEADER.getColor());
cvBackground.addPanel(txTitle);
flName = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(32, 32, 72, -48), 0), "", FieldFilterString.INSTANCE);
flName.setMaxLength(16);
flName.setWatermark("Username");
cvBackground.addPanel(flName);
PanelButton btnInvite = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-72, 32, 32, -48), 0), 1, QuestTranslation.translate("betterquesting.btn.party_invite"));
cvBackground.addPanel(btnInvite);
CanvasScrolling cvNameList = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(32, 64, 40, 32), 0));
cvBackground.addPanel(cvNameList);
PanelVScrollBar scNameScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0));
cvBackground.addPanel(scNameScroll);
scNameScroll.getTransform().setParent(cvNameList.getTransform());
cvNameList.setScrollDriverY(scNameScroll);
int listWidth = cvBackground.getTransform().getWidth() - 64;
int nameSize = RenderUtils.getStringWidth("________________", fontRenderer);
int columnNum = listWidth/nameSize;
List<String> nameList = NameCache.INSTANCE.getAllNames();
for(NetworkPlayerInfo info : mc.player.connection.getPlayerInfoMap())
{
if(!nameList.contains(info.getGameProfile().getName()))
{
nameList.add(info.getGameProfile().getName());
}
}
boolean[] invited = new boolean[nameList.size()];
for(int i = 0; i < nameList.size(); i++)
{
UUID memID = NameCache.INSTANCE.getUUID(nameList.get(i));
invited[i] = memID != null && party.getStatus(memID) != null;
}
for(int i = 0; i < nameList.size(); i++)
{
int x1 = i % columnNum;
int y1 = i / columnNum;
String name = nameList.get(i);
PanelButtonStorage<String> btnName = new PanelButtonStorage<>(new GuiRectangle(x1 * nameSize, y1 * 16, nameSize, 16), 2, name, name);
cvNameList.addPanel(btnName);
btnName.setActive(!invited[i]);
}
scNameScroll.setActive(cvNameList.getScrollBounds().getHeight() > 0);
}
@Override
public void onPanelEvent(PanelEvent event)
{
if(event instanceof PEventButton)
{
onButtonPress((PEventButton)event);
}
}
@SuppressWarnings("unchecked")
private void onButtonPress(PEventButton event)
{
IPanelButton btn = event.getButton();
if(btn.getButtonID() == 0) // Exit
{
mc.displayGuiScreen(this.parent);
} else if(btn.getButtonID() == 1 && flName.getRawText().length() > 0) // Manual Invite
{
NBTTagCompound tags = new NBTTagCompound();
tags.setInteger("action", EnumPacketAction.INVITE.ordinal());
tags.setInteger("partyID", PartyManager.INSTANCE.getID(party));
tags.setString("target", flName.getRawText());
PacketSender.INSTANCE.sendToServer(new QuestingPacket(PacketTypeNative.PARTY_EDIT.GetLocation(), tags));
} else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Invite
{
NBTTagCompound tags = new NBTTagCompound();
tags.setInteger("action", EnumPacketAction.INVITE.ordinal());
tags.setInteger("partyID", PartyManager.INSTANCE.getID(party));
tags.setString("target", ((PanelButtonStorage<String>)btn).getStoredValue());
PacketSender.INSTANCE.sendToServer(new QuestingPacket(PacketTypeNative.PARTY_EDIT.GetLocation(), tags));
btn.setActive(false);
}
}
}
|
C#
|
UTF-8
| 2,435 | 2.59375 | 3 |
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using QTask.Models;
namespace QTask.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class TaskController : Controller
{
private readonly TaskManagementDbContext _context;
public TaskController(TaskManagementDbContext context)
{
_context = context;
if (_context.Tasks.Count() == 0)
{
//_context.Tasks.Add(new Task { Name = "First Task" });
//_context.SaveChanges();
}
}
// GET: api/Task
[HttpGet]
public IEnumerable<Task> Get()
{
return _context.Tasks
.Include(t => t.Executor)
.ToList();
}
// GET: api/Task/5
[HttpGet("{id}", Name = "GetTask")]
public IActionResult GetById(long id)
{
var task = _context.Tasks
.Include(t => t.Project)
.Include(t => t.Executor)
.FirstOrDefault(t => t.TaskId == id);
if (task == null)
{
return NotFound();
}
return new ObjectResult(task);
}
// POST: api/Task
[HttpPost]
public IActionResult Post([FromBody]Task task)
{
_context.Tasks.Add(task);
_context.SaveChanges();
return new ObjectResult(task);
}
// PUT: api/Task/5
[HttpPut("{id}")]
public IActionResult Put(long id, [FromBody]Task task)
{
var foundTask = _context.Tasks.Find(id);
if (foundTask == null)
{
return NotFound();
}
foundTask.IsCompleted = task.IsCompleted;
foundTask.Name = task.Name;
_context.Tasks.Update(foundTask);
_context.SaveChanges();
return NoContent();
}
// DELETE: api/Task/5
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
var task = _context.Tasks.Find(id);
if (task == null)
{
return NotFound();
}
_context.Tasks.Remove(task);
_context.SaveChanges();
return NoContent();
}
}
}
|
Markdown
|
UTF-8
| 1,465 | 3.0625 | 3 |
[] |
no_license
|
---
layout: post
title: Codility - PermMissingElem
date: 2018-02-21 20:37:1 +0900
category: codility
---
[RESULT](https://app.codility.com/demo/results/trainingRVBEZW-857)
```java
import java.util.*;
class Solution {
public int solution(int[] A) {
boolean[] array = new boolean[100002];
for (int a : A) {
array[a] = true;
}
for (int i = 1; i <= array.length; i++) {
if (!array[i]) {
return i;
}
}
return 100001;
}
}
```
문제를 잘못 읽어 배열 크기 산정을 잘못했다.
[RESULT](https://app.codility.com/demo/results/training9HAYQ2-JDV)
```java
import java.util.*;
class Solution {
public int solution(int[] A) {
boolean[] array = new boolean[A.length + 2];
for (int a : A) {
array[a] = true;
}
for (int i = 1; i <= array.length; i++) {
if (!array[i]) {
return i;
}
}
return 100001;
}
}
```
다른 풀이를 보지 않았다면 생각해 낼 수 있었을까?
[RESULT](https://app.codility.com/demo/results/trainingESVKRT-VN6)
```java
import java.util.*;
class Solution {
public int solution(int[] A) {
long sum = (long) (A.length + 1) * (A.length + 2) / 2;
for (int a : A) {
sum -= a;
}
return (int) sum;
}
}
```
|
Java
|
UTF-8
| 1,028 | 2.9375 | 3 |
[] |
no_license
|
package com.soebes.katas.java8;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
public class StreamsTest {
@Test
public void testName() throws Exception {
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
List<Runnable> runnables = List.of(
() -> {
String threadName = Thread.currentThread()
.getName();
System.out.println("Hello 1 " + threadName);
},
() -> {
String threadName = Thread.currentThread()
.getName();
System.out.println("Hello 2 " + threadName);
},
() -> {
String threadName = Thread.currentThread()
.getName();
System.out.println("Hello 3 " + threadName);
},
() -> {
String threadName = Thread.currentThread()
.getName();
System.out.println("Hello 4 " + threadName);
});
runnables.forEach(newSingleThreadExecutor::submit);
}
}
|
Markdown
|
UTF-8
| 1,017 | 3.09375 | 3 |
[] |
no_license
|
# **Finding Lane Lines on the Road**
Overview
---
[//]: # (Image References)
[img]: ./test_images/solidWhiteRight.jpg "Input"
[outImg]: ./test_images_output/solidWhiteRight.jpg "Ouput"
This project includes a Jupyter Notebook with the same code as in LineDetect.py so you can run it how you prefer.
It will run through all the images stored in test_images
and create a copy of each with lane lines drawn on as well as a line down the middle in a folder named test_images_output(this folder will be created if it doesn't exist and overwritten if it does).
It then also runs though all the videos in test_videos
and draws similar lines on each frame of each video before saving it to
test_videos_output(this folder will be created if it doesn't exist and overwritten if it does).
The four directories test_images_output and test_videos_output already have example output corresponding to the images and videos in test_images and test_videos
Example input image:
![img]
Corresponding output image:
![outImg]
|
Markdown
|
UTF-8
| 1,358 | 2.671875 | 3 |
[] |
no_license
|
---
layout: post
title: Pylint
wordpress_id: 140
wordpress_url: http://blog.malev.com.ar/?p=140
comments: true
categories:
- title: Programacion
slug: programacion
autoslug: programacion
- title: Python
slug: python
autoslug: python
tags:
- title: buenas practicas
slug: buenas-practicas
autoslug: buenas-practicas
- title: Python
slug: python
autoslug: python
---
{{ page.title }}
================
**Pylin** [1] un programa que analiza el código **python** en busca de errores, bugs y “malas prácticas”. Muy interesante si recién estas empezando con python y quieres escribir código como corresponde.
Eso sí, pylint reta bastante, de hecho [2] nos recomienda un archivo de configuración para que pylint nos trate un poco mejor :D
Por cierto, [3] nos enseña a configurarlo en Eclipse. Yo uso gedit, así que no he probado esa opción.
Una cosa más, quiero agradecer a Gonzalo [4] por recomendarlo.
[1] [http://pypi.python.org/pypi/pylint](http://pypi.python.org/pypi/pylint)
[2] [http://conalambre.wordpress.com/2009/01/31/pylint-chequear-codigo-escrito-en-python/](http://conalambre.wordpress.com/2009/01/31/pylint-chequear-codigo-escrito-en-python/)
[3] [http://hdlorean.wikidot.com/tutoriales:pylint](http://hdlorean.wikidot.com/tutoriales:pylint)
[4] [http://twitter.com/gonzalodelgado](http://twitter.com/gonzalodelgado)
|
C#
|
UTF-8
| 685 | 3.40625 | 3 |
[] |
no_license
|
using System;
namespace Aula_9_atividade
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine ("Digite o valor do produto");
double Valoruser = double.Parse (Console.ReadLine () ) ;
Console.WriteLine ("Digite o valor do desconto");
double Porc = double.Parse (Console.ReadLine () ) ;
Console.WriteLine (contavinicius (Valoruser, Porc) );
}
static double contavinicius (double v1, double v2){
double resultado =0;
resultado = (v1 * v2) / 100;
// resultado ;
return resultado;
}
}
}
|
C#
|
UTF-8
| 434 | 2.90625 | 3 |
[] |
no_license
|
using System;
namespace RabbitWrapper
{
public static class DateTimeExtensions
{
static readonly DateTime EpochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
// Unix time
public static long SecondsSinceEpoch(this DateTime date)
{
var timeSinceEpoch = date.Subtract(EpochTime);
return (long) timeSinceEpoch.TotalSeconds;
}
}
}
|
Python
|
UTF-8
| 921 | 2.5625 | 3 |
[] |
no_license
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#Author by 2019/05/11 Split fa[sta] into sliding window
import sys,re
from Bio import SeqIO
winw = int(sys.argv[3])
step = int(sys.argv[4])
with open(sys.argv[2], "w") as out:
for record in SeqIO.parse(sys.argv[1], "fasta"):
seq = str(record.seq)
lnth = len(seq)
if winw>=lnth:
if re.search(r"^N+$", seq, flags=0):
pass
else:
out.write(">"+record.id+"\n")
out.write(seq+"\n")
continue
num = (lnth-winw) // step + 1
for i in range(1, num+1):
stt = step*(i-1)
end = step*(i-1) + winw
slice = seq[stt:end]
if re.search(r"^N+$", slice, flags=0):
pass
else:
out.write(">"+record.id+"-"+str(i)+"\n")
out.write(slice+"\n")
|
JavaScript
|
UTF-8
| 1,369 | 2.625 | 3 |
[] |
no_license
|
// $(document).ready(function () {
// $.ajax({
// //url: 'http://localhost:3000/api/get/aaa',
// url: 'ttie.eba-9cjewynp.ap-southeast-2.elasticbeanstalk.com',
// success:function(data) {
// let all = data;
// console.log(data);
// let fruit = $("#111");
// let a = data[0].L_Name
// let para = '<p>' + a + '</p>'
// fruit.append(para)
// }
// });
var url = 'http://ttie-env.eba-9cjewynp.ap-southeast-2.elasticbeanstalk.com'
// });
function choose() {
//var selectarea = document.getElementById("selectionarea");
//var valarea = selectarea.option[selectarea.selectedIndex].value
var valarea = $( "#selectionarea option:selected" ).text();
var valfruit = $( "#selectionfruit option:selected" ).text();
//var selectfruit = document.getElementById("selectionfruit");
//var valfruit = selectfruit.option[selectfruit.selectedIndex].value
console.log(valarea)
console.log(valfruit)
$.ajax({
url: this.url + '/api/get/' + valarea + '/' + valfruit,
success:function(data) {
console.log(data)
let div = $("#qwert")
let para = '<p>' + data[0].Preventive_Methods + data[0].Control_Methodds+'</p>'
div.append(para)
}
})
}
|
C#
|
UTF-8
| 818 | 3.53125 | 4 |
[] |
no_license
|
using System;
using NodaTime;
class Test
{
static void Main()
{
ShowAge(1988, 9, 6);
ShowAge(1991, 3, 31);
ShowAge(1991, 2, 25);
}
private static readonly PeriodType YearMonth =
PeriodType.YearMonthDay.WithDaysRemoved();
static void ShowAge(int year, int month, int day)
{
var birthday = new LocalDate(year, month, day);
// For consistency for future readers :)
var today = new LocalDate(2012, 2, 3);
Period period = Period.Between(birthday, today, YearMonth);
Console.WriteLine("Birthday: {0}; Age: {1} years, {2} months",
birthday, period.Years, period.Months);
}
}
|
Java
|
UTF-8
| 3,432 | 2.640625 | 3 |
[] |
no_license
|
package com.lightmesh.h2compress;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.DeleteDbFiles;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
public static String path_to_h2 = System.getProperty("user.dir");
public static String h2_file = "test.h2";
private H2ReWrite app;
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
public void setUp() {
// create database
this.app = new H2ReWrite(path_to_h2 + "/" + h2_file,
path_to_h2 + "/test_clean.h2");
try {
System.out.println( "Creating test database in " + path_to_h2 );
create_test_db(path_to_h2 + "/" + h2_file);
System.out.println( "Test DB written");
} catch(Exception e) {
System.out.println(e);
}
}
//public void tearDown() {
// // delete database
// DeleteDbFiles.execute(path_to_h2, h2_file, true);
// System.out.println("test database deleted.");
//}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
// Test exporting database
public void testExport()
{
boolean backup_ok = false;
try {
backup_ok = this.app.exportDatabase();
} catch( SQLException e ) {
System.out.println( e );
}
assertTrue( backup_ok == true );
}
// Test backing up database
public void testBackup()
{
boolean backup_ok = false;
try {
backup_ok = this.app.backupDatabase();
} catch( SQLException e ) {
System.out.println( e );
}
assertTrue( backup_ok == true );
}
// Test restore database
public void testRestore()
{
boolean restore_ok = false;
try {
restore_ok = this.app.restoreDatabase();
} catch( SQLException e ) {
System.out.println( e );
}
assertTrue( restore_ok == true );
}
/********************************************************************
* PRIVATE Helpers
**/
private void create_test_db(String h2_db_file) throws java.sql.SQLException {
Connection conn = this.app.getDBConnection(h2_db_file);
Statement stmt = null;
try {
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.execute("CREATE TABLE PERSON(id int primary key, name varchar(255))");
stmt.execute("INSERT INTO PERSON(id, name) VALUES(1, 'Anju')");
stmt.execute("INSERT INTO PERSON(id, name) VALUES(2, 'Sonia')");
stmt.execute("INSERT INTO PERSON(id, name) VALUES(3, 'Asha')");
ResultSet rs = stmt.executeQuery("select * from PERSON");
System.out.println("H2 Database inserted through Statement");
while (rs.next()) {
System.out.println("Id "+rs.getInt("id")+" Name "+rs.getString("name"));
}
stmt.close();
conn.commit();
} catch (SQLException e) {
System.out.println("Exception Message " + e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
}
}
}
|
SQL
|
UTF-8
| 12,002 | 3.359375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 3.3.10
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2016 年 07 月 28 日 22:22
-- 服务器版本: 5.6.14
-- PHP 版本: 5.4.34
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- 数据库: `fecshop`
--
-- --------------------------------------------------------
--
-- 表的结构 `admin_config`
--
CREATE TABLE IF NOT EXISTS `admin_config` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`label` varchar(150) DEFAULT NULL,
`key` varchar(255) DEFAULT NULL,
`value` varchar(2555) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`created_person` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
--
-- 转存表中的数据 `admin_config`
--
INSERT INTO `admin_config` (`id`, `label`, `key`, `value`, `description`, `created_at`, `updated_at`, `created_person`) VALUES
(6, '品牌统计-订单处理脚本,多少月前', 'brand_order_month_before', '10', '取多少个月前的订单', '2016-04-26 17:53:30', '2016-06-30 11:58:50', 'admin'),
(7, '品牌统计-广告数量最大个数', 'brand_show_count', '22', '品牌统计-广告数量最大个数', '2016-04-28 16:41:13', '2016-07-05 10:01:34', 'admin'),
(8, '废弃-多少月前的数据 - erp_on_way_count_by_day', 'erp_on_way_count_by_day_before_months', '24', '对应erpCollInit脚本 - 处理表:erp_on_way_count_by_day ,增加subtotal字段功能,处理多少个月之前的表数据', '2016-05-24 15:56:39', '2016-06-30 12:01:53', 'admin'),
(9, 'ebayOrder脚本的跑的月范围', 'ebay_order_month_before', '10', '当前时间多少月之前的订单,进行处理', '2016-07-01 14:59:48', '2016-07-01 14:59:48', 'admin');
-- --------------------------------------------------------
--
-- 表的结构 `admin_menu`
--
CREATE TABLE IF NOT EXISTS `admin_menu` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`name` varchar(150) DEFAULT NULL,
`level` int(5) DEFAULT NULL,
`parent_id` int(15) DEFAULT NULL,
`url_key` varchar(255) DEFAULT NULL,
`role_key` varchar(150) DEFAULT NULL COMMENT '权限key,也就是controller的路径,譬如/fecadmin/menu/managere,controller 是MenuController,当前的值为:/fecadmin/menu',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`sort_order` int(10) NOT NULL DEFAULT '0',
`can_delete` int(5) DEFAULT '2' COMMENT '是否可以被删除,1代表不可以删除,2代表可以删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=189 ;
--
-- 转存表中的数据 `admin_menu`
--
INSERT INTO `admin_menu` (`id`, `name`, `level`, `parent_id`, `url_key`, `role_key`, `created_at`, `updated_at`, `sort_order`, `can_delete`) VALUES
(164, '控制面板', 1, 0, '/ddd', NULL, '2016-01-15 10:21:36', '2016-01-15 10:21:36', 0, 1),
(165, '用户管理', 2, 164, '/ddd', NULL, '2016-01-15 10:23:01', '2016-01-15 10:23:01', 0, 1),
(166, '菜单管理', 2, 164, '/fecadmin/menu/manager', '/fecadmin/menu', '2016-01-15 10:23:22', '2016-01-16 16:45:23', 0, 1),
(167, '我的账户', 3, 165, '/fecadmin/myaccount/index', '/fecadmin/myaccount', '2016-01-15 10:24:29', '2016-01-16 16:07:58', 0, 1),
(168, '账户管理', 3, 165, '/fecadmin/account/manager', '/fecadmin/account', '2016-01-15 10:24:51', '2016-01-21 15:24:18', 0, 1),
(169, '权限管理', 3, 165, '/fecadmin/role/manager', '/fecadmin/role', '2016-01-15 10:25:10', '2016-01-21 13:22:39', 0, 1),
(170, '操作日志', 2, 164, '/fecadmin/log/index', '/fecadmin/log', '2016-01-15 10:35:19', '2016-01-16 16:45:18', 0, 1),
(171, '缓存管理', 2, 164, '/fecadmin/cache/index', '/fecadmin/cache', '2016-01-15 10:35:40', '2016-01-16 16:45:14', 0, 1),
(177, 'CMS', 1, 0, '/x/x/x', '/x/x', '2016-07-11 21:16:56', '2016-07-16 09:32:30', 5, 2),
(178, 'Article', 2, 177, '/cms/article/index', '/cms/article', '2016-07-11 21:17:17', '2016-07-11 21:17:17', 0, 2),
(179, 'Catalog', 1, 0, '/x/x/x', '/x/x', '2016-07-22 16:01:37', '2016-07-22 16:01:44', 100, 2),
(180, '产品管理', 2, 179, '/catalog/product/index', '/catalog/product', '2016-07-22 16:02:01', '2016-07-22 16:07:03', 100, 2),
(181, 'Url 重写管理', 2, 179, '/catalog/urlrewrite/index', '/catalog/urlrewrite', '2016-07-22 16:02:49', '2016-07-22 16:10:14', 0, 2),
(182, '分类管理', 2, 179, '/catalog/category/index', '/catalog/category', '2016-07-22 16:03:05', '2016-07-22 16:07:11', 90, 2),
(183, '后台配置', 2, 164, '/fecadmin/config/manager', '/fecadmin/config', '2016-07-22 16:05:31', '2016-07-22 16:05:31', 0, 2),
(184, 'LOG打印输出', 2, 164, '/fecadmin/systemlog/manager', '/fecadmin/systemlog', '2016-07-22 16:05:56', '2016-07-22 16:05:56', 0, 2),
(185, '产品信息管理', 3, 180, '/catalog/productinfo/index', '/catalog/productinfo', '2016-07-22 16:08:17', '2016-07-22 16:08:17', 0, 2),
(186, '产品评论管理', 3, 180, '/catalog/productreview/index', '/catalog/productreview', '2016-07-22 16:08:35', '2016-07-22 16:08:35', 0, 2),
(187, '产品搜索管理', 3, 180, '/catalog/productsearch/index', '/catalog/productsearch', '2016-07-22 16:09:41', '2016-07-22 16:09:41', 0, 2),
(188, '产品Tag管理', 3, 180, '/catalog/producttag/index', '/catalog/producttag', '2016-07-22 16:09:57', '2016-07-22 16:09:57', 0, 2);
-- --------------------------------------------------------
--
-- 表的结构 `admin_role`
--
CREATE TABLE IF NOT EXISTS `admin_role` (
`role_id` int(15) NOT NULL AUTO_INCREMENT,
`role_name` varchar(100) CHARACTER SET utf8 DEFAULT NULL COMMENT '权限名字',
`role_description` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '权限描述',
PRIMARY KEY (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- 转存表中的数据 `admin_role`
--
INSERT INTO `admin_role` (`role_id`, `role_name`, `role_description`) VALUES
(4, 'admin', '超级用户'),
(12, '账户管理员', '账户管理员'),
(13, 'ceshi', 'ceshi');
-- --------------------------------------------------------
--
-- 表的结构 `admin_role_menu`
--
CREATE TABLE IF NOT EXISTS `admin_role_menu` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`menu_id` int(15) NOT NULL,
`role_id` int(15) NOT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;
--
-- 转存表中的数据 `admin_role_menu`
--
INSERT INTO `admin_role_menu` (`id`, `menu_id`, `role_id`, `created_at`, `updated_at`) VALUES
(4, 164, 4, '2016-01-16 11:19:15', '2016-01-16 11:19:15'),
(33, 165, 12, '2016-01-16 12:05:01', '2016-01-16 12:05:01'),
(34, 167, 12, '2016-01-16 12:05:01', '2016-01-16 12:05:01'),
(36, 169, 12, '2016-01-16 12:05:01', '2016-01-16 12:05:01'),
(37, 164, 12, '2016-01-16 12:05:01', '2016-01-16 12:05:01'),
(38, 165, 4, '2016-01-16 14:46:17', '2016-01-16 14:46:17'),
(39, 167, 4, '2016-01-16 14:46:17', '2016-01-16 14:46:17'),
(41, 169, 4, '2016-01-16 14:46:17', '2016-01-16 14:46:17'),
(43, 171, 4, '2016-01-16 14:46:17', '2016-01-16 14:46:17'),
(46, 166, 4, '2016-01-16 17:47:30', '2016-01-16 17:47:30'),
(49, 168, 4, '2016-01-18 12:16:49', '2016-01-18 12:16:49'),
(50, 170, 4, '2016-01-18 12:16:49', '2016-01-18 12:16:49'),
(51, 164, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(52, 165, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(53, 167, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(54, 168, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(55, 169, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(56, 166, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(57, 170, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(58, 171, 13, '2016-01-21 14:12:09', '2016-01-21 14:12:09'),
(64, 177, 4, '2016-07-11 21:17:46', '2016-07-11 21:17:46'),
(65, 178, 4, '2016-07-11 21:17:46', '2016-07-11 21:17:46'),
(66, 179, 4, '2016-07-22 16:04:25', '2016-07-22 16:04:25'),
(67, 180, 4, '2016-07-22 16:04:25', '2016-07-22 16:04:25'),
(68, 182, 4, '2016-07-22 16:04:25', '2016-07-22 16:04:25'),
(69, 181, 4, '2016-07-22 16:04:25', '2016-07-22 16:04:25'),
(70, 183, 4, '2016-07-22 16:06:10', '2016-07-22 16:06:10'),
(71, 184, 4, '2016-07-22 16:06:10', '2016-07-22 16:06:10'),
(72, 185, 4, '2016-07-22 16:10:22', '2016-07-22 16:10:22'),
(73, 186, 4, '2016-07-22 16:10:22', '2016-07-22 16:10:22'),
(74, 187, 4, '2016-07-22 16:10:22', '2016-07-22 16:10:22'),
(75, 188, 4, '2016-07-22 16:10:22', '2016-07-22 16:10:22');
-- --------------------------------------------------------
--
-- 表的结构 `admin_user`
--
CREATE TABLE IF NOT EXISTS `admin_user` (
`id` int(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL COMMENT '用户名',
`password_hash` varchar(80) DEFAULT NULL COMMENT '密码',
`password_reset_token` varchar(60) DEFAULT NULL COMMENT '密码token',
`email` varchar(60) DEFAULT NULL COMMENT '邮箱',
`person` varchar(100) DEFAULT NULL COMMENT '用户姓名',
`code` varchar(100) DEFAULT NULL,
`auth_key` varchar(60) DEFAULT NULL,
`status` int(5) DEFAULT NULL COMMENT '状态',
`created_at` int(18) DEFAULT NULL COMMENT '创建时间',
`updated_at` int(18) DEFAULT NULL COMMENT '更新时间',
`password` varchar(50) DEFAULT NULL COMMENT '密码',
`access_token` varchar(60) DEFAULT NULL,
`allowance` int(20) DEFAULT NULL,
`allowance_updated_at` int(20) DEFAULT NULL,
`created_at_datetime` datetime DEFAULT NULL,
`updated_at_datetime` datetime DEFAULT NULL,
`birth_date` datetime DEFAULT NULL COMMENT '出生日期',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `access_token` (`access_token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- 转存表中的数据 `admin_user`
--
INSERT INTO `admin_user` (`id`, `username`, `password_hash`, `password_reset_token`, `email`, `person`, `code`, `auth_key`, `status`, `created_at`, `updated_at`, `password`, `access_token`, `allowance`, `allowance_updated_at`, `created_at_datetime`, `updated_at_datetime`, `birth_date`) VALUES
(1, 'terry', '$2y$13$EyK1HyJtv4A/19Jb8gB5y.4SQm5y93eMeHjUf35ryLyd2dWPJlh8y', NULL, 'zqy234@126.com', '', '3333', 'HH-ZlZXirlG-egyz8OTtl9EVj9fvKW00', 1, 1441763620, 1467522167, '', 'yrYWR7kY-A9bUAP6UUZgCR3yi3ALtUh-', 599, 1452491877, '2016-01-12 09:41:44', '2016-07-03 13:02:47', NULL),
(2, 'admin', '$2y$13$T5ZFrLpJdTEkAoAdnC6A/u8lh/pG.6M0qAZBo1lKE.6x6o3V6yvVG', NULL, '3727@qq.com', '超级管理员', '111', '_PYjb4PdIIY332LquBRC5tClZUXV0zm_', 1, NULL, 1468917063, '', '1Gk6ZNn-QaBaKFI4uE2bSw0w3N7ej72q', NULL, NULL, '2016-01-11 09:41:52', '2016-06-26 01:40:55', NULL);
-- --------------------------------------------------------
--
-- 表的结构 `admin_user_role`
--
CREATE TABLE IF NOT EXISTS `admin_user_role` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`user_id` int(30) NOT NULL,
`role_id` int(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- 转存表中的数据 `admin_user_role`
--
INSERT INTO `admin_user_role` (`id`, `user_id`, `role_id`) VALUES
(1, 2, 4),
(2, 2, 12),
(3, 1, 12),
(4, 1, 13);
-- --------------------------------------------------------
--
-- 表的结构 `admin_visit_log`
--
CREATE TABLE IF NOT EXISTS `admin_visit_log` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`account` varchar(25) DEFAULT NULL COMMENT '操作账号',
`person` varchar(25) DEFAULT NULL COMMENT '操作人姓名',
`created_at` datetime DEFAULT NULL COMMENT '操作时间',
`menu` varchar(100) DEFAULT NULL COMMENT '菜单',
`url` varchar(255) DEFAULT NULL COMMENT 'URL',
`url_key` varchar(150) DEFAULT NULL COMMENT '参数',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- 转存表中的数据 `admin_visit_log`
--
|
Shell
|
UTF-8
| 443 | 2.9375 | 3 |
[] |
no_license
|
#!/bin/sh
# Specify appropriate SWT library!
SWT_JAR=libs/ext/swt/swt-gtk-linux-x86_64.jar
JARS=$SWT_JAR
for f in libs/*.jar
do
JARS=$JARS:$f
done
export MOZILLA_FIVE_HOME=/usr/lib/`rpm -q firefox | sed -e "s/\(firefox-[^-]*\)-.*/\1/"`
#export MOZILLA_FIVE_HOME=/usr/lib64/xulrunner-1.9.2.20/
export LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME:$LD_LIBRARY_PATH
java -Xmx512M -classpath build/classes:$JARS -Djava.library.path=$SWT_JAR: Demo
|
C
|
UTF-8
| 3,212 | 3.625 | 4 |
[] |
no_license
|
#include "grafo.h"
#include "pilha.h"
#include "fila.h"
//funcao retorna um tad de grafo
Grafo criaGrafo(int n){
int i;
//cria ponteiro para uma estrutura de grafo
Grafo* g = (Grafo*) malloc(sizeof(Grafo));
//cria uma lista de ponteiros que apontam para as listas de adjacencia
g->lista = (No**) malloc(sizeof(No*)*n);
//guarda o inicio de cada uma das listas, sendo cada noh um dos vertices do grafo (0 a n-1)
for(i = 0; i < n; i++){
No* n = (No*) malloc(sizeof(No)); //alocando espaco de um no da lista ligada
n->vert = i; //define o vertice
n->prox = NULL; //proximo = NULL -> lista vazia
g->lista[i] = n; //guarda o ponteiro no array de ponteiros do grafo
}
return (*g); //retorna o tad apontado pelo ponteiro de grafo
}
void insereAresta(Grafo *g, int v, int u){
//cria um noh auxiliar com o valor de vertice v
No* copia_v = (No*) malloc(sizeof(No));
copia_v->vert = v;
copia_v->prox = NULL;
//cria um noh auxiliar com o valor de vertice u
No* copia_u = (No*) malloc(sizeof(No));
copia_u->vert = u;
copia_u->prox = NULL;
//cria um noh auxiliar que contem o inicio da lista ligada do vertice v
No* aux = g->lista[v];
while(aux->prox) aux = aux->prox;
aux->prox = copia_u; //coloca u como sendo o ultimo da lista ligada de v
//cria um noh auxiliar que contem o inicio da lista ligada do vertice v
aux = g->lista[u];
while(aux->prox) aux = aux->prox;
aux->prox = copia_v; //coloca v como sendo o ultimo da lista ligada de u
return;
}
void buscaLargura(Grafo g, int s){
int visitados[MAX] = {0}; //cria array de vertices visitados com todos nao visitados
int vertice;
Fila f = criaFila();
pushFila(&f, s); //insere o vertice source na fila
visitados[s] = 1; //marca como visitado
printf("Busca em Largura:");
printf(" %d", s);
while(!filaVazia(f)){ //enquanto a filha tiver algum elemento
vertice = popFila(&f); //retira esse elemento
No* noh = g.lista[vertice]; //pega o inicio da lista de arestas desse vertice
while(noh->prox){ //percorre a lista
noh = noh->prox;
if(!visitados[noh->vert]){ //se um dos vertices adjacentes nao tiver sido visitado
pushFila(&f, noh->vert); //coloca na fila
visitados[noh->vert]++; //marca como visitado
printf(" %d", noh->vert); //imprime o vertice
}
}
//repete o procedimento efetuando uma busca em largura
}
printf("\n");
return;
}
void buscaProfundidade(Grafo g, int s){
int visitados[MAX] = {0}; //cria array de vertices visitados com todos nao visitados
int vertice;
Pilha p = criaPilha();
pushPilha(&p, s); //insere o vertice source na pilha
printf("Busca em Profundidade:");
while(!pilhaVazia(p)){ //enquanto a pilha tiver algum elemento
vertice = popPilha(&p); //retira esse elemento
if(!visitados[vertice]){ //olha se ele ja foi visitado, caso nao tenha sido:
visitados[vertice]++; //marca como visitado
printf(" %d", vertice); //imprime o vertice
No* noh = g.lista[vertice]; //busca a sua lista de vertices adjacentes
while(noh->prox){ //percorre a lista inserindo todos os elementos da mesma na pilha
noh = noh->prox;
pushPilha(&p, noh->vert);
}
}
//repete o procedimento efetuando uma busca em profundidade
}
printf("\n");
return;
}
|
Java
|
UTF-8
| 5,039 | 2.9375 | 3 |
[] |
no_license
|
package cpsc2150.banking.models;
/**
* @author Annie Hayes, Marc Caramello
*
* @invariant MONTHSPERYEAR = 12 AND payment >= 0 AND Rate >= 0 AND Customer != null AND DebtToIncomeRatio >= 0 AND
* Principal >= 0 AND NumberOfPayments >= 0 AND PercentDown >= 0 AND MIN_YEARS <= homeYears <= MAX_YEARS
*
* @Correspondence self.Payment = payment AND self.Rate = rates AND self.Customer = person AND
* self.DebtToIncomeRatio = DebtIncomeRatio AND self.Principal = principal AND
* self.NumberOfPayments = numberOfPayments AND self.PercentDown = percentDown AND
* self.MonthlyInterestRate = monthlyInterestRate
*/
public class Mortgage extends AbsMortgage implements IMortgage {
private final double homeCost, homeDP, payment, rates, principal, DebtIncomeRatio, percentDown, monthlyInterestRate;
private final int homeYears, numberOfPayments;
private final int MONTHSPERYEAR = 12;
private final ICustomer person;
/**
* This creates a new object to keep track of information for the mortgage.
*
* @param houseCost the dollar amount of the house being bought
* @param downPayment the dollar amount of the customer's down payment
* @param years the number od years the mortgage is set at
* @param customer the customer's data from Customer.java
*
* @pre houseCost >= 0 AND downPayment >= 0 AND years >= 0 AND customer != null
* @post homeCost = houseCost AND homeDP = downPayment AND homeYears = years AND
* person = customer AND payment = getPayment() AND rates = getRate() AND
* principal = getPrincipal AND percentDown = homeDP / homeCost AND
* DebtIncomeRatio = person.getMonthlyDebtPayments() / (person.getIncome() / MONTHSPERYEAR)
* AND numberOfPayments = homeYears + MONTHSPERYEAR AND monthlyInterestRate = getRate() / MONTHSPERYEAR
*/
Mortgage(double houseCost, double downPayment, int years, ICustomer customer) {
//assign parameters to correct variables
homeCost = houseCost;
homeDP = downPayment;
homeYears = years;
person = customer;
//assign getter functions to correct variables
payment = getPayment();
rates = getRate();
principal = getPrincipal();
//the percent down is the down payment percent of the total home cost
percentDown = downPayment / houseCost;
//ratio of debt payments divided by the income over a period of time
DebtIncomeRatio = person.getMonthlyDebtPayments() / (person.getIncome() / MONTHSPERYEAR);
//the number of payments is the length of the mortgage times 12
numberOfPayments = years * MONTHSPERYEAR;
monthlyInterestRate = getRate() / MONTHSPERYEAR;
}
@Override
public boolean loanApproved () {
//if APR >= 10% or if percentDown < 3.5% or if DebtIncomeRatio >= 40% return false
if (rates >= RATETOOHIGH || percentDown < MIN_PERCENT_DOWN || DebtIncomeRatio >= DTOITOOHIGH) {
return false;
}
else {
return true;
}
}
@Override
public double getPayment() {
//monthly interest rate
//double mInterestRate = getRate() / MONTHSPERYEAR;
double top = monthlyInterestRate * principal;
double bottom = 1 - (Math.pow((1 + monthlyInterestRate),(- numberOfPayments)));
return top/bottom;
}
@Override
public double getRate() {
//rate is equal to .025
double rate = BASERATE;
//if homeYears < 30
if(homeYears < MAX_YEARS) {
//add .005 to rate
rate = rate + GOODRATEADD;
} else {
//add .01 to rate
rate = rate + NORMALRATEADD;
}
//if percentDown < .2
if(percentDown < PREFERRED_PERCENT_DOWN)
{
//add .005 to rate
rate += GOODRATEADD;
}
//if credit score >= 750
if(person.getCreditScore() >= GREATCREDIT) {
return rate;
}
//if credit score >= 700
else if(person.getCreditScore() >= GOODCREDIT) {
rate += GOODRATEADD;
}
//if credit score >= 600
else if(person.getCreditScore() >= FAIRCREDIT) {
rate += NORMALRATEADD;
}
//if credit score >= 500
else if(person.getCreditScore() >= BADCREDIT) {
rate += BADRATEADD;
}
//if credit score < 500
else if(person.getCreditScore() < BADCREDIT) {
rate += VERYBADRATEADD;
}
return rate;
}
@Override
public double getPrincipal () {
return homeCost - homeDP;
}
@Override
public int getYears () {
return homeYears;
}
}
|
Swift
|
UTF-8
| 6,682 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
//
// ColorOctree.swift
//
// Copyright (c) 2015 Miles Hollingsworth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: RGB Octree
internal class ColorOctree {
fileprivate let root = OctreeNode(index: 0, parent: nil)
fileprivate var heap = MinBinaryHeap<OctreeNode>()
fileprivate let colorDepth: Int
internal var nodeCount: Int {
return heap.nodes.count
}
internal var totalWeight: Int {
return heap.nodes.reduce(0) { $0 + $1.value }
}
fileprivate func sortedColors() -> [UIColor]? {
var mutableColors = [(UIColor, Int)]()
for heapNode in heap.nodes {
let octreeNode = heapNode.reference
mutableColors.append((octreeNode.color, octreeNode.weight))
}
mutableColors.sort() { $0.1 > $1.1 }
return mutableColors.map() { $0.0 }
}
init(colorDepth: Int) {
self.colorDepth = colorDepth
}
/**
Insert 1 pixel of a color into the octree and updates the min heap
- parameter color: The RGBA pixel data to insert
*/
func insertColor(_ color: UInt32) {
var currentNode = root
var bitPosition = UInt32(8)
let lastBitPosition = bitPosition - UInt32(colorDepth)
// THIS IS SLOW. NOT SURE WHY
// for position in (lastBitPosition...bitPosition).reverse() {
// let redBit = (color >> position) & 1
// let greenBit = (color >> (position + 8)) & 1
// let blueBit = (color >> (position + 16)) & 1
//
// let index = Int(redBit + greenBit << 1 + blueBit << 2)
//
// if let child = currentNode.children[index] {
// currentNode = child
// } else {
// currentNode = currentNode.createChild(index)
// }
// }
repeat {
bitPosition -= 1
let redBit = (color >> bitPosition) & 1
let greenBit = (color >> (bitPosition + 8)) & 1
let blueBit = (color >> (bitPosition + 16)) & 1
let index = Int(redBit + greenBit << 1 + blueBit << 2)
if let child = currentNode.children[index] {
currentNode = child
} else {
currentNode = currentNode.createChild(index)
}
} while bitPosition > lastBitPosition
currentNode.addColor(color)
heap.insert(currentNode)
}
/**
Pare down the octree to `count` leaf nodes and return the remaining colors.
- parameter count: The maximum number of colors to be returned
- returns: An optional array of `UIColor`s with a maximum length of `count`. Will return fewer colors if fewer leaf nodes are present.
*/
func quantizeToColorCount(_ count: Int) -> [UIColor]? {
while(heap.count > count) {
foldMinColor()
}
return sortedColors()
}
/**
Folds the leaf node with the smallest weight into the octree until a non-leaf parent is encountered. If that parent was occupied, it will be inserted into the heap.
*/
fileprivate func foldMinColor() {
if let minOctreeNode = heap.extract() {
var currentOctreeNode = minOctreeNode
while (currentOctreeNode.isLeaf) {
if let parent = currentOctreeNode.parent {
let parentWasOccupied = parent.weight > 0
currentOctreeNode.fold()
currentOctreeNode = parent
if parentWasOccupied {
break
}
} else {
break
}
}
if currentOctreeNode.weight > minOctreeNode.weight {
heap.insert(currentOctreeNode)
}
}
}
}
//MARK: Octree Node
private class OctreeNode: Heapable {
var red = 0, green = 0, blue = 0, alpha = 0
var weight = 0
var color: UIColor {
let red = CGFloat(self.red/weight)/255.0
let green = CGFloat(self.green/weight)/255.0
let blue = CGFloat(self.blue/weight)/255.0
let alpha = CGFloat(self.alpha/weight)/255.0
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
let parent: OctreeNode?
let childIndex: Int
var children = [OctreeNode?](repeating: nil, count: 8)
var childCount: Int {
return children.filter({$0 != nil}).count
}
var isLeaf: Bool {
return childCount == 0
}
init(index: Int, parent: OctreeNode?) {
childIndex = index
self.parent = parent
}
/**
Add color data to a node.
- parameter color: The UInt32 of RGBA color data
*/
func addColor(_ color: UInt32) {
let redMask = UInt32(UINT8_MAX), greenMask = redMask << 8, blueMask = greenMask << 8, alphaMask = blueMask << 8
red += Int(color & redMask)
green += Int((color & greenMask) >> 8)
blue += Int((color & blueMask) >> 16)
alpha += Int((color & alphaMask) >> 24)
weight += 1
}
/**
Create a new child node at `childIndex`
- parameter childIndex: The index of the new child node relative to the existing node
- returns: A new `OctreeNode` that is the child of the existing node at `childIndex`
*/
func createChild(_ childIndex: Int) -> OctreeNode {
let child = OctreeNode(index: childIndex, parent: self)
children[childIndex] = child
return child
}
/**
Fold an existing node into its' parent node
*/
func fold() {
if let parent = parent {
parent.red += red
parent.green += green
parent.blue += blue
parent.alpha += alpha
parent.weight += weight
parent.children[childIndex] = nil
} else {
print("Attempting to fold root node")
}
}
//MARK: Heapable
var heapIndex: Int?
var value: Int {
return weight
}
}
|
Java
|
UTF-8
| 809 | 1.960938 | 2 |
[] |
no_license
|
package research.resources;
import com.mongodb.DB;
import research.db.DBConnection;
import research.db.DBHandler;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.net.UnknownHostException;
/**
* Created by nuwantha on 8/23/16.
*/
@Path("/tem")
@Produces(MediaType.TEXT_PLAIN)
public class Tem {
@GET
public String getProfiles(){
try {
DB connection = DBConnection.getDBConnection().getConnection();
return DBHandler.setData(connection,"formatting_specification");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "yes";
}
}
|
Java
|
UTF-8
| 2,972 | 2.40625 | 2 |
[] |
no_license
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package org.usfirst.frc.team195.robot;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This is a demo program showing the use of the RobotDrive class. The
* SampleRobot class is the base of a robot application that will automatically
* call your Autonomous and OperatorControl methods at the right time as
* controlled by the switches on the driver station or the field controls.
*
* <p>The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SampleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the build.properties file in the
* project.
*
* <p>WARNING: While it may look like a good choice to use for your code if
* you're inexperienced, don't. Unless you know what you are doing, complex code
* will be much more difficult under this system. Use IterativeRobot or
* Command-Based instead if you're new.
*/
public class Robot extends SampleRobot {
private Spark s0 = new Spark(0);
private Spark s1 = new Spark(1);
private DifferentialDrive m_robotDrive = new DifferentialDrive(s0, s1);
private Joystick m_stick = new Joystick(0);
private SendableChooser<String> m_chooser = new SendableChooser<>();
private CKAutoBuilder<Spark> ckAuto;
public Robot() {
m_robotDrive.setExpiration(0.1);
try {
ckAuto = new CKAutoBuilder<Spark>(s0, s1, this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void robotInit() {
}
@Override
public void autonomous() {
ckAuto.addAutoStep(0, 0, 3000);
ckAuto.addAutoStep(1, 0, 5000);
ckAuto.addAutoStep(1, 0.25, 2000);
ckAuto.addAutoStep(0, 0, 200);
ckAuto.start();
while(!isOperatorControl() && isEnabled()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
;
}
}
}
@Override
public void operatorControl() {
m_robotDrive.setSafetyEnabled(true);
while (isOperatorControl() && isEnabled()) {
// Drive arcade style
m_robotDrive.arcadeDrive(-m_stick.getY(), m_stick.getX());
// The motors will be updated every 5ms
Timer.delay(0.005);
}
}
@Override
public void test() {
}
}
|
PHP
|
UTF-8
| 3,187 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use App\Service;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image ;
use Session;
use Storage;
class ServiceController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
{
$services=Service::all();
return view('Admin.form.service')->with('services',$services)->with('no','1');
}
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'logo' => 'required',
'title' =>'required',
'description'=>'required',
]);
$services = new Service();
$services->logo = $request->logo;
$services->title = $request->title;
$services->description =$request->description;
$services->save();
return redirect('adminlog/service')->with('success',"Your introduction Content Is Saved Successfully!!!");
}
/**
* Display the specified resource.
*
* @param \App\Service $service
* @return \Illuminate\Http\Response
*/
public function show(Service $service)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Service $service
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
{
$services= Service::find($id);
return view('Admin.form.service')->with('services',$services);
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Service $service
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'logo' =>'required',
'title'=>'required',
'description'=>'required',
]);
//Save the data in database
$services=Service::find($id);
$services->logo = $request->input('logo');
$services->title = $request->input('title');
$services->description = $request->input('description');
$services->save();
//Set Flash message aand return view
return redirect('adminlog/service')->with('success',"Successfully Updated!!!!");
}
/**
* Remove the specified resource from storage.
*
* @param \App\Service $service
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$services=Service::find($id);
Storage::delete($services->image);
$services->delete();
return redirect('adminlog/service')->with('delete',"Your Data Has Been Deleted!!!!");
}
}
|
Java
|
UTF-8
| 3,490 | 2.09375 | 2 |
[] |
no_license
|
package net.sf.anathema.character.generic.impl.magic.persistence.builder;
import net.sf.anathema.character.generic.impl.traits.TraitTypeUtils;
import net.sf.anathema.character.generic.magic.charms.CharmException;
import net.sf.anathema.character.generic.magic.charms.ComboRestrictions;
import net.sf.anathema.character.generic.magic.charms.IComboRestrictions;
import net.sf.anathema.character.generic.magic.charms.type.CharmType;
import net.sf.anathema.lib.xml.ElementUtilities;
import org.dom4j.Element;
import java.util.List;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.ATTRIB_ALL_ABILITIES;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.ATTRIB_COMBOABLE;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.ATTRIB_ID;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.ATTRIB_SELECT_ABILITIES;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.ATTRIB_TYPE;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.TAG_CHARM;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.TAG_CHARMTYPE;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.TAG_COMBO;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.TAG_RESTRICTIONS;
import static net.sf.anathema.character.generic.impl.magic.ICharmXMLConstants.TAG_TRAIT_REFERENCE;
public class ComboRulesBuilder implements IComboRulesBuilder {
private final TraitTypeUtils traitUtils = new TraitTypeUtils();
@Override
public IComboRestrictions buildComboRules(Element rulesElement) throws CharmException {
Element comboElement = rulesElement.element(TAG_COMBO);
if (comboElement == null) {
return new ComboRestrictions();
}
Boolean allAbilities = ElementUtilities.getBooleanAttribute(comboElement, ATTRIB_ALL_ABILITIES, false);
String selectAbilities = comboElement.attributeValue(ATTRIB_SELECT_ABILITIES, "");
String comboAllowedValue = comboElement.attributeValue(ATTRIB_COMBOABLE);
Boolean comboAllowed = comboAllowedValue == null ? null : Boolean.valueOf(comboAllowedValue);
ComboRestrictions comboRules = new ComboRestrictions(allAbilities, selectAbilities, comboAllowed);
Element restrictionElement = comboElement.element(TAG_RESTRICTIONS);
if (restrictionElement != null) {
buildRestrictionList(comboRules, restrictionElement);
}
return comboRules;
}
protected void buildRestrictionList(ComboRestrictions comboRules, Element restrictionElement) throws CharmException {
List<Element> restrictedCharmList = ElementUtilities.elements(restrictionElement, TAG_CHARM);
for (Element element : restrictedCharmList) {
comboRules.addRestrictedCharmId(element.attributeValue(ATTRIB_ID));
}
List<Element> restrictedCharmTypeList = ElementUtilities.elements(restrictionElement, TAG_CHARMTYPE);
for (Element element : restrictedCharmTypeList) {
String charmType = element.attributeValue(ATTRIB_TYPE);
comboRules.addRestrictedCharmType(CharmType.valueOf(charmType));
}
List<Element> restrictedTraitTypeList = ElementUtilities.elements(restrictionElement, TAG_TRAIT_REFERENCE);
for (Element element : restrictedTraitTypeList) {
String traitType = element.attributeValue(ATTRIB_ID);
comboRules.addRestrictedTraitType(traitUtils.getTraitTypeById(traitType));
}
}
}
|
C++
|
UTF-8
| 425 | 2.859375 | 3 |
[] |
no_license
|
struct node*update(struct node*start,int p)
{
struct node* first=start;
struct node* pre=NULL;
struct node* second=start;
while(second->next!=NULL)
{
second=second->next;
}
for(int i=0;i<p;i++)
{
pre=first;
first=first->next;
}
second->next=start;
start->prev=second;
pre->next=NULL;
first->prev=start;
return first;
}
|
C#
|
UTF-8
| 609 | 3.375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode
{
public static partial class LeetCode51_100
{
public static int ClimbStairs(int n)
{
if (n < 1) { return 0; }
if (n == 1) { return 1; }
if (n == 2) { return 2; }
int a = 1, b = 2, c = 0;
n -= 2;
while (n != 0)
{
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
}
}
|
Python
|
UTF-8
| 1,888 | 3.125 | 3 |
[
"Unlicense"
] |
permissive
|
"""
Facebook AI powered chatbot in Excel.
There are two functions:
- parlai_create_world creates a world containing two agents (the AI and the human).
- parlai_speak takes an input from the human and runs the model to get the AI response.
The entire conversation is returned by parlai_speak so it can be viewed in Excel
rather than just the last response.
See https://parl.ai/projects/blender/
"""
from pyxll import xl_func
from parlai.core.params import ParlaiParser
from parlai.core.agents import create_agent
from parlai.core.worlds import create_task
from excel_agent import HumanExcelAgent
@xl_func("str: object")
def parlai_create_world(model="zoo:blender/blender_90M/model"):
parser = ParlaiParser(True, True, 'Interactive chat with a model')
parser.add_argument(
'-it',
'--interactive-task',
type='bool',
default=True,
help='Create interactive version of task',
)
parser.set_defaults(interactive_mode=True, task='interactive')
args = ['-t', 'blended_skill_talk', '-mf', model]
opt = parser.parse_args(print_args=False, args=args)
agent = create_agent(opt, requireModelExists=True)
human_agent = HumanExcelAgent(opt)
world = create_task(opt, [human_agent, agent])
return world
@xl_func("object, str, int: str[][]")
def parlai_speak(world, input, limit=None):
human, bot = world.get_agents()[-2:]
human.set_input(input)
world.parley()
messages = [[x.get('id', ''), x.get('text', '')] for x in human.get_conversation()]
if limit:
messages = messages[-limit:]
if len(messages) < limit:
messages = ([['', '']] * (limit - len(messages))) + messages
return messages
if __name__ == "__main__":
world = parlai_create_world()
conversation = parlai_speak(world, "Hello")
for id, msg in conversation:
print(f"{id}: {msg}")
|
C++
|
UTF-8
| 528 | 2.671875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef vector<ll> vll;
ll M = 2147483648;
int main()
{
vll A;
ll sum1 = 1;
while (sum1 <= M)
{
A.push_back(sum1);
ll sum2 = 3 * sum1;
while (sum2 <= M)
A.push_back(sum2), sum2 *= 3;
sum1 *= 2;
}
sort(A.begin(), A.end());
ll n;
while (cin >> n, n)
{
auto it = lower_bound(A.begin(), A.end(), n);
cout << *it << '\n';
}
}
|
C
|
UTF-8
| 2,158 | 2.59375 | 3 |
[] |
no_license
|
#include <stddef.h>
#include <memory.h>
#define CR4_BIT_PGE (1U << 7)
#define MAX_HEAP_PAGES 64
#define HEAP_START_ADDR 0x00040000
static char heap_alloc_table[MAX_HEAP_PAGES] = {0};
void mem_init(void)
{
struct page_directory_entry *pde;
struct page_table_entry *pte;
unsigned int paging_base_addr;
unsigned int i;
unsigned int cr4;
/* Enable PGE(Page Global Enable) flag of CR4*/
__asm__("movl %%cr4, %0":"=r"(cr4):);
cr4 |= CR4_BIT_PGE;
__asm__("movl %0, %%cr4"::"r"(cr4));
/* Initialize kernel page directory */
pde = (struct page_directory_entry *)0x0008f000;
pde->all = 0;
pde->p = 1;
pde->r_w = 1;
pde->pt_base = 0x00090;
pde++;
for (i = 1; i < 0x400; i++) {
pde->all = 0;
pde++;
}
/* Initialize kernel page table */
pte = (struct page_table_entry *)0x00090000;
for (i = 0x000; i < 0x007; i++) {
pte->all = 0;
pte++;
}
paging_base_addr = 0x00007;
for (; i <= 0x085; i++) {
pte->all = 0;
pte->p = 1;
pte->r_w = 1;
pte->g = 1;
pte->page_base = paging_base_addr;
paging_base_addr += 0x00001;
pte++;
}
for (; i < 0x095; i++) {
pte->all = 0;
pte++;
}
paging_base_addr = 0x00095;
for (; i <= 0x09f; i++) {
pte->all = 0;
pte->p = 1;
pte->r_w = 1;
pte->g = 1;
pte->page_base = paging_base_addr;
paging_base_addr += 0x00001;
pte++;
}
for (; i < 0x0b8; i++) {
pte->all = 0;
pte++;
}
paging_base_addr = 0x000b8;
for (; i <= 0x0bf; i++) {
pte->all = 0;
pte->p = 1;
pte->r_w = 1;
pte->pwt = 1;
pte->pcd = 1;
pte->g = 1;
pte->page_base = paging_base_addr;
paging_base_addr += 0x00001;
pte++;
}
for (; i < 0x400; i++) {
pte->all = 0;
pte++;
}
}
void mem_page_start(void)
{
unsigned int cr0;
__asm__("movl %%cr0, %0":"=r"(cr0):);
cr0 |= 0x80000000;
__asm__("movl %0, %%cr0"::"r"(cr0));
}
void *mem_alloc(void)
{
unsigned int i;
for (i = 0; heap_alloc_table[i] && (i < MAX_HEAP_PAGES); i++);
if (i >= MAX_HEAP_PAGES)
return (void *)NULL;
heap_alloc_table[i] = 1;
return (void *)(HEAP_START_ADDR + i * PAGE_SIZE);
}
void mem_free(void *page)
{
unsigned int i = ((unsigned int)page - HEAP_START_ADDR) / PAGE_SIZE;
heap_alloc_table[i] = 0;
}
|
Java
|
UTF-8
| 2,126 | 3.265625 | 3 |
[] |
no_license
|
import java.io.*;
/**
* A classe LojaHabitavel implementa uma loja habitável que difere da loja apenas num sentido : é possível habitar a loja.
*/
public class LojaHabitavel extends Apartamento implements Habitavel, ImovelComum, Serializable
{
private String negocio;
/**
* Cria uma instância LojaHabitavel
*/
public LojaHabitavel()
{
super();
negocio = "";
}
/**
* Construtor por parâmetros
*/
public LojaHabitavel(Apartamento p, String n)
{
super(p);
negocio = n;
}
/**
* Construtor por parâmetros
*/
public LojaHabitavel(String r, String es, String i, int pp, int pm, int c, int p, int t, int q, int w, int a, double aTot, boolean g, String n)
{
super(r, es, i, pp, pm, c, t, q, w, p, a, aTot, g);
negocio = n;
}
/**
* Construtor de cópia
*/
public LojaHabitavel(LojaHabitavel l)
{
super(l);
negocio = l.getNegocio();
}
/**
* Retorna o tipo de negócio
*/
public String getNegocio()
{
return negocio;
}
/**
* Define o tipo de negócio através do parâmetro
*/
public void setNegocio(String n)
{
negocio = n;
}
/**
* Compara a igualdade entre objetos
*/
public boolean equals(Object o)
{
if (o == null) return false;
if (o == this) return true;
if (this.getClass() != o.getClass()) return false;
LojaHabitavel obj = (LojaHabitavel) o;
return (super.equals(obj) && (obj.getNegocio().equals(negocio)));
}
/**
* Devolve uma cópia desta instância
*/
public LojaHabitavel clone()
{
return new LojaHabitavel(this);
}
/**
* Devolve uma representação no formato textual
*/
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Tipo de negócio: ").append(negocio); sb.append("\n");
return sb.toString();
}
}
|
SQL
|
UTF-8
| 2,025 | 3.53125 | 4 |
[] |
no_license
|
/* Formatted on 8/22/2014 11:24:47 AM (QP5 v5.163.1008.3004) */
ALTER TABLE TEMP_INGRESOS_A102003 READ WRITE;
UPDATE TEMP_INGRESOS_A102003 A1
SET NATID_CENTRO_PRIMER_TRASLADO =
NVL ( (SELECT UBI_CAH_CODIGO
FROM UBICACIONES
WHERE UBI_CODIGO = A1.NATID_CAMA_PRIMER_TRASLADO),
-1);
ALTER TABLE TEMP_INGRESOS_A102003 READ ONLY;
SELECT *
FROM TEMP_INGRESOS_A102003
WHERE NATID_CENTRO_PRIMER_TRASLADO = -1 AND NATID_CAMA_PRIMER_TRASLADO > 0;
SELECT UBI_CAH_CODIGO
FROM UBICACIONES
WHERE UBI_CODIGO = 67744;
/
SELECT NATID_ADMISION, UBIC_TERMINAL
FROM (SELECT NATID_ADMISION, UBIC_TERMINAL, RANK () OVER (PARTITION BY ADMISION ORDER BY TRASLADO_ID) R
FROM TEMP_INGRESOS_A102003 JOIN ADM_TRASLADO ON (NATID_ADMISION = ADMISION)
WHERE TRASLADO_PADRE IS NULL)
WHERE R = 1
/
SELECT TRASLADO_ID,
NATID_ADMISION,
UBIC_TERMINAL,
RANK () OVER (PARTITION BY ADMISION ORDER BY TRASLADO_ID) R
FROM TEMP_INGRESOS_A102003 JOIN REP_HIS_OWN.ADM_TRASLADO@SEE41DAE ON (NATID_ADMISION = ADMISION)
WHERE TRASLADO_PADRE IS NULL AND NATID_ADMISION IN (1646048, 6677780, 1953225, 1955163, 1961513, 1975408, 1976755, 1986846, 1997705, 2012618, 2069942, 2841750, 2841762, 2920758, 3395731, 4284714, 5884785, 6077740, 1891464)
ORDER BY TRASLADO_ID -- RANK () OVER (PARTITION BY ADMISION ORDER BY TRASLADO_ID) DESC
/
SELECT NATID_ADMISION, UBIC_TERMINAL, UBI_CAH_CODIGO
FROM ( SELECT NATID_ADMISION, MAX (UBIC_TERMINAL) KEEP (DENSE_RANK FIRST ORDER BY TRASLADO_ID) UBIC_TERMINAL
FROM TEMP_INGRESOS_A102003 JOIN REP_HIS_OWN.ADM_TRASLADO@SEE41DAE ON (NATID_ADMISION = ADMISION)
GROUP BY NATID_ADMISION)
JOIN
(SELECT UBI_CODIGO, UBI_CAH_CODIGO FROM REP_PRO_EST.UBICACIONES@SEE41DAE)
ON (UBIC_TERMINAL = UBI_CODIGO)
|
Python
|
UTF-8
| 79 | 2.765625 | 3 |
[] |
no_license
|
N, A, B, C, D = map(int,input().split())
print(min((N+A-1)//A*B, (N+C-1)//C*D))
|
Python
|
UTF-8
| 1,313 | 2.9375 | 3 |
[] |
no_license
|
def contabiliza_combustivel(dicionario):
gasolina_litros = 0
etanol_litros = 0
gasolina_preço = 0
etanol_preço = 0
tipos = []
for item in dicionario:
if dicionario[item]['tipo'] not in tipos:
tipos.append(dicionario[item]['tipo'])
resposta = dict.fromkeys(tipos)
informacoes_relevantes = ['total litros', 'custo por litro']
for item in resposta:
resposta[item] = dict.fromkeys(informacoes_relevantes)
for item in dicionario:
if resposta[dicionario[item]['tipo']]['total litros'] == None:
resposta[dicionario[item]['tipo']]['total litros'] = 0
resposta[dicionario[item]['tipo']]['custo por litro'] = 0
resposta[dicionario[item]['tipo']]['total litros'] += dicionario[item]['litros']
resposta[dicionario[item]['tipo']]['custo por litro'] += dicionario[item]['custo']
for item in resposta:
resposta[item]['custo por litro'] /= resposta[item]['total litros']
return resposta
print(contabiliza_combustivel({
'dia 3': {
'tipo': 'Ar',
'litros': 100,
'custo': 20.0
},
'dia 5': {
'tipo': 'Gasolina',
'litros': 25,
'custo': 175.0
},
'dia 20': {
'tipo': 'Ar',
'litros': 50,
'custo': 10.0
}
}))
|
PHP
|
UTF-8
| 1,256 | 2.84375 | 3 |
[] |
no_license
|
<?php
namespace App\ConferenceRepositories;
use App\Models\Rooms;
class RoomRepository
{
public function all()
{
return Rooms::all();
}
public function find($roomId)
{
return Rooms::find($roomId);
}
public function get($filters = null)
{
if (empty($filters)) {
$rooms = Rooms::with('building')->get();
} else {
$conditions = [];
foreach ($filters as $key => $filter) {
$conditions[] = [$key, '=', $filter];
}
$rooms = Rooms::with('building')->where($conditions)->get();
}
return $rooms;
}
public function create($data)
{
$room = new Rooms();
$room->name = $data['name'];
$room->abbrev = $data['abbrev'];
$room->description = $data['description'];
$room->building_id = $data['building_id'];
$room->save();
return $room;
}
public function update($id, $data)
{
$room = Rooms::find($id);
$room->name = $data['name'];
$room->abbrev = $data['abbrev'];
$room->description = $data['description'];
$room->save();
return $room;
}
public function destroy($id)
{
$room = Rooms::find($id);
$room->delete();
return $room;
}
}
|
PHP
|
UTF-8
| 7,181 | 2.765625 | 3 |
[] |
no_license
|
<?php
include "./layout/pdo.php";
session_start();
$years=$_POST['years'];
$period=$_POST['period'];
switch ($period) {
case '1':
$ped="1.2月";
break;
case '2':
$ped="3.4月";
break;
case '3':
$ped="5.6月";
break;
case '4':
$ped="7.8月";
break;
case '5':
$ped="9.10月";
break;
case '6':
$ped="11.12月";
break;
}
$date=['years'=>$years,'period'=>$period];
$row=find("award",$date);
// print_r($row);
// echo $row[0]['years'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php include "./layout/title.php" ;?></title>
<link rel="stylesheet" href="./plugins/bootstrap.css">
<link rel="stylesheet" href="./css/style.css">
</head>
<body class="bg-dark">
<h1 class="text-white d-flex mt-5 justify-content-center"><?php echo $years . "年" . $ped;?>發票兌獎</h1>
<div class="justify-content-center align-items-center d-flex mt-5 container">
<div class="card shadow p-3 col-6">
<div class="btn-group mb-3 d-flex row">
<?php
if($period != 1){
echo "<div class='col p-1 ml-2 mr-2'> ";
echo "<form action='#' method='post'>";
echo "<input type='number' name='years' value=". $years ." hidden>";
echo "<input type='number' name='period' value='1' hidden>";
echo "<button type='submit' class='btn btn-outline-secondary p-2 w-100'>1.2月</button>";
echo "</form>";
echo "</div>";
}
if($period != 2){
echo "<div class='col p-1 ml-2 mr-2'> ";
echo "<form action='#' method='post'>";
echo "<input type='number' name='years' value=". $years ." hidden>";
echo "<input type='number' name='period' value='2' hidden>";
echo "<button type='submit' class='btn btn-outline-secondary p-2 w-100'>3.4月</button>";
echo "</form>";
echo "</div>";
}
if($period != 3){
echo "<div class='col p-1 ml-2 mr-2'> ";
echo "<form action='#' method='post'>";
echo "<input type='number' name='years' value=". $years ." hidden>";
echo "<input type='number' name='period' value='3' hidden>";
echo "<button type='submit' class='btn btn-outline-secondary p-2 w-100'>5.6月</button>";
echo "</form>";
echo "</div>";
}
if($period != 4){
echo "<div class='col p-1 ml-2 mr-2'> ";
echo "<form action='#' method='post'>";
echo "<input type='number' name='years' value=". $years ." hidden>";
echo "<input type='number' name='period' value='4' hidden>";
echo "<button type='submit' class='btn btn-outline-secondary p-2 w-100'>7.8月</button>";
echo "</form>";
echo "</div>";
}
if($period != 5){
echo "<div class='col p-1 ml-2 mr-2'> ";
echo "<form action='#' method='post'>";
echo "<input type='number' name='years' value=". $years ." hidden>";
echo "<input type='number' name='period' value='5' hidden>";
echo "<button type='submit' class='btn btn-outline-secondary p-2 w-100'>9.10月</button>";
echo "</form>";
echo "</div>";
}
if($period != 6){
echo "<div class='col p-1 ml-2 mr-2'> ";
echo "<form action='#' method='post'>";
echo "<input type='number' name='years' value=". $years ." hidden>";
echo "<input type='number' name='period' value='6' hidden>";
echo "<button type='submit' class='btn btn-outline-secondary p-2 w-100'>11.12月</button>";
echo "</form>";
echo "</div>";
}
?>
</div>
<form action="award.php" method="post">
<input type="number" name="years" value="<?=$years;?>" hidden>
<input type="number" name="period" value="<?=$period;?>" hidden>
<?php
if(empty($row[0]['id']) == 0){
echo "<input type='number' name='id' value=". $row[0]['id'] ." hidden>";
}
?>
<div class="form-group row">
<div class="col-2">
<label>特別獎:</label>
</div>
<div class="col">
<input type="number" class="form-control" id="invoice_Special_award" name="Special_award" value="<?=$row[0]['Special_award'];?>" required>
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>特獎:</label>
</div>
<div class="col">
<input type="number" class="form-control" id="invoice_S_award" name="S_award" value="<?=$row[0]['S_award'];?>" required>
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>頭獎:</label>
</div>
<div class="col">
<input type="number" class="form-control mb-1" id="invoice_h1_award" name="h1_award" value="<?=$row[0]['h1_award'];?>" required>
<input type="number" class="form-control mb-1" id="invoice_h2_award" name="h2_award" value="<?=$row[0]['h2_award'];?>" required>
<input type="number" class="form-control" id="invoice_h3_award" name="h3_award" value="<?=$row[0]['h3_award'];?>" required>
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>二獎:</label>
</div>
<div class="col text-center">
末七碼與頭獎相同者各得獎金四萬元
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>三獎:</label>
</div>
<div class="col text-center">
末六碼與頭獎相同者各得獎金一萬元
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>四獎:</label>
</div>
<div class="col text-center">
末五碼與頭獎相同者各得獎金四千元
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>五獎:</label>
</div>
<div class="col text-center">
末四碼與頭獎相同者各得獎金一千元
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label>六獎</label>
</div>
<div class="col text-center">
末三碼與頭獎相同者各得獎金二百元
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label>增開六獎:</label>
</div>
<div class="col">
<input type="number" class="form-control" id="invoice_six_award" name="six_award" value="<?=$row[0]['six_award'];?>" required>
</div>
<div class="col">
<input type="number" class="form-control" id="invoice_six2_award" value="<?=$row[0]['six2_award'];?>" name="six2_award" >
</div>
<div class="col">
<input type="number" class="form-control" id="invoice_six3_award" value="<?=$row[0]['six3_award'];?>" name="six3_award" >
</div>
</div>
<div class="btn-group d-flex">
<a href='index.php' class='btn btn-info'>回首頁</a>
<button type="submit" class="btn btn-primary">送出</button>
</div>
</div>
</div>
</body>
</html>
|
Java
|
UTF-8
| 756 | 2.015625 | 2 |
[] |
no_license
|
package com.myf.weixin.entity.weixin.customservice;
import com.myf.weixin.entity.weixin.WxJsonResult;
import java.util.List;
/**
* Created by myf on 2016/6/8.
*/
public class WaitCaseListRet extends WxJsonResult {
private int count;//未接入会话数量
private List<WaitCaseListItem> waitcaselist;//未接入会话列表,最多返回100条数据,按照来访顺序
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<WaitCaseListItem> getWaitcaselist() {
return waitcaselist;
}
public void setWaitcaselist(List<WaitCaseListItem> waitcaselist) {
this.waitcaselist = waitcaselist;
}
}
|
Python
|
UTF-8
| 141 | 3.515625 | 4 |
[] |
no_license
|
def main():
a, b = 10, 1
statement = "a is less" if a < b else "a is not less"
print(statement)
if __name__=="__main__" : main()
|
Markdown
|
UTF-8
| 940 | 2.78125 | 3 |
[] |
no_license
|
# app_loja
Projeto de uma loja em Flutter, com sistema de compras integrado com Firebase, sistema de carrinho de compras, pedidos, acompanhamento do pedido, cupons de desconto e outras funções de uma loja.
Requisitos:
Flutter e Dart, vscode ou Android Studio.
Para emular no iOS precisa de um Macbook.
ATENÇÂO!!!
Possivelmente a loja vai estar fora do ar, pois criei o vinculo com o Firebase apenas para testar e desenvolver.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
|
Java
|
UTF-8
| 1,340 | 2.8125 | 3 |
[] |
no_license
|
package com.sps.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.sps.game.screens.MenuScreen;
import com.sps.game.screens.SplashWorker;
/**
* This class creates the game and launches the Menu Screen.
* @author Miraj Shah, Miguel Abaquin, Devin Shingadia.
* @version 1.0
*/
public class SpacePiratesShoedown extends Game {
/**
*
* @see #create
*/
public SpriteBatch batch;
private SplashWorker splashWorker;
/*private static PlayScreen playScreen;
private static MenuScreen menuScreen;
public static enum ScreenType{
PlayGame,
MainMenu
}
public Screen getScreenType(ScreenType screenType){
switch (screenType){
case PlayGame:
return playScreen;
case MainMenu:
return menuScreen;
default:
return menuScreen;
}
}*/
@Override
public void create () {
batch = new SpriteBatch(); //check if this is needed
setScreen(new MenuScreen(this));
}
@Override
public void render () {
super.render();//delegates menu method to whatever screen is active at the time
}
@Override
public void dispose () {
batch.dispose();
}
public SplashWorker getSplashWorker() {
return splashWorker;
}
public void setSplashWorker(SplashWorker splashWorker) {
this.splashWorker = splashWorker;
}
}
|
C++
|
GB18030
| 405 | 3.4375 | 3 |
[] |
no_license
|
//3С
#include<stdio.h>
//int main()
//{
// int a, b, c, t;
// scanf_s("%d%d%d", &a, &b, &c);
// //λa<=b<=cʽ
// if (a > b)
// {
// t = a;
// a = b;
// b = t;
// }
// if (a > c)
// {
// t = a;
// a = c;
// c = t;
// }
// if (b > c)
// {
// t = b;
// b = c;
// c = t;
// }
// printf("%d %d %d\n", a, b, c);
//
// return 0;
//}
|
Java
|
UTF-8
| 1,531 | 2.484375 | 2 |
[
"Unlicense"
] |
permissive
|
package org.erik.timesheets.ui.views.timesheet;
import com.vaadin.flow.data.renderer.TemplateRenderer;
import org.erik.timesheets.AbstractGrid;
import org.erik.timesheets.domain.dto.TimesheetEntryDTO;
public class TimesheetGrid extends AbstractGrid<TimesheetEntryDTO> {
private static final String TEMPLATE =
"<div class=timesheet-grid__entry>" +
"<div class=timesheet-grid__entry-header>" +
"<span class=timesheet-grid__entry-client>[[item.client]]</span>" +
"<span class=timesheet-grid__entry-project>[[item.project]]</span>" +
"</div>" +
"<div class=timesheet-grid__entry-comment>[[item.comment]]</div>" +
"<div class=timesheet-grid__entry-time>" +
"<span class=timesheet-grid__entry-duration>[[item.duration]]</span>" +
"<span class=timesheet-grid__entry-timestamp>[[item.timestamp]]</span>" +
"</div>" +
"</div>";
public TimesheetGrid() {
addColumn(TemplateRenderer.<TimesheetEntryDTO>of(TEMPLATE)
.withProperty("client", entry -> entry.getClient().getName())
.withProperty("project", entry -> entry.getProject().getName())
.withProperty("comment", TimesheetEntryDTO::getComment)
.withProperty("timestamp", TimesheetEntryDTO::getFormattedTimestamp)
.withProperty("duration", TimesheetEntryDTO::getFormattedDuration));
}
}
|
Python
|
UTF-8
| 42 | 2.796875 | 3 |
[] |
no_license
|
name = "你好,世界"
print(name )
|
JavaScript
|
UTF-8
| 84 | 2.703125 | 3 |
[] |
no_license
|
var a = 5 ;
a++;
a++;
a++;
a++;
a--;
var a = "asldjkh "
alert(a + 5 + " the end ")
|
Java
|
UTF-8
| 1,365 | 2.4375 | 2 |
[] |
no_license
|
package bns;
import bns.comm.UnifyEnum;
import bns.thread.KeyThread;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource(UnifyEnum.BNS.v()));
primaryStage.setTitle("BNS");
Scene scene = new Scene(root, 122, 67);
primaryStage.setScene(scene);
primaryStage.getIcons().add(new Image(
Main.class.getResourceAsStream(UnifyEnum.JAVA.v())));
primaryStage.setAlwaysOnTop(true);//窗口总是在最前面
primaryStage.setResizable(false);//禁止改变窗口大小
primaryStage.initStyle(StageStyle.UTILITY);
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
KeyThread.kill();
System.out.println("线程已被强制杀死");
}
});
}
public static void main(String[] args) {
launch(args);
}
}
|
Markdown
|
UTF-8
| 2,575 | 2.8125 | 3 |
[] |
no_license
|
# Article 2
Pour l'application des dispositions du présent arrêté, on entend par :
Emballage : tout produit constitué de matériaux de toute nature, destiné à contenir et à protéger des marchandises données, allant des matières premières aux produits finis, à permettre leur manutention et leur acheminement du producteur au consommateur ou à l'utilisateur, et à assurer leur présentation.
Emballage en bois : tout emballage constitué d'éléments en bois assemblés y compris les éléments ou produits auxiliaires d'assemblage, ainsi que les éventuels éléments de calage en bois. Les bois d'emballages peuvent notamment être des palettes simples, des palettes-caisses et autres plateaux de chargement en bois, des caisses, caissettes, cageots, cylindres et emballages de même nature en bois, ou des tourets en bois.
Biomasse :
a) Les produits composés d'une matière végétale agricole ou forestière susceptible d'être employée comme combustible en vue d'utiliser son contenu énergétique ;
b) Les déchets ci-après :
i) Déchets végétaux agricoles et forestiers ;
ii) Déchets végétaux provenant du secteur industriel de la transformation alimentaire, si la chaleur produite est valorisée ;
iii) Déchets végétaux fibreux issus de la production de pâte vierge et de la production de papier à partir de pâte, s'ils sont coïncinérés sur le lieu de production et si la chaleur produite est valorisée ;
iv) Déchets de liège ;
v) Déchets de bois, à l'exception des déchets de bois qui sont susceptibles de contenir des composés organiques halogénés ou des métaux lourds à la suite d'un traitement avec des conservateurs du bois ou du placement d'un revêtement, y compris notamment les déchets de bois de ce type provenant de déchets de construction ou de démolition.
Installation de combustion : tout dispositif technique dans lequel des produits combustibles sont oxydés en vue d'utiliser la chaleur ainsi produite ;
Personnel compétent : le personnel qui, de par son expérience ou sa formation, est compétent pour examiner et évaluer les propriétés des emballages en bois ;
Inspection visuelle : inspection d'un lot dans sa totalité en recourant aux sens humains tels la vue ou l'odorat ou à tout matériel non spécialisé ;
Lot sortant : ensemble fini de broyats d'emballages en bois en un ou plusieurs conditionnements destiné à être livré chez un même client.
Echantillonnage : méthode permettant de constituer un échantillon représentatif d'un lot quantitativement plus important.
|
Python
|
UTF-8
| 901 | 3.0625 | 3 |
[] |
no_license
|
with open('input') as f:
line1 = f.readline().split(',')
line2 = f.readline().split(',')
dirs = {'U': [0, -1], 'D': [0, 1], 'R': [1, 0], 'L': [-1, 0]}
path = dict()
position = [0, 0]
step = 0
for instruction in line1:
direction = instruction[0]
amount = int(instruction[1:])
#print(direction, amount)
for i in range(1, amount+1):
step += 1
position[0] += dirs[direction][0]
position[1] += dirs[direction][1]
path[tuple(position)] = step
# print(path)
position = [0, 0]
dist = 9999999999
step = 0
for instruction in line2:
direction = instruction[0]
amount = int(instruction[1:])
for i in range(1, amount+1):
step += 1
position[0] += dirs[direction][0]
position[1] += dirs[direction][1]
tpos = tuple(position)
if tpos in path:
dist = min(dist, step + path[tpos])
print(dist)
|
C++
|
UTF-8
| 715 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include "code.hpp"
#include "decode.hpp"
int main()
{
char decision;
std::cout << "\n" << "CODER AND DECODER V1.0 MODULAR c++ version | by __ilprofessore\n\n";
std::cout << "alternate syntax: '0 <code>' to encode and '1 <decode>' to decode.\n";
std::cout << "enter 0 to code or 1 to decode: ";
std::cin >> decision;
switch (decision)
{
case '0':
code();
getchar(); // a kind of pause for exit.
break;
case '1':
decode();
getchar();
break;
default:
std::cout << "\ninvalid entry, try again!\n\n";
getchar();
break;
}
return 0;
}
|
C
|
UTF-8
| 1,882 | 2.9375 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: itollett <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/01 11:29:53 by itollett #+# #+# */
/* Updated: 2020/11/06 18:21:59 by itollett ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int find_start(char *str, char *set)
{
int i;
int j;
i = 0;
while (str[i])
{
j = 0;
while (set[j] && str[i])
{
if (str[i] == set[j])
break ;
j++;
}
if (j == (int)ft_strlen(set))
break ;
i++;
}
return (i);
}
int find_end(char *str, char *set)
{
int i;
int j;
i = ft_strlen(str);
while (i > 0)
{
j = 0;
while (set[j] && str[i])
{
if (str[i] == set[j])
break ;
j++;
}
if (j == (int)ft_strlen(set))
break ;
i--;
}
return (i + 1);
}
char *ft_strtrim(char const *s1, char const *set)
{
int i;
int start;
int end;
char *str;
int len;
i = -1;
if (!s1 || !set)
return (NULL);
start = find_start((char *)s1, (char *)set);
end = find_end((char *)s1, (char *)set);
if (start > end)
return (ft_strdup(""));
if (!(str = (char *)malloc(sizeof(char) * (end - start + 1))))
return (NULL);
len = end - start;
while (++i < len)
{
str[i] = s1[start];
start++;
}
str[i] = '\0';
return (str);
}
|
Markdown
|
UTF-8
| 5,469 | 2.984375 | 3 |
[] |
no_license
|
一七
桑雅道:“不知道,那家医院只说他是监护人,没说明他们两者之间,有亲属关系。”
原振侠吸了一口气,沉默了片刻。在沉默了片刻之后,原振侠才说:“如果陶启泉是她的监护人,你还要为她的手术费去筹募,这不是滑稽么?最近的世界豪富录中,陶启泉排在第五名,估计他的财产,超过五百亿美元!”
桑雅也很不自然地笑了笑,原振侠作了一个请他继续说下去的手势。
桑雅对于那少女有这样的一个古怪名字,又对于那少女有这样声名烜赫的大豪富作监护人这两点,实在没有法子不觉得奇怪。他勉力使自己镇定下来,才道:“请告诉我她的联络地址。”
对方说出了一个地址,桑雅听了之后,不禁苦笑——地址是在本市,很简单:“陶氏大厦顶楼。”
§第六章
陶氏大厦顶楼,当然不是普通人能随便上去的——通向顶楼的电梯,据说就有可以同时容纳五十人舒服坐着的大面积——桑雅自然也没有去过。
桑雅在呆了半晌之后,想想陶启泉的地址是在陶氏大厦顶楼,倒也不足为怪。陶启泉在世界各地都有联络地址,本市的地址,当然是他事业的大本营——陶氏大厦顶楼。
桑雅想的是,自己如何才能和这个庞大的企业王国的中心联络得上?
正在他发愁时,电话那边的日本医生的声音又传了过来:“有一个联络电话留下来,特别声明二十四小时有人接听,尤其是有关求诊病人的事,一定会有答复。”
桑雅大喜过望:“快告诉我!”
对方讲了这个电话号码,又道:“如果你能使这个病人的情形有所改善,这是整形外科史上的奇迹!”
桑雅说了一声:“我会努力。”就急急放下电话。看看时间,是凌晨零时五十二分。
他连忙拨了那个电话号码,电话一响就有人接——是一个十分甜蜜,但是职业化了,没有甚么感情的声音:“陶启泉先生秘书处。”
桑雅吸了一口气:“我是整形外科医生桑雅,要和玛仙迪奥小姐联络。”
那甜蜜的声音道:“先生,你打错电话了,这里是陶启泉先生秘书处。”
桑雅道:“那就请陶先生听电话。”
甜蜜的声音听来更平板:“好的,请把你要和陶先生通话的目的告诉我,再告诉我你的联络电话,然后尽可能不要离开电话。陶先生在二十四小时之内,随时可能亲自,或再通过秘书处和你联络。”
桑雅苦笑:“我不能直接和他通话?”
声音传过来:“恐怕不能,陶先生正在巴西,和巴西政府,讨论开发亚马孙河流域资源的事。”
桑雅只好投降:“请告诉他我的职业,事情和玛仙小姐有关,我相信他也会认为事情相当重要。”
然后,他就放下电话来等。电话响了好几次,却全是各地医院打来的,回答他并没有他查询的数据。
出乎桑雅的意料之外,一小时之后,又是那个甜蜜的声音打电话来:“桑雅医生?陶先生的电话。”
接着,就是一个听来相当稳重的声音:“桑雅医生,玛仙的事,你是听谁说的?”
桑雅怔了一怔,并不明白陶启泉这样问是甚么意思。他据实回答:“是她来找我的,而且,让我看到了她——畸形的头脸!”
陶启泉的声音,听来有点懊丧:“全世界的医生都告诉过她,她的情形是没有希望的,她为甚么不肯听?”
桑雅道:“不必绝望,虽然希望不大。我必须和她联络,好决定如何改造的步骤。”
陶启泉的声音听来有点疲倦:“好!不论多少费用,绝无问题。”
桑雅问:“请问玛仙和你的关系是——”
桑雅这样问,是因为他知道,他和玛仙之间的关系,发展下去,绝不会是医生和病人之间的关系那么简单。他对玛仙的迷恋程度,几乎每一分钟都在增加,才不过知道了她的名字,他就感到了莫名的兴奋。
可是,他这个问题,别说没有得到回答,根本问题都没有问完,陶启泉已显然放下了电话。接着,又是那个甜蜜的声音:“玛仙小姐的地址是夕阳大道三十三号,她准备见你!”
桑雅长长地吁了一口气,在剧烈的心跳中,一秒钟也不耽搁,就离开了办公室。兴奋使得他全然不知道甚么叫作疲倦,他驾车直驶向夕阳大道。
夕阳大道在市区的西郊,路程相当远。整条道上,全是相隔有相当距离的、式样各有不同、争奇斗巧的洋房,那是一个只属于富人的区域。当他的车子在三十三号门口停下,他先定了定神才下车。
三十三号是幢十分精致的小洋房,有一个种植了太多花木,看起来有点像树林一样的一个花园。花园中的树木之多、之密,叫人联想起屋子的主人,一定有意想要隐藏或是掩饰一些甚么。在黑暗中看来,神秘感也更浓。
桑雅才一下车,一阵猛烈的犬吠声,从围墙后传了出来。两条极大的獒犬,扑向花园的铁门,人立起来,比桑雅还要高。
牠们扑上来的时候,铁门都为之震动,可知力量是何等之大。
|
Markdown
|
UTF-8
| 1,543 | 2.75 | 3 |
[] |
no_license
|
```yaml
area: Hertfordshire
og:
description: Police are appealing for witnesses following a serious injury road traffic collision in Hitchin this morning (Saturday, February 17).
publish:
date: 17 Feb 2018
title: Did you witness road traffic collision in Hitchin?
url: https://www.herts.police.uk/news-and-appeals/did-you-witness-road-traffic-collision-in-hitchin-1647
```
* ### The collision occurred in Nightingale Road at around 9.30am.
* ### A vehicle and a pedestrian were involved.
* ### The pedestrian suffered serious injuries.
* ### Witnesses to the incident are being sought.
Police are appealing for witnesses following a serious injury road traffic collision in Hitchin this morning (Saturday, February 17).
The incident occurred in Nightingale Road shortly after 9.30am when, for reasons unknown at this time, a blue Peugeot was in collision with a pedestrian.
The pedestrian, a man aged in his 80s, suffered serious injuries and was taken to hospital.
The driver of the Peugeot was uninjured.
Sergeant William Hood, from the Bedfordshire, Cambridgeshire and Hertfordshire (BCH) Road Policing Unit, said: "Investigations are being carried out to establish the circumstance around the incident and I am appealing for anyone who witnessed the collision, or events leading up to it, to please get in touch."
Anyone with information is asked to contact the BCH Road Policing Unit via the non-emergency number 101, quoting ISR 179 of February 17. You can also report information online at https://www.herts.police.uk/Report
|
Java
|
UTF-8
| 3,464 | 2.34375 | 2 |
[] |
no_license
|
package com.iit.jee.springboot.springsecurity.web;
import com.iit.jee.springboot.springsecurity.model.Convention;
import com.iit.jee.springboot.springsecurity.service.ConventionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class ConventionController {
@Autowired
private ConventionService service;
@RequestMapping("/")
public String viewHomePage(Model model,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = "5") int size,
@RequestParam(name = "keyword", defaultValue = "") String mc) throws ParseException {
if (mc.equals("")) {
Page<Convention> listConventions = service.listAll(page, size);
model.addAttribute("listConventions", listConventions.getContent());
model.addAttribute("pages", new int[listConventions.getTotalPages()]);
model.addAttribute("currentPage", page);
return "index";
} else if (mc.contains("-")) {
DateFormat date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date frmDate = date.parse(mc);
Page<Convention> listConventions = service.chercher(frmDate, page, size);
model.addAttribute("listConventions", listConventions.getContent());
model.addAttribute("pages", new int[listConventions.getTotalPages()]);
model.addAttribute("currentPage", page);
return "index";
} else {
Page<Convention> listConventions = service.listAll2(mc, page, size);
model.addAttribute("listConventions", listConventions.getContent());
model.addAttribute("pages", new int[listConventions.getTotalPages()]);
model.addAttribute("currentPage", page);
return "index";
}
}
@RequestMapping("/new")
public String showNewProductPage(Model model) {
Convention convention = new Convention();
model.addAttribute("convention", convention);
return "Nouveau_Convention";
}
@GetMapping("/edit/{id}")
public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {
// get convention from the service
Convention convention = service.get(id);
// set convention as a model attribute to pre-populate the form
model.addAttribute("convention", convention);
return "edit_convention";
}
@GetMapping("/delete/{id}")
public String deleteEmployee(@PathVariable(value = "id") long id) {
// call delete employee method
this.service.delete(id);
return "redirect:/";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveProduct(@RequestParam("debut") @DateTimeFormat(pattern = "yyyy-MM-dd") Date debut,
@RequestParam("signaturee") @DateTimeFormat(pattern = "yyyy-MM-dd") Date signaturee,
@RequestParam("expiration") @DateTimeFormat(pattern = "yyyy-MM-dd") Date expiration,
@RequestParam("edition") @DateTimeFormat(pattern = "yyyy-MM-dd") Date edition,
@ModelAttribute("convention") Convention convention) {
convention.setDeclenche(debut);
convention.setDateEdition(edition);
convention.setDateExpiration(expiration);
convention.setSignature(signaturee);
service.save(convention);
return "redirect:/";
}
}
|
Python
|
UTF-8
| 353 | 2.765625 | 3 |
[] |
no_license
|
from copy import *
from numpy import *
def fill_matrix(A):
M = copy(A)
for i in range(M.shape[1]):
a = M[:, i]
b = a[a>0]
if sum(b) == 0:
m = 3
else:
m = mean(b)
for j in range(M.shape[0]):
if M[j, i] == 0:
M[j, i] = m
return M
|
Java
|
UTF-8
| 1,003 | 2.25 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
package io.sphere.sdk.inventories.commands.updateactions;
import io.sphere.sdk.commands.UpdateAction;
import io.sphere.sdk.inventories.InventoryEntry;
import java.time.Instant;
import java.util.Optional;
/**
*
* {@include.example io.sphere.sdk.inventories.commands.InventoryEntryUpdateCommandTest#setExpectedDelivery()}
*/
public class SetExpectedDelivery extends UpdateAction<InventoryEntry> {
private final Optional<Instant> expectedDelivery;
private SetExpectedDelivery(final Optional<Instant> expectedDelivery) {
super("setExpectedDelivery");
this.expectedDelivery = expectedDelivery;
}
public Optional<Instant> getExpectedDelivery() {
return expectedDelivery;
}
public static SetExpectedDelivery of(final Instant expectedDelivery) {
return of(Optional.of(expectedDelivery));
}
public static SetExpectedDelivery of(final Optional<Instant> expectedDelivery) {
return new SetExpectedDelivery(expectedDelivery);
}
}
|
Markdown
|
UTF-8
| 707 | 2.625 | 3 |
[] |
no_license
|
# Index
This is [my](https://willcodefor.beer) public brain. It's built using [[foam]] and runs on [[github-pages]].
[[read-in-2020]]
## Daily notes
- [[2020-07-11]]
- [[2020-07-10]]
- [[2020-07-09]]
- [[2020-07-08]]
- [[2020-07-07]]
- [[2020-07-06]]
[//begin]: # "Autogenerated link references for markdown compatibility"
[foam]: foam "Foam"
[github-pages]: github-pages "GitHub Pages"
[read-in-2020]: read-in-2020 "Read in 2020"
[2020-07-11]: 2020-07-11 "2020-07-11"
[2020-07-10]: 2020-07-10 "2020-07-10"
[2020-07-09]: 2020-07-09 "2020-07-09"
[2020-07-08]: 2020-07-08 "2020-07-08"
[2020-07-07]: 2020-07-07 "2020-07-07"
[2020-07-06]: 2020-07-06 "2020-07-06"
[//end]: # "Autogenerated link references"
|
Java
|
UTF-8
| 436 | 1.882813 | 2 |
[] |
no_license
|
package com.startedup.base.utils;
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.startedup.base.R;
public class AnimUtil {
public static void animateItemRemove(Context context,View itemView){
Animation animation= AnimationUtils.loadAnimation(context, R.anim.item_to_left);
itemView.startAnimation(animation);
}
}
|
TypeScript
|
UTF-8
| 1,043 | 3.015625 | 3 |
[] |
no_license
|
import { t } from 'testcafe';
/**
* @author Sagar
* @version 1.0
* @since 26/09/20
*/
/** Print custom message in the console
*
* @param message `<custom message to be printed in the console>`
*/
export const annotateTestOutput = function (message: string) {
/* tslint:disable-next-line:no-console */
console.log(`${message}`);
};
/** Clear text field
*
* @param txtBox `<textbox selector>` from which data needs to be cleared
*/
export const clearTextField = async (txtBox: Selector) => {
await t
.click(txtBox)
.pressKey('ctrl+a delete');
}
/** Create random string
*
* @param length <length> of String size to be required
*/
export const randomString = function (length: number): string {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return `${text}`;
};
|
Java
|
UTF-8
| 919 | 2.140625 | 2 |
[] |
no_license
|
package ua.service.implementation;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ua.entity.Eduranse;
import ua.repository.EduranseRepository;
import ua.service.EduranseService;
@Service
public class EduranseServiceImpl implements EduranseService{
@Autowired
private EduranseRepository repository;
@Override
@Transactional(readOnly=true)
public Eduranse findOne(int id) {
return repository.findOne(id);
}
@Override
@Transactional(readOnly=true)
public List<Eduranse> findAll() {
return repository.findAll();
}
@Override
public void save(Eduranse eduranse ) {
repository.save(eduranse);
}
@Override
public void delete(int id) {
repository.delete(id);
}
}
|
C++
|
UTF-8
| 1,094 | 3.71875 | 4 |
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#include <algorithm>
#include <iostream>
#include <string>
void increment(std::string &password) {
int location = password.size() - 1;
while(password[location] == 'z') {
password[location--] = 'a';
}
password[location]++;
}
bool isValid(const std::string &password) {
bool paired, triple = false;
paired = ((std::adjacent_find(password.cbegin(), password.cend()) < password.cend() - 3) && std::adjacent_find(std::adjacent_find(password.cbegin(), password.cend()) + 2, password.cend()) != password.cend());
for(int i = 2; i < password.size(); i++) {
if(password[i - 1] == password[i - 2] + 1 && password[i] == password[i - 1] + 1) {
triple = true;
}
}
return (paired && triple && password.find_first_of("iol") == password.npos);
}
void next(std::string &password) {
while(!isValid(password)) {
increment(password);
}
}
int main(int argc, char const *argv[]) {
std::string password = "hepxcrrq";
next(password);
std::cout << "Star 1: " << password << std::endl;
increment(password);
next(password);
std::cout << "Star 2: " << password << std::endl;
return 0;
}
|
Java
|
UTF-8
| 929 | 1.898438 | 2 |
[] |
no_license
|
package org.xfs.scm.map.model.list;
import org.xfs.scm.map.model.base.BaseMapModel;
public class ListRequestModel extends BaseMapModel{
private String filter;
private String coord_type_output;
private int page_index=1;
private int page_size=10;
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public String getCoord_type_output() {
return coord_type_output;
}
public void setCoord_type_output(String coord_type_output) {
this.coord_type_output = coord_type_output;
}
public int getPage_index() {
return page_index;
}
public void setPage_index(int page_index) {
this.page_index = page_index;
}
public int getPage_size() {
return page_size;
}
public void setPage_size(int page_size) {
this.page_size = page_size;
}
}
|
C
|
UTF-8
| 230 | 2.515625 | 3 |
[] |
no_license
|
#include <sys/types.h>
#include <unistd.h>
void *simple_malloc (size_t size)
{
void *p;
p = sbrk ( 0);
/*If sbrk f a i l s , we return NULL */
if ( sbrk ( size ) == (void*)−1)
return NULL;
return p;
}
|
Python
|
UTF-8
| 2,923 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class DataQualityOperator(BaseOperator):
"""
Data Quality operator. Connects to a data-warehouse through provided connection ID, and loops over provided set of tests, each specifying an SQL query and a condition string to be evaluated. Operator records passes and raises a `ValueError` on the first occurence of an error.
Args:
redshift_conn_id : an Airflow conn_id for Redshift
tests : a list containing tuples (SQL_statement, test), where:
- SQL_statement : an sql statement, results of which would be compared to the test statement
- test : a string containing "{} condition", where "{}" is auto-filled, and contains the results on an SQL_statement, and "condition" is an evaluable expression, ex. quality operator "==". See `README.md` in the main file for an example
Returns:
None
Example of a single test: [(SQL_statement,test)]
SQL_statement : ''' SELECT COUNT(*) FROM test_table ''' -> a simple count of number of records in a table
test : ''' {}[0][0] >= 1 ''' : the result of 'SQL_statement' is put in round brackets {}. The result is still formatted as 2 dimensional array but with once cell. [0][0] accesses first row and cell of run query, then runs a check '>=1'. Test is passed if the evaluation is 'True', otherwise the test is failed.
"""
template_fields = ("tests",) # this allows us to use context variables from test SQL queries
ui_color = '#89DA59'
@apply_defaults
def __init__(self,
redshift_conn_id="",
tests=[],
*args, **kwargs):
super(DataQualityOperator, self).__init__(*args, **kwargs)
self.redshift_conn_id=redshift_conn_id
self.tests=tests
def execute(self, context):
redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)
for i,(sql_test,condition) in enumerate(self.tests):
sql_test_records = redshift.get_records(sql_test)
test = eval( condition.format(sql_test_records) )
if(test):
self.log.info( str("[") + str(i+1) + str("/") + str(len(self.tests)) + "] test passed. \n\n SQL STATEMENT: " + str(sql_test) + "\n\n Test Passed, because: \n\n " + condition.format(sql_test_records) )
else:
self.log.info( str("[") + str(i+1) + str("/") + str(len(self.tests)) + "] test failed. \n\n SQL STATEMENT: " + str(sql_test) + "\n\n Test failed, because: \n\n " + condition.format(sql_test_records) )
raise ValueError(f"Data quality check failed. Expected value different than obtained: " + condition.format(sql_test_records) )
|
Markdown
|
UTF-8
| 862 | 3.421875 | 3 |
[] |
no_license
|
# FenwickTree/Binary Indexed Tree
1. The idea is to store partial sum in each node and get total sum by traversing the tree from leaf to root. The tree has a height of log(n).
2. Mutable updating prefix sum problems
3. Leetcode 307(Range Sum Query - Mutable):[https://leetcode.com/problems/range-sum-query-mutable/](https://leetcode.com/problems/range-sum-query-mutable/)
4. Time complexity:
- init O(nlogn)
- query: O(logn)
- update: O(logn)
5. Code:
```Python3
class FenwickTree:
def __init__(self, n):
self.prefixSum = [0]*(n+1)
self.n = len(self.prefixSum)
def update(self, i, diff):
while i < self.n:
self.prefixSum[i] += diff
i += i & -i
def query(self, i):
s = 0
while i > 0:
s += self.prefixSum[i]
i -= i & -i
return s
```
|
C++
|
UTF-8
| 2,022 | 2.71875 | 3 |
[] |
no_license
|
/*
* Wll1Loader.h
*
* Created on: 2015-12-13
* Author: wll
*/
#ifndef WLL1LOADER_H_
#define WLL1LOADER_H_
#include "LanguageTypes.h"
#include "WllLoader.h"
#include <vector>
using namespace std;
class Wll1Loader : public WllLoader
{
public:
Wll1Loader(const vector<Symbols>& input_symbols);
virtual bool LoadWll(vector<LanguageTranslations>& translations);
virtual void ShowErrorMessage();
protected:
//Load* 函数一般都含有比较复杂的语法成分,当匹配输入的符号串时返回true,不匹配返回false; 不匹配时不消耗输入符号
bool LoadTranslation(LanguageTranslations& translation);
bool LoadSourceRule(LanguageRules& source_rule);
bool LoadDestinationRule(LanguageRules& destination_rule);
bool LoadRule(LanguageRules& rule);
bool LoadRootSymbol(Symbols& root_symbol);
bool LoadExpression(LanguageExpressions& expression);
bool LoadSymbol(LanguageExpressions& symbol);
bool LoadVariable(Symbols& variable);
bool LoadConstant(LanguageExpressions& constant);
bool LoadRemark(Symbols& remark);
bool LoadIdent(string& ident);
bool LoadString(LanguageExpressions& str);
bool LoadOriginalString(LanguageExpressions& str);
bool EncountRemark(Symbols& remark);
//Expect* 函数在匹配对应类型字符后,会消耗该输入符号,并把它通过引用参数保存起来,以便下一步使用;不匹配的时候不消耗输入符号
bool ExpectRemark(Symbols& remark);
bool ExpectLetter(char& c);
bool ExpectDigit(char& c);
bool ExpectCharacter(Symbols& symbol);
bool ExpectSpace(char& c);
bool SkipSpaces();
//Accept* 函数在匹配指定字符或者表达式字符串时会消耗输入符号串,不匹配的时候并不消耗输入符号
bool Accept(const Symbols& symbol);
bool Accept(const LanguageExpressions& expression);
//Encount* 函数测试下一个输入符号是否和指定的符号匹配,并不消耗输入符号
bool Encount(const Symbols& symbol);
const Symbols& GetSymbol();
protected:
int input_pos;
};
#endif /* WLL1LOADER_H_ */
|
Python
|
UTF-8
| 2,011 | 2.9375 | 3 |
[] |
no_license
|
import random
class Graph(object):
def __init__(self,file):
self.edges=[]
self.vertices={}
self.nodes=[str(x) for x in range(1,201)]
with open(file,'r') as graph:
for line in graph:
t = line.strip().split()
i=True
for x in t:
if i==True:
u=x
self.vertices[u]=[]
i=False
else:
if (x,u) not in self.edges:
self.edges.append((u,x))
self.vertices[u].append(x)
def contract(self,v1,v2):
self.edges.remove((v1,v2))
self.nodes.remove(v1)
self.nodes.remove(v2)
while v2 in self.vertices[v1]:
self.vertices[v1].remove(v2)
while v1 in self.vertices[v2]:
self.vertices[v2].remove(v1)
new=v1+'&'+v2
self.nodes.append(new)
checks=[]
for x in self.vertices[v1]:
checks.append(x)
for x in self.vertices[v2]:
checks.append(x)
self.vertices[new]=checks
self.vertices.pop(v1, None)
self.vertices.pop(v2, None)
for x in checks:
for y in self.vertices[x]:
if y==v1 or y==v2:
self.vertices[x].remove(y)
self.vertices[x].append(new)
else:
pass
self.update_edges()
def update_edges(self):
self.edges=[]
for x in self.nodes:
u=x
for v in self.vertices[u]:
if (v,u) not in self.edges:
self.edges.append((u,v))
def random_contraction(self):
while len(self.nodes)>2:
u,v=random.choice(self.edges)
self.contract(u,v)
return len(self.edges)
#17
|
C++
|
UTF-8
| 1,113 | 2.875 | 3 |
[] |
no_license
|
// https://www.acmicpc.net/problem/1654
// 랜선 자르기
// Written in C++ langs
// 2020. 02. 27.
// Wizley
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <cstring>
#include <cstdlib>
using namespace std;
int K, N;
long long LAN[1000001]={0,};
long long H=0;
long long getH(long long val){
long long res = 0;
for(long long i=0; i<K; i++){
if(LAN[i]>=val){
res += LAN[i] / val;
}
}
return res;
}
void bisect(long long begin, long long end){
if(end - begin <=1){
H = begin;
}
else{
long long mid = (begin+end)/2;
if(getH(mid) >= N){
return bisect(mid, end);
}
else{
return bisect(begin, mid);
}
}
}
int main(){
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> K >> N;
long long maxM = 0;
for(long long i=0; i<K; i++){
cin >> LAN[i];
maxM = max(maxM, LAN[i]);
}
bisect(0, maxM+1);
cout << H << "\n";
return 0;
}
|
Markdown
|
UTF-8
| 736 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: Cinematic Color
date: 2012-09-11 15:32
author: ventspace
comments: true
categories: [Photography]
tags: [cinema, cinematography, Graphics, graphics]
---
I chose not to go to SIGGRAPH 2012, and I'm starting to wish I had. Via <a href="http://lousodrome.net/blog/light/2012/09/11/readings-on-color-management/">Julien Guertault</a>, I found the course on <a href="http://cinematiccolor.com/">Cinematic Color</a>.
I've mentioned this in the past: I believe that as a graphics programmer, a thorough understanding of photography and cinematography through the entire production pipeline is necessary. Apparently I am not alone in this regard. Interesting corollary: should cinematographers understand computer graphics? Hmm.
|
C++
|
UTF-8
| 783 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
vector<int> map(26,0);
for(int i = 0; i < p.length(); i++)
map[ p[i] - 'a' ]++;
int n_unmatched = p.length();
int left, right = 0;
// Idea: using two pointers, check only two characters:
// the newly added character indicated by the right pointer
// and the deteleted character indicated by the left pointer
while( right < s.length() ){
if( map[ s[right++] - 'a' ]-- > 0 ) n_unmatched--;
if( right > p.length() && map[ s[left++] - 'a' ]++ >= 0 ) n_unmatched++;
if( n_unmatched == 0 ) res.push_back(left);
}
return res;
}
};
|
C
|
UTF-8
| 1,475 | 2.71875 | 3 |
[] |
no_license
|
/***************************************************************
stdio.c
***************************************************************/
#include <windows.h>
#include "wince.h" /* for wce_mbtowc */
FILE *freopen(const char *filename, const char *mode, FILE *file)
{
wchar_t *wfilename, *wmode;
FILE *fp;
wfilename = wce_mbtowc(filename);
wmode = wce_mbtowc(mode);
fp = _wfreopen(wfilename, wmode, file);
free(wfilename);
free(wmode);
return fp;
}
FILE *fdopen( int handle, const char *mode )
{
wchar_t *wmode;
FILE* fp;
wmode = wce_mbtowc(mode);
fp = _wfdopen( (void*)handle, wmode );
free(wmode);
return fp;
}
errno_t fopen_s(FILE **file, const char *filename, const char *mode) {
FILE* p;
if(file == NULL || filename == NULL) {
return EINVAL;
}
p = fopen(filename, mode);
if(p == NULL) {
return EINVAL;
}
file = &p;
return 0;
}
int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ... ){
int ret;
va_list argptr;
va_start(argptr, format);
ret = sprintf(buffer, format, argptr);
va_end(argptr);
return ret;
}
int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr ) {
int ret;
ret = _vsnprintf(buffer, sizeOfBuffer, format, argptr);
return ret;
}
int _vscprintf(const char *format, va_list argptr) {
char buffer[8192];
return _vsnprintf(buffer, 8192, format, argptr);
}
|
Java
|
UTF-8
| 453 | 1.851563 | 2 |
[] |
no_license
|
package com.crm.service;
import com.crm.domain.PageResult;
import com.crm.domain.Transfer;
import com.crm.query.TransferQueryObject;
import java.util.List;
public interface ITransferService {
PageResult queryForPage(TransferQueryObject queryObject);
int deleteByPrimaryKey(Long id);
int insert(Transfer record);
Transfer selectByPrimaryKey(Long id);
List<Transfer> selectAll();
int updateByPrimaryKey(Transfer record);
}
|
Java
|
UTF-8
| 8,396 | 1.859375 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-apple-excl",
"BSD-3-Clause",
"APAFML"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sejda.sambox.pdmodel.interactive.form;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sejda.io.SeekableSources;
import org.sejda.sambox.input.PDFParser;
import org.sejda.sambox.pdmodel.PDDocument;
import org.sejda.sambox.rendering.PDFRenderer;
import org.sejda.sambox.rendering.TestPDFToImageTest;
import javax.imageio.ImageIO;
/**
* Test flatten different forms and compare with rendering of original (before-flatten) document.
* <p>
* The tests are currently disabled to not run within the CI environment as the test results need
* manual inspection. Enable as needed.
*/
public class PDAcroFormFlattenTest
{
private static final File TARGETPDFDIR = new File("target/pdfs");
private static final File IN_DIR = new File("target/test-output/flatten/in");
private static final File OUT_DIR = new File("target/test-output/flatten/out");
@BeforeClass
public static void beforeAll()
{
IN_DIR.mkdirs();
for (File file : IN_DIR.listFiles())
{
file.delete();
}
OUT_DIR.mkdirs();
for (File file : OUT_DIR.listFiles())
{
file.delete();
}
}
/*
* PDFBOX-142 Filled template.
*/
@Test
public void testFlattenPDFBOX142() throws IOException
{
flattenAndCompare("Testformular1.pdf");
}
@Test
public void testNbspaceFormFieldValue() throws IOException
{
PDDocument doc = PDFParser.parse(
SeekableSources.seekableSourceFrom(new File(TARGETPDFDIR, "Testformular1.pdf")));
PDField field = doc.getDocumentCatalog().getAcroForm().getField("Vorname");
field.setValue("nbspace\u00A0");
doc.writeTo(new File(TARGETPDFDIR, "Testformular1-filled-out-nbspace.pdf"));
doc.close();
flattenAndCompare("Testformular1-filled-out-nbspace.pdf");
}
/*
* PDFBOX-563 Filled template.
*/
@Test
public void testFlattenPDFBOX563() throws IOException
{
flattenAndCompare("TestFax_56972.pdf");
}
/*
* PDFBOX-2469 Empty template.
*/
@Test
public void testFlattenPDFBOX2469Empty() throws IOException
{
flattenAndCompare("FormI-9-English.pdf");
}
/*
* PDFBOX-2469 Filled template.
*/
@Test
public void testFlattenPDFBOX2469Filled() throws IOException
{
flattenAndCompare("testPDF_acroForm.pdf");
}
/*
* PDFBOX-2586 Empty template.
*/
@Test
public void testFlattenPDFBOX2586() throws IOException
{
flattenAndCompare("test-2586.pdf");
}
/*
* PDFBOX-3083 Filled template rotated.
*/
@Test
public void testFlattenPDFBOX3083() throws IOException
{
flattenAndCompare("mypdf.pdf");
}
/*
* PDFBOX-3262 Hidden fields
*/
@Test
public void testFlattenPDFBOX3262() throws IOException
{
flattenAndCompare("hidden_fields.pdf");
}
/*
* PDFBOX-3396 Signed Document 1.
*/
@Test
public void testFlattenPDFBOX3396_1() throws IOException
{
flattenAndCompare("Signed-Document-1.pdf");
}
/*
* PDFBOX-3396 Signed Document 2.
*/
@Test
public void testFlattenPDFBOX3396_2() throws IOException
{
flattenAndCompare("Signed-Document-2.pdf");
}
/*
* PDFBOX-3396 Signed Document 3.
*/
@Test
public void testFlattenPDFBOX3396_3() throws IOException
{
flattenAndCompare("Signed-Document-3.pdf");
}
/*
* PDFBOX-3396 Signed Document 4.
*/
@Test
public void testFlattenPDFBOX3396_4() throws IOException
{
flattenAndCompare("Signed-Document-4.pdf");
}
/*
* PDFBOX-3587 Empty template.
*/
@Test
public void testFlattenOpenOfficeForm() throws IOException
{
flattenAndCompare("OpenOfficeForm.pdf");
}
/*
* PDFBOX-3587 Filled template.
*/
@Test
public void testFlattenOpenOfficeFormFilled() throws IOException
{
flattenAndCompare("OpenOfficeForm_filled.pdf");
}
/**
* PDFBOX-4157 Filled template.
*/
@Test
public void testFlattenPDFBox4157() throws IOException
{
flattenAndCompare("PDFBOX-4157-filled.pdf");
}
/**
* PDFBOX-4172 Filled template.
*/
@Test
public void testFlattenPDFBox4172() throws IOException
{
flattenAndCompare("PDFBOX-4172-filled.pdf");
}
/**
* PDFBOX-4615 Filled template.
*/
@Test
public void testFlattenPDFBox4615() throws IOException
{
flattenAndCompare("resetboundingbox-filled.pdf");
}
/**
* PDFBOX-4693: page is not rotated, but the appearance stream is.
*/
@Test
public void testFlattenPDFBox4693() throws IOException
{
flattenAndCompare("stenotypeTest-3_rotate_no_flatten.pdf");
}
/**
* PDFBOX-4788: non-widget annotations are not to be removed on a page that has no widget
* annotations.
*/
@Test
public void testFlattenPDFBox4788() throws IOException
{
flattenAndCompare("flatten.pdf");
}
/**
* PDFBOX-4889: appearance streams with empty /BBox.
*
* @throws IOException
*/
@Test
public void testFlattenPDFBox4889() throws IOException
{
flattenAndCompare("f1040sb test.pdf");
}
/**
* PDFBOX-4955: appearance streams with forms that are not used.
*
* @throws IOException
*/
@Test
public void testFlattenPDFBox4955() throws IOException
{
flattenAndCompare("PDFBOX-4955.pdf");
}
/*
* Flatten and compare with generated image samples.
*/
private void flattenAndCompare(String fileName) throws IOException
{
File inputFile = new File(TARGETPDFDIR, fileName);
File outputFile = new File(OUT_DIR, fileName);
generateScreenshotsBefore(inputFile, IN_DIR);
try (PDDocument doc = PDFParser.parse(SeekableSources.seekableSourceFrom(inputFile)))
{
doc.getDocumentCatalog().getAcroForm().flatten();
assertTrue(doc.getDocumentCatalog().getAcroForm().getFields().isEmpty());
doc.writeTo(outputFile);
}
// compare rendering
TestPDFToImageTest testPDFToImage = new TestPDFToImageTest(this.getClass().getName());
if (!testPDFToImage.doTestFile(outputFile, IN_DIR, OUT_DIR))
{
System.out.println("Rendering of " + outputFile
+ " failed or is not identical to expected rendering in "
+ inputFile.getParent() + " directory;");
fail("Test failed");
}
}
private void generateScreenshotsBefore(File inputFile, File destinationFolder)
throws IOException
{
PDDocument document = PDDocument.load(inputFile);
String outputPrefix = inputFile.getName() + "-";
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < numPages; i++)
{
String fileName = outputPrefix + (i + 1) + ".png";
BufferedImage image = renderer.renderImageWithDPI(i, 96); // Windows native DPI
ImageIO.write(image, "PNG", new File(destinationFolder, fileName));
}
document.close();
}
}
|
Java
|
UTF-8
| 114 | 1.90625 | 2 |
[] |
no_license
|
package com.yfgz.es.bean;
public interface BasePrice {
Double obtainPrice();
Double obtainDiscount();
}
|
Markdown
|
UTF-8
| 4,541 | 2.53125 | 3 |
[] |
no_license
|
---
title: "virtual(C# 참조) | Microsoft 문서"
ms.date: 2015-07-20
ms.prod: .net
ms.technology:
- devlang-csharp
ms.topic: article
f1_keywords:
- virtual_CSharpKeyword
- virtual
dev_langs:
- CSharp
helpviewer_keywords:
- virtual keyword [C#]
ms.assetid: 5da9abae-bc1e-434f-8bea-3601b8dcb3b2
caps.latest.revision: 26
author: BillWagner
ms.author: wiwagn
translation.priority.ht:
- cs-cz
- de-de
- es-es
- fr-fr
- it-it
- ja-jp
- ko-kr
- pl-pl
- pt-br
- ru-ru
- tr-tr
- zh-cn
- zh-tw
translationtype: Human Translation
ms.sourcegitcommit: a06bd2a17f1d6c7308fa6337c866c1ca2e7281c0
ms.openlocfilehash: e2268fcc3888bf4b3a30f5855a31bfafcbd3ca49
ms.lasthandoff: 03/13/2017
---
# <a name="virtual-c-reference"></a>virtual(C# 참조)
`virtual` 키워드는 메서드, 속성, 인덱서 또는 이벤트 선언을 수정하고 파생 클래스에서 재정의하도록 허용하는 데 사용됩니다. 예를 들어 이 메서드는 이를 상속하는 모든 클래스에서 재정의할 수 있습니다.
```
public virtual double Area()
{
return x * y;
}
```
가상 멤버의 구현은 파생 클래스의 [재정의 멤버](../../../csharp/language-reference/keywords/override.md)로 변경할 수 있습니다. `virtual` 키워드 사용 방법에 대한 자세한 내용은 [Override 및 New 키워드를 사용하여 버전 관리](../../../csharp/programming-guide/classes-and-structs/versioning-with-the-override-and-new-keywords.md) 및 [Override 및 New 키워드를 사용해야 하는 경우](../../../csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md)를 참조하세요.
## <a name="remarks"></a>주의
가상 메서드가 호출되면 재정의 멤버에 대해 개체의 런타임 형식이 확인됩니다. 파생 클래스가 멤버를 재정의하지 않은 경우 가장 많이 파생된 클래스의 재정의 멤버(원래 멤버일 수 있음)가 호출됩니다.
기본적으로 메서드는 가상이 아닙니다. 가상이 아닌 메서드는 재정의할 수 없습니다.
`virtual` 한정자는 `static`, `abstract, private` 또는 `override` 한정자와 사용할 수 없습니다. 다음 예제에서는 가상 속성을 보여 줍니다.
[!code-cs[csrefKeywordsModifiers#26](../../../csharp/language-reference/keywords/codesnippet/CSharp/virtual_1.cs)]
선언과 호출 구문에서의 차이점을 제외하면 가상 속성은 추상 메서드처럼 작동합니다.
- 정적 속성에서 `virtual` 한정자를 사용하는 것은 오류입니다.
- `override` 한정자를 사용하는 속성 선언을 포함함으로써 상속된 가상 속성을 파생 클래스에서 재정의할 수 있습니다.
## <a name="example"></a>예제
이 예제에서 `Shape` 클래스는 두 개의 좌표 `x`, `y`와 `Area()` 가상 메서드를 포함합니다. `Circle`, `Cylinder` 및 `Sphere`와 같은 서로 다른 도형의 클래스는 `Shape` 클래스를 상속하며, 각 모양에 대해 노출 영역이 계산됩니다. 각 파생 클래스에는 `Area()`의 자체 재정의 구현이 있습니다.
다음 선언에 나와 있는 것처럼 상속된 클래스 `Circle`, `Sphere` 및 `Cylinder`는 모두 기본 클래스를 초기화하는 생성자를 사용합니다.
```
public Cylinder(double r, double h): base(r, h) {}
```
다음 프로그램은 메서드와 연결된 개체에 따라 `Area()` 메서드의 적절한 구현을 호출하여 각 그림의 해당 영역을 계산하고 표시합니다.
[!code-cs[csrefKeywordsModifiers#23](../../../csharp/language-reference/keywords/codesnippet/CSharp/virtual_2.cs)]
## <a name="c-language-specification"></a>C# 언어 사양
[!INCLUDE[CSharplangspec](../../../csharp/language-reference/keywords/includes/csharplangspec_md.md)]
## <a name="see-also"></a>참고 항목
[C# 참조](../../../csharp/language-reference/index.md)
[C# 프로그래밍 가이드](../../../csharp/programming-guide/index.md)
[한정자](../../../csharp/language-reference/keywords/modifiers.md)
[C# 키워드](../../../csharp/language-reference/keywords/index.md)
[다형성](../../../csharp/programming-guide/classes-and-structs/polymorphism.md)
[abstract](../../../csharp/language-reference/keywords/abstract.md)
[override](../../../csharp/language-reference/keywords/override.md)
[new](../../../csharp/language-reference/keywords/new.md)
|
C++
|
UTF-8
| 610 | 2.96875 | 3 |
[] |
no_license
|
#ifndef MENU_H
#define MENU_H
#include "DoublyLinkedList.h"
// The menu class is constructed with a DoublyLinkedList parameter and handles
// all user interaction and manipulation of list
class Menu{
public:
// @pre None.
// @param list - the linked list passed to the menu object to be operated on by the menu
// @post A menu object is created containing a member DoublyLinkedList
Menu(DoublyLinkedList list);
// @pre None.
// @post The menu's run() method begins operation of user interface
void run();
private:
DoublyLinkedList m_list;
int selection;
};
#endif
|
Java
|
GB18030
| 3,123 | 2 | 2 |
[] |
no_license
|
package com.sinosoft.mm.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.sinosoft.mm.entity.AccountInfo;
import com.sinosoft.mm.entity.Accountdetail;
import com.sinosoft.mm.entity.AccountdetailId;
import com.sinosoft.mm.struts.formbean.AccountDetailForm;
import com.sinosoft.mm.utils.AccountManageDelegate;
public class AccountDetailAction extends CitiAction {
@Override
public ActionForward citiExecute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest request,
HttpServletResponse httpServletResponse) throws Exception {
// TODO Auto-generated method stub
AccountDetailForm accountDetailForm = (AccountDetailForm)actionForm;
String operate = accountDetailForm.getOperate();
String accountCode = accountDetailForm.getAccountCode();
String transDate = accountDetailForm.getTransDate();
String beginBalance = accountDetailForm.getBeginBalance();
if(operate.equals("insert")){
Accountdetail accountDetail = null;
AccountdetailId accountdetailId = null;
AccountInfo accountInfo = null;
AccountManageDelegate accountManageDelegate = new AccountManageDelegate();
//жϸ˻Ƿѳʼ
String hql = "from Accountdetail a where a.id.accountcode='"+accountCode+"' and a.id.transseq ='1'";
List listTemp = accountManageDelegate.query(hql);
if(listTemp.size()!=0){
accountDetail = (Accountdetail)listTemp.get(0);
accountDetail.setBeginbalance(Double.valueOf(beginBalance));
accountDetail.setEndbalance(Double.valueOf(beginBalance));
accountManageDelegate.setAccountInfo(accountDetail, "update");
}else{
accountdetailId = new AccountdetailId();
accountDetail = new Accountdetail();
accountInfo = (AccountInfo)accountManageDelegate.get(AccountInfo.class.getName(), accountCode);
//ID
long seq = 1;
accountdetailId.setAccountcode(accountCode);
accountdetailId.setTransdate(transDate);
accountdetailId.setTransseq(Long.valueOf(seq));
accountDetail.setId(accountdetailId);
accountDetail.setBeginbalance(Double.valueOf(beginBalance));
accountDetail.setDebitamount(Double.valueOf(0));
accountDetail.setCreditamount(Double.valueOf(0));
accountDetail.setEndbalance(Double.valueOf(beginBalance));
accountDetail.setCurrency(accountInfo.getCurrency());
accountDetail.setDepositclass(accountInfo.getDepositclass());
accountDetail.setBrief(accountInfo.getAccountdesc());
accountDetail.setIntedatefrom(transDate);
accountDetail.setCheckflag("1");//˱־
accountDetail.setReceflag("");//Ѵδ
accountDetail.setBalchkflag("1");//ϸ˶Ա־
accountDetail.setSourceflag("1");//Դ˵
accountDetail.setTemp3("1");//ʼ־
accountManageDelegate.setAccountInfo(accountDetail, "insert");
}
}
return null;
}
}
|
Java
|
ISO-8859-1
| 1,160 | 2.21875 | 2 |
[] |
no_license
|
package gcom.gui.portal;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
public class AcessarPortalActionForm extends ActionForm {
private static final long serialVersionUID = -897961541167999297L;
private String matricula;
private String cpfCnpj;
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public String getCpfCnpj() {
return cpfCnpj;
}
public void setCpfCnpj(String cpfCnpj) {
this.cpfCnpj = cpfCnpj;
}
public ActionErrors validate(HttpSession sessao, boolean validarCpfCnpj) {
ActionErrors errors = new ActionErrors();
if (matricula == null || matricula.trim().equals("")) {
errors.add("matricula", new ActionError("errors.portal.obrigatorio", "a Matrcula do Imvel"));
}
if (validarCpfCnpj && (cpfCnpj == null || cpfCnpj.trim().equals(""))) {
errors.add("cpfCnpj", new ActionError("errors.portal.obrigatorio", "o CPF/CNPJ"));
}
return errors;
}
}
|
C#
|
UTF-8
| 909 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MirthDotNet.Model
{
[Serializable]
public class MirthDateTime
{
public static readonly DateTime UnixEpoch = new DateTime(1970,1,1,0,0,0,0);
public long time { get; set; }
public string timezone { get; set; }
public DateTime DateTime
{
get
{
return UnixEpoch.AddMilliseconds(time).ToLocalTime();
}
set
{
time =
(long)
(DateTime.SpecifyKind(value, DateTimeKind.Unspecified) -
DateTime.SpecifyKind(UnixEpoch, DateTimeKind.Unspecified))
.TotalMilliseconds;
timezone = "America/New_York"; // hard coded :(
}
}
}
}
|
Java
|
UTF-8
| 1,961 | 2.578125 | 3 |
[] |
no_license
|
package project.back.back.model;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "MEMBER_HAS_KEYWORD", schema = "dbo")
@IdClass(MemberHasKeywordPK.class)
public class MemberHasKeyword {
private String keywordLabel;
private int memberId;
private Keyword keywordByKeywordLabel;
private Member memberByMemberId;
@Id
@Column(name = "KEYWORD_LABEL", nullable = false, length = 100)
public String getKeywordLabel() {
return keywordLabel;
}
public void setKeywordLabel(String keywordLabel) {
this.keywordLabel = keywordLabel;
}
@Id
@Column(name = "MEMBER_ID", nullable = false, precision = 0)
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberHasKeyword that = (MemberHasKeyword) o;
return memberId == that.memberId &&
Objects.equals(keywordLabel, that.keywordLabel);
}
@Override
public int hashCode() {
return Objects.hash(keywordLabel, memberId);
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "KEYWORD_LABEL", referencedColumnName = "KEYWORD_LABEL", nullable = false)
public Keyword getKeywordByKeywordLabel() {
return keywordByKeywordLabel;
}
public void setKeywordByKeywordLabel(Keyword keywordByKeywordLabel) {
this.keywordByKeywordLabel = keywordByKeywordLabel;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MEMBER_ID", referencedColumnName = "MEMBER_ID", nullable = false)
public Member getMemberByMemberId() {
return memberByMemberId;
}
public void setMemberByMemberId(Member memberByMemberId) {
this.memberByMemberId = memberByMemberId;
}
}
|
PHP
|
UTF-8
| 926 | 2.546875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
<?php
require_once(realpath(dirname(__FILE__).'/../') . '/class.imagefilter.php');
Class FilterJcrop extends ImageFilter{
public static function run($res, $width, $height, $dst_x, $dst_y, $background_fill='fff'){
$dst_w = Image::width($res);
$dst_h = Image::height($res);
if(!empty($width) && !empty($height)) {
$dst_w = $width;
$dst_h = $height;
}
elseif(empty($height)) {
$ratio = ($dst_h / $dst_w);
$dst_w = $width;
$dst_h = round($dst_w * $ratio);
}
elseif(empty($width)) {
$ratio = ($dst_w / $dst_h);
$dst_h = $height;
$dst_w = round($dst_h * $ratio);
}
$tmp = imagecreatetruecolor($dst_w, $dst_h);
self::__fill($tmp, $background_fill);
imagecopyresampled($tmp, $res, $src_x, $src_y, $dst_x, $dst_y, Image::width($res), Image::height($res), Image::width($res), Image::height($res));
@imagedestroy($res);
return $tmp;
}
}
|
C++
|
UTF-8
| 349 | 3.1875 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdlib> // just for practice
int main()
{
int x{}, y{}, z{};
x = 5 - -1;
std::cout << x << '\n';
y = 4;
y+=1;
std::cout << "x / y = " << x/y << '\n'; //integer division
std::cout << "double(x)/y = " << static_cast<double>(x)/y << '\n'; // static cast
return EXIT_SUCCESS;
}
|
C#
|
UTF-8
| 3,136 | 3.296875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
namespace Triangles.Excercise
{
public class TriangleInfo
{
public string DisplayName { get { return RowIdentifier.ToUpper() + ColumnIdentifier; } }
public List<Vertex2D> Vertices { get; set; }
private string RowIdentifier { get; set; }
private string ColumnIdentifier { get; set; }
public bool IsValid { get; set; }
public TriangleInfo(string rowId, int columnId, int sideLenght = 100)
{
Vertices = new List<Vertex2D>();
if (!ValidateInput(rowId, columnId))
{
this.IsValid = false;
}
else
{
// calculate 0-base row number
int row = rowId.ToUpper().ToCharArray().FirstOrDefault() - 'A';
RowIdentifier = rowId;
ColumnIdentifier = columnId.ToString();
// calculate 0-base column number
columnId--;
int column = columnId / 2;
int columnPos = columnId % 2;
Vertex2D A = new Vertex2D() { Y = row * sideLenght, X = column * sideLenght };
Vertex2D B = new Vertex2D() { Y = (row + 1) * sideLenght, X = (column + 1) * sideLenght };
Vertex2D C = new Vertex2D() { Y = (columnPos == 0) ? ((row + 1) * sideLenght) : row * sideLenght, X = (columnPos == 0) ? (column * sideLenght) : (column + 1) * sideLenght };
Vertices.Add(A);
Vertices.Add(B);
Vertices.Add(C);
this.IsValid = true;
}
}
private bool ValidateInput(string rowId, int columnId)
{
string ident = rowId.ToUpper() + columnId.ToString();
var reg = new Regex(@"^([A-F])([1-9]|1[012])$");
return reg.IsMatch(ident);
}
public TriangleInfo(int v1x, int v1y, int v2x, int v2y, int v3x, int v3y, int sideLenght = 100)
{
Vertices = new List<Vertex2D>();
Vertex2D A = new Vertex2D() { X = v1x, Y = v1y };
Vertex2D B = new Vertex2D() { X = v2x, Y = v2y };
Vertex2D C = new Vertex2D() { X = v3x, Y = v3y };
Vertices.Add(A);
Vertices.Add(B);
Vertices.Add(C);
var maxY = Vertices.Select(a => a.Y).Max();
var row = maxY / sideLenght;
RowIdentifier = "" + (char)(65 + row - 1);
var maxX = Vertices.Select(a => a.X).Max();
var column = maxX / sideLenght;
var sorted = Vertices.Select(a => a.X).OrderBy(a => a).ToArray();
if (sorted[0] == sorted[1])
{
ColumnIdentifier = ((column * 2) - 1).ToString();
}
else
{
ColumnIdentifier = (column * 2).ToString();
}
}
public string SVG
{
get
{
return string.Join(", ", Vertices);
}
}
}
}
|
Java
|
UTF-8
| 3,527 | 2.140625 | 2 |
[] |
no_license
|
package com.jumbo.wms.model.warehouse;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.jumbo.wms.model.BaseModel;
/**
* EMS订单确认队列
*
* @author sjk
*
*/
@Entity
@Table(name = "T_EMS_CONFIRM_ORDER_QUEUE")
public class EMSConfirmOrderQueue extends BaseModel {
/**
*
*/
private static final long serialVersionUID = -3274655534952334972L;
/**
* PK
*/
private Long id;
/**
* 作业单号
*/
private String staCode;
/**
* 订单号
*/
private String billNo;
/**
* 重量
*/
private String weight;
/**
* 物品长度
*/
private String length;
/**
* 创建时间
*/
private Date createTime;
/**
* 大客户号
*/
private String sysAccount;
/**
* 大客户密码
*/
private String passWord;
/**
* 执行次数
*/
private Long exeCount;
/**
* 单据标识
*/
private Long order_flag;
/**
* 订单分类 (1:线下包裹 )
*
* @return
*/
private Integer type;
@Column(name = "TYPE")
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Id
@Column(name = "ID")
@SequenceGenerator(name = "SEQ_SFCQQ", sequenceName = "S_T_EMS_CONFIRM_ORDER_QUEUE", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_SFCQQ")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "STA_CODE", length = 60)
public String getStaCode() {
return staCode;
}
public void setStaCode(String staCode) {
this.staCode = staCode;
}
@Column(name = "weight", length = 20)
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
@Column(name = "create_time")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Column(name = "BILL_NO", length = 50)
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
@Column(name = "SYS_ACCOUNT", length = 50)
public String getSysAccount() {
return sysAccount;
}
public void setSysAccount(String sysAccount) {
this.sysAccount = sysAccount;
}
@Column(name = "PASSWORD", length = 50)
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Column(name = "EXE_COUNT")
public Long getExeCount() {
return exeCount;
}
public void setExeCount(Long exeCount) {
this.exeCount = exeCount;
}
public String getLength() {
return length;
}
public void setLength(String length) {
this.length = length;
}
@Column(name = "ORDER_FLAG")
public Long getOrder_flag() {
return order_flag;
}
public void setOrder_flag(Long order_flag) {
this.order_flag = order_flag;
}
}
|
Java
|
UTF-8
| 1,910 | 2.359375 | 2 |
[] |
no_license
|
package com.example.taylorflowers.friender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class registration extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
}
public void openHome(View view) throws Exception{
final EditText e = findViewById(R.id.email);
final EditText password = findViewById(R.id.password);
final EditText n = findViewById(R.id.name);
final EditText a = findViewById(R.id.age);
final EditText p = findViewById(R.id.phone);
final EditText b = findViewById(R.id.bio);
String pass = password.getText().toString();
String email = e.getText().toString();
People temp = People.containsEmail(email);
if (temp != null) {
Toast errorToast = Toast.makeText(registration.this, "Email already exists! Sorry. Try again!", Toast.LENGTH_SHORT);
errorToast.show();
} else if (!email.contains("@")) {
Toast errorToast = Toast.makeText(registration.this, "Email is not valid. Try again!", Toast.LENGTH_SHORT);
errorToast.show();
} else {
String name = n.getText().toString();
int age = Integer.parseInt(a.getText().toString());
String bio = b.getText().toString();
String phoneTemp = p.getText().toString();
long phone = Long.parseLong(phoneTemp);
People user = new People(name, age, bio, phone, email, pass);
People.setCurr(user);
Intent intent = new Intent(registration.this, homes.class);
startActivity(intent);
finish();
}
}
}
|
C#
|
UTF-8
| 1,755 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Timers;
using System.Windows.Forms;
using Timer = System.Timers.Timer;
namespace SimpleReactionMachine
{
static class SimpleReactionMachine
{
static private IController Contoller;
static private IGui Gui;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Create a time for Tick event
Timer timer = new Timer(10);
// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Connect GUI with the Controller and vice versa
ReactionMachineForm MainForm = new ReactionMachineForm();
Contoller = new SimpleReactionController();
Gui = MainForm;
Gui.Connect(Contoller);
Contoller.Connect(Gui, new RandomGenerator());
//Reset the GUI
Gui.Init();
// Start the timer
timer.Enabled = true;
Application.Run(MainForm);
}
// This event occurs every 10 msec
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Contoller.Tick();
}
// Internal implementation of Random Generator
private class RandomGenerator : IRandom
{
Random rnd = new Random(100);
public int GetRandom(int from, int to)
{
return rnd.Next(from) + to;
}
}
}
}
|
Python
|
UTF-8
| 325 | 4.59375 | 5 |
[] |
no_license
|
#Declare a variable called full_name that is equal to artist's first and last names with a space in between
artist = {
"first": "Neil",
"last": "Young",
}
full_name = artist["first"] + " " + artist["last"]
#or
full_name2 = f"{artist['first']} {artist['last']}"
print(full_name)
print()
print(full_name2)
|
Java
|
UTF-8
| 2,226 | 2.5625 | 3 |
[] |
no_license
|
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import analisisVisual.Imagen;
import analisisVisual.Manipulador;
import analisisVisual.Resultado;
/**
* Prueba para Chrome y Firefox, con www.google.com
*/
public class PruebaXChromeFF {
public static void main(String[] args) {
Manipulador manipulador = new Manipulador("Prueba Google - Chrome-Firefox", "C:\\xtest");
//CHROME
System.setProperty("webdriver.chrome.driver", "C:\\browser-drivers\\chromedriver\\chromedriver.exe");
//crea un options para Chrome
ChromeOptions options = new ChromeOptions();
//para desactivar la barra "Chrome is being controlled by automated test software"
options.addArguments("disable-infobars");
//crea el WebDriver para Chrome pasando como parametro el options creado anteriormente
WebDriver chromeDriver = new ChromeDriver(options);
//abre la pagina en chrome
chromeDriver.get("https://www.google.com");
//realiza la captura de pantalla
Imagen img1 = manipulador.capturarPantallaFullscreen(chromeDriver);
chromeDriver.close();
//FIREFOX
System.setProperty("webdriver.gecko.driver","C:\\browser-drivers\\geckodriver\\geckodriver.exe");
//crea el WebDriver para firefox
WebDriver firefoxDriver= new FirefoxDriver();
//abre la pagina en firefox
firefoxDriver.get("https://www.google.com");
//realiza la captura de pantalla
Imagen img2 = manipulador.capturarPantallaFullscreen(firefoxDriver);
firefoxDriver.close();
//ejecuta la comparacion pixel a matriz de pixeles
//se envian las dos imagenes, los valores de delta y toleranciaRGB
Resultado resultado1 = manipulador.compararImagenesPixAMatrizPix(img1, img2, 4, 40);
//crea el reporte con los resultados
manipulador.crearReporte(resultado1);
}
}
|
Java
|
UTF-8
| 437 | 1.945313 | 2 |
[
"Apache-2.0"
] |
permissive
|
package cl.kaiser.hana;
public class KProcedureException extends Exception {
private static final long serialVersionUID = 4354608826209653826L;
public KProcedureException() { super(); }
public KProcedureException(String message) { super(message); }
public KProcedureException(String message, Throwable cause) { super(message, cause); }
public KProcedureException(Throwable cause) { super(cause); }
}
|
PHP
|
UTF-8
| 1,193 | 2.640625 | 3 |
[] |
no_license
|
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class InitApp extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:init';
/**
* The console command description.
*
* @var string
*/
protected $description = 'アプリケーションを初期化する';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
public function handle()
{
print("-- start: ".get_class($this)."\n");
// キャッシュクリア等
Artisan::call('app:fresh');
printf ("\e[32m%s: \e[m %s\n", "start", "migrate: fresh");
Artisan::call('migrate:fresh', ['--seed' => true]);
printf ("\e[32m%s: \e[m %s\n\n", "finish", "migrate: fresh");
// Artisan::call('storage:clear', ['--all' => true]);
// Artisan::call('firebase:clear');
// ジョブ実行
// Artisan::call('queue:work');
print("-- finish: ".get_class($this)."\n\n");
}
}
|
C
|
UTF-8
| 696 | 3.3125 | 3 |
[] |
no_license
|
#include <stdio.h>
int main(void) {
int i;
int t, c;
scanf("%d", &t);
for (c = 1; c <= t; c++) {
int n, p[26];
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", p + i);
printf("Case #%d: ", c);
while (1) {
int max, maxIdx;
max = 0;
for (i = 0; i < n; i++)
if (p[i] > max) {
max = p[i];
maxIdx = i;
}
if (n == 2) {
p[0]--;
p[1]--;
printf("AB%c", " \n"[max == 1]);
if (max == 1)
break;
} else if (max == 1 && maxIdx == n - 2) {
printf("%c%c\n", 'A' + n - 2, 'A' + n - 1);
break;
} else {
p[maxIdx]--;
printf("%c ", 'A' + maxIdx);
}
}
}
return 0;
}
|
Java
|
UTF-8
| 926 | 2.484375 | 2 |
[] |
no_license
|
public class Estudiante{
String NoEstudiante;
String Nombre;
Fecha FechaNacimiento;
int Puntuacion;
private Estudiante(String NoEstudiante, String Nombre, Fecha FechaNacimiento,int Puntuacion){
NoEstudiante = iNoEstudiante;
Nombre = iNombre;
FechaNacimiento = iFechaNacimiento;
Puntuacion = iPuntuacion;
}
public void setNoEstudiante(String iNoEstudiante){
NoEstudiante = iNoEstudiante;
}
public String getNoEstudiante(){
return NoEstudiante;
}
public void setNombre(String iNombre){
Nombre = iNombre;
}
public String getNombre(){
return Nombre;
}
public void setFechaNAcimiento(Fecha iFechaNacimiento){
FechaNacimiento = iFechaNacimiento;
}
public Fecha getFechaNacimiento(){
return FechaNacimiento;
}
public void setPuntuacion(int iPuntuacion){
Puntuacion = iPuntuacion;
}
public int getPuntuacion(){
return Puntuacion;
}
public int Puntuacion{
for ( i = )
}
}
|
Rust
|
UTF-8
| 1,373 | 4.25 | 4 |
[] |
no_license
|
fn main() {
// let number = 30;
//
// if number < 5 {
// println!("condition was true");
// } else {
// println!("condition was false");
// }
//
// let mut counter = 0;
// let result = loop {
// println!("again!");
// counter += 1;
// if counter == 10 { break counter * 2; }
// };
//
// println!("The result id {result}");
// let mut count = 0;
// 'counting_up: loop {
// println!("count = {count}");
// let mut remaining = 10;
//
// loop {
// println!("remaining = {remaining}");
// if remaining == 9 {
// break;
// }
// if count == 2 {
// break 'counting_up;
// }
// remaining -= 1;
// }
// count += 1;
// }
// println!("End count = {count}");
let mut number = 3;
while number != 0 {
println!("{number}");
number -= 1;
}
let arr = [20, 30, 30, 40, 10, 200];
let len = arr.len();
println!("len = {}", len);
for item in arr {
println!("{}", item);
}
fib(10);
}
fn fib(mut counter: u8) {
let mut i = 0;
let mut j = 1;
while counter > 0 {
j = i + j;
i = j - i;
println!("j = {}", j);
counter -= 1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.